text
stringlengths
8
267k
meta
dict
Q: Javascript, jQuery pattern to create HTML document I'm not sure if I'm asking the right question or not. But my application heavily relies on Javascript and jQuery to create HTML document. So I have a lot of this "jQuery(") and then a lot of div.attr("id","123"). So, is there a better way to do this, or some design pattern to deal with this? Thanks a lot. A: Yes, jQuery Templates. They make it easier to build html with jQuery, you can do: <script id="movieTemplate" type="text/x-jquery-tmpl"> <li><b>${Name}</b> (${ReleaseYear})</li> </script> <ul id="movieList"></ul> <script> var movies = [ { Name: "The Red Violin", ReleaseYear: "1998" }, { Name: "Eyes Wide Shut", ReleaseYear: "1999" }, { Name: "The Inheritance", ReleaseYear: "1976" } ]; /* Render the template with the movies data and insert the rendered HTML under the "movieList" element */ $( "#movieTemplate" ).tmpl( movies ) .appendTo( "#movieList" ); </script> And get: * *The Red Violin (1998) *Eyes Wide Shut (1999) *The Inheritance (1976)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using CGImageProperties to get EXIF properties I want to be able to add a text comment to the metadata of a JPEG and be able to read it back from within an iphone app. I thought this would be fairly simple as ios4 contains support for EXIF info. So I added metadata using a Windows tool called used AnalogExif and read it back from my app using: NSData *jpeg = UIImageJPEGRepresentation(myUIImage,1.0); CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)jpeg, NULL); NSDictionary *metadata = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source,0,NULL); NSMutableDictionary *metadataAsMutable = [[metadata mutableCopy]autorelease]; [metadata release]; NSMutableDictionary *EXIFDictionary = [[[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyExifDictionary] And that works...to a point :) What I get back in the metadata dictionary is something like: (gdb) po metadata { ColorModel = RGB; Depth = 8; Orientation = 1; PixelHeight = 390; PixelWidth = 380; "{Exif}" = { ColorSpace = 1; PixelXDimension = 380; PixelYDimension = 390; }; "{JFIF}" = { DensityUnit = 0; JFIFVersion = ( 1, 1 ); XDensity = 1; YDensity = 1; }; "{TIFF}" = { Orientation = 1; }; } But thats all I can get! I've edited the JPEG file with every EXIF editor I can find (mostly PC ones I should say) and although they all say I have added JPEG comments and EXIF captions and keywords, none of that info seems to be available from the Apple SDK in my app. Has anyone managed to set a text field in the metadata of a jpeg and manage to read it back from an iphone app? I didn't want to use a third party library if at all possible many thanks in advance A: You're correct in thinking that iOS does support more metadata than what you're seeing. You probably lost the data when you created a UIImage and then converted it back to JPEG. Try NSData *jpeg = [NSData dataWithContentsOfFile:@"foo.jpg"] and you should see the EXIF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Retrieving a Specific Value From A Serialized Array MySQL Database structure is as follows: id|metaKey|metaValue --+-------+----------------------------------- 55|product|a:8:{s:3:"sku";s:0:"";s:8:"products";a:3:{i:1;a:3:{s:6:"option";s:1:"1";s:5:"price";s:5:"14.95";s:9:"saleprice";s:0:"";}i:2;a:3:{s:6:"option";s:0:"";s:5:"price";s:0:"";s:9:"saleprice";s:0:"";}i:3;a:3:{s:6:"option";s:0:"";s:5:"price";s:0:"";s:9:"saleprice";s:0:"";}}s:11:"description";s:124:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";s:8:"shiprate";s:1:"A";s:8:"featured";s:2:"no";s:4:"sale";s:3:"yes";s:10:"cart_radio";s:1:"0";s:6:"optset";s:0:"";} This is from a wordpress site, I need to retrieve the first "price" value which is 14.95 what is the best way to retrieve a specific value from a serialized array stored in mysql? A: Create query, read data from SQL, unserialize() metaValue and access it like an array. You can also try to use regular expressions if you need to extract it inside mysql, but that's a not very good approach. A: Use unserialize() to retrieve the metaValue data. The following code can retrieve the first price value: $result = mysql_query("SELECT * FROM tbl WHERE id=55"); $row = mysqLfetch_assoc($result); $serial = $row['metaValue']; $data = unserialize($serial); echo $data['products'][1]['price']; The data in this row is structured as: array(8) { ["sku"]=> string(0) "" ["products"]=> array(3) { [1]=> array(3) { ["option"]=> string(1) "1" ["price"]=> string(5) "14.95" ["saleprice"]=> string(0) "" } [2]=> array(3) { ["option"]=> string(0) "" ["price"]=> string(0) "" ["saleprice"]=> string(0) "" } [3]=> array(3) { ["option"]=> string(0) "" ["price"]=> string(0) "" ["saleprice"]=> string(0) "" } } ["description"]=> string(124) "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." ["shiprate"]=> string(1) "A" ["featured"]=> string(2) "no" ["sale"]=> string(3) "yes" ["cart_radio"]=> string(1) "0" ["optset"]=> string(0) "" }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why do I receive a "cannot find symbol" error when compiling this interface method? I'm using the interface Place: public interface Place { int distance(Place other); } But when I try to implement the interface and compile the following code, a "cannot find symbol - variable xcor" error returns. public class Point implements Place { private double xcor, ycor; public Point (double myX, double myY) { xcor = myX; ycor = myY; } public int distance(Place other) { double a = Math.sqrt( (other.xcor - xcor) * (other.xcor - xcor) + (other.ycor - ycor) * (other.ycor -ycor) ) + 0.5; return (int)a; } } Any ideas for what I might be doing wrong? Does it have something to do with the scope of the fields? A: The interface Place has no member xcor. Add a method double getXcor() to your interface and implement it in your class. The same applies to ycor. Then you can use these getters in your implementation of the distance method. public interface Place { int distance(Place other); double getXcor(); double getYcor(); } A: It is because the Place interface doesn't expose a symbol named 'xcor'. It only exposes the method 'distance'. so when you have a variable of type Place the compiler doesn't know which underlying type it is. You either have to have Place expose a getter for xcor/ycor etc or downcast the instance of 'Place' to 'Point'. downcasting is usually frowned on when you have multiple implementations of Place, but this is the usual problem with having an interface that overlays implementations that have different underlying properties. Like having a 'Shape' that has 'area()' with implementations of Rectangle and Circle that use different methods of computing area. A: A Place does not have an xcor and ycor members, a Point does. A: The parameter to the distance method is a Place, not a Point. Only the Point class has a field named xcor. A: Several earlier posters mention the problem, which is that distance is being given a Place that has no xcor. I'm going to go a little further and suggest this is a place for generics. It probably makes no sense to define a distance function between arbitrary places. (If it does, then xcor and ycor can be pulled up into an abstract class between Place and Point.) public interface Place<T> { int distance (Place<T> other); } class Point implements Place<Point> etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Handling Timeouts in a Socket Server I have an asynchronous socket server that contains a thread-safe collection of all connected clients. If there's no activity coming from a client for a set amount of time (i.e. timeout), the server application should disconnect the client. Can someone suggest the best way to efficiently track this timeout for each connected client and disconnect when the client times out? This socket server must be very high performance and at any given time, hundreds of client could be connected. One solution is to have each client associated with a last activity timestamp and have a timer periodically poll the collection to see which connection has timed out based on that timestamp and disconnect it. However, this solution to me isn't very good because that would mean the timer thread has to lock the collection whenever it polls (preventing any other connections/disconnections) for the duration of this process of checking every connected client and disconnecting when timed out. Any suggestions/ideas would be greatly appreciated. Thanks. A: If this is a new project or if you're open to a major refactor of your project, have a look at Reactive Extensions. Rx has an elegant solution for timeouts in asynchronous calls: var getBytes = Observable.FromAsyncPattern<byte[], int, int, int>(_readStream.BeginRead, _readStream.EndRead); getBytes(buffer, 0, buffer.Length) .Timeout(timeout); Note, the code above is just intended to demonstrate how to timeout in Rx and it would be more complex in a real project. Performance-wise, I couldn't say unless you profile your specific use case. But I have seen a talk where they used Rx in a complex data-driven platform (probably like your requirements) and they said that their software was able to make decisions within less than 30ms. Code-wise, I find that using Rx makes my code look more elegant and less verbose. A: Your solution is quite OK for many cases when the number of connected clients is small compared to the performance of the enumerating the collection of their contexts. If you allow some wiggle room in the timeout (i.e. it's OK to disconnect the client somewhere between 55 and 65 seconds of inactivity), I'd just run the purging routine every so often. The other approach which worked great for me was using a queue of activity tokens. Lets use C#: class token { ClientContext theClient; // this is the client we've observed activity on DateTime theTime; // this is the time of observed activity }; class ClientContext { // ... what you need to know about the client DateTime lastActivity; // the time the last activity happened on this client } Every time an activity happens on a particular client, a token is generated and pushed into FIFO queue and lastActivity is updated in the ClientContext. There is another thread which runs the following loop: * *extracts the oldest token from the FIFO queue; *checks if theTime in this token matches the theClient.lastActivity; *if it does, shuts down the client; *looks at the next oldest token in the queue, calculates how much time is left till it needs to be shutdown; *Thread.Sleep(<this time>); *repeat The price of this approach is a little, but constant, i.e. O(1) overhead. One can come up with faster best case solutions, but it seems to me that it's hard to come up with a one with faster worst case performance. A: I think it is easier to control timeout form within the connection thread. So you may have something like this: // accept socket and open stream stream.ReadTimeout = 10000; // 10 seconds while (true) { int bytes = stream.Read(buffer, 0, length) // process the data } The stream.Read() call will either return data (which means client is alive) or throw IO exception (abnormal disconnect) or return 0 (client closed the socket).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: testing backbone.js view events with jasmine I'm trying to implement view tests for a Coffeescript implementation of the ubiquitous backbone.js 'todo' example (see github.com/rsim/backbone_coffeescript_demo.) My jasmine tests of the above demo work pretty well, except for view events. I expect I am stuck on one or both of the following i) I do not understand the event binding in the view code, ii) I do not understand how to properly set up the Jasmine test of the view code events. Here is an example of the 'edit' event... class TodoApp.TodoView extends Backbone.View tagName: "li" template: TodoApp.template '#item-template' events: "dblclick div.todo-content" : "edit" ... initialize: -> _.bindAll this, 'render', 'close' @model.bind 'change', @render @model.bind 'destroy', => @remove() render: -> $(@el).html @template @model.toJSON() @setContent() this edit: -> $(@el).addClass "editing" @input.focus() ... ...now here's a test of whether focus was gained upon double clicking: describe "edit state", -> li = null beforeEach -> setFixtures('<ul id="todo-list"></ul>') model = new Backbone.Model id: 1, content: todoValue, done: false view = new TodoApp.TodoView model: model, template: readFixtures("_item_template.html") $("ul#todo-list").append(view.render().el) li = $('ul#todo-list li:first') target = li.find('div.todo-content') expect(target).toExist() target.trigger('dblclick') # here's the event! it "input takes focus", -> expect(li.find('.todo-input').is(':focus')).toBe(true) The expectation on neither i) the spy nor ii) the focus is met. Is there a peculiarity to testing backbone.js event code about which I should be aware in Jasmine? A: you're spying on the view's edit method. this replaces the method with a spy object, which means the actual edit method won't get called. therefore, you're @input.focus will never fire. since you want the test to actually call your edit method, i would remove the spy for it. side note: don't call expect methods in your beforeEach. if you truly need to set an expectation on those, create an it block for them. A: I'm not great with coffescript so I might be missing something but where are you setting up your spy? In order to test event calling you may need to refresh the view's events once you've set up the spy. spyOn(view, 'edit'); view.delegateEvents(); target.trigger('dblclick'); it("should call edit when target is double clicked", function() { expect(view.edit).toHaveBeenCalled() }); A: I did not write my test in coffeescript, but I did have the same problem, so I hope you will forgive me for answering in javadcript. I ended up breaking down your test into two different tests. First, I tested if calling the view's edit function set the focus on the input box. After that, I tested whether the edit was called when the label was double-clicked, and have not yet gotten that test to pass. But here's how I tested if the edit function worked. describe ("A todo item view", function() { var my_model; var todo_view; beforeEach(function() { my_model = new Todo({content:"todo value", done:false}); todo_view = new TodoView({model:my_model}); }); it("should set the focus on the input box when the edit function is called", function(){ $('body').append( todo_view.$el ); //append the view to Specrunner.html todo_view.edit(); //call the view's edit function var focus= document.activeElement; //finds what element on the page has focus expect(focus).toBe('.todo-input'); //jasmine-jquery matcher checks if focused element has the .todo-input class }); Something that might be causing problems is that your model And your view are declared inside beforeEach. Declaring them inside beforeEach means they only exist inside beforeEach's scope, and no longer exist when you run your it. Also, does setFixtures do what you think it does? The focus cannot be set on an element that is not part of the DOM tree, so I appended the view's el to the body of the jasmine spec itself. (I'm using the HTML specrunner, not the command-line version) That makes it part of the dom tree and therefore allows it to have focus, and also makes whether it has focus testable. A: The issue with this is that Backbone.View events object is using event delegation. For the events to be able to be called work the element has to be part of DOM, you can do this by doing something like $('body').append(someView.el) in your beforeEach. Personally, I try not to test if Backbone is correctly setting the events and triggering clicks manually, is more practical for unit tests to call the callback handlers directly avoiding the DOM completely which can slow down your tests a lot. For :focus is the same problem, there has to be an element in the DOM so that jQuery can tell if an element is focused. In this case it's better to set some state as part of your component and not checking for state via querying the DOM, e.g.: someView.hasFocus === true. Alternatively you can spy on the elements focus implementation and check if it was called.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how to prevent misuse of bool's in Core Data (i.e. forgetting to put "boolValue" to convert from NSNumber) I still muck up with bool's in my core data config data. The NSManagedObject for say a core data "config" class one can quickly type in the following and you don't get an error: if (self.myCoreDataConfigObject.isOn) { ... but it doesn't give the correct result as what is required is the conversion from NSNumber to a bool: if ([self.myCoreDataConfigObject.isOn boolValue]) { ... Question - Any tips/tricks on how to avoid this? It would be great if XCode would show a warning in this case... A: You could rename the field to something like isOnValue and then provide an accessor on your NSManagedObject subclass called isOn that runs the -boolValue conversion for you. Don't forget, however, that "optional" values may be nil and you may care about this as something distinct than NO. A: Under 'Targets' -> 'Build Settings' in the project settings there is a group of options for compiler warnings. I'm not 100% on this but turning on 'Pedantic Warnings' might do it, if not there are dozens of different settings for each different type of compiler. Try toggling some of them on and see if it generates a warning where you want one. However, if (self.myCoreDataConfigObject.isOn) is a perfectly valid expression, so no errors (warnings maybe, but not errors) will ever get generated because using if(SOME_OBJECT) just checks if it is equivalent to nil or 0. (Unless, of course, you specify for the compiler to treat warnings as errors) A: One thing you could do is use the C99 bool type in if(). For instance, the following: NSNumber *num = [NSNumber numberWithInt:0]; if (num == true) { NSLog(@"num is true"); } makes XCode issue a warning. You'd have to adhere to a convention of always using "== true" in conditions though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I run Net::SSH and AMQP in the same EventMachine reactor? Some background: Gerrit exposes an event stream through SSH. It's a cute trick, but I need to convert those events into AMQP messages. I've tried to do this with ruby-amqp and Net::SSH but, well, it doesn't seem as if the AMQP sub-component is even being run at all. I'm fairly new to EventMachine. Can someone point out what I am doing incorrectly? The answer to "Multiple servers in a single EventMachine reactor) didn't seem applicable. The program, also available in a gist for easier access, is: #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'net/ssh' require 'json' require 'yaml' require 'amqp' require 'logger' trap(:INT) { puts; exit } options = { :logs => 'kili.log', :amqp => { :host => 'localhost', :port => '5672', }, :ssh => { :host => 'localhost', :port => '22', :user => 'nobody', :keys => '~/.ssh/id_rsa', } } optparse = OptionParser.new do|opts| opts.banner = "Usage: kili [options]" opts.on( '--amqp_host HOST', 'The AMQP host kili will connect to.') do |a| options[:amqp][:host] = a end opts.on( '--amqp_port PORT', 'The port for the AMQP host.') do |ap| options[:amqp][:port] = ap end opts.on( '--ssh_host HOST', 'The SSH host kili will connect to.') do |s| options[:ssh][:host] = s end opts.on( '--ssh_port PORT', 'The SSH port kili will connect on.') do |sp| options[:ssh][:port] = sp end opts.on( '--ssh_keys KEYS', 'Comma delimeted SSH keys for user.') do |sk| options[:ssh][:keys] = sk end opts.on( '--ssh_user USER', 'SSH user for host.') do |su| options[:ssh][:user] = su end opts.on( '-l', '--log LOG', 'The log location of Kili') do |log| options[:logs] = log end opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end end optparse.parse! log = Logger.new(options[:logs]) log.level = Logger::INFO amqp = options[:amqp] sshd = options[:ssh] queue= EM::Queue.new EventMachine.run do AMQP.connect(:host => amqp[:host], :port => amqp[:port]) do |connection| log.info "Connected to AMQP at #{amqp[:host]}:#{amqp[:port]}" channel = AMQP::Channel.new(connection) exchange = channel.topic("traut", :auto_delete => true) queue.pop do |msg| log.info("Pulled #{msg} out of queue.") exchange.publish(msg[:data], :routing_key => msg[:route]) do log.info("On route #{msg[:route]} published:\n#{msg[:data]}") end end end Net::SSH.start(sshd[:host], sshd[:user], :port => sshd[:port], :keys => sshd[:keys].split(',')) do |ssh| log.info "SSH connection to #{sshd[:host]}:#{sshd[:port]} as #{sshd[:user]} made." channel = ssh.open_channel do |ch| ch.exec "gerrit stream-events" do |ch, success| abort "could not stream gerrit events" unless success # "on_data" is called when the process writes something to # stdout ch.on_data do |c, data| json = JSON.parse(data) if json['type'] == 'change-merged' project = json['change']['project'] route = "com.carepilot.event.code.review.#{project}" msg = {:data => data, :route => route} queue.push(msg) log.info("Pushed #{msg} into queue.") else log.info("Ignoring event of type #{json['type']}") end end # "on_extended_data" is called when the process writes # something to stderr ch.on_extended_data do |c, type, data| log.error(data) end ch.on_close { log.info('Connection closed') } end end end end A: Net::SSH is not asynchronous, so your EventMachine.run() is never reaching the end of the block, thus never resuming the reactor thread. This causes the AMQP code to never start. I would suggest running your SSH code within another thread. A: If you go back to EventMachine, give em-ssh https://github.com/simulacre/em-ssh a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: linq to sql query help - common values userkey keyboardkey keypressed ---------------------------------------- u1 kb1 A u1 kb1 B u1 kb2 C u2 kb1 A u2 kb1 B u3 kb1 A u3 kb1 B u3 kb1 D u4 kb1 E How can i write a linq to sql query to get only the common keypressed. For instance find the common keypressed where user account is in (u1, u2, u3) and keyboardkey = kb1. This will give the output as alist containing A,B. And find the common keypressed where user account is in (u1, u2, u3, u4) and keyboardkey = kb1 then it should return nothing. Thanks. A: Something like this should work: var commonKeysPressed = db.keys .Where(k => userKeyList.Contains(k.userkey) && k.keyboardkey == someKeyboardkey) .GroupBy(k => k.keypressed) .Where( g => g.Select( x=> x.userkey).Distinct().Count() == userCount) .Select(g => g.Key) .ToList(); This requires: * *keys to be the SQL table in question *userKeyList to be an array of user accounts, i.e. a string array - in your example (u1, u2, u3) *someKeyboardkey to be some keyboard key value, in your example kb1. *userCount the number of users in the userKeyList array (userKeyList.Length) A: This works for me: var users = new [] { "u1", "u2", "u3", }; var common = users .GroupJoin( values.Where(v => v.keyboardkey == "kb1"), u => u, v => v.userkey, (u, vs) => vs.Select(v => v.keypressed)) .Aggregate( (zs, z) => zs.Intersect(z)); I tested this in LINQPad on a MySQL database and it worked fine. A: Not a single line of LINQ, but this is the best I could come up with: private List<String> GetCommonKeys(List<a> input, string[] users, string[] keyboardkeys) { var result = input.Where(c => users.Contains(c.userkey) && keyboardkeys.Contains(c.keyboardkey)).GroupBy (c => c.userkey); var returnList = result.First().Select(c => c.keypressed); foreach (var ls in result) { returnList = returnList.Intersect(ls.Select(t => t.keypressed)); } return returnList.ToList(); } struct a { public String userkey; public String keyboardkey; public String keypressed; } Edit: as an extension: public static class myExtensions { public static IEnumerable<TSelectType> SelectCommon<TSourceType, TSelectType>(this IEnumerable<IGrouping<TSelectType, TSourceType>> source, Func<TSourceType, TSelectType> action) { var firstResult = source.FirstOrDefault(); if(firstResult == null) return new List<TSelectType>(); var returnCollection = firstResult.Select(action); foreach(var ls in source) returnCollection = returnCollection.Intersect(ls.Select(action)); return returnCollection; } } Used like this: var res = lst.Where(c => new[] {"u1", "u2", "u3"}.Contains(c.userkey) && c.keyboardkey == "kb1").GroupBy (c => c.userkey).SelectCommon(c => c.keypressed);
{ "language": "en", "url": "https://stackoverflow.com/questions/7590759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: android view and textview confusion in inflating and returning package com.test1; import android.app.Activity; import android.app.ExpandableListActivity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; public class Test1Activity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); c1 c1obj = new c1(); setContentView(c1obj.m1()); } public class c1 { public View m1() { LayoutInflater i = (LayoutInflater) Test1Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = i.inflate(R.layout.main, null); TextView tv = (TextView) v.findViewById(R.id.textView1); tv.setText("Hello world !!!"); return v; } } } if i try to return textview(tv) it gives me runtime error if i return view(v) it works fine can anyone tell me why is that. A: You observe a runtime error because Android Framework throws an IllegalStateException since you try to add a TextView view into your activity's views hierarchy. In other words you're trying to set new parent for the view (TextView) which already has a parent (some kind of layout). Android Framework doesn't allow to change the parent automatically and it throws an exception. Try to add following lines - seems this will help you: ViewGroup vg = (ViewGroup)tv.getParent(); vg.removeView(tv);
{ "language": "en", "url": "https://stackoverflow.com/questions/7590760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access SVN server from machine on work subnet via an SSH tunnel I'm attempting to access my work SVN server via an SSH tunnel to a separate machine. Something like this: (Local_Machine) -- SSH_Tunnel --> (Workstation) -- LAN --> (SVN_Server) I can currently tunnel into my workstation via ssh, but cannot access the svn server via the tunnel on my local machine. Is what I'm attempting to do possible, or do I need to also tunnel into the SVN_Server from the Workstation? Further information : Local machine is a Windows 7 box using putty to tunnel. Workstation is another Windows 7 box using winsshd. SVN_Server is a Windows Server 2008 box (No SSH access) A: The endpoint of a remote tunnel doesn't need to be on the same machine. So, you can set up a tunnel that goes from your local machine to the remote SVN server. This is how you might do that using the ssh command line: ssh -L 3690:svn_server:3690 workstation This connects to your SSH server on your workstation, and sets up a tunnel from local port 3690 to port 3690 on svn_server. If you're already going through a tunnel to get to your workstation, you can embed the above tunnel inside the tunnel you've already got.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET WebForms in an ASP.NET MVC 2 application Is it possible to call normal ASPX pages with their normal life-cycle in an ASP.NET MVC 2 application? What about web controls and ajax.net toolkit? Thank you! A: You don't need to do anything. Simply create your MVC application and add a new web forms page. Thats it. A: Yes. Deploying ASP.NET MVC on ASP.NET 2.0 Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications I recommend creating a WebForms project and using this NuGet package: AddMvc3ToWebForms
{ "language": "en", "url": "https://stackoverflow.com/questions/7590768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP on link click effects I have one question which is somewhat two-parted (though the parts go hand in hand). I've started picking up PHP, and I wanted to do two things when an image is clicked. I want the click to * *Increment a session variables, say $_SESSION['entry']. *Reload the current page (say index.php). How should I go about this? To be clear, I'm not asking for someone to code this for me, I'd just like to be pointed in the right direction because I'm not too sure what the best way would be. A: The way to do this would be to link the image to "itself" $_SERVER['PHP_SELF'] perhaps or just to /index.php, and check the session to see if that value is set, and if so increment it. <?php session_start(); if (isset($_SESSION['entry'])) { $_SESSION['entry']++; } else { $_SESSION['entry'] = 1; } // if entry is greater than some value in your DB, then set it back to 1 A: Well, anchor links "reload" the page if the href points to the same page. So, all you need to do is tell PHP you want to increment the session variable. You could use a GET variable to do this: <a href="index.php?increment=true">Increment the counter</a> And then in your index.php: if (isset($_GET['increment']) && $_GET['increment'] == 'true') { $_SESSION['counter']++; } This assumes you've already initialized the session variable counter at some point. You can check out the wonderful PHP docs to explain the functions used above if you aren't familiar with them. A: <a href="?incr=1"><img src=.../></a> <?php if($_GET['incr']) $_SESSION['entry']++; ?> this should give you the idea. A: * *Load page with image that has a link around it: "?imageClick=1" for instance *On image click the page is therefor automatically loaded *If $_GET[ 'imageClick' ] equals 1 increment the session variable *Redirect to same page without the imageClick variable If you are concerned that index.php?imageClick=1 may be remembered by the browser in it's history, and therefor can be used to reload without an actual image click: * *Load page with a form that has method POST and an input element of type image, named imageClick (acting as a submit button) with value 1 *On image button click the form is submitted to the same page *If $_POST[ 'imageClick_x' ] or `$_POST[ 'imageClick_y' ] is set and increment the session variable *Redirect to same page A: You could do an AJAX call to a PHP script that increments $_SESSION['entry'].
{ "language": "en", "url": "https://stackoverflow.com/questions/7590770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use includes with 3 models w ActiveRecord? Given the following model: Room (id, title, suggested) has_many :room_apps, :dependent => :destroy RoomApp (room_id, app_id, appable_id, appable_type) belongs_to :appable, :polymorphic => true has_many :colors, :as => :appable has_many :shirts, :as => :appable Colors (room_id) belongs_to :room belongs_to :room_app belongs_to :app What I want to do is get all the suggested rooms. In my controller I have: @suggested_rooms = Room.includes(:room_apps).find_all_by_suggested(true).first(5) Problem here is the includes is not working and the db is being hit several times: Processing by PagesController#splash as HTML Room Load (0.6ms) SELECT "rooms".* FROM "rooms" WHERE "rooms"."suggested" = 't' ORDER BY last_activity_at DESC RoomApp Load (0.6ms) SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND ("room_apps".room_id IN (5,4,3)) ORDER BY created_at DESC RoomApp Load (5.9ms) SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND "room_apps"."id" = 6 AND ("room_apps".room_id = 5) ORDER BY created_at DESC LIMIT 1 Color Load (0.4ms) SELECT "colors".* FROM "colors" WHERE "colors"."id" = 5 LIMIT 1 RoomApp Load (0.6ms) SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND "room_apps"."id" = 5 AND ("room_apps".room_id = 4) ORDER BY created_at DESC LIMIT 1 Color Load (0.4ms) SELECT "colors".* FROM "colors" WHERE "colors"."id" = 4 LIMIT 1 RoomApp Load (0.4ms) SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND "room_apps"."id" = 4 AND ("room_apps".room_id = 3) ORDER BY created_at DESC LIMIT 1 Color Load (0.3ms) SELECT "colors".* FROM "colors" WHERE "colors"."id" = 3 LIMIT 1 Is something setup incorrectly? I'd like to be able to get suggested rooms and use includes for room_apps with one hit versus currently where it's a hit for every room. Ideas? Thanks A: I think you'll either want to use the full Rails3 arel interface like so: @suggested_rooms = Room.includes(:room_apps).where(:suggested => true).limit(5) Or do this for Rails 2.3x: @suggested_rooms = Room.find_all_by_suggested(true, :include=>:room_apps).first(5) A: Did some digging around and I think I have an idea what's going on. include by default does not generate a single query. It generates N queries, where N is the number of models being included. ruby-1.9.2-p180 :014 > Room.where(:suggested => true).includes(:room_apps => :colors) Room Load (0.5ms) SELECT "rooms".* FROM "rooms" WHERE "rooms"."suggested" = 't' RoomApp Load (0.8ms) SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."room_id" IN (1) Color Load (0.5ms) SELECT "colors".* FROM "colors" WHERE "colors"."room_app_id" IN (1) One exception to this is if you have a where clause that references one of the model tables being included, in this case it will use a LEFT OUTER JOIN to add the where clause to that table. If you want to INNER JOIN a bunch of models AND include them, you have to use both joins and includes with the given models. joins alone will only do the INNER JOIN across the relations, includes will pull in the fields and setup the returned models with their relations intact. ruby-1.9.2-p180 :015 > Room.where(:suggested => true).joins(:room_apps => :colors) Room Load (0.8ms) SELECT "rooms".* FROM "rooms" INNER JOIN "room_apps" ON "room_apps"."room_id" = "rooms"."id" INNER JOIN "colors" ON "colors"."room_app_id" = "room_apps"."id" WHERE "rooms"."suggested" = 't' ruby-1.9.2-p180 :016 > Room.where(:suggested => true).joins(:room_apps => :colors).includes(:room_apps => :colors) SQL (0.6ms) SELECT "rooms"."id" AS t0_r0, "rooms"."suggested" AS t0_r1, "rooms"."created_at" AS t0_r2, "rooms"."updated_at" AS t0_r3, "room_apps"."id" AS t1_r0, "room_apps"."room_id" AS t1_r1, "room_apps"."created_at" AS t1_r2, "room_apps"."updated_at" AS t1_r3, "colors"."id" AS t2_r0, "colors"."room_id" AS t2_r1, "colors"."room_app_id" AS t2_r2, "colors"."created_at" AS t2_r3, "colors"."updated_at" AS t2_r4 FROM "rooms" INNER JOIN "room_apps" ON "room_apps"."room_id" = "rooms"."id" INNER JOIN "colors" ON "colors"."room_app_id" = "room_apps"."id" WHERE "rooms"."suggested" = 't' The big convoluted SELECT part in the last query is ARel making sure that the fields from all of the models are unique and able to be differentiated when they need to be mapped back to the actual models. Whether you use includes alone or includes with joins is a matter of how much data your bringing back, and how much speed difference there might be if you were not doing the INNER JOIN, causing a great deal of duplicate data to be returned. I would imagine that if 'rooms' had something like a dozen fields and 'colors' had 1 field, but there was 100 colors that mapped to a single room, instead of pulling back 113 fields in total (1 room * 13 + 100 colors * 1) you would end up with 1400 fields (13 + 1 * 100 colors). Not exactly a performance boost. Though the downside of using includes alone is that if you do have a large number of colors per room, the IN(ids) will be huge, bit of a double edged sword. Here's a quick test I did with various configurations using sqlite3 I setup two sets of rooms, one with :suggested => true, the other :suggested => false. The suggested rooms had a 1:1:2 ratio between rooms/room_apps/colors, the suggested false rooms were setup with a 1:1:10 ratio of the same, and there is a 10:1 ratio between suggested and not suggested. # 100/10 rooms # insert only 100 * 1/1/2: 8.1ms 10 * 1/1/10: 3.2ms # insert + joins 100 * 1/1/2: 6.2ms 10 * 1/1/10: 3.1ms # 1000/100 rooms # insert only 1000 * 1/1/2: 76.8ms 100 * 1/1/10: 19.8ms # insert + joins 1000 * 1/1/2: 54.5ms 100 * 1/1/10: 23.1ms The times are not relevant themselves, this is being run via IRB on a Ubuntu guest on a WinXP host on a crappy HDD. Given that you've got a limit(5) in there it probably isn't going to make a huge difference either way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Absolute positioned div with overflow auto causing child absolute div to be cut off I have a absolute positioned div with overflow auto. Inside this div is another absolute positioned div. My problem is that this child div gets cut off due to the overflow. I want it to escape the container div as it would if overflow was not set. I have tried setting z-indexes but it does not help. What can I do? HTML <div class="parent"> <div class="child"></div> </div> CSS .parent { position:absolute; z-index:0 overflow:auto; width:400px; height:400px; border:1px solid #000; } .child { poisiton:absolute; z-index:1 width:300px; height:450px; border:1px solid #f00; } A: See if you can rely on another method to clear your floats. Changing your CSS to overflow: visible is definitely a good solution. Your other solution is to take the div outside of its container so it doesn't get cut off, and put them both inside of a new container: <div class="container"> <div class="parent"> </div> <div class="child"> </div> </div> CSS: .container { /* apply positioning from .parent */ } .parent { position: absolute; top: 0; left: 0; } .child { /* apply positioning from .child */ } A: If you want some elements to not overflow the parent and some elements to not, you'd be better off placing the current child div outside of the current parent. Just make it an absolutely positioned peer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How does reassigning a disposable object variable work? In C# when reassigning a disposable object variable with a new object, how does it work in the memory? Will the memory space occupied by the old object simply be overwritten by the new object? Or do I still have to call Dispose() to release the resources it uses? DisposableThing thing; thing = new DisposableThing(); //....do stuff //thing.Dispose(); thing = new DisposableThing(); A: In this case you have one slot / reference and two instances of an IDisposable object. Both of these instances must be disposed indepedently. The compiler doesn't insert any magic for IDisposable. It will simply change the instance the reference points to A good pattern would be the following using (thing = new DisposableThing()) { // ... do stuff } thing = new DisposableThing(); Ideally the second use of thing should also be done within a using block A: It works the same as any other assignment: = does not care about IDisposable or do any magic. The object initially assigned to the variable will have to have Dispose invoked manually (or better yet, with using) as required. However, it may not always be correct to call Dispose at this point: who owns the object and controls the lifetime? Will the memory space occupied by the old object simply be overwritten by the new object? Does not apply. Variables "name" objects. An object is itself and a variable is a variable - not the object or "location in memory". (See Eric Lippert's comment bellow: the preceding is a high-level view of variables while Eric's comment reflects variables more precisely in C# implementation, spirit, and terminology.) Variables only affect object lifetimes insomuch as they can* keep an object from being reclaimed (and thus prevent the finalizer from [possibly eventually] running). However, variables do not control the objects semantic-lifetime -- an object may be Disposed even when not reclaimable -- or eliminate the need to invoke Dispose as required. Happy coding. When dealing with disposable objects that extend beyond simple scopes -- the objects may be assigned to many different variables during their lifetime! -- I find it best to define who "takes control" which I annotate in the documentation. If the object lifetime is nicely limited to a scope then using works well. *A local variable itself is not necessarily sufficient to keep an object strongly reachable as it is possible that the variable/assignment is aggressively optimized out if not used later from the same scope. This may plague objects like timers. A: It is possible, and common, for multiple references to the same IDisposable object to exist. There is nothing wrong with overwriting or destroying all but one of those references, provided that one reference will have Dispose called on it before it is destroyed. Note that the purpose of IDisposable.Dispose isn't actually to destroy an object, but rather to let an object which has previously asked other entities to do something on its behalf (e.g. reserve a GDI handle, grant exclusive use of a serial port, etc.), notify those entities that they no longer need to keep doing so. If nothing tells the outside entities that they no longer need to keep doing something on behalf of the IDisposable object, they'll keep doing it--even if the object they're doing it for no longer exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Loading locals onto stack for method call in IL generation? I'm trying to generate IL to mimic the following method MyMethod: public void DoSomething(object a, object b, string c, string d){...}; public virtual void MyMethod(object a, object b) { DoSomething(a, b, "hello", this.SomeInstanceString); } This is what I've got so far, but I'm unable to understand the proper way to load the 3rd and 4th arguments onto the stack to call DoSomething(a, b, "hello", this.SomeInstanceString)): MethodBuilder myMethod = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new[] { typeof(object), typeof(object) }); ILGenerator myMethodILGen = mbFromCustomObject.GetILGenerator(); myMethodILGen.Emit(OpCodes.Ldarg_0); myMethodILGen.Emit(OpCodes.Ldarg_1); // How do I load the string "hello" and the local instance // variable this.SomeInstanceString onto the stack? myMethodILGen.Emit(OpCodes.Call, GetMethodInfoForDoSomething()); myMethodILGen.Emit(OpCodes.Ret); So, how do I load the string "hello" and the local instance variable this.SomeInstanceString onto the stack to call DoSomething? A: Loading a string literal is fairly easy. myMethodILGen.Emit(OpCodes.Ldstr, "hello"); Loading a field from the object instance requires that you first load the object instance onto the stack and then use the Ldfld opcode. You should presumably have a FieldBuilder for your SomeInstanceString field already that you can use for this. FieldBuilder fieldBuilder = typeBuilder.DefineField( "SomeInstanceString", typeof(string), FieldAttributes.Public); myMethodILGen.Emit(OpCodes.Ldarg_0); myMethodILGen.Emit(OpCodes.Ldfld, fieldBuilder); Also, keep in mind that Ldarg_0 does not do what you think it does. Instance methods have an implicit argument that is in the zero slot which contains the instance that the method is currently operating within. That's why we're using Ldarg_0 to dereference the field, because presumably you want the instance that the method is in. This does not apply to static methods, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Key Presses in Java Swing Problem I have made a calculator using Java Swing, and it's mostly done but I was wondering how you could make it work so that when you press a key from 0 - 9 on the keyboard, it will perform the same function as manually pressing the JButton on the calculator. I tried using but1.setMnemonic(KeyEvent.VK_1); but I it didn't do anything when I pressed the 1 key. How can I make it so it will correctly activate said button when I press a keyboard key? Here is the code I am using, thanks for any help! import java.awt.Color; import java.awt.FlowLayout; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.Action; // For key presses import java.awt.event.KeyEvent; // key presses import java.awt.event.KeyListener; public class ui_calculator implements ActionListener { JFrame frame = new JFrame("Calculator"); // Creates the frame JPanel panel = new JPanel(new FlowLayout()); // Add FlowLayout with center alignment // Make new buttons, text areas JTextArea text = new JTextArea(1, 20); JButton but1 = new JButton("1"); JButton but2 = new JButton("2"); JButton but3 = new JButton("3"); JButton but4 = new JButton("4"); JButton but5 = new JButton("5"); JButton but6 = new JButton("6"); JButton but7 = new JButton("7"); JButton but8 = new JButton("8"); JButton but9 = new JButton("9"); JButton but0 = new JButton("0"); JButton butadd = new JButton("+"); JButton butsub = new JButton("-"); JButton butmul = new JButton("*"); JButton butdiv = new JButton("/"); JButton buteq = new JButton("="); JButton butclear = new JButton("C"); Double number1, number2, result; // Numbers double as precise as a float int addc = 0, subc = 0, mulc = 0, divc = 0; public void ui() { frame.setVisible(true); // Make frame visible frame.setSize(250, 200); // Calculator Size frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // What happens when frame closes (exits program when user closes frame. frame.add(panel); panel.add(text); // Adding number buttons panel.add(but1); panel.add(but2); panel.add(but3); panel.add(but4); panel.add(but5); panel.add(but6); panel.add(but7); panel.add(but8); panel.add(but9); panel.add(but0); // Adding action buttons panel.add(butadd); panel.add(butsub); panel.add(butmul); panel.add(butdiv); panel.add(buteq); panel.add(butclear); but1.addActionListener(this); but2.addActionListener(this); but3.addActionListener(this); but4.addActionListener(this); but5.addActionListener(this); but6.addActionListener(this); but7.addActionListener(this); but8.addActionListener(this); but9.addActionListener(this); but0.addActionListener(this); butadd.addActionListener(this); butsub.addActionListener(this); butmul.addActionListener(this); butdiv.addActionListener(this); buteq.addActionListener(this); butclear.addActionListener(this); //but1.setMnemonic(KeyEvent.VK_1); // Colored buttons (red) butadd.setForeground(Color.red); butsub.setForeground(Color.red); butmul.setForeground(Color.red); butdiv.setForeground(Color.red); buteq.setForeground(Color.red); butclear.setForeground(Color.red); // Colored buttons (blue) but1.setForeground(Color.blue); but2.setForeground(Color.blue); but3.setForeground(Color.blue); but4.setForeground(Color.blue); but5.setForeground(Color.blue); but6.setForeground(Color.blue); but7.setForeground(Color.blue); but8.setForeground(Color.blue); but9.setForeground(Color.blue); but0.setForeground(Color.blue); } @Override public void actionPerformed(ActionEvent e) { // Invokes when certain action occurs Object source = e.getSource(); // Object on which event occured if(source == butclear) // Reset all text { number1 = 0.0; number2 = 0.0; text.setText(""); } // Specific buttons trigger text if(source == but1) { text.append("1"); } /* if(KeyEvent.VK_1 = true) { text.append("1"); } */ if(source == but2) { text.append("2"); } if(source == but3) { text.append("3"); } if(source == but4) { text.append("4"); } if(source == but5) { text.append("5"); } if(source == but6) { text.append("6"); } if(source == but7) { text.append("7"); } if(source == but8) { text.append("8"); } if(source == but9) { text.append("9"); } if(source == but0) { text.append("0"); } if(source == butadd) // Addition actions { number1 = number_reader(); text.setText(""); addc = 1; subc = 0; mulc = 0; divc = 0; } if(source == butsub) // Subtraction actions { number1 = number_reader(); text.setText(""); addc = 0; subc = 1; mulc = 0; divc = 0; } if(source == butmul) // Multiplication actions { number1 = number_reader(); text.setText(""); addc = 0; subc = 0; mulc = 1; divc = 0; } if(source == butdiv) // Division actions { number1 = number_reader(); text.setText(""); addc = 0; subc = 0; mulc = 0; divc = 1; } if(source == buteq) // Equals actions { number2 = number_reader(); if(addc > 0) { result = number1 + number2; text.setText(Double.toString(result)); } if(subc > 0) { result = number1 - number2; text.setText(Double.toString(result)); } if(mulc > 0) { result = number1 * number2; text.setText(Double.toString(result)); } if(divc > 0) { result = number1 / number2; text.setText(Double.toString(result)); } } } public double number_reader() { Double num1; String s; s = text.getText(); num1 = Double.valueOf(s); return num1; } } A: The mnemonic will make the button press when used with a modifier (usually Alt or Ctrl), so pressing Alt+1 (or Ctrl+1) will work. To make the buttons correspond to the Keypad, you should have a look at InputMap and ActionMap. See http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Programmatically translating recurring calendar events? Does anyone know of a solution or strategy for parsing and translating recurring events in any given language? I've got some code that sort of works, but I'm having trouble even wrapping my brain around a solid approach. A: By "parse" you mean free-form text in any language? That is nearly impossible to do. The problem is, you can describe that in many ways (even in English, right?). Put inflection in the picture and... You would need some kind of cognitive system, that is you would need to employ machine learning. Theoretically speaking you'll be interested in only few ontologies but getting translated versions of them might not be too easy (I have seen a presentation of such web service but I believe it was more academic work and the service is not publicly available). Taking these facts into account, I can suggest (unless you really must parse free form text, i.e. sent via email or something) that you create a form where people can actually choose recurring frequency and options (i.e. ignore holidays, etc.). It is still uneasy task but... A: There are various libraries which can parse RRULE's in several languages. RRULE Libraries C - libical Python - python-dateutil Ruby - ice_cube Javascript - google-caja or rrule Java - iCal4j PHP - when As for strategies, take a look at the standard here which provides architectural pseudo-code for abstracting rrule data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I query how many likes a Facebook post has? I developed a custom app to upload videos that will be used in a contest, the video with the most likes wins. Is there a way to keep track of these likes without further user intervention? I mean, the user uploads the video now, with a "like counter" thing, and the day the contest ends, I just query the most liked (o three most liked) video(s). Is there a way to do this? A: Do you have the ids of the posts? To get the number of likes for a Facebook post, you can do: https://graph.facebook.com/[post_id]/likes (From https://developers.facebook.com/docs/reference/api/post/) Note that you must supply an access token for a user who has access to this post, or the posts must be public. A: You can get the likes for all the videos with FQL, then get the counts in your app code: SELECT object_id FROM like WHERE object_id IN (YOUR, VIDEO, IDS) Or if you have the post_ids instead of the video object_ids: SELECT post_id FROM like WHERE post_id IN (YOUR, POST, IDS)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange output in JSON that I make in my PHP after an AJAX call I am a bit new at this and totally messing something up. I have a PHP result set through which I iterate like this: $rows = array(); while($r = mysql_fetch_assoc($result)) { $rows[] = $r; } echo json_encode($rows); and then I output it like this in jQuery code: success: function(json) { $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); // Here can update the right side of the screen with the newly entered information alert (json); var ob = $.parseJSON(json); alert (ob.creator_member_id); alert (ob.problem_title); alert (ob.problem_description); alert (ob.problem_date); } But there is an error on the var ob = $.parseJSON(json); line it seems. My JS console gives this error: Uncaught TypeError: Object function (D,E){return new n.fn.init(D,E)} has no method 'parseJSON' What can this mean and how can I fix this? Thanks!! A: If you are getting JSON results via jQuery ajax call you don't need parsing resultant json - jQuery does it for you. Just specify the dataType: 'json' [http://api.jquery.com/jQuery.ajax/], and your success handler will have the already parsed object. If you want parsing JSON anywhay, try adding json2.js to your project. You'll have to call JSON.parse(json) then. A: I'm new to Jquery, too. eval is just plain JS and it suits my needs. I don't see any evil with this code but of course it's possible to inject bad code into a response. Probably it's not very good practise. It can be exploited for a reverse shell for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding C# WPF controls to a dictionary Hi :) I’m just learning C# and WPF and I need to write a tool that: * *Loads a data file (string Key, int Value) *Binds the data to a WPF UI for edits *Saves a new data file My thought was a dictionary would be best. The data is only loaded once from file, and changes are only made with the WPF controls. I’ve tried many things but I still keep hitting road blocks when I bind data to the controls. I’ve been working with a simplified version of the tool – below. The data binds to the WPF control – but there is no change event to update the dictionary. I haven’t found a good example to follow. Could someone explain how to get the dictionary to update? And is the strategy the right one? - using a dictionary -using DataContext. If you'd like to see the full project and UI - there is a link at the bottom. I've been working many-many days...with progress but I'm way too slow ;) Cheers Danny MainWindow.xaml <Window x:Class="configGen.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="200" Width="150"> <StackPanel Margin="20" Width="80"> <TextBox Text="{Binding [item1]}" /> <TextBlock Text="{Binding [item1]}" /> <TextBox Text="{Binding [item2]}" /> <TextBlock Text="{Binding [item2]}" /> <TextBox Text="{Binding [item3]}" /> <TextBlock Text="{Binding [item3]}" /> <Slider Value="{Binding [item4]}" Minimum="0" Maximum="256" /> <TextBlock Text="{Binding [item4]}" /> </StackPanel> MainWindow.xaml.cs namespace configGen { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); dataClass record = new dataClass(); DataContext = record.generate(); } } public class dataClass { public Dictionary<string, int> generate() { Dictionary<string, int> _data = new Dictionary<string, int>(); _data.Add("item1", 100); _data.Add("item2", 120); _data.Add("item3", 140); _data.Add("item4", 160); return _data; } } } Link to full project... http://www.baytower.ca/btsRV7config.zip Thanks for all the great feedback everyone!! I will set back to work :) A: Instead of using a Dictionary as your DataContext I'd create a custom object like MainViewModel. Give it properties that correspond to item1, item2, etc, except give them appropriate names. Then use <TextBox Text="{Binding MyPropertyName}" />. To handle updates, you can either set your DataContext to a new MainViewModel object or you can set up your class to broadcast property changes. You can do that either through INotifyPropertyChanged on the class or with dependency properties. At least that's what it seems like you're trying to accomplish. If you're going for displaying an arbitrary number of controls you'd need something different. A: A dictionary is definitly not a convenient way to do a two way data binding in WPF. It seems an ObservableCollection is more suited to your requirements. Something like: public class ItemsList : ObservableCollection<Item> { public ItemsList() : base() { Add(new Item("item 1", 100)); Add(new Item("item 2", 120)); Add(new Item("item 3", 140)); Add(new Item("item 4", 160)); } } Item is a simple class with a name and a value properties. I have ommitted it here because it is self explanatory. The advantage here is that you can bind to a dynamic number of items not only the ones declared imperatively. Once you bind you datacontext to it, you get the automatic property notification for two way databinding. Your XAML will have to change to accomodate binding to a collection of course. Maybe an ItemsControl that takes that collection as its ItemsSource. A: Here is an example of how I would do it. Main Class (Code Behind) /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { private List<MyObject> _myObjects; public List<MyObject> MyObjects { get { return _myObjects; } set { _myObjects = value; if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("MyObjects")); } } } public MainWindow() { MyObjects = new List<MyObject>(); // Add 20 records for sample data for (int i = 0; i < 20; i++) { MyObject o = new MyObject(); o.Label = string.Format("Key{0}", i); o.MyValue = string.Format("Value{0}", i); MyObjects.Add(o); } InitializeComponent(); DataContext = this; } public event PropertyChangedEventHandler PropertyChanged; } Secondary Class public class MyObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _label; public string Label { get { return _label; } set { _label = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Label")); } } } private string _myValue; public string MyValue { get { return _myValue; } set { _myValue = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("MyValue")); } } } } XAML File <Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <DataTemplate x:Key="listboxstyle"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Path=Label}" /> <TextBox Grid.Column="1" Text="{Binding Path=MyValue}" /> </Grid> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding Path=MyObjects}" ItemTemplate="{StaticResource listboxstyle}" /> </Grid> </Window> A: I've tried tsell's example, using his class in a list. The list is just a convenient way to generate and manage a fixed number of elements. The Item1 WPF control binds to the Item1 object and its value. The object is found by its index number. The binding and dataContext in this case is simple enough for me to use (as a beginner). It works, but I'm not sure it's exactly an elegant way to do it. public MainWindow() { MyObjects = new List<MyObject>(); MyObject item1 = new MyObject(); item1.MyValue = string.Format("100"); MyObjects.Add(item1); MyObject item2 = new MyObject(); item2.MyValue = string.Format("120"); MyObjects.Add(item2); MyObject item3 = new MyObject(); item3.MyValue = string.Format("140"); MyObjects.Add(item3); MyObject item4 = new MyObject(); item4.MyValue = string.Format("160"); MyObjects.Add(item4); InitializeComponent(); DataContext = this; } xaml <Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel Margin="20" Width="80"> <TextBox Text="{Binding MyObjects[0].MyValue}" /> <TextBlock Text="{Binding MyObjects[0].MyValue}" /> <TextBox Text="{Binding MyObjects[1].MyValue}" /> <TextBlock Text="{Binding MyObjects[1].MyValue}" /> <TextBox Text="{Binding MyObjects[2].MyValue}" /> <TextBlock Text="{Binding MyObjects[2].MyValue}" /> <Slider Value="{Binding MyObjects[3].MyValue}" Minimum="0" Maximum="256" /> <TextBlock Text="{Binding MyObjects[3].MyValue}" /> </StackPanel> </Window> BTW, I will change to int for MyValues..they are all int numbers. For now it is a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to resolve "String was not recognized as a valid DateTime"? I'm converting a text field into date time and inserting into db. However, when the text field is null, it throws an exception that String was not recognized as a valid DateTime This is what I did: nvpt4Entities db = new nvpt4Entities(); ClassInfo order = new ClassInfo { ClassID = classID.Text, ClassName = className.SelectedItem.Text, ClassTime = classTime1.Text, ClassDate = DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null), ClassDay = classDay.SelectedValue, ClassMonth = classMonth.SelectedValue, ClassLocation = classLocation.SelectedItem.Text, ClassNotes= classNotes.Text, ClassInstructor = classInstructor.SelectedValue, ClassInstructor1 = classInstructor2.SelectedValue, ClassInstructor2 = classInstructor3.SelectedValue, MultiDate2 = DateTime.ParseExact(multidate2.Text, "MM/dd/yyyy", null), MultiDate3 = DateTime.ParseExact(multidate3.Text, "MM/dd/yyyy", null), MultiDate4 = DateTime.ParseExact(multidate4.Text, "MM/dd/yyyy", null), MultiDate5 = DateTime.ParseExact(multidate5.Text, "MM/dd/yyyy", null), ClassStrength = Convert.ToInt16(classStrength.Text), ClassProvider = classProvider.SelectedItem.Text, LocationID = Convert.ToInt16(classLocation.SelectedValue), ClassCID = Convert.ToInt16(className.SelectedValue), ProviderID = Convert.ToInt16(classProvider.SelectedValue) }; So, I want to know how to handle null strings to be converted to datetime while inserting into db A: This has nothing to do with the database. Pay attention to the error message and where the exception originates. The only thing of relevance is where the error comes from: DateTime.ParseExact(__, "MM/dd/yyyy", null) Replace this with an appropriate method call that handles the "empty/invalid string" case, however is appropriate, or use validation to ensure this step is never reached; DateTime? should be used for nullable columns, a sentinel can be used otherwise. (See Mark Byers' answer for what the contents of said method may look like.) Happy coding. A: If your fields are nullable DateTimes you can use this: ClassDate = string.IsNullOrEmpty(classDate1.Text) ? (DateTime?)null : DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null),
{ "language": "en", "url": "https://stackoverflow.com/questions/7590799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a DataVisualization.Charting Chart to show before points are added? How may I get a DataVisualization.Charting Chart to show its axes and gridlines before points are added? Currently the chart area is blank even if axes scale limits are set manually, and I can see no good reason for this. A: Set the Axis.Enabled properties to 'AxisEnabled.True' instead of 'AxisEnabled.Auto' chartArea.AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True; chartArea.AxisY.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True;
{ "language": "en", "url": "https://stackoverflow.com/questions/7590804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MongoDB Geospatial Haystack Indexing How do you create a Geospatial Haystack Index using the 10gen C# Driver for MongoDB JS Example: db.foo.ensureIndex({ pos : "geoHaystack", type : 1 }, { bucketSize : 1 }) C# Example that does not work: BsonDocument keys = new BsonDocument(); keys.Add("pos", "geoHaystack"); keys.Add("type", "1"); IMongoIndexKeys indexKeys = new IndexKeysDocument(keys); IndexOptionsDocument indexOptions = new IndexOptionsDocument("bucketSize", new BsonInt32(1)); collection.CreateIndex(indexKeys, indexOptions); Gives this error: MongoDB.Driver.MongoSafeModeException : Safemode detected an error 'can only have 1 index plugin / bad index key pattern'. (Response was { "err" : "can only have 1 index plugin / bad index key pattern", "code" : 13007, "n" : 0, "connectionId" : 6, "ok" : 1.0 }). So if I remove the 'type' key, like this: BsonDocument keys = new BsonDocument(); keys.Add("pos", "geoHaystack"); IMongoIndexKeys indexKeys = new IndexKeysDocument(keys); IndexOptionsDocument indexOptions = new IndexOptionsDocument("bucketSize", new BsonInt32(1)); collection.CreateIndex(indexKeys, indexOptions); I get this error: MongoDB.Driver.MongoSafeModeException : Safemode detected an error 'no other fields specified'. (Response was { "err" : "no other fields specified", "code" : 13317, "n" : 0, "connectionId" : 7, "ok" : 1.0 }). A: I got it working with: IMongoIndexKeys keys = new IndexKeysDocument { { "Position", "geoHaystack" }, { "type", 1 } }; IMongoIndexOptions options = new IndexOptionsDocument { { "bucketSize", 1 } }; collection.EnsureIndex(keys, options); The problem I had was to do with data already loaded in the collection. You should then be able to query with: var command = new CommandDocument { { "geoSearch", "foo" }, { "near", new BsonArray { 33, 33 } }, { "maxDistance", 6 }, { "search", new BsonDocument { { "type", "restaurant" } } }, { "limit", 30 } }; database.RunCommand(command); A: Actually the problem was index direction was specified as a string value keys.Add("type", "1"); Change it to integer keys.Add("type", 1); This will work as expected
{ "language": "en", "url": "https://stackoverflow.com/questions/7590807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: specify ouput file name flash builder 4 This should be easy, but I can't find it. I want my .html and .swf files to be named something differently than the project name. Project name is foo, I want the outputs to be bar.html and bar.swf. Thanks. A: Flextras was on the right track. You can't change the output filename (even using the "-output" compiler param) if you're compiling in Flash Builder. Not sure why. The solution that has worked for me has been to use a bit of indirection: * *use mxmlc to compile to ApplicationClass.swf *command line copy ApplicationClass.swf to YourCustomSwf.swf *command line run YourCustomSwf.swf You can do this with either a simple (platform-dependent) build script, or with Flex Ant Tasks. I highly recommend the latter; it's easy to setup, integrates well with Flash Builder, and (as a mostly platform-independent solution) will work in a multi-team multi-OS environment. Here are the above steps as ant tasks that will perform the magic for you: <project name="sample-build" default="run-your-swf"> <property file="${basedir}/your.properties.file"/> <target name="compile-your-app"> <mxmlc file="${SOURCE_DIR}/ApplicationFile.mxml" compiler.debug="${IS_DEBUG}" incremental="true" failonerror="true"> <load-config filename="${DEFAULT_FLEX_CONFIG}"/> <define name="CONFIG::DEBUG" value="${IS_DEBUG}"/> <define name="CONFIG::FLASH_AUTHORING" value="${IS_FLASH_AUTHORING}"/> <define name="CONFIG::IS_RELEASE" value="${IS_RELEASE}"/> </mxmlc> </target> <target name="rename-your-swf" depends="compile-your-app"> <copy file="${OUTPUT_DIR}/feed/FeedComponent.swf" tofile="${OUTPUT_DIR}/YourNewSexyFilename.swf"/> </target> <target name="run-your-swf" depends="rename-your-swf"> <exec executable="${STANDALONE_FLASH_DEBUG_PLAYER}"> <arg line="${OUTPUT_DIR}/YourNewSexyFilename.swf"/> </exec> </target> </project> you need only define all ${VARIABLES} I've listed in "your.properties.file", like so: FLASH_PLAYER_DEBUG=/Applications/Adobe Flash CS5/Players/Debug/Flash Player Debugger.app/Contents/MacOS/Flash Player Debugger IS_DEBUG=true (et cetera) And anyway - what's in a name? A program by any other name, would be as awesome... B-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Distributed Cache that supports incr I'm looking for a distributed key/value store that supports a balanced load of reads and writes. Necessary Features: * *Get, Set, Incr *Disk backed *Blazingly fast (i.e. eventual consistency is OK) *High availability (i.e. rebalancing load upon node failures) Nice to have Features: * *Overflow to disk (Assuming the load has nice locality properties) *Platform-agnostic (e.g. java based) Because a lot of the distributed caching solutions support get/set but not incr, it looks like the only option that fits the requirements is terracotta. (Though Redis has a cluster model in their unstable branch). Any Suggestions? A: I can speak namely for redis. Necessary Features: * *Yes, support also for other advanced data structures like hashed, (ordered) sets and lists *Yes, by default redis saves snapshot of the data set on disk. *Yes. *Rebalancing load upon node failures is rather a partition tolerance than high availability in terms of CAP theorem. Redis support replication and cluster is in development. Nice to have Features: * *Read the article about virtual memory. *Most of the POSIX systems. Maybe your can try to take a look also on membase or couchbase server. A: http://www.basho.com/ Riak will do this for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Codeigniter - Set a variable in in view Can I set a variable in view file? for exemple: I have a controller: welcome.php Its load: $this->load->view('header'); $this->load->view('main'); $this->load->view('footer'); I need set a variable on file main.php and get on footer.php Its possible? A: You can pass a variable from one view to another just like you would from a controller to a view. You just have to load the view file that sets that variable before the view that uses that variable: $this->load->view('main'); //load before $this->load->view('footer'); //load after Inside of main.php do $this->load->vars(array('your_variable'=>'it's value')); and you will be able to call it in the footer like you would any other variable. The only requirement is that main.php be loaded before footer.php. A: It is not possible to set a variable in a view file and access it from another. There is no reason you should be setting variables in your view files anyway. The controller should be handling all of your application logic so you should be setting the variable there. I would recommend reading through the user guide or looking at some articles to get a better grasp of MVC principles. To access the same variable in multiple views, pass it to each view you load. // Set your variable $data['variable'] = 'value'; // Pass variable to multiple views $this->load->view('main', $data); $this->load->view('footer', $data); A: You can pass both array or object to your view, for example: $data = new StdClass; $data->title = "The Title"; $data->content = "The Content"; $this->load->view('main', $data); or $data = new SomeClass; $this->load->view('main', $data); Also, in each view you are able to pass a different data: $data1 = array("key" => "val"); $data2 = $this->some_class->some_method($params); $data3 = $this->another_class->another_method($params); $this->load->view('navigation', $data1); $this->load->view('main', $data2); $this->load->view('footer', $data3); A: Yes you can, to pass variable from controller you can type the variable data after the name of view, this is the example : $data["vehicle"] = $vehicle; $this->load->view('header',$data); then in your view just call the name of variable : <td> <?php echo $vehicle ?> </td> Hope it can help
{ "language": "en", "url": "https://stackoverflow.com/questions/7590827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Help with XML response from PHP I am new to PHP, and I am using it to POST data from an iPhone. I have written a basic code to get data from the iPhone, post it to the php script on my server, and then using PHP, send that data to another webserver. However, the webserver is returning a response in XML, and since I am a newbie to PHP, I need help with it. My code to send data: <?php $ch = curl_init("http://api.online-convert.com/queue-insert"); $count = $_POST['count']; $request["queue"] = file_get_contents($count); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); $response = curl_exec($ch); curl_close ($ch); echo $response; ?> I know I need to parse the XML response, but I have no idea how to do that. The XML response would be something like this: <?xml version="1.0" encoding="utf-8"?> <queue-answer> <status> <code>0</code> <message>Successfully inserted job into queue.</message> </status> <params> <downloadUrl>http://www.online-convert.com/result/07d6c1491bb5929acd71c531122d2906</downloadUrl> <hash>07d6c1491bb5929acd71c531122d2906</hash> </params> </queue-answer> A: You're probably looking for SimpleXML or DOMDocument. SimpleXML To load data from a string into an object: simplexml_load_string(). DOMDocument To create one from a string: DOMDocument->loadXML(). A: Read about SimpleXML: http://php.net/manual/en/book.simplexml.php A: Google is your friend! The built-in PHP XML Parser is your best bet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS table rounded corners and image modification I found a cool css "tooltip" script that works perfectly for my site, but it's been made to work when someone hovers over an href. I have very limited CSS skills, especially with positioning. So, this may help me out, depending on how I can explain what I need to do. Below is the and tag , that currently works when you hover your mouse. <style type="text/css"> .tooltip { border-bottom: 1px dotted #000000; color: #000000; outline: none; cursor: help; text-decoration: none; position: relative; } .tooltip span { margin-left: -999em; position: absolute; } .tooltip:hover span { border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); font-family: Calibri, Tahoma, Geneva, sans-serif; position: absolute; left: 1em; top: 2em; z-index: 99; margin-left: 0; width: 250px; } .tooltip:hover img { border: 0; margin: -10px 0 0 -55px; float: left; position: absolute; } .tooltip:hover em { font-family: Candara, Tahoma, Geneva, sans-serif; font-size: 1.2em; font-weight: bold; display: block; padding: 0.2em 0 0.6em 0; } .custom { padding: 0.5em 0.8em 0.8em 2em; } * html a:hover { background: transparent; } .warning { background: #FFFFAA; border: 1px solid #FFAD33; } </style> <table style="width:100%;"> <tr> <td> <a class="tooltip" href="#">Warning<span class="custom warning"> <img src="/images/tooltip/warning.png" alt="Warning" height="48" width="48" /> <em>Warning</em>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua!</span> </a> </td> </tr> </table> You'll see I have an image too. It's a simple yellow exclamation hazard sign. But it settles nicely to the left of the tooltip box. I'm now trying to use this same tooltip (rounded edges and all), without the hover. In other words, I liked it so much I want to place it on my web page, maybe in the header, on the right side, and have it as a static thing. After playing with the styles, I have basically come to the conclusion I need help with positioning. You'll see .tooltip span { margin-left: -999em; position: absolute; } This has been a primary problem with me. I figured if I took out the margin-left it would simply show the tooltip, without needing the :hover to display. Alas, it eludes me! How can I simply "delete" the , and just show the tooltip, as is, without needing the hover? A: Edit I felt like being nice, and i'm bored. So here it is again with fixed top right positioning. I also changed the class names (tooltip just seems like it will probably be used for something else) Fixed Positioning Ok, so I have stripped out everything you don't need (from a glance) See Here HTML <div class="tooltip" href="#"><span class="custom warning"> <img src="/images/tooltip/warning.png" alt="Warning" height="48" width="48" /> <em>Warning</em>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua!</span> </div> CSS .tooltip { cursor: help; position: relative; } .tooltip span { border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); font-family: Calibri, Tahoma, Geneva, sans-serif; position: absolute; left: 1em; top: 2em; z-index: 99; margin-left: 0; width: 250px; } .tooltip img { border: 0; margin: -10px 0 0 -55px; float: left; position: absolute; } .tooltip em { font-family: Candara, Tahoma, Geneva, sans-serif; font-size: 1.2em; font-weight: bold; display: block; padding: 0.2em 0 0.6em 0; } .custom { padding: 0.5em 0.8em 0.8em 2em; } .warning { background: #FFFFAA; border: 1px solid #FFAD33; } A: Simply remove the entire ".tooltip span" rule. What it does, is it puts the content outside of the page (-999em is faaaaaar away from within the page), and when you hover over it, it brings it back in. So, simply remove that CSS rule completetely and it should display fine. It did when I tried it in jsfiddle anyways. Edit: remove the ":hover" from your ".tooltip:hover span" rule as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find EOF in a string in java? I am working in school project. In that what they told is, I will be given a String which contains an actual program like.... import java.io.*\npublic class A{\n...........EOF And My job is to find particular regular expressions in that String(Program). Now My question is.. void myFunc(String s) { while(s.charAt(i) != EOF) /*needed replacement for EOF*/ { // Actual Code } } In the above code, how to find whether EOF is reached in a string? A: There is no EOF character in a string. You just need to iterate over the characters in the string: for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); //Process char } A: It's unlikely that you need this - you probably just need to read till the end of the string, and since it's a representation of a file's contents, your teacher referred to it as EOF. However... There is a character called EOF. It's also called control-Z, because that's how you type it. If you want to include it in a string, you have to type it as "\u001a" as in: String iHaveAnEof = "file ends here\u001a"; If you really need this, your teacher is probably older than me, and I'm probably old enough to be your grandfather ;-) A: BufferedReader rd=new BufferedReader(new InputStreamReader(new FileInputStream("Input.txt"),"UTF-8")); char ch; int r; while(true) { r=rd.read(); //Reading a character in integer format if(r==-1) //Checking for the End of File break; else { ch=(char)r; //Converting to char format System.out.println(ch); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jQuery selector problem with IE but works in ff I don't get why this code would work in FF and not IE. Can someone shed some light on this? The $(".ui-tabs-nav li a") seems to be the problem. In IE this.text is undefined. http://jsfiddle.net/4Y2dU/25/ A: this by itself is not a jQuery object. $(this).text(); is probably what you're looking for. After viewing your link I think you may be after something else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: svcutil ignores out paramter of async WCF call I have a service WCF interface: [ServiceContract(Namespace = "net.pipe://QFX_DLL/TradingService")] public interface IGenericTradingInterface { [OperationContract] void GetServerInformation(out ServerAttributes attributes); } The host for this is up and running correct. I create the client proxy object with svcutil as follows: svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config net.pipe://localhost/QFX_DLL/mex /async /tcv:Version35 The generated proxy for the async call looks like this: public void GetServerInformationAsync() { this.GetServerInformationAsync(null); } As you see, the out parameter attributes is completely missing! The non-async methods look fine. With this declaration of GetServerInformationAsync I can't get the result back. What's going on here? A: The out parameter (and any results) will be in the EventArgs class which is passed to the event which is fired when GetServerInformation completes (likely GetServerInformationCompleted). The property name will be either Result (which is likely the case in an operation returning only 1 value) or the parameter name (attributes).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java - KeyListener not working This has been making me want to tear out my hair all day. I'm trying to make it so when I press the right-arrow key, my speed will go to 10. I know that my methods that make my sprite move work, because if I set a value beforehand, it moves across the screen. It's the KeyListener that isn't doing anything: import java.awt.Image; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; public class Sprite implements KeyListener{ public Image player = Toolkit.getDefaultToolkit().getImage("player.png"); int x, y, dx, dy; public void doInit(){ JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setSize(600, 400); window.setLocationRelativeTo(null); window.getContentPane().add(new ImageDraw()); window.setVisible(true); window.setIgnoreRepaint(true); window.createBufferStrategy(2); window.getContentPane().addKeyListener(this); } public Image getSpriteHandle(){ return player; } public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == KeyEvent.VK_RIGHT){ dx = 10; } } //end keyPressed public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == KeyEvent.VK_RIGHT){ dx = 0; } } public void keyTyped(KeyEvent arg0) { } public int moveX(){ return dx; } } //end class Please help me! A: It's the KeyListener that isn't doing anything You should NOT be using a KeyListener. Swing was designed to be used with Key Bindings. You can map an Action to a KeyStroke even when a component doesn't have focus.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting the AVAssetReader's Sample Data I'm trying to get the PCM data from an MP3. I'm using AVAssetReaderOutput and it seems to reading the data fine. while(true) { nextBuffer = [assetReaderOutput copyNextSampleBuffer]; if(nextBuffer) { countsample = CMSampleBufferGetNumSamples(nextBuffer); NSLog(@"%i", countsample); } } I noticed that if I add up countsample, it equates to the number of seconds in the song (assuming 44100hz sample rate). For this reason, I'm sure the reading is being handled perfectly. What I'd like to do, however, is perform various DSP filters on this data but I need to do it on the sample information itself. How can I access the sample data? Also, I noticed that the CMSampleBufferGetNumSamples always returned 8192 except at the end of the song. Is there a way to increase/decrease this read rate? Thank you A: Append the data to a NSMutableData object. NSMutabelData *samples = [NSMutabelData data]; while(countsample) { nextBuffer = [assetReaderOutput copyNextSampleBuffer]; if(nextBuffer) { countsample = CMSampleBufferGetNumSamples(nextBuffer); [samples appendBytes:nextBuffer length:countsample]; } } countsample and nextBuffer are assumed to already exist in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I canot add Mobile SDK (Sun Wireless Toolkit) to IntelliJ IDEA I have IntelliJ IDEA 10.3 Community Edition installed along with JDK 1.6 which has been working fine for Android development. Now that I am trying to develop J2ME applications, I installed Sun WTK 3.0, but I am unable to add it to IDEA since there is no "Add mobile SDK" option in Project Structure dialog. A: Java ME plug-in is not available in the Community Edition. It is supposed to be available from Settings | Plugins, but for some reason it was not published there. The solution would be to download and Ultimate Edition and copy IDEA_UE/plugins/j2meplugin into IDEA_CE/plugins. There is an open issue for this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do images download fully before they are re sized by html or css code? Basically exactly what the question asks. Do images on a website download the full file before re sizing them. I have a bunch of pictures and I use html to resize the images down to thumbnails to easily display on the page. However, these images take way to long to load while they are only 100px x 100px big. My only explanation is that it is downloading the entire file before re sizing. A: Yes. The full image is downloaded. If the source url is 1000x1000 and you size it on the screen to 100x100, it still has to load the entire image. You should store the thumbnail at 100x100 and the full size at 1000x1000 and reference each when appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get max of two entries query Query: select machinename, StatusCode, size from machine where MachineID In( '33','22') and StatusCode = 166 ORDER BY size DESC Result: machinename StatusCode size ----------- ---------- ---- test1 166 50 test1 166 25 test2 166 75 test2 166 48 Requirement: I need to display only one entry for each machine. I have to do this by taking the max size value between the two entries as shown above. like for test1 i have two sizes 50 and 25 I have to show the row which has 50 and ignore row which has 25. Thanks Desired Result: machinename StatusCode size ----------- ---------- ---- test1 166 50 test2 166 75 A: This will work, but you won't be able to order by starttime select machinename, StatusCode, max(size) as size from machine where MachineID In( '33','22') and StatusCode = 166 group by machinename, StatusCode order by max(size) DESC A: If you wanted to order by StartTime you would have to use ROW_NUMBER so that you could select the starttime field: SELECT machinename, StatusCode, size FROM ( SELECT machinename, StatusCode, StartTime size, ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn FROM machine WHERE MachineID IN ('33','22') AND StatusCode = 166 ) T1 WHERE rn = 1 ORDER BY StartTime DESC But if you want to order by size, it's easier: SELECT machinename, StatusCode, MAX(size) AS size FROM machine WHERE MachineID IN ('33','22') AND StatusCode = 166 GROUP BY MachineID ORDER BY MAX(size) DESC A: Use a windowing function to generate ids to partition on your key and then order by largest to smallest. This will generate 1-N for each partition where 1 will correspond to the largest value from the ORDER BY. We then filter for the largest one. ; WITH MACHINES AS ( select machinename, StatusCode, size , ROW_NUMBER() OVER (PARTITION BY machinename ORDER BY size DESC) AS RN from machine where MachineID In( '33','22') and StatusCode = 166 ) SELECT select machinename, StatusCode, size FROM MACHINES M WHERE M.rn = 1; A: select machinename, StatusCode, size from machine a where MachineID In( '33','22') and StatusCode = 166 and size = (select max(size) from machine b where MachineID In( '33','22') and StatusCode = 166 and a.machinename = b.machinename) ORDER BY StartTime DESC HTH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AJAX returns unusual status codes So I've finally gotten around to trying AJAX again (rather than hidden iframes), and I now remember why I hated AJAX so much in the first place. It's a simple script that queries the server for the number of private messages the user has received. The server responds with a single number, and the script updates the indicator and sets a timeout for five seconds to query again. On rare occasion (usually when I go AFK for a while), I start getting the most bizarre HTTP status codes. On Chrome: "AJAX request failed to retrieve /ajax/network.php, HTTP status 0" On IE: "AJAX request failed to retrieve /ajax/network.php, HTTP status 12029" Neither of these codes are valid. What's going on here, and how can I stop it from happening? A: That is an annoying aspect of AJAX. I find it's best to simply treat all non-200 statuses as an error. Really, you're not going to show your users any specific error messages relating to the actual result ("A problem has occurred"), so I'd simply not worry overly about inconsistent error conditions. jQuery normalizes some of the AJAX behavior, so you may also want to look into using that. By the way, error 0 in Chrome and 12029 in IE indicate connection problems; since that has nothing to do with HTTP, that's why invalid codes are shown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Custom validation error messages in Kohana 3.0 I'm attempting to load custom error messages to use when validating my 'sign up' form. User model: https://github.com/ashleyconnor/Egotist/blob/master/classes/model/user.php Account Controller: https://github.com/ashleyconnor/Egotist/blob/master/classes/controller/user/account.php Sign Up View: https://github.com/ashleyconnor/Egotist/blob/master/views/account/signup.php I then placed user.php in /messages/models/user.php but my new error messages are not being displayed in the form. <?php defined('SYSPATH') or die('No direct script access.'); return array ( 'username' => array ( 'not_empty' => 'your message', 'max_length' => 'your message', 'alpha_dash' => 'your message', 'default' => 'default message' ), ); ?> https://github.com/ashleyconnor/Egotist/blob/master/messages/models/user.php So submitting an empty form gives the following error messages: * *Username must not be empty *Email Address must not be empty *Password must not be empty Which are the default ones. A: From Kohana Validation class, errors method source code: * Returns the error messages. If no file is specified, the error message * will be the name of the rule that failed. When a file is specified, the * message will be loaded from "field/rule", or if no rule-specific message * exists, "field/default" will be used. If neither is set, the returned * message will be "file/field/rule". * * By default all messages are translated using the default language. * A string can be used as the second parameter to specified the language * that the message was written in. * * // Get errors from messages/forms/login.php * $errors = $Validation->errors('forms/login'); Try using $errors = $post->errors('models/user') instead $errors = $post->errors('signup')
{ "language": "en", "url": "https://stackoverflow.com/questions/7590861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best way to query for items with the most "upvotes" I am working on adding up and down votes to some items in the database, and displaying them ordered by the highest upvotes. How would this query look like? How can I make something like this in SQL? SELECT col1 col2 FROM some_table WHERE "highest number of upvotes" A: Assuming upvotes is a field in your table, you can use ORDER BY and optionally a LIMIT: SELECT col1, col2 FROM some_table ORDER BY upvotes DESC LIMIT 10
{ "language": "en", "url": "https://stackoverflow.com/questions/7590867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i create a form with input mask in javascript I want to create a html form with a text-field which checks if DD-MM-YYYY are correctly entered into the field and alerts the user if it's not the case. How can i approach this with javascript? A: Couldn't you just make 3 <input> fields - one for month, day, and year? A: In JS, after the user key's off or hits enter, you could test the value (assuming the <input> has an id of inpdate for sake of example): var val = document.getElementById('inpdate').value; var check = /^\s*\d{2}-\d{2}-\d{4}\s*$/; if(check.test(val)){ // it's good } else { // not valid } I put \s* in to allow leading and trailing whitespace. Up to you if you would want to allow that. A: JS Fiddle Went a little overboard (and it's still not robust), but it allows you to change the format (MM-DD-YYYY) to something else like (YYYYMMDD). HTML <input type="text" name="date" id="date-input" onkeyup="checkDate.call(this)" /> <pre id="debug"></pre> JS var debug = document.getElementById('debug'); var checkDate = function(){ var format = 'MM-DD-YYYY'; var delim = '-'; var inputs = { object : this , day : { order : undefined , length : undefined , value : undefined } , month : { order : undefined , length : undefined , value : undefined } , year : { order : undefined , length : undefined , value : undefined } }; // Decipher Format Positioning var temp = ['Y','M','D']; var pos = []; for (var i=0,n=temp.length; i<n; i++){ pos[i] = []; pos[i].push(format.indexOf(temp[i])); // start pos[i].push(temp[i]); // letter pos[i].push(format.lastIndexOf(temp[i])-pos[i][0]); // length } pos.sort(); // Store the positions for (var i=0,n=pos.length; i<n; i++){ switch (pos[i][1]){ case 'D': inputs.day.order =i; inputs.day.length =pos[i][2]; break; case 'M': inputs.month.order =i; inputs.month.length =pos[i][2]; break; case 'Y': inputs.year.order =i; inputs.year.length =pos[i][2]; break; } } // Build Regex //alert(format); var temp = format.split(/[^a-zA-Z]/); var regex = ''; for(var i=0,n=temp.length; i<n; i++){ regex += '(\\d{' + temp[i].length + '})'; } var re = new RegExp(regex); var matches = re.exec(inputs.object.value.replace(/[^0-9]/g,'')); if (matches && matches.length>0){ inputs.day.value = matches[inputs.day.order +1]; inputs.month.value = matches[inputs.month.order +1]; inputs.year.value = matches[inputs.year.order +1]; debug.innerHTML = 'Valid Date: \n' + '\tDay: ' + inputs.day.value + '\n' + '\tMonth: ' + inputs.month.value + '\n' + '\tYear: ' + inputs.year.value + '\n'; } else { debug.innerHTML = 'Not a valid date!'; } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7590870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby - Abbreviating a string containing a name to first name last initial Fairly simple question I need to take a string containing, for example, "Bob Smith" and return "Bob S." - or "Javier de Luca" and return "Javier de L.". In other words, abbreviate the last word in a string to just the first initial and add a period. Here's what I have - it works, but it seems clumsy. str = str.split(' ') str[str.length - 1] = "#{str.last[0]}." str = str.join(' ') Surely, there's a more elegant way. A: >> "Bob Smith".sub(/(.+\b.).+\z/, '\1.') => "Bob S." >> "Javier de Luca".sub(/(.+\b.).+\z/, '\1.') => "Javier de L." This regular expression captures the entire string until the second character of the last word. It then replaces this string with the capture plus a period ala \1. A: What about this: name = 'Javier de Luca' name.sub!(/(\w)\w+$/, '\1.') A: You could use tap in 1.9: str = str.split(/\s+/).tap { |a| a[-1].sub!(/(.).+/) { "#{$1}." } }.join(' ') Using a[-1].sub! will modify the last element in-place so the tap block modifies a as well as passing it through to the join call. And, the .+ takes care of leaving strange names like Joe B alone; if you want that to become Joe B. them use .* instead of .+.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Permission migration from publish_stream to publish_action I am wondering if you have a users permission to publish_stream and you want to publish_action from now on does publish_stream cover both or do we need to re-request the users permission? If so whats the easiest way of detecting wether they have this permission granted etc. User journey suggestions welcome. The login system I have in place is users can use with facebook or their account credentials. But some users sign up without facebook and then connect later. I don't create the session every time they login as I only need the publish_stream permission which works without needing a live user session with facebook to post when the user does specific actions. There is one column in the table which specifies wether the user is connected or not. Suggestions welcome. Thanks! -Stefan A: As of now, publish_stream includes publish_actions permissions. see https://developers.facebook.com/docs/publishing/#publish_stream The publish_stream permission is a superset of publish_actions allowing everything that publish_actions allows plus more. A: publish_stream and publish_actions are two separate permissions. publish_stream does not include publish_actions. To publish actions to the open graph, you will need to get this new permission for new users and for existing users. You can check the permissions a user has granted your app by GETing /me/permissions from the Graph API. In the latest version of the permissions dialog, users will have the option to NOT grant publish_stream - its always an optional permission. If the app requests publish_actions, this permission is considered required. Once Timeline has launched beyond Developer Beta, you should not need to ask for publish_stream. If you want to publish a feed story, use the Feed Dialog. A: Publish_stream is Deprecated Permissions from v2.2, that's why u can not use, just only publish_action u can still use, https://developers.facebook.com/docs/facebook-login/permissions regards djavalatte.com A: You must request publish_stream as a new permission because the prompt is much different. It is more around "Add to timeline" and a straight up permission. To know if you have the permission, you can do many things. The easiest is to try and publish and see if it succeeds. but that will skew your metrics in insights. Better is to use the access token info endpoint and check the scopes you have there. A: I have successfully published actions to the timeline with only the publish_stream permission. I cannot say if this is will be the case when it is fully launched or if it's only working because of the developer's beta. We can know for sure once we're 48 hours away from the official launch by checking out the beta tier. http://developers.facebook.com/support/beta-tier/
{ "language": "en", "url": "https://stackoverflow.com/questions/7590878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Configuring and installing python2.6.7 and mod_wsgi3.3 on RHEL for production This is a long question detailing all that I did from the start. Hope it helps. I am working on a django application and need to deploy it on to the production server. The production server is a virtual server managed by IT, and I do not have the root access. They have given me rights to manage the installations of my modules in /swadm and /home/swadm. So I have planned to do create the following arrangement: * */swadm/etc/httpd/conf where I maintain httpd.conf */swadm/etc/httpd/user-modules where I maintain my apache modules (mod_wsgi) */swadm/var/www/django/app where I maintain my django code */swadm/usr/local/python/2.6 where I will maintain my python 2.6.7 installation with modules like django, south etc. */home/swadm/setup where I will be storing the required source tarballs and doing all the building and installing out of. */home/swadm/workspace where I will be maintaining application code that is in development. The system has python2.4.3 and python2.6.5 installed but IT recommended that I maintain my own python installation if I required lot of custom modules to be installed (which I would be). So I downloaded python2.6.7 source. I needed to ensure python is installed such that its shared library is available. When I ran the configure script with only the option --enable-shared and --prefix=/swadm/usr/local/python/2.6, it would get installed but surprisingly point to the system's installation of python2.6.5. $ /swadm/usr/local/python/2.6/bin/python Python 2.6.5 (r265:79063, Feb 28 2011, 21:55:45) [GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> So I ran the configure script following instructions from Building Python with --enable-shared in non-standard location as ./configure --enable-shared --prefix=/swadm/usr/local/python/2.6 LDFLAGS="-Wl,-rpath /swadm/usr/local/python/2.6/lib" Also making sure I had created the directories beforehand ( as the link suggests) to avoid the errors expected. Now typing /swadm/usr/local/python/2.6/bin/python would start the correct python version 2.6.7. So I moved on to configuring and installing mod_wsgi. I configured it as ./configure --with-python=/swadm/usr/local/python/2.6/bin/python the Makefile that was created tries to install the module into /usr/lib64/httpd/modules and I have no write permissions there, so I modified the makefile to install into /swadm/etc/httpd/user-modules. (There might be a command argument but I could not figure it out). The module got created fine. A test wsgi script which I used was import sys def application(environ, start_response): status = '200 OK' output = 'Hello World!' output = output + str(sys.version_info) output = output + '\nsys.prefix = %s' % repr(sys.prefix) output = output + '\nsys.path = %s' % repr(sys.path) response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] And the output shown was, surprisingly Hello World!(2, 6, 5, 'final', 0) sys.prefix = '/swadm/usr/local/python/2.6' sys.path = ['/swadm/usr/local/python/2.6/lib64/python26.zip', '/swadm/usr/local/python/2.6/lib64/python2.6/', '/swadm/usr/local/python/2.6/lib64/python2.6/plat-linux2', '/swadm/usr/local/python/2.6/lib64/python2.6/lib-tk', '/swadm/usr/local/python/2.6/lib64/python2.6/lib-old', '/swadm/usr/local/python/2.6/lib64/python2.6/lib-dynload']` So you see somehow the mod_wsgi module still got configured with the system's python 2.6.5 installation and not my custom one. I tried various things detailed in the mod_wsgi documentation * *Set WSGIPythonHome in httpd.conf to /swadm/usr/local/python/2.6 and WSGIPythonPath to /swadm/usr/local/python/2.6/lib/python2.6 *Created a symlink in the python config directory to point to the libpython2.6.so file $ ln -s ../../libpython2.6.so When I do ldd libpython2.6.so this is what I see: $ ldd libpython2.6.so linux-vdso.so.1 => (0x00007fffc47fc000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00002b666ed62000) libdl.so.2 => /lib64/libdl.so.2 (0x00002b666ef7e000) libutil.so.1 => /lib64/libutil.so.1 (0x00002b666f182000) libm.so.6 => /lib64/libm.so.6 (0x00002b666f385000) libc.so.6 => /lib64/libc.so.6 (0x00002b666f609000) /lib64/ld-linux-x86-64.so.2 (0x00000031aba00000) And ldd mod_wsgi.so gives $ ldd /swadm/etc/httpd/user-modules/mod_wsgi.so linux-vdso.so.1 => (0x00007fff1ad6e000) libpython2.6.so.1.0 => /usr/lib64/libpython2.6.so.1.0 (0x00002af03aec7000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00002af03b270000) libdl.so.2 => /lib64/libdl.so.2 (0x00002af03b48c000) libutil.so.1 => /lib64/libutil.so.1 (0x00002af03b690000) libm.so.6 => /lib64/libm.so.6 (0x00002af03b893000) libc.so.6 => /lib64/libc.so.6 (0x00002af03bb17000) /lib64/ld-linux-x86-64.so.2 (0x00000031aba00000) I have been trying re-installing and re-configuring python and mod_wsgi but to no avail. Please let me know where I am going wrong. (Sorry for the very long post) TLDR; System with non-root access has default python installation. I am maintaining my own python and python modules. mod_wsgi configured and built with the custom python, still points to the system's python when I run a test script that prints out the sys version_info and path. UPDATE: On Browsing through the stackoverflow (should have done it earlier) I found this answer by Graham Dumpleton on mod_wsgi python2.5 ubuntu 11.04 problem which solved the error for me. Now when I do ldd mod_wsgi.so I see that it is linked to the correct shared library of python. I now installed Django and MySQLdb using my custom python install. And Now I am facing this error: The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/var/www/.python-eggs' The Python egg cache directory is currently set to: /var/www/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. So I did change the value of PYTHON_EGG_CACHE by doing export PYTHON_EGG_CACHE=/swadm/var/www/.python-eggs. but I am still getting the same error. I am investigating more. Will update when I solve this. A: Egg cache issue solved by setting environment variable in WSGI script: http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Access_Rights_Of_Apache_User or in Apache configuration: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonEggs http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess Which of latter two is used depends on whether using emebedded mode or daemon mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC validation for unique Hi I have an MVC app that I used to insert update invoices: public class Invoice : IEntity, IValidatableObject { public virtual int InvoiceId { get; set; } [Required(ErrorMessage = "Invoice Number is a required field.")] [Column(TypeName = "varchar")] [StringLength(20)] [Display(Name = "Invoice Number:")] public virtual string InvoiceNumber { get; set; } [Required(ErrorMessage = "Organisation is a required field.")] [Display(Name = "Organisation:")] public int OrganisationId { get; set; } ... } The problem is I have a requirement "The combination of organisation and invoice number must be unique. So this has been set up by the DBA in the database. So if I try to do this it will return an exception. Is there a way instead of displaying the exception to catch it and add a custom error message to the validation summary? A: You could catch the exception and add the error to the model state so that your client code handles all errors the same way. Something like: ModelState.AddModelError("InvoiceNumber", "The combination of organisation and invoice number must be unique."); A: you can achieve this by putting remote attribute on both properties and in AdditionalField parameter you pass the name of other property like [Remote("IsUnique","home",AdditionalFields = "OrganisationID",ErrorMessage = "abc")] virtual string InvoiceNumber { get; set; } [Required(ErrorMessage = "Organisation is a required field.")] [Display(Name = "Organisation:")] [Remote("IsUnique","home",AdditionalFields = "InvoiceNumber",ErrorMessage = "abc")] public int OrganisationId { get; set; } and you can write InUnique method in home controller (for instance) like public JsonResult IsUnique(string InvoiceNumber, int? OrganisationID) { if(InvoiceNumber == null || !Organisation.HasValue) { return Json({valid = true});//null check is not job of this attribute } else { bool result = CheckDbForUniqueness(InvoiceNumber, OrganisationID.Value); return Json({valid = result}); } } This method will be invoked when you change value of either inputs on the form and take the other value as parameter. if either value is null it would return true and null checking will be handled by Required attributes. A: Without getting fancy...you could catch it in the controller, then display the message in the view via a member of the model or ViewBag/ViewData. A: You can also write a custom validator that checks this for you (even with some client-side validation as well). I wrote one that checked a database for whether a username existed or not, a similar check could be done for this, without relying on exceptions (although you still would want to handle it I wouldn't recommend using exceptions for a normal course of action).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why is my WCF client timing out sometimes when trying to connect to the WCF Service on localhost? I have a WCF service hosted within a Windows service. The client that is connecting to it is on the same machine so I would expect it to take long to connect and definitely not timeout. For some reason when I start the client and it tries to connect to the service it times out. This only happens occasionally, but enough where it is annoying since the entire app relies on a good connection tot he service. What could cause a client on the same machine as the service time out when connecting? Here are the app.config files from the host and the client. Here is the client config: <system.serviceModel> <bindings> <wsDualHttpBinding> <binding name="WSDualHttpBinding_IWCFService" closeTimeout="00:00:10" openTimeout="00:00:10" receiveTimeout="00:10:00" sendTimeout="00:00:30" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" /> <security mode="Message"> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" /> </security> </binding> </wsDualHttpBinding> </bindings> <client> <endpoint address="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IWCFService" contract="WCFService.IWCFService" name="WSDualHttpBinding_IWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> </client> And the service config: <system.serviceModel> <services> <service name="WCF.WCFService" behaviorConfiguration="WCFBehavior"> <endpoint address="" binding="wsDualHttpBinding" contract="WCF.IWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WCFBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> Is there anything I can do to make the client connect better and make the the connection more stable in general? Change the binding? Anything? A: Try to add one more endpoint with "netNamedPipeBinding" that was originally designed for local calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Table cells resizing when browser resizes I have this: table td { width: 300px; } <table> <tr> <td>Text</td> <td>Text</td> <td>Text</td> </tr> </table> Everything is fine if the browser is big enough. But if I resize my browser and make it too small, my cells resize. How can I make them stay a fixed width? Here it is in jsFiddle: http://jsfiddle.net/y2wHn/ A: Do this to your CSS: table td { min-width: 300px; } This specifies a minimum-width, so it can never be smaller than 300px. amosrivera's suggestion is also a good way to go about it. A: Set a fixed width on the table: table { width: 900px; } A: set width of the whole table not td table{width:900px;} table td { border:1px solid black; } http://jsfiddle.net/y2wHn/6/ A: You have to set the table to a specified width as well, otherwise it will resize based on the browsers window size. Updated code: table { width: 900px; } table td { width: 300px; background-color: #432152; } A: what about if u add a current css rule: table { width: 900px; } fixed table width no?
{ "language": "en", "url": "https://stackoverflow.com/questions/7590912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compile and run a coffeescript file on node.js on change I am currently using this node.js command to watch coffeescript files for changes and compile them to a folder: coffee -cwo ./js ./src I wonder if there is a way to watch a folder/files for changes and if there is a change, run a compiled js file. In this way I don't have to manually run "coffee file.coffee" each time I made a change in coffeescript files. A: You can either save the compiled JS or run it with a single coffee command, but not both. The command to run the .coffee files in src every time they change is simply coffee -w src For more complex compilation needs, you should write a Cakefile. Check out the one in sstephenson's node-coffee-project, for instance. That way, you can customize the whole compilation pipeline for your project's needs, e.g. compile -> run tests -> run the project if tests passed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to style MVC3/ASP.net DropDownList? How can I style a mvc3/asp.net DropDownList in css like I can with a text box: --Site.css - Style for text box-- input[type="text"], input[type="password"] { border: 1px solid #93A9C8; padding: 2px; font-size: 1em; color: #444; width: 200px; border-radius: 3px 3px 3px 3px; -webkit-border-radius: 3px 3px 3px 3px; -moz-border-radius: 3px 3px 3px 3px; -o-border-radius: 3px 3px 3px 3px; } MVC3 Display: A: input[type="text"], input[type="password"], select { border: 1px solid #93A9C8; padding: 2px; font-size: 1em; color: #444; width: 200px; border-radius: 3px 3px 3px 3px; -webkit-border-radius: 3px 3px 3px 3px; -moz-border-radius: 3px 3px 3px 3px; -o-border-radius: 3px 3px 3px 3px; alternatively, you can add a style to the dropdownlist: @Html.DropDownListFor(m => m.ID, Model.MyList, new { @class="selectStyle" }) so you could do the following in the css: .selectStyle { /* whatever */ } A: Add select to your CSS. Check out the JSFiddle. A: The drop down list renders to a "select" element, not an "input" element, so your CSS would have to include "select" as well. Know also that selects are sometimes notoriously difficult to style. Much of their design is governed by the platform, not the CSS on the page. There are a number of ways around this, the most elegant of which are usually simple jQuery plugins. The one called "Chosen" is particularly good, in my opinion. But be aware that obscuring the standard select element functionality can sometimes cause usability issues on mobile devices and other touch interfaces. So test your target platforms accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I initialize a struct in a Class constructor list? I want to initialize a struct within a default class initializer list. For example, if I have a class like like this: class Foo { private: int x; int y; int z; somestruct p; public: Foo(): x(1), y(2), z(3) { // other stuff } }; So, I can clearly initialize primitive types this way - how do I initialize a struct, for example the somestruct p parameter? Are there any limitations on the design of p if initialized this way? A: In the code below, m_strct is a member of MyClass, and is initialized by the default constructor. struct MyStruct { MyStruct(int i): // Constructor myData(i) { } int myData; }; class MyClass { public: MyClass() : // default constructor m_strct(0) { } private: MyStruct m_strct; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7590924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Transparency on images inside opaque UIImageView I often export PNG images from Photoshop for use in an iPhone app, using the Save For Web and Devices feature. I always leave the transparency option selected, even if there are no transparent parts to the image. This is because I assumed that it would have no effect if the image has no transparent areas, and it's easier to just leave the option selected. I was told recently that by doing this, the opaque property of a UIImageView is effectively ignored because the UIImage will have an alpha channel, having a negative impact on performance. Is this correct? Should I turn off the transparency option if it's not needed when exporting PNGs from Photoshop? A: The image itself should have zero effect on a UIImageView or its opaque property except for the amount of image data that has to be loaded into the UIImageView's image property. Since, an image with transparency will usually have a larger amount of data than the same image without any transparency, it would take slightly longer for it to load into a UIImageView.image when setting it (imageView.image = [UIImage imageNamed:@"myTransparentImage.png"];). Unless, of course, you use a different quality/compression/format/color depth/etc when exporting from Photoshop. You can verify all of this and see the exact amount of time, I/O, memory, etc for each different image by using the Instruments App with the System Usage, Time Profiler, and/or Activity Monitor templates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: NSNumberFormatter bug? When I try to convert the NSString @"8.8" to a NSNumber by NSNumberFormatter NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setMaximumFractionDigits:2]; [formatter setPositiveFormat:@"###0.##"]; NSNumber *result = [formatter numberFromString:@"8.8"]; NSLog(@"%@", [result stringValue]); [formatter release]; the result is 8.800000000000001. For any other value (i.e: 6.6, 7.7, 9.9, 1.2, 4.7 etc.), the logged result was exactly the same NSString passed to numberFromString method. I'm using XCode 4.1 and the 4.3 simulator. There is no difference if I put (or not) setMaximumFractionDigits or/and setPositiveFormat, the result is always 8.800000000000001. What is happening? A: Most numbers that are not integers can not be represented accurately in floating point variables. There is a class NSDecimalNumber that handles exact values at a cost of overhead, this is mainly used for monetary calculations. See: WIkipedia: Floating point numbers are rational numbers because they can be represented as one integer divided by another. The base however determines the fractions that can be represented. For instance, 1/5 cannot be represented exactly as a floating point number using a binary base but can be represented exactly using a decimal base.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: $.post followed by form.submit seems to cancel the $.post On a web application with multiple forms on it, if you click an option that moves to another page, we save any unsaved content by calling $.post(window.location.pathname, options, saveReturn, 'json'); and then go to the new page by setting some parameters and calling form.submit();. This normally works fine, but on our customer's production server (but not their test servers, of course), the actions of the $.post don't seem to happen - the stuff that's supposed to be saved to the database aren't saved. I've got one of our customer tech support people to run a firebug session, and the POST that is triggered by the $.post command is shown in red, and there is no "Response" header. Is there some sort of race condition caused by us leaving the page before the POST completes? Is there some way to wait for the POST to complete, short of making the saveReturn function be responsible for the form.submit()? I'd rather not add that functionality to saveReturn because this same $.post call is done if they manually save their work using the "Save" button. A: that's because you're killing the connection when you leave the page. You should submit the form in $.post's callback. $.post(window.location.pathname, options, function(data){ saveReturn(data); form.submit(); }, 'json'); A: Your intuition seems to be right. If you want to separate saveReturn from form.submit "more" you could attach form.submit to the complete event of the request: $.post(window.location.pathname, options). success(saveReturn). complete(function(){ form.submit(); }); This is kind of nice because it clearly separates the two actions (assuming of course that you want to; that seems to be what you want given your question).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get tuples with max value from each key from a list I have a list of tuples like this: [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)] I want to keep the tuples which have the max first value of every tuple with the same second value. For example (2, 1) and (3, 1) share the same second (key) value, so I just want to keep the one with the max first value -> (3, 1). In the end I would get this: [(1, 0), (3, 1), (6, 2), (2, 3)] I don't mind at all if it is not a one-liner but I was wondering about an efficient way to go about this... A: from operator import itemgetter from itertools import groupby [max(items) for key, items in groupby(L,key = itemgetter(1))] It's assuming that you initial list of tuples is sorted by key values. groupby creates an iterator that yields objects like (0, <itertools._grouper object at 0x01321330>), where the first value is the key value, the second one is another iterator which gives all the tuples with that key. max(items) just selects the tuple with the maximum value, and since all the second values of the group are the same (and is also the key), it gives the tuple with the maximum first value. A list comprehension is used to form an output list of tuples based on the output of these functions. A: Probably using a dict: rd = {} for V,K in my_tuples: if V > rd.setdefault(K,V): rd[K] = V result = [ (V,K) for K,V in rd.items() ] A: import itertools import operator l = [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)] result = list(max(v, key=operator.itemgetter(0)) for k, v in itertools.groupby(l, operator.itemgetter(1))) A: You could use a dictionary keyed on the second element of the tuple: l = [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)] d = dict([(t[1], None) for t in l]) for v, k in l: if d[k] < v: d[k] = v l2 = [ (v, k) for (k, v) in d.items() if v != None ] print l2
{ "language": "en", "url": "https://stackoverflow.com/questions/7590932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I extend WCF in the Callback direction? I can attach an IParameterInspector using behaviors to each operation in the ClientRuntime and also to each operation in the DispatchRuntime on the service side. But it seems this only works from client to service. I also want to be able to attach an IParameterInspector in the callbacks from service to client on both sides of the wire as above but I can't find any extensibility points to do this. Any ideas? A: This is a little obscure and does not appear to be all that well documented but you can customise both ends using standard WCF behavior capabilities. On the client, this attribute would make it happen. public class InspectorBehaviorAttribute : Attribute, IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) { foreach (var item in clientRuntime.CallbackDispatchRuntime.Operations) { item.ParameterInspectors.Add(ParameterInspector.Instance); } } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) { } public void Validate(ServiceEndpoint endpoint) { } } Simply apply this attribute on the class that implements your callback interface. On the server, it gets a little trickier. You need to hook up via the ApplyDispatchBehavior. In this case I have done it through a service behavior but the principal applies to OperationBehaviors and EndpointBehaviors as well. public class InspectorBehaviorAttribute : Attribute, IServiceBehavior { public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { foreach (var item in serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>()) { foreach (var ep in item.Endpoints) { foreach (var op in ep.DispatchRuntime.CallbackClientRuntime.Operations) { op.ParameterInspectors.Add(ParameterInspector.Instance); } } } } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { } } Again, simply apply this attribute to your service implementation to have your parameter inspector utilised for all callback operations. While these examples demonstrate hooking up IParameterInspector implementations, the same approach for all other WCF extension points can be used to customise callback channels at both the client and server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Are the String lliterals stored in the string pool unique? I understand that Strings may be interned, but it it an action that is performed religiously when a new string object is created? Jls section 3.10.5 string literals. A: All String literals go into the string pool. Otherwise, your application must call intern() on the String, or it won't go into the pool. A String literal is a string that appears in source code with double quotes around it: String greeting = "Hello, "; String s = greeting + name; In this example, "Hello, " is a literal string. It is in the intern pool. It is also referenced by the variable greeting. The String referred to by s is not a literal, and is not in the intern pool… unless you make this call: s = s.intern();
{ "language": "en", "url": "https://stackoverflow.com/questions/7590935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FreeTDS connection problems I'm using FreeTDS 0.91 to connect to a remote MSSQL server but all attempts have borne no fruit thus far. Upon doing a tsql command on my Unix, I get the following error: locale is "en_US.UTF-8" locale charset is "UTF-8" using default charset "UTF-8" Error 20004 (severity 9) Read from the server failed OS error 104, "Connection reset by peer" Error 20002 (severity 9) Adaptive Server connection failed There was a problem connecting to the server The freetds.log has the following in it: 16:05:49.144905 20207 (log.c:196):Starting log file for FreeTDS 0.91 on 2011-09-28 16:05:49 with debug flags 0xffff. 16:05:49.145281 20207 (iconv.c:330):tds_iconv_open(0x3d29320, UTF-8) 16:05:49.145426 20207 (iconv.c:187):local name for ISO-8859-1 is ISO-8859-1 16:05:49.145448 20207 (iconv.c:187):local name for UTF-8 is UTF-8 16:05:49.145459 20207 (iconv.c:187):local name for UCS-2LE is UCS-2LE 16:05:49.145469 20207 (iconv.c:187):local name for UCS-2BE is UCS-2BE 16:05:49.145479 20207 (iconv.c:349):setting up conversions for client charset "UTF-8" 16:05:49.145489 20207 (iconv.c:351):preparing iconv for "UTF-8" "UCS-2LE" conversion 16:05:49.145508 20207 (iconv.c:391):preparing iconv for "ISO-8859-1" "UCS-2LE" conversion 16:05:49.145533 20207 (iconv.c:394):tds_iconv_open: done 16:05:49.145550 20207 (net.c:205):Connecting to 70.70.218.13 port 2600 (TDS version 7.0) 16:05:49.145686 20207 (net.c:270):tds_open_socket: connect(2) returned "Operation now in progress" 16:05:49.236008 20207 (net.c:310):tds_open_socket() succeeded 16:05:49.236061 20207 (util.c:156):Changed query state from DEAD to IDLE 16:05:49.236083 20207 (login.c:782):quietly sending TDS 7+ login packet 16:05:49.236173 20207 (token.c:328):tds_process_login_tokens() 16:05:49.857930 20207 (util.c:331):tdserror(0x3d29080, 0x3d29320, 20004, 104) 16:05:49.858072 20207 (util.c:361):tdserror: client library returned TDS_INT_CANCEL(2) 16:05:49.858090 20207 (util.c:384):tdserror: returning TDS_INT_CANCEL(2) 16:05:49.858114 20207 (util.c:156):Changed query state from IDLE to DEAD 16:05:49.858137 20207 (token.c:337):looking for login token, got 0() 16:05:49.858155 20207 (token.c:122):tds_process_default_tokens() marker is 0() 16:05:49.858168 20207 (token.c:125):leaving tds_process_default_tokens() connection dead 16:05:49.858179 20207 (login.c:466):login packet accepted 16:05:49.858189 20207 (util.c:331):tdserror(0x3d29080, 0x3d29320, 20002, 0) 16:05:49.858209 20207 (util.c:361):tdserror: client library returned TDS_INT_CANCEL(2) 16:05:49.858220 20207 (util.c:384):tdserror: returning TDS_INT_CANCEL(2) 16:05:49.858232 20207 (mem.c:615):tds_free_all_results() Does this at all seem like it could be an issue with the SQL server, or am I installing or have configured FreeTDS wrong? So lost. Please help. When I connect to the server via telnet, this is the response I get back: Trying 70.70.218.13... Connected to 70.70.218.13. Escape character is '^]'. ^^ Connection closed by foreign host. Would this mean that the telnet connection to the host was successful? The SQL database is run on a windows server. Would connecting to the Windows server (just like you would through remote desktop) be the right sort of values to use for the hostname and port? Or would I have to find a direct hostname to the SQL server on the windows server? A: Khan. I just encountered this same situation. And I resolved this problem by adding a .freetds.conf to my home, [global] # TDS protocol version tds version = 7.0 And I know this is exactly the answer to most FreeTDS connect problems. And this method is also provided by @Michael Berkowski. A: With apologies for the five year necromancy, it appears that this error will also occur when tsql successfully connects to an open port, but the listener is some service other than SQL Server. It seems FreeTDS does not try to check if it's talking to a service other than SQL Server on login, so the error messages are cryptic. (In my case, I was using the port number for Remote Desktop.) A: If you don't want to create .freetds.conf you can simply set the TDSVER Environment variable instead (e.g. on Windows to connect to SQL Server 2008 use TDS version 7.3): set TDSVER=7.3 (for *nix use export). See http://www.freetds.org/userguide/envvar.htm for more environment variables. See http://www.freetds.org/userguide/choosingtdsprotocol.htm for TDS versions of different RDBMSs You can also specify a path for a log file which can provide more information by setting the environment variable TDSDUMP, which will help troubleshoot problems and show you where config files are looked for. e.g. set TDSDUMP=C:\temp\freetds.log In my case setting the TDSDUMP variable revealed an error in the logs: iconv.c:346:setting up conversions for client charset "CP1252;LC_CTYPE=English_United States.1252;LC_MONETARY=C;LC_NUMERIC=C;LC_TIME=C" iconv.c:348:preparing iconv for "CP1252;LC_CTYPE=English_United States.1252;LC_MONETARY=C;LC_NUMERIC=C;LC_TIME=C" <-> "UCS-2LE" conversion iconv.c:423:tds_iconv_info_init: client charset name "-1" invalid Apparently FreeTDS didn't parse the charset name from the string "CP1252;LC_CTYPE=English_United States.1252;LC_MONETARY=C;LC_NUMERIC=C;LC_TIME=C" I created a .freetds.conf file with the following contents: [global] tds version = 7.3 # version 7.3 for MSSQL 2008 client charset = UTF-8 # so that we can get unicode characters And saved it to C:\Windows\System32\config\systemprofile\AppData\Roaming\ as suggested by the log file, which fixed the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Derive minimal regular expression from input I have a remote "agent" that returns "yes" or "no" when handed a string. Communicating with this agent is expensive, so I'm hoping to find a library that will allow me to iteratively build a regular expression given positive and negative feedback, while being intelligent about its construction. This would allow me to cache answers on the sending side. For example, suppose we query the agent with "good" and receive a "yes". The initial derived regular expression ought to be "good". Suppose I query then with "goop" and receive a "yes". I would expect the derived regular expression to be "goo[dp]", not "good|goop". And so forth. I do not need backtracking or any other fancy non-linear time operations in my derived regex. Presumably the generated regex would be a DFA under the hood. Is anyone aware of any c/c++ regular expression libraries capable of doing this? Alternatively, reasons why this is a dumb idea and better solutions to my real problem would also be useful. A: Rather than a regular expression, you could use a Trie. Then for each new string you walk the trie one node for each character. I suspect that you would also want a marker character for end of string - once you reach this character, if the node exists, it holds the yes/no answer. A: Well, unless I'm missing something in your situation, I think that memory is cheap enough to just straight up implement a dumb cache - say, an unordered_map of <std::string, bool>. Not only will this be much easier to build, it will probably be faster too, since you're building a hash map. The only downside to this is if you were going to query the remote service with a bazillion different keys, then this might not be the best approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: List of unique items in a list of tuples I have a list of tuples like this: mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]. If I use the list comprehension slist = [item for sublist in mylist for item in sublist], I could get slist = [1,2,3,6,1,1,7,8,1,3,4,5]. How should I modify if I need only unique elements in slist like this [1,2,3,6,7,8,4,5]? A: You can actually make your first part a bit easier by using itertools.chain.from_iterable and then passing the result to set, which will only retain the unique elements: >>> mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)] >>> import itertools >>> set(itertools.chain.from_iterable(mylist)) set([1, 2, 3, 4, 5, 6, 7, 8]) A: import itertools chain = itertools.chain(*mylist) print(set(chain)) taken from Flattening a shallow list in Python and adapted for use in this question. A: Use a set instead of a list. set(slist) If you really need it as a list then you can convert it back to a list: slist = list(set(slist)) Note that this conversion won't preserve the original order of the elements. If you need the same order you can use this instead: >>> result = [] >>> seen = set() >>> for innerlist in mylist: for item in innerlist: if not item in seen: seen.add(item) result.append(item) >>> result [1, 2, 3, 6, 7, 8, 4, 5] A: You should use python sets http://docs.python.org/library/sets.html set(yourlist) it will do the trick
{ "language": "en", "url": "https://stackoverflow.com/questions/7590950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Outputting Javascript from PHP, but Javascript doesn't get executed The PHP script doesn't seem to call dis(); function..Here it is: PHP: if (!$_SESSION['user']) { echo"<script type='text/javascript'>dis();</script>"; } JS: <script type="text/javascript"> function dis() { $(document).ready(function() { $("#main_text_area").attr("disabled", "disabled"); }); } When I place just $("#main_text_area").attr("disabled", "disabled"); it disables correctly...but I need to do it on a function call...Thanks for comments. A: I'd recommend, instead of disabling the textarea, outputting the content of the <textarea> as static text. Maybe something like this: <?php if( !$_SESSION['user'] ): ?> <div class="text"> <?php echo $textareaContents; ?> </div> <?php else: ?> <textarea id="main_text_area"> <?php echo $textareaContents; ?> </textarea> <?php endif; ?> The Javascript approach you're currently taking is trivially easy to get around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: GWT MVP UiBinder - passing arguments to the presenter I've started a GWT project, I've decided to give the UiBinder a try. I'm having a difficult time laying an MVP pattern on top of UiBinder. When I was using GWT-pure-java: I'd use Gin to inject my presenter with the corresponding view. It was pretty straight forward, and if I wanted to pass an id into the presenter, then I would simply pass an id into the presenter's constructor. Not so straight forward with UiBinder. I'm almost certain that I'm missing something, because lots of people are claiming that UiBinder and MVP are a match made in heaven...so I'm hoping to get some solid responses on this query ;-) What I've seen in several trivial GWT-UiBinder examples, is that the view is created by the binder then either: * *The view constructs the presenter either in its constructor or via a @UIFactory method. *The corresponding presenter is passed to the view (via a setter, needless to say after the view is constructed). With the first approach, how does one pass an id to the presenter if the presenter is being constructed in the view? Would you do view.getPresenter().setId(42);, and then the presenter would go to the server get some info and ask the view to display it...smells bad. With the second approach, one would end up with a non-intuitive object graph in which it is not clear who is the consumer and who is the producer. Also, in situations where the view requires information from the presenter (almost all use-cases require this) what would one do: //some code would create the presenter pass it the id and then call view.setPresenter class MyView { void setPresenter(MyPresenter p) { this.presenter = p; //OK now that i have my presenter how do I ask it to fetch data from the server. //do i turn around and do: presenter.setView(this); and then the presenter takes //over and uses the view to display the data? } } This is equally smelly...Sorry for the long post, and thanks in advance... A: You're right in that it does seem a bit unclean to have both a View reference its Presenter, and have the presenter reference the View. The way I see it, and how the google dev pages on MVP outline there are two flavours of MVP: * *Have a view that doesn't know about its presenter, and "wrap" it with a presenter. The view provides a sufficient API for the presenter to get/set all the data it cares about. Additionally the presenter must know about all event types the view can generate, in order to respond to user interaction. This is the method of MPV part 1. *The presenter once more knows about the view, but this time only in a get/set data capacity. The presenter does not concern itself with the UI events in the view. Instead, the presenter provides an API for the view to call/notify it when events happen in the form of "onSomethingHappened()" methods in our presenter. This allows us to capture all behaviour/logic in the presenter itself, and invoke it as necessary when something happens in the view. The view can then handle events at a very low level in any way suitable - whether using GWT events/widgets or raw DOM events with elements/HTML (UiBinder/GWT performance best practices). This is the method of MVP part 2. I prefer option 2 as it allows the presenter to be purely focused on the necessary behaviour. The view can deal with widgets/html/event handling as necessary and simplify it to calls to "onSomething()" calls for the presenter. Those widget/event implementations might be simple or complex and optimized events. The presenter is unaffected (and unpolluted) by the detail, as it just gets notified. I feel this option is a cleaner separation of presentation and behaviour. Note it's also a 1 to 1 implementation of the Observer Pattern, so the interconnection between View and Presenter is necessary. As for creation, I feel the Presenter is the stronger entity despite it playing the Observer role. I would create the necessary presenter and then pass it the view of concern. The presenter can then take control of the view, and pass the view a self reference. As for your producer/consumer analogy I think the presenter is the consumer. The view produces UI events (user interaction) and the presenter responds by providing the necessary behaviour. That should be the only point of contact between the view and presenter - the view calls methods like "onSomethingHappened()" and the presenter does the work. The view would never tell the presenter "fetchData()" or anything like that. I've just started using UiBinder + MVP recently myself, so this is just what I think. I hope it helps! A: It has been a few days since I started this thread and read the responses. I've decided on my approach. And I'd thought I just mention it here. Once again, thanks for the thoughtful responses...they were helpful. As filip-fku pointed out presenters are the main entity, so I decided to continue to threat them as such during the life-cycle management of my mvp objects. In other words, the views do not instantiate the presenters. The presenters are instantiated by other presenters (at some point i'll delegate to Gin). The builder of a presenter has access to its corresponding view, and injects the presenter (via constructor) with the view. The views themselves are either instantiated by the builder or instantiated by UiBinder as part of a larger view. In the latter case where UiBinder instantiates the view the parent view has a getter. Here is an example of this case: /*pojo for the parent ui-binder*/ public class Form implements FormPresenter.View { @UiField PromptView namePrompt; @override PromptPresenter.View getNamePromptDisplay() { return namePrompt; //introduced into this pojo via @UiField } //bunch of view code }//end of the class Then in the FormPresenter I do: private void buildNamePrompt() { new PromptPresenter(display.getNamePromptDisplay(), etc....); } I have essentially kept the mvp life-cycle similar to the pure java approach. Once I get some milage out of this, I'll refactor it with Gin. Thanks again. P.S. if you haven't seen the i/o presentation mentioned above, it is worth checking out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Writing own jQuery-PHP picture upload utility for site After looking around for weeks and being totally confounded by the tutorials that were already on the books, I have decided to write my own jQuery upload script. I thought I could get it to work but I am having issues. I will enumerate them: On the page that I am writing this for, I have placed a jQuery script that looks a little like this: $(document).ready(function() { var thumb = $('#thumb'); $('#profilepicinput').live('change', function(){ $("#preview").html(''); $("#preview").html('<img src="loader.gif" alt="Uploading...."/>'); $("#registerpt3").ajaxForm({ target: $('#registerpt3').attr('action') }).submit(); }); $('#profilepicbutton').change(function(){ alert("Boy I hate PHP"); $.ajax({ type: "POST", url: "register3.php", success: function(msg) { alert( "Data Saved: " + msg ); $.ajax({ type: "POST", url: "retrievePic.php", success: function(msg) { var image = new Image(); $(image).load(function(){ console.log("we have uploaded this image"); }).attr('src', 'images/'); alert("AJAX Success!"); }, error: function(msg) { alert(" didn't work"); } }); }, error:function(msq){ alert("didn't work!: " + msg); } }); }); }); This calls the following script which will load a picture into a database: <?php session_start(); $email = ''; if (isset($_SESSION['user_email'])) { $email = $_SESSION['user_email']; } else { $email = 'dww2@pitt.edu'; } $link = mysql_connect('censcoredFool.com', 'greetmeet', 'Maverick$41'); mysql_select_db(first_1) or die("Opps, You are pretty Got-Damned Stupid! Did you realize that?!?!?"); $target = './Uploads/'; $target = $target . basename( $_FILES['uploaded']['name']); $ok = 1; $path = "uploads/"; $Email = $_SESSION['user_email']; $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if (strlen($name)) { list($txt, $ext) = explode(".", $name); if (in_array($ext,$valid_formats)) { if ($size<(1024*1024)) { // Image size max 1 MB $actual_image_name = time().$session_id.".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if (move_uploaded_file($tmp, $path.$actual_image_name)) { mysql_query("insert into personal_photos (Email, Pics) values('$email', '$tmp')"); echo "<img src='uploads/".$actual_image_name."' class='preview'>"; } else { echo "failed"; } } else { echo "Image file size max 1 MB"; } } else { echo "Invalid file format.."; } } else { echo "Please select image..!"; } exit; } What I have doesn't even seem to work. I get the success alert, but the picture doesn't even upload. I am guessing the PHP script ran the whole way through but didn't throw an exception or anything. How do I get this thing to work? UPDATE: After running Firebug My PHP script isn't getting the Picture Not sure why that is. Need to figure out how the $_File datastructure works. A: Most browsers won't send files via ajax for security purposes. To have a pretend-ajax effect on uploads, you might try the excellent jQuery form plugin, which uses an hidden iframe to do the uploading. Since this is the only answer so far - and it's also right - allow me to give you some OT advice: * *Most of the people using PHP like PHP (more things in Heaven and Earth, Horatio). Most of them will take your "PHP Sucks" thing as a pretty pretentious thing to say, since your problem has more to do with a lack of basic knowledge of Ajax and http implementations than it has to do with the language's faults. Thus the lack of answers and the unwelcoming comments. *Your witty is my distracting: please make the debugging output in the code you post as descriptive as possible - actually, it would be a useful thing to do to simply write descriptive output anyway - it's easier to find problems that way, trust me. *If a form is made of one hundred fields ond only one is relevant, please post the relevant field only. A: For security purposes JavaScript can't normally get access to the files on your hard drive. That's why AJAX often is not good for uploading. (although this might have changed in up-to-date browsers). What people have been using for file uploads are: * *iFrame. You need to create invisible iframe and submit a form with your upload form targeting that iframe. Your page will not refresh, and you can even execute some javascript from within that frame. *Flash. Using flash uploader allows you to send multiple files. Although, you are probably better of using some of the existing upload libraries / methods. I've wrote my own uploader, and it's not an easy task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Problem with debug.exe I'm trying to use the debug tool in windows to for a simple program. I want to input a string of characters and then inspect the memory to see the characters saved. Here's the code I have: mov bx,200 mov byte [bx],33 ;; Set maximum string length (32 + Ent) mov ah, 0Ah int 21h Every time I assemble the code and run it, it lets me input the string and then DEBUG automatically quits. This my first time ever using it so I'm not sure what the problem is. Any help/tips would be greatly appreciated. Thanks! A: Function 0Ah expects the buffer address in DS:DX, your code only sets up BX, never DX. Here's how I type the code in: C:\>debug -a 100 13DB:0100 mov bx, 200 13DB:0103 mov byte [bx], 33 13DB:0106 mov ah, 0a 13DB:0108 mov dx, bx 13DB:010A int 21 13DB:010C Here's what I get: -u 100 13DB:0100 BB0002 MOV BX,0200 13DB:0103 C60733 MOV BYTE PTR [BX],33 13DB:0106 B40A MOV AH,0A 13DB:0108 89DA MOV DX,BX 13DB:010A CD21 INT 21 Here's what's in the registers: -r AX=0000 BX=0000 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=0100 NV UP EI PL NZ NA PO NC 13DB:0100 BB0002 MOV BX,0200 Next I just use the "proceed" command to execute the code instruction by instruction: AX=0000 BX=0000 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=0100 NV UP EI PL NZ NA PO NC 13DB:0100 BB0002 MOV BX,0200 -p AX=0000 BX=0200 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=0103 NV UP EI PL NZ NA PO NC 13DB:0103 C60733 MOV BYTE PTR [BX],33 DS:0200=33 -p AX=0000 BX=0200 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=0106 NV UP EI PL NZ NA PO NC 13DB:0106 B40A MOV AH,0A -p AX=0A00 BX=0200 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=0108 NV UP EI PL NZ NA PO NC 13DB:0108 89DA MOV DX,BX -p AX=0A00 BX=0200 CX=0000 DX=0200 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=010A NV UP EI PL NZ NA PO NC 13DB:010A CD21 INT 21 -p Then type in "QWE" followed by enter: QWE AX=0A0D BX=0200 CX=0000 DX=0200 SP=FFEE BP=0000 SI=0000 DI=0000 DS=13DB ES=13DB SS=13DB CS=13DB IP=010C NV UP EI PL NZ NA PO NC 13DB:010C 0000 ADD [BX+SI],AL DS:0200=33 - Done. And here it is in the memory: -d 200 13DB:0200 33 03 51 57 45 0D 00 00-00 00 00 00 00 00 00 00 3.QWE........... 13DB:0210 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 13DB:0220 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................
{ "language": "en", "url": "https://stackoverflow.com/questions/7590956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS container mask with single line ul of varying width Trying to make something like this image. So, it's like a jQuery carousel, but not using jQuery, dont want any animation, just simple pagination to move the "visible" section around. Here's the code so far: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Untitled Document</title> <style> .container { width:480px; height:70px; background:#ff0000; overflow:hidden; } .container ul { list-style-type:none; display:block; margin:0; padding:0; width:auto; } .container ul li { float:left; display:inline; } </style> </head> <body> <div class="container"> <ul> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> <li><img src="image.png" /></li> </ul> </div> </body> </html> The current problem is that once the ul reaches the width of the .container, it breaks and makes 2 rows. I need the ul to stretch, just be one row, and be masked by the container. We have an indeterminate amount of images pulled in from a database, so that will always change the width of the ul. The container width and li width will always be the same. I can't figure this out, and I would like to avoid jQuery/Javascript. A: You can achieve this by using inline-blocks. When using them you can add white-space: nowrap to the parent, so they wouldn't jump on the new line and you could scroll it using, for example, negative margin on the first li. Here I created fiddle for you showing this behavior: http://jsfiddle.net/kizu/qrmC5/ Also, don't forget about display:inline;zoom:1; fix for IE, add this ti your block-lever inline-blocks in conditional comments. A: When you're rendering your page, set the width on the <ul> directly using the style attribute. Since the <li> width will always be constant, width will be: number of images returned * li width Assuming PHP as your server side language, it would be something like so: <div class="container"> <ul style="width: <?php echo $count_imgs * CONSTANT_WIDTH ?>px"> // echo your image <li>'s </ul> </div> Here's an example of it working. If setting the width while rendering the page isn't an option, you could just define an arbitrarily large width on the <ul>. It wouldn't be as nice though since you'd end up with empty space at the end of your list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Native PyQt function returning selected QTreeWidgetItems in order of selection? I have a QTreeWidget which uses the QAbstractItemView.ExtendedSelection property, allowing users to shift click and control click items. I'd like to preform actions on these items based on the order in which they are selected-- I can think of ways to design my own systems to determine the selection order, but is there a native function/property that will return a list of items sorted via selection order? Thank you for your advice! A: The underlying selection model naturally preserves in the order in which items are selected. So you don't really need to do anything special - just iterate over them like this: for item in treewidget.selectedItems(): print item.text(0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing fixed bi-dimensional array to take size given at runtime I've been trying to wrap my head around this the whole day... The code that I have so far works as planed, the idea is that I'll have to change tCell * cells[3][5]; to take a size that's given at runtime. What changes do I need to make to retain the functionality? typedef struct { int active; } tCell; typedef struct { tCell * cells[3][5]; } tGrid; // creates a grid and initialize all the cells to NULL tGrid *init_grid() { tGrid *grid= malloc(sizeof(tGrid)); if(grid == NULL) exit(127); // failed to malloc int i, j; for(i=0; i < 3; i++) for(j=0; j < 5; j++) grid->cells[i][j]= NULL; return grid; } // adds a cell to the grid void add_cell(tGrid *grid) { tCell cell; int y = rand() % 4; if(grid->cells[0][y] != NULL) exit(127); // cell is taken cell.active = 1; grid->cells[0][y] = &cell; } void remove_cell(tGrid *grid, int x, int y) { if(x < 0 || x > 3 || y < 0 || y > 5) exit(127); // out of bounds grid->cells[x][y]= NULL; } Basically, init_grid will have to take x and y as parameters: tGrid *init_grid(int x, int y); But then, how do I change tGrid struct definition? Whatever I've tried so far yielded a compiler error (e.g. tCell * cells[][];) On a slightly related note, how do you read "tCell * cells[3][5];" outloud? Note: * *this is a C question *I'm using gcc 4.1 to compile the code A: Easy. typedef struct { int rows; int columns; tCell **cells; } tGrid; And allocating: tGrid *pGrid = (pGrid*)malloc(sizeof(tGrid)); /* check results etc */ pGrid->rows = rows; pGrid->columns = columns; pGrid->cells = (tCell**)malloc(sizeof(tCell*)*rows); /* check results */ do{ pGrid->cells[rows-1] = (tCell*)malloc(sizeof(tCell)*columns); /* check results */ } while (--rows); Done. Or, you can also do: typedef struct { int rows; int columns; tCell *cells; } tGrid; /*****whatever in the middle ***********/ pGrid->cells = (tCell*)malloc(sizeof(tCell)*rows*columns); instead of the do-while loop. The difference is that in the first case, each row will be a separate array in the memory, which may be useful when handling the thing. Of course, in the end, for each malloc there has to be a free.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: linqpad 4.31 ...try removing one of the duplicate references I can see my entities on the left panel, can see all related to them as columns and relations to other entities. when try to select then entity to take(50) I get this error An assembly with the same identity 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' has already been imported. Try removing one of the duplicate references. got no clue where to start on this error...any help? thanks (if I right click on linqpad editor to go into Query properties the two tabs have nothing on them) A: I have seen this before and it was indicative of me adding references to my own libraries which were built with the .NET 3.5 Framework and using them by referencing them in LINQPad 4.0. If you are adding reference to your libraries, you should use version 3.5 of LINQPad. I actually have both installed into two different sub-directories with a 'link' to either on my desktop/quick-launch bar. Perhaps the query that you are using (if you based it on an earlier one) was created with a different version of LINQPad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C Cannot find interface declaration I have been scratching my head for awhile trying to figure this one out. I have the following .h files //ClassA.h #import "ClassB.h" @interface ClassA { } @property SomeEnum blah; @end //ClassB.h #import "ClassA.h" typedef enum SomeEnum { value1, value2 }SomeEnum; @interface ClassB { } @property SomeEnum otherblah; @end @interface ClassA (Category) { } @end I think the problem is that ClassA needs SomeEnum from ClassB and so it needs to import it, and ClassB needs ClassA for its category so it needs to import it. Is there a problem with them importing each other? Do I need to include a third class? Here are the compiler errors I'm getting: In ClassB.h: Cannot find interface declaration for 'ClassA' In ClassA.h: Unknown type name 'SomeEnum' EDIT: I got it to work by moving the category declaration into ClassA and then having an @class ClassA in ClassB.h...but I'm still not sure why it wouldn't work in the first place A: Do you have (non-category declaration): @interface ClassB @end declared anywhere, usually in ClassB.h? Or a forward declaration: @class ClassB in ClassA.h? Try this for your ClassA.h: //ClassA.h @class ClassB @interface ClassB (Category) + (id)classMethod @end Then put #import "ClassB.h" in ClassA.m. You should put this in ClassA.h: @interface ClassA (Category) { } @end And then the: @implementation ClassA (Category) in ClassA.m above the non-category @implementation ClassA. Personally, I create seperate files for categories. For example, this is in UIView-Extended.h: @interface UIView (UIView_Extended) enum { UIViewAutoresizingHorizontal = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin), UIViewAutoresizingVertical = (UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin), UIViewAutoresizingAll = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin) }; typedef NSUInteger UIViewAutoresizing; - (UIView *)findFirstResponder; - (UIView *)setFirstResponder:(NSUInteger)viewTag; - (IBAction)dismissKeyboard:(id)sender; - (IBAction)nextPrevious:(id)sender; @end And then in UIView-Extended.m: #import "UIView-Extended.h" @implementation UIView (UIView_Extended) - (UIView *)findFirstResponder { if ([self isFirstResponder]) { return self; } for (UIView *subview in [self subviews]) { UIView *firstResponder = [subview findFirstResponder]; if (firstResponder) { return firstResponder; } } return nil; } - (UIView *)setFirstResponder:(NSUInteger)viewTag { if (self.tag == viewTag) { [self becomeFirstResponder]; return self; } for (UIView *subview in self.subviews) { UIView *v = [subview setFirstResponder:viewTag]; if (v) { return v; } } return nil; } - (IBAction)dismissKeyboard:(id)sender { [[self findFirstResponder] resignFirstResponder]; } - (IBAction)nextPrevious:(id)sender { UIView *responder = [self findFirstResponder]; if (!responder) return; NSInteger newTag; NSInteger tagMod = 1; if (sender) { tagMod = (((UISegmentedControl *)sender).selectedSegmentIndex ? 1 : -1); } UIView *v = [self viewWithTag:responder.tag + tagMod]; if ([v isKindOfClass:[UITextField class]] || [v isKindOfClass:[UITextView class]]) { newTag = responder.tag + tagMod; [self setFirstResponder:newTag]; } else { // do something else... but what?? } } @end Then, in my Prefix file (Project-Prefix.pch): #import "UIView-Extended.h" A: You'll want to break out your dependencies. Put the definition of enum SomeEnum in one header file, then include an import for that header in ClassA.h and ClassB.h. In ClassA.h remove the import of ClassB.h. A: #import <UIKit/UIKit.h> you should import <UIKit/UIKit.h> in any object contains "interface declaration" e.g: UIImage NSDate etc..
{ "language": "en", "url": "https://stackoverflow.com/questions/7590971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User control (ascx) in asp.net and its bindable properties dont show up in the data container When I add a user control which has bindable properties to an asp.net page I do not see its bindable properties on the designer's dialog box when I click the edit Data bindings on the Repeater-Listview should I add any other propery descriptors? the markup would be like this inside a repeater or similar control <uc1:Menu ID="Menu1" superman="<% Eval("userid") %>" runat="server" /> on the bindable property I only use [System.ComponentModel.DefaultBindingProperty("superman")] [System.ComponentModel.Bindable(true)] public int superman { get; set; } People discuss it here but they couldn't find a solution A: I think this might be a problem with Visual Studio, I have not found a way to show the properties of user controls, but still, you can bind the property even when it does not appear in the options box: This is how you bind it: In the user control code behind: [Bindable(true)] public string MyProperty { get { return this.lblMessage.Text; } set { this.lblMessage.Text = value + DateTime.Now.ToString(); } } In the ASCX file: <asp:Label ID="lblMessage" Text="something" runat="server" /> In the ASPX page: <asp:DataList runat="server" ID="dataList" Width="50%" DataSourceID="ObjectDataSource1"> <ItemTemplate> <uc1:WebUserControl1 runat="server" ID="myUC" MyProperty='<%# Eval("Name") %>' /> </ItemTemplate> </asp:DataList> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetProducts" TypeName="WebApplication1.Repository"> </asp:ObjectDataSource> Simple just add the property you created in your UC in the tag: <uc1:WebUserControl1 runat="server" ID="myUC" MyProperty='<%# Eval("Name") %>' /> This is the output: A: I think you just make the markup by typing it, the user control must be drag and drop to the page in the design view. try this may helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bind an AppWidget to a Service I implemented a service and I bind my activities in the app to it.. How can I bind an AppWidget too? I need to call some service's method from AppWidget's buttons... Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7590981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sort TabItems in the TabControl I have a collection of type Page with an Order property, I set ItemsSource property of a TabControl an ObservableCollection. What I need to whenever I changed the Order property of an Entity the related TabItem go in the correct location. WPF XAML : <TabControl Grid.Row="1" ItemsSource="{Binding Pages.ListViewModels}" SelectedItem="{Binding Pages.Current}" > <TabControl.ContentTemplate> <DataTemplate> <views:EditPageView /> </DataTemplate> </TabControl.ContentTemplate> <TabControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Header}"/> </DataTemplate> </TabControl.ItemTemplate> </TabControl> C# Codes: public class QuestionPageSection : INotifyPropertyChanged { public virtual int Id { get; set; } public virtual string Header { get; set; } private int _Order; public virtual int Order { get { return _Order; } set { _Order = value; this.RaisePropertyChanged(() => this.Order , PropertyChanged); } } public event PropertyChangedEventHandler PropertyChanged; } I want to force TabControl to sort TabItems based on the Order property. So now I have these questoins: * *Is there any way to do it declaratively? *Does TabControl have a SortColumn property? *Does TabItem have a TabOrder property? *Is there any type of collection that listen to its childs to automatically sort itself based on a property of childs?? Any other idea would be apperciated. A: You can sort you're ObservableCollection on the UI side by using CollectionViewSource. Here's a link with examples: http://msdn.microsoft.com/en-us/library/ms742542.aspx A: You simply need to sort the collection that your TabControl is bound to I've always hated the fact that ObservableCollection doesn't have a built-in Sort method, so I usually use my own custom class that inherits from ObservableCollection public class ObservableCollectionEx<T> : ObservableCollection<T> { public ObservableCollectionEx() : base() { } public ObservableCollectionEx(List<T> l) : base(l) { } public ObservableCollectionEx(IEnumerable<T> l) : base(l) { } #region IndexOf /// <summary> /// Returns the index of the first object which meets the specified function /// </summary> /// <param name="keySelector">A bool function to compare each Item by</param> /// <returns>The index of the first Item which matches the function</returns> public int IndexOf(Func<T, bool> compareFunction) { return Items.IndexOf(Items.FirstOrDefault(compareFunction)); } #endregion #region Sorting /// <summary> /// Sorts the items of the collection in ascending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> public void Sort<TKey>(Func<T, TKey> keySelector) { InternalSort(Items.OrderBy(keySelector)); } /// <summary> /// Sorts the items of the collection in descending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> public void SortDescending<TKey>(Func<T, TKey> keySelector) { InternalSort(Items.OrderByDescending(keySelector)); } /// <summary> /// Sorts the items of the collection in ascending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param> public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer) { InternalSort(Items.OrderBy(keySelector, comparer)); } /// <summary> /// Moves the items of the collection so that their orders are the same as those of the items provided. /// </summary> /// <param name="sortedItems">An <see cref="IEnumerable{T}"/> to provide item orders.</param> private void InternalSort(IEnumerable<T> sortedItems) { var sortedItemsList = sortedItems.ToList(); foreach (var item in sortedItemsList) { Move(IndexOf(item), sortedItemsList.IndexOf(item)); } } #endregion } I can use it like this: ListViewModels = GetListViewModels(); ListViewModels.Sort(p => p.Order); A: Thanks Rachel, your solution gave me the clue, but still your solution is an answer because I can manually call the Sort method whenever I change the Order property, but I wanted to make it automatic. So I end up with a dynamic version of your code. Based on the Rachel I approached to this solution. public class ObservableCollectionEx<T> : ObservableCollection<T> { public ObservableCollectionEx() : base() { } public ObservableCollectionEx(List<T> l) : base(l) { } public ObservableCollectionEx(IEnumerable<T> l) : base(l) { } Func<IEnumerable<T>,IEnumerable<T>> sortFunction; Action reset; #region IndexOf /// <summary> /// Returns the index of the first object which meets the specified function /// </summary> /// <param name="keySelector">A bool function to compare each Item by</param> /// <returns>The index of the first Item which matches the function</returns> public int IndexOf(Func<T , bool> compareFunction) { return Items.IndexOf(Items.FirstOrDefault(compareFunction)); } #endregion IndexOf #region Sorting /// <summary> /// Sorts the items of the collection in ascending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> public void SetSort<TKey>(Func<T , TKey> keySelector) { sortFunction = list => list.OrderBy(keySelector); InternalSort(); reset = () => SetSort(keySelector); } /// <summary> /// Sorts the items of the collection in descending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> public void SetSortDescending<TKey>(Func<T , TKey> keySelector) { sortFunction = list => list.OrderByDescending(keySelector); InternalSort(); reset = () => SetSortDescending(keySelector); } /// <summary> /// Sorts the items of the collection in ascending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param> public void SetSort<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer) { sortFunction = list => list.OrderBy(keySelector , comparer); InternalSort(); reset = () => SetSort(keySelector , comparer); } /// <summary> /// Sorts the items of the collection in descending order according to a key. /// </summary> /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam> /// <param name="keySelector">A function to extract a key from an item.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param> public void SetSortDescending<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer) { sortFunction = list => list.OrderByDescending(keySelector , comparer); InternalSort(); reset = () => SetSortDescending(keySelector , comparer); } /// <summary> /// Moves the items of the collection so that their orders are the same as those of the items provided. /// </summary> private void InternalSort() { UpdateTracking(null , Items.ToList()); } private void MoveItemToItsLocation(T item) { var sortListCache = sortFunction(Items).ToList(); Move(IndexOf(item) , sortListCache.IndexOf(item)); } #endregion Sorting public void UpdateTracking(IEnumerable<T> oldItems , IEnumerable<T> newItems) { if (sortFunction == null) return; PropertyChangedEventHandler changeTracker = (o , change) => { MoveItemToItsLocation((T)o); }; Action<T> attachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged += changeTracker); Action<T> detachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged -= changeTracker); var greeting = new[] { attachChangeTracker , MoveItemToItsLocation }; var farwell = new[] { detachChangeTracker }; oldItems.ForEach(detachChangeTracker); newItems.ForEach(attachChangeTracker , MoveItemToItsLocation); } protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { base.OnCollectionChanged(e); switch (e.Action) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: UpdateTracking(e.OldItems.SafeGet(x => x.Cast<T>()) , e.NewItems.SafeGet(x => x.Cast<T>())); break; case NotifyCollectionChangedAction.Reset: UpdateTracking(Items.ToList() , null); if (reset != null) reset(); break; default: break; } } } I only made a little change to make it follow the changes in the underlying collection, so it will sort itself automatically after any changes made to underlying collection or any element in the underlying collection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why would declaring variables as volatile speed up code execution? Any ideas? I'm using the GCC cross-compiler for a PPC750. Doing a simple multiply operation of two floating-point numbers in a loop and timing it. I declared the variables to be volatile to make sure nothing important was optimized out, and the code sped up! I've inspected the assembly instructions for both cases and, sure enough, the compiler generated many more instructions to do the same basic job in the non-volatile case. Execution time for 10,000,000 iterations dropped from 800ms to 300ms! assembly for volatile case: 0x10eeec stwu r1,-32(r1) 0x10eef0 lis r9,0x1d # 29 0x10eef4 lis r11,0x4080 # 16512 0x10eef8 lfs fr0,-18944(r9) 0x10eefc li r0,0x0 # 0 0x10ef00 lis r9,0x98 # 152 0x10ef04 stfs fr0,8(r1) 0x10ef08 mtspr CTR,r9 0x10ef0c stw r11,12(r1) 0x10ef10 stw r0,16(r1) 0x10ef14 ori r9,r9,0x9680 0x10ef18 mtspr CTR,r9 0x10ef1c lfs fr0,8(r1) 0x10ef20 lfs fr13,12(r1) 0x10ef24 fmuls fr0,fr0,fr13 0x10ef28 stfs fr0,16(r1) 0x10ef2c bc 0x10,0, 0x10ef1c # 0x0010ef1c 0x10ef30 addi r1,r1,0x20 # 32 asssembly for non-volatile case: 0x10ef04 stwu r1,-48(r1) 0x10ef08 stw r31,44(r1) 0x10ef0c or r31,r1,r1 0x10ef10 lis r9,0x1d # 29 0x10ef14 lfs fr0,-18832(r9) 0x10ef18 stfs fr0,12(r31) 0x10ef1c lis r0,0x4080 # 16512 0x10ef20 stw r0,16(r31) 0x10ef24 li r0,0x0 # 0 0x10ef28 stw r0,20(r31) 0x10ef2c li r0,0x0 # 0 0x10ef30 stw r0,8(r31) 0x10ef34 lwz r0,8(r31) 0x10ef38 lis r9,0x98 # 152 0x10ef3c ori r9,r9,0x967f 0x10ef40 cmpl crf0,0,r0,r9 0x10ef44 bc 0x4,1, 0x10ef4c # 0x0010ef4c 0x10ef48 b 0x10ef6c # 0x0010ef6c 0x10ef4c lfs fr0,12(r31) 0x10ef50 lfs fr13,16(r31) 0x10ef54 fmuls fr0,fr0,fr13 0x10ef58 stfs fr0,20(r31) 0x10ef5c lwz r9,8(r31) 0x10ef60 addi r0,r9,0x1 # 1 0x10ef64 stw r0,8(r31) 0x10ef68 b 0x10ef34 # 0x0010ef34 0x10ef6c lwz r11,0(r1) 0x10ef70 lwz r31,-4(r11) 0x10ef74 or r1,r11,r11 0x10ef78 blr If I read this correctly, it's loading the values from memory during every iteration in both cases, but it seems to have generated a lot more instructions to do so in the non-volatile case. Here's the source: void floatTest() { unsigned long i; volatile double d1 = 500.234, d2 = 4.000001, d3=0; for(i=0; i<10000000; i++) d3 = d1*d2; } A: Are you sure you didn't also change optimization settings? The original looks un-optimized - here's the looping part: 0x10ef34 lwz r0,8(r31) //Put 'i' in r0. 0x10ef38 lis r9,0x98 # 152 //Put MSB of 10000000 in r9 0x10ef3c ori r9,r9,0x967f //Put LSB of 10000000 in r9 0x10ef40 cmpl crf0,0,r0,r9 //compare r0 to r9 0x10ef44 bc 0x4,1, 0x10ef4c //branch to loop if r0<r9 0x10ef48 b 0x10ef6c //else branch to end 0x10ef4c lfs fr0,12(r31) //load d1 0x10ef50 lfs fr13,16(r31) //load d2 0x10ef54 fmuls fr0,fr0,fr13 //multiply 0x10ef58 stfs fr0,20(r31) //save d3 0x10ef5c lwz r9,8(r31) //load i into r9 0x10ef60 addi r0,r9,0x1 //add 1 0x10ef64 stw r0,8(r31) //save i 0x10ef68 b 0x10ef34 //go back to top, must reload r9 The volatile version looks quite optimized - It rearanges instructions, and uses the special purpose counter register instead of storing i on the stack: 0x10ef00 lis r9,0x98 # 152 //MSB of 10M //.. 4 initialization instructions here .. 0x10ef14 ori r9,r9,0x9680 //LSB of 10,000000 0x10ef18 mtspr CTR,r9 // store r9 in Special Purpose CTR register 0x10ef1c lfs fr0,8(r1) // load d1 0x10ef20 lfs fr13,12(r1) // load d2 0x10ef24 fmuls fr0,fr0,fr13 // multiply 0x10ef28 stfs fr0,16(r1) // store result 0x10ef2c bc 0x10,0, 0x10ef1c // decrement counter and branch if not 0. The CTR optimization reduces the loop to 5 instructions, instead of the 14 in the original code. I don't see any reason 'volatile' by itself would enable that optimization.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validate a date - asp.net mvc 2 I need to validate a date of birth field. I have [Required] [DataType(DataType.Date, ErrorMessage = "Invalid date")] [DisplayName("Date of Birth")] public DateTime DateOfBirth { get; set; } It does absolutely nothing on the client side (no error message is displayed for invalid date). It shows an error message when the field is empty (the [Required] part). All other fields validate and display errors. A: You'll need to create your own attribute, there is nothing built in that will handle it. The DataTypeAttribute will just check if it can convert the value from whatever the user entered to a DateTime. public class PreviousDateAttribute : ValidationAttribute { public override bool IsValid(object o) { rerturn ((DateTime)o < DateTime.Now); } } Is a sample, you'll need to build on it a little. A: Maybe you can use the Date Validator from DataAnnotations Extension? It does exactly what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to iterate through a list in jquery? I need to get to an element in jquery or to use it as a value for a time picker min/max range, that is something like this dealershipInfo.OpenCloseTime.ElementAt(i); where i will be an integer value. & OpenCloseTime is a List<string>. I am working in MVC. The objective is to provide a timepicker based on the min max values provided through the OpenCloseTime object. What will be the best way to implement this? A: You don't want to do this with jQuery, but rather with code in your view. The following assumes your model has OpenCloseTime as a List<DateTime> with the first being the start date and the second being the end date -- not sure why you wouldn't just map these onto individual properties on the model, but ... @{ var startTime = Model.OpenCloseTime.ElementAt(0).ToString("MM/dd/yyyy"); var endTime = Model.OpenCloseTime.ElementAt(1).ToString("MM/dd/yyyy"); } <script type="text/javascript"> $(function() { $('#StartTime').datepicker({ defaultDate: '@startTime' }); $('#EndTime').datepicker({ defaultDate: '@endTime' }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7590991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel column data type exclusive of the header row Using spreadsheetgear, is there any way to get the "probable" data type for a column, exclusive of the header row (if one exists) and reasonably tolerant of sparse population without having to do a sample myself...is there already a way to do this? so for example if I had an excel row like | Customers | Sales Item | Sale Date | Contact | Quantity | | IBM | Keyboard | 28-10-2011 | | 2 | | MS | Mouse | 27-09-2011 | joe | 5 | I would expect to see String, String, DateTime, String, Numeric EDIT So I ended up having to sample like @Tim Anderson suggested, but I needed to handle the case of sparse data, and default to string when conflicting types in the col. (this is called in a loop that walks the cols, I can't post that as it contains some IP) DataValueType is just a local enum and rowcount is the number of rows to sample and because I am already sampling I simply ignore row 0 in case it's a header row. private DataType GetDataTypeFromColRange(IRange range, int rowcount, int col) { var dtlist = GetValueTypes(range, rowcount, col).Distinct(); // If conflicting types for the col default to string. if (dtlist.Count() != 1) { return new DataType(DataTypeValue.String); } else { return new DataType(dtlist.First()); } } private IEnumerable<DataTypeValue> GetValueTypes(IRange range, int rowcount, int col) { for (int i = 1; i < rowcount; i++) { switch (range[i, col].ValueType) { case SpreadsheetGear.ValueType.Text: yield return DataTypeValue.String; break; case SpreadsheetGear.ValueType.Number: if (range[i, col].NumberFormatType == NumberFormatType.Date || range[i, col].NumberFormatType == NumberFormatType.DateTime) { yield return DataTypeValue.Date; } else { yield return DataTypeValue.Numeric; } break; case SpreadsheetGear.ValueType.Logical: yield return DataTypeValue.Bool; break; default: // ignore empty or errored cells. continue; } } } I am sure this can be further improved so please feel free to post improvements, but this does what I need for now. A: In never use spreadsheetgear, but in Excel i use this UDF Function GetType(rg As Range) As String If IsNumeric(rg.Value) Then GetType = "Numeric" ElseIf IsDate(rg.Value) Then GetType = "Date Time" Else GetType = "String" End If End Function I believe it is possible to adapt []'s A: No helper method or other API exists in SpreadsheetGear to automatically return the “probable data type” for a column of values. It would not be very difficult to implement something like this to meet your own particular requirements, although there’s no way to do this without “sampling” the data. Below is a very simple method that accepts the range to check and a Boolean that indicates whether or not the range includes a header row. All it does is check the first row of data to determine the type; you might want to build something a little more robust: private SpreadsheetGear.ValueType[] GetColumnTypes(IRange range, bool hasHeader) { SpreadsheetGear.ValueType[] columnTypes = new SpreadsheetGear.ValueType[range.ColumnCount]; for (int i = 0; i < range.ColumnCount; i++) { columnTypes[i] = range[hasHeader ? 1 : 0, i].ValueType; } return columnTypes; } One thing you should be aware of, however, is that SpreadsheetGear uses the same basic internal data types as Excel and will return these types when checking IRange.ValueType (these include Empty, Error, Logical, Number, Text). Note there is no DateTime. In your example this would impact the value type returned on the “Sale Date” column because dates/times are actually stored in Excel and SpreadsheetGear as a doubles representing a date/time serial number. So this type of value would return Number, not something like DateTime. The fact that they show up as a “date” in the cell is simply a function of the NumberFormat of the cell. A: Here is another try based on error handler and VBA type conversion: Function probableType(vInput As Variant) Dim vResult As Variant 'set error handler to resume (the procedure will check the error number) On Error Resume Next 'check if it is an integer vResult = CInt(vInput) If Err.Number = 0 Then probableType = "Integer" Exit Function End If Err.Clear 'check if it is a date vResult = CDate(vInput) If Err.Number = 0 Then probableType = "Date" Exit Function End If Err.Clear 'else this is probably a string probableType = "String" End Function Can be tested with this sub: Sub uniTest() MsgBox probableType("12/12/12") MsgBox probableType("12") MsgBox probableType("myTest") End Sub You could generalize this with all the conversion functions of Excel VBA (see this link on ozgrid)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detecting the device upside down what are the correct values for detecting the device upside down? I have the following and it starts detecting when the user has titled the device on its back. I use the following values float xx = -[acceleration x]; float yy = [acceleration y]; float angle = atan2(yy, xx); if(angle >= 0.75 && angle <= 2.25) { NSLog(@"Upside down"); } A: Start listening for orientation events by using: UIDevice *currDevice = [UIDevice currentDevice]; [currDevice beginGeneratingDeviceOrientationNotifications]; Then, get the orientation using: currDevice.orientation These are the values that are returned: {'1' : 'Portrait', '2' : 'PortraitUpsideDown', '3' : 'LandscapeLeft', '4' : 'LandscapeRight', '5' : 'FaceUp', '6' : 'FaceDown'} A: UIDevice Class Reference See 'Getting the Device Orientation' part. A: this is my approach (with code) to implement device orientations handling on iOS, and you can use it if you like: How to handle UIDeviceOrientation for manage views layouts
{ "language": "en", "url": "https://stackoverflow.com/questions/7590996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to remotely connect to another windows machine in the network and get the OS information from that machine? (other than Telnet) I have been assigned to write a Perl script wherein I will have to connect to another windows machine on the network and then get that machine's OS name and version. I have achieved this successfully using Perl's NET::Telnet module. But as Telnet is not installed on Windows by default, it will be a prerequisite for running my script and my TL does not want that. Could anybody please suggest me some way to do this using something which is a part of Windows default installation like rpc. Also it will be great if the suggested approach can also work for unix, MAC or HP machines. A: Getting configuration information remotely on Windows systems is typically done by querying WMI data (Windows Management Instrumentation). You can also do this from Perl. Please see a module such as Win32::Process::Info::WMI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: New Open Graph - important life moments Will I be able to display a user's Timeline highlights (important life moments) with my Open Graph App? Will this be possible with the new changes? I'm looking for some kind of API for the Timeline highlights. A: You won't be able to get the user's aggregations or timeline highlights via the API, but you will be able to read back any actions the user published into the Graph using your application. There will soon be the ability for you to request access to other actions the user performed in other apps, and you can then make use of this data, but this will be the raw actions, not aggregations of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dotted Line between h2 span I have been trying to get some dotted lines all over my site. I'm starting to understand the idea but I ran into another problem... I am making another dotted line, this time between text and an image. This one's a bit different. I am also getting problems where sometimes the image goes under the lines due to the width changes: when I update my site, etc. How can I make it here so that I can have the dotted lines' width change to the total width of the h2? I want the dotted lines not to bother anything and just go smooth through it. This is the code I'm using, and I need to keep it in the basic principle: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.serviceDesc').hide(); $('.serviceName:first').addClass('active').next().show(); $('.serviceName').click(function(){ if( $(this).next().is(':hidden') ) { $('.serviceName').removeClass('active').next().slideUp(); $(this).toggleClass('active').next().slideDown(); } return false; }); }); </script> <style> #servicesContainer { width: 485px; height: 400px; margin: 0 auto; margin-top: 20px; } h2.serviceName { margin: 0; margin-bottom: 5px; margin-top: 5px; background-image: url(http://i.imgur.com/IcnZl.png); background-position: right top; background-repeat:no-repeat; height: 29px; line-height: 24px; width: 480px; font-size: 18px; font-weight: bold; float: left; color:#000; } h2.serviceName a { color: #000; text-decoration: none; display: block; } h2.active { background-position: right bottom; } .serviceDesc { margin: 0 0 10px; padding: 0; overflow: hidden; width: 480px; clear: both; } .serviceDesc .block { } .serviceDesc .block p { color: #413f44; margin: 0; font-size:18px; } </style> <div id="servicesContainer"> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.<br /> <br /> </p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................<br /> </a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p> </div> </div> <h2 class="serviceName"><a href="#">Text...............................................................................</a></h2> <div class="serviceDesc"> <div class="block"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p> </div> </div> </div> http://jsfiddle.net/K7MHK/ A: As with the phone/email question, it's the same idea. You can use a background image on the element to create the dotted lines. Since you've already got a background on the <h2>, add it to the <a>: h2.serviceName a { background: url(dots.gif) repeat-x bottom left; /* Other CSS styles */ } Here's an example. As a bonus, it means you can get rid of all your hard coded dots too. Update: If you want to block the dots from behind the words, add a <span> element with solid background color that wraps the text: HTML <h2> <a href=""> <span>Juicy text</span> </a> </h2> CSS a span { background-color: #fff; } This will prevent the dotted background of the <a> from showing through. A: Example h2.serviceName { margin: 0; margin-bottom: 5px; margin-top: 5px; position: relative; height: 29px; line-height: 24px; width: 480px; font-size: 18px; font-weight: bold; float: left; color:#000; overflow: hidden; } h2.serviceName a { color: #000; text-decoration: none; display: block; } h2.serviceName a:after { content : ""; border-bottom: 2px dotted #000; position: absolute; width: 100%; height: 15px; z-index: -1; } h2.serviceName a:before { content : ""; background-image: url(http://i.imgur.com/IcnZl.png); width: 30px; height: 29px; float: right; } It's a little hacky and you can still kinda see the dots on the right... but it gives you a little better idea the power of CSS3
{ "language": "en", "url": "https://stackoverflow.com/questions/7591006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python-twilio api error? im using twilio-python and im following this tutorial: http://readthedocs.org/docs/twilio-python/en/latest/usage/twiml.html?highlight=nest But when i try this: from twilio import twiml r = twiml.Response() r.say("hello") with r.gather(finishOnKey=4) as g: g.say("world") print str(r) But i get this: AttributeError: __exit__ Any idea? A: It seems they aren't really compatible with the with statement. Try this: from twilio import twiml r = twiml.Response() r.say("hello") g = r.gather(finishOnKey=4) g.say("world") print str(r) Here's what I get: >>> from twilio import twiml >>> >>> r = twiml.Response() >>> r.say("hello") <twilio.twiml.Say object at 0x1098d05d0> >>> g = r.gather(finishOnKey=4) >>> g.say("world") <twilio.twiml.Say object at 0x1098d0950> >>> print str(r) <?xml version="1.0" encoding="UTF-8"?><Response><Say>hello</Say><Gather finishOnKey="4"><Say>world</Say></Gather></Response> A: Emmet - good catch. Matt - pitch perfect response. We've just pushed a fix for this issue with 3.3.2 - you can pick it up off PyPi or at the GitHub repo here: https://github.com/twilio/twilio-python Just update your module and the documented approach will work. Please shoot an email to the address in my profile - you guys just earned a Twilio T-shirt. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7591009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP to Smarty, displaying some nested Arrays I'm having some issues displaying some nested array results in smarty... here's what I have: $searchResults - an array, where each row is a result set. No problem here. $searchResults[$row][users][] - this is the nested array I created. If users exist for this row of the search results, I want to display every user.... So, here we have my smarty code: {section name=i loop=$searchResults} {section name=j loop=$searchResults[i].users} {$searchResults[i].users[j].firstName} {/section} {/section} However, this doesn't seem to work out for me... it displays the users results in a crazy fashion in my table, instead of being inside the same <td></td> where the section is placed inside. UPDATE - Using For Each, with more code... {section name=i loop=$searchResults} <tr> <td>{$searchResults[i].id}</td> <td> {if $searchResults[i].users} {foreach from=$searchResults[i].users item=user} {$user.firstName} {$user.lastName} <br> {/foreach} {/if} </td> </tr> {/section} This displays a table like this: ID ID ID Bob Boberton John Appleton Chris Cooley Carl Agley Cynthia Nobody When it should be like this: ID Bob Boberton John Appleton ID Chris Cooley ID Carl Agley Cynthia Nobody A: You could go further and use another foreach for the main loop. I've found them to be easier to read and find what the issue is. {foreach from=$searchResults item=result} <tr> <td>{$result.id}</td> <td> {if $result.users} {foreach from=$result.users item=user} {$user.firstName} {$user.lastName}<br/> {/foreach} {/if} </td> </tr> {/foreach} That said, I could not reproduce your issue with how $searchResults was described; both your loop and mine worked the same in the end. Below is the array I was using. $smarty->assign('searchResults', array( array( 'id' => 1, 'users' => array( array( 'firstName' => 'Bob', 'lastName' => 'Boberton', ), array( 'firstName' => 'John', 'lastName' => 'Appleton', ), ), ), array( 'id' => 10, 'users' => array( array( 'firstName' => 'Chris', 'lastName' => 'Cooley', ), ), ), array( 'id' => 100, 'users' => array( array( 'firstName' => 'Carl', 'lastName' => 'Agley', ), array( 'firstName' => 'Cynthia', 'lastName' => 'Nobody', ), ), ), ));
{ "language": "en", "url": "https://stackoverflow.com/questions/7591010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not sure about my interpretation of function declaration in C++? It seems to be stupid question but I have never seen something like this! int operator() (const std::string& s1, const std::string& s2) const to me operator is a const member function that return an intger and no variable argument! but need two const variables s1 and s2?!?! I can't get the point of this! class str_dist_ : public std::binary_function<std::string, std::string, int> { public: int op() (const std::string& s1, const std::string& s2) const { if (s1 == s2) return 0; else if (s1.empty()) return std::max(s2.size()/2, 1u); else if (s2.empty()) return std::max(s1.size()/2, 1u); else return min_edit_distance(s1, s2, zero_one_cost<char>(' ')); } std::string empty() const { return std::string(); } }; A: The operator() part says that objects of type str_dist_ can be "called", as though it were a function. The (const std::string& s1, const std::string& s2) tells us what the argument actually are. For example, say we have an object str_dist_ obj;, and two std::string objects, str1 and str2. Then we can write something like this int result = obj(str1, str2); Under the covers, the previous line is identical to int result = obj.operator()(str1, str2); Notice that the first set of parenthesis are part of the name of the member function operator(), while the second set actually lists the arguments. If you want more information, look up Functors or Function Objects. These are the terms used to refer to things such as str_dist_ objects, which have the operator() defined for them. If you google either of those terms, you're sure to find a lot of information. A: It's the parenthesis-operator (or "function-call operator"): Foo x; int n = x(12, 'a'); int m = x.operator()(12, 'a'); // equivalent Here the operator was declared as int Foo::operator()(int, char). A: It's the "function call operator", it allows an object to be used "as a function", i.e.: str_dist_ myObject; cout<<myObject("A string", "Another string"); // calls operator() The first two parentheses denote that it's the function call operator (as the + would denote that it's the + operator, etc.), then follows the arguments list. The whole point of overloading the function call operator is to create functors (function objects), that have several advantages over plain functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add parameters to Django class based generic view decorators? I have written a decorator to display success message on object creation: from django.contrib import messages def success_message(klass): def form_valid(self, form): response = super(klass, self).form_valid(form) messages.success(self.request, 'Object added successfully') return response klass.form_valid = form_valid return klass and use it to decorate class based generic view: @success_message class BandCreateView(CreateView): model = Band Now I want to parameterize the decorator so this is possible: @success_message('Band created successfully.') class BandCreateView(CreateView): model = Band How do I do it? I tried adding message parameter to success_message but the compiler complained about parameter count mismatch so I figure there must be another way. A: Looks like you have to use closure: def decorator(arg): def wrap(klass): ... return wrap because your call is evaluated to class BandCreateView(CreateView): ... BandCreateView = @success_message('Band created successfully.')(BandCreateView) note double call A: I previously did this kind of thing as a mixin, but a decorator makes more sense (and is a bit less of a hassle to add to classes). You might like to get the form instance's verbose name like the following, to eliminate the need to pass a message to the decorator: from django.utils.translation import ugettext_lazy as _ def ucfirst(value): return value[0].upper() + value[1:] def success_message(klass): __orig_form_valid = klass.form_valid def form_valid(self, form): response = __orig_form_valid(self, form) messages.success(self.request, _("%(object)s \"%(object_name)s\" was saved successfully.") % {'object': ucfirst(form.instance._meta.verbose_name), 'object_name': unicode(form.instance)}) return response klass.form_valid = form_valid return klass This will produce a success message something along the lines of: Customer "ACME Inc." was saved successfully. A: TL;DR Parameterless decorator is declared as a class -> class function. Decorator with parameters is declared as a higher order args -> (class -> class) function. It takes parameters and returns a function that will take class and return class (i.e. the “simple” decorator). Explanation An answer from a related thread by t.dubrownik literally saved me. Anyway, the syntax for decorators with arguments is a bit different—the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. Although he is talking about function decorators, the concept is applicable to class decorators as well. Here is what I got: from django.contrib import messages def success_message(message): def actual_decorator(klass): def form_valid(self, form): response = super(klass, self).form_valid(form) messages.success(self.request, message) return response klass.form_valid = form_valid return klass return actual_decorator Note how actual_decorator itself repeats the parameterless version of success_message and how success_message is now a higher order function because its return value is function itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selective URL rewriting from within a Firefox add-on? I'd like to create a Firefox add-on that rewrites certain URLs. For example, if the page attempts to load a file http://my.com/foo.js, I want to rewrite the URL so that it loads from http://my-other.org/bar.js. And I don't want it to look like a 302 redirect, because the request might have originated from an XHR call, and I don't want the browser to deny the request on a redirect on the grounds that it's cross-domain. I've looked in the TamperData and HttpFox source code to learn how to solve this. I've tried creating an observer that listens for http-on-modify-request, and within the listener, attempts to rewrite the URL. The problem is that the nsiHttpChannel object seems to let me do just about everything - override headers, cancel the request, capture the response, etc - except override the URL. Simply changing the content of the originalURI and URI attributes of nsiHttpChannel doesn't seem to work either. The only promising pointer I could find was to the HTTPS-everywhere addon, but the code there is rather intricate, and it feels like there ought to be a simpler way to achieve this. A: gliptak's answer is correct but now out of date. I wrote a very simple Firefox addon that does what you describe. You may use its source as a reference. // intercept and occasionally modify HTTP/HTTPS requests... let httpObserver = { observe: function (aSubject, aTopic, aData) { aSubject.QueryInterface(Ci.nsIHttpChannel); let url = aSubject.URI.spec; let modUrl = modifyUrlIfNeeded(url); if (modUrl){ // replace URL and referrer in request... let urlObj = ioService.newURI(modUrl, aSubject.URI.originCharset, null); aSubject.redirectTo(urlObj); } } }; observerService.addObserver(httpObserver, "http-on-modify-request", false); https://github.com/tristanisme/gahmm/blob/master/index.js A: We can do this my overriding the nsiHttpChannel with a new one, doing this is slightly complicated but luckily the add-on https-everywhere implements this to force a https connection. https-everywhere's source code is available here Most of the code needed for this is in the files IO Util.js ChannelReplacement.js (no longer in the source tree) We can work with the above files alone provided we have the basic variables like Cc,Ci set up and the function xpcom_generateQI defined. var httpRequestObserver = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel); var requestURL = subject.URI.spec; if(isToBeReplaced(requestURL)) { var newURL = getURL(requestURL); ChannelReplacement.runWhenPending(subject, function() { var cr = new ChannelReplacement(subject, ch); cr.replace(true,null); cr.open(); }); } } }, get observerService() { return Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); }, register: function() { this.observerService.addObserver(this, "http-on-modify-request", false); }, unregister: function() { this.observerService.removeObserver(this, "http-on-modify-request"); } }; httpRequestObserver.register(); The code will replace the request not redirect. While I have tested the above code well enough, I am not sure about its implementation. As far I can make out, it copies all the attributes of the requested channel and sets them to the channel to be overridden. After which somehow the output requested by original request is supplied using the new channel. P.S. I had seen a SO post in which this approach was suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: BES Vulnerability Management We try to follow security best practices by keeping software and device settings up to date and specifying whether or not applications can initiate specific types of connections, but I would like to be more proactive. I saw a blog from eEye regarding a free mobility scanning module (http://blog.eeye.com/general/sneak-peek-free-mobility-scanning-from-eeye) and wanted to know what other people are doing for vulnerability management?
{ "language": "en", "url": "https://stackoverflow.com/questions/7591028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a standard way to describe SSO token extraction from an HTTP request? I'm working on building a pluggable SSO architecture for web servers, where we could be using any SSO technology. This means I need to find the SSO token using headers, cookies, parameters, and/or resourceURI. So I need to teach my web server where to look for the SSO token to perform authentication, in a declarative manner ideally. My proposal: an XML format to describe where to locate the SSO token: <!-- from an arbitrary cookie --> <!-- from an arbitrary header --> <token> <token> <location>cookie</location> <location>header</location> <name>cookieName</name> <name>headerName</name> </token> </token> We can do the same thinkg for parameters, and for path elements we can specify "first", "last" or by position which path element to choose, or use regular expressions to match the path. So is there a standard way of "matching" elements of a full HttpRequest to extract a string?
{ "language": "en", "url": "https://stackoverflow.com/questions/7591029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Odd behaviour with Map in Groovy I was writing code and I noticed some odd behavior in Groovy when I am dealing with XML and Maps. I thought about it and can't figure out why is it happening and should it that way. I wrote sample code with 3 examples. Crucial difference between map1 & map3 is only on the following part: Map1: map1 << ["${it.name()}":it.value()] Map3: map3["${it.name()}"]=it.value() Here is full code, you can copy-paste it into Groovy console: def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map1 = [:] def node = new XmlParser().parseText(xml) node.each { map1 << ["${it.name()}": it.value()] } println map1 println map1["head"] println ">>>>>>>>>>>>>>>>>>>>>>" Map map2 = [:] map2 << ["head":"headHere"] map2 << ["body":"bodyHere"] println map2 println map2["head"] println "<<<<<<<<<<<<<<<<<<<<<<" def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map3 = [:] def node2 = new XmlParser().parseText(xml2) node2.each { map3["${it.name()}"]=it.value() } println map3 println map3["head"] The result that I am getting is following: [head:[headHere], body:[bodyHere]] null [head:headHere, body:bodyHere] headHere [head:[headHere], body:[bodyHere]] [headHere] Even thou map1 and map3 look the same, the result of map["head"] is totally different, first gives null and second gives the actual result. I don't understand why is it happening. I spent some time on it and still don't get it. I used .getProperty() to get info on a class, but it looks the same and feels the same on both maps and object inside. I tried couple more things and nothing gives me any idea on what is happening. I even tried different OS (Win XP, Mac OS) and still nothing. I don't have any ideas anymore, please can one some explain odd behavior, why is it happening and what is the difference between map << [key:object] and map[key] = object? Thank you. A: Here is a demonstration of this quirk of double quoted strings in Groovy: Double quoted strings are plain java.lang.String if there’s no interpolated expression, but are groovy.lang.GString instances if interpolation is present. groovy:000> m = [:] ===> {} groovy:000> tmp = "wat" ===> wat groovy:000> key = "${tmp}" ===> wat groovy:000> m << ["${key}": "hi"] ===> {wat=hi} groovy:000> m["${key}"] = "hi" ===> hi groovy:000> m ===> {wat=hi, wat=hi} groovy:000> m["wat"] = "fuuuuuu!" ===> fuuuuuu! groovy:000> m ===> {wat=hi, wat=fuuuuuu!} groovy:000> m.keySet().each { println it.class } class org.codehaus.groovy.runtime.GStringImpl class java.lang.String Enjoy ;) A: One thing that might help is, don't use GStrings for your keys. Groovy supports using objects directly as keys by wrapping them in parentheses. From the manual: Map keys are strings by default: [a:1] is equivalent to ["a":1]. But if you really want a variable to become the key, you have to wrap it between parentheses: [(a):1]. Fully working example: def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map1 = [:] def node = new XmlParser().parseText(xml) node.each { map1 << [ (it.name()): it.value() ] } println map1 println map1["head"] println ">>>>>>>>>>>>>>>>>>>>>>" Map map2 = [:] map2 << ["head":"headHere"] map2 << ["body":"bodyHere"] println map2 println map2["head"] println "<<<<<<<<<<<<<<<<<<<<<<" def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map3 = [:] def node2 = new XmlParser().parseText(xml2) node2.each { map3[it.name()] = it.value() } println map3 println map3["head"] The output is: [head:[headHere], body:[bodyHere]] [headHere] >>>>>>>>>>>>>>>>>>>>>> [head:headHere, body:bodyHere] headHere <<<<<<<<<<<<<<<<<<<<<< [head:[headHere], body:[bodyHere]] [headHere]
{ "language": "en", "url": "https://stackoverflow.com/questions/7591036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Getting timed out trying to check website availability I am using the following code to check the availability of websites : public boolean isSiteAvailable() { try { URL u = new URL("http://www.google.com"); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.connect(); int response=huc.getResponseCode(); if ((response >= 400) || (response < 200)) return false; return true; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("OOPSIE"); e.printStackTrace(); } return false; } However, I am getting the following message .. 09-28 19:45:41.487: WARN/System.err(28801): java.net.SocketException: The operation timed out 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.platform.OSNetworkSystem.connectStreamWithTimeoutSocketImpl(Native Method) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:115) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:244) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:533) 09-28 19:45:41.487: WARN/System.err(28801): at java.net.Socket.connect(Socket.java:1055) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927) 09-28 19:45:41.487: WARN/System.err(28801): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909) 09-28 19:45:41.487: WARN/System.err(28801): at corp.mithila.app.mithila.isSiteAvailable(mithila1.java:210) 09-28 19:45:41.487: WARN/System.err(28801): at corp.mithila.app.mithila$5.run(mithila1.java:121) 09-28 19:45:41.487: WARN/System.err(28801): at android.os.Handler.handleCallback(Handler.java:587) 09-28 19:45:41.487: WARN/System.err(28801): at android.os.Handler.dispatchMessage(Handler.java:92) 09-28 19:45:41.487: WARN/System.err(28801): at android.os.Looper.loop(Looper.java:123) 09-28 19:45:41.487: WARN/System.err(28801): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-28 19:45:41.487: WARN/System.err(28801): at java.lang.reflect.Method.invokeNative(Native Method) 09-28 19:45:41.487: WARN/System.err(28801): at java.lang.reflect.Method.invoke(Method.java:521) 09-28 19:45:41.487: WARN/System.err(28801): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 09-28 19:45:41.487: WARN/System.err(28801): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 09-28 19:45:41.487: WARN/System.err(28801): at dalvik.system.NativeStart.main(Native Method) A: added the following line to the code : huc.setRequestProperty("Connection", "close"); huc.setConnectTimeout(2000); // Timeout 2 seconds. this seems to have solved the problem....
{ "language": "en", "url": "https://stackoverflow.com/questions/7591042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Middleware class being create but process_template_response not executed I have defined a middleware class. and i have added it to the middleware_classes attribute in setting. When a request comes in, the middleware class gets created (the debugger catches the code when the breakpoint is on the class CommonFiilter(): line) Now i expect the function def process_template_response(self, request, response): to get called. I have debug point on the inside of the function and the debugger never traps the execution. The debugger, though, traps the execution at the line where the function name and parameters are defined. This is the class: class CommonFilter():#<---- debugger breaks here def process_template_response(self, request, response): #<--- debugger breaks here if response.template_name=='store/index2.html': #<--- NOT HERE (or after this line) catnames=getCategories() response.context_data.update({'catnames':catnames,'user':request.GET.get(key='user',default=None)}) return response Also tried this: class CommonFilter():#<---- debugger breaks here def process_template_response(self, request, response):#<---- debugger breaks here if response.template_name=='store/index2.html':#<--- NOT HERE (or after here) catnames=getCategories() response.context_data['catnames']=catnames response.context_data['user']=request.GET.get(key='user',default=None) return response Just in case, this is the setting MIDDLEWWARE_CLASSES variable: MIDDLEWARE_CLASSES = ( 'store.models.CommonFilter', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) store is an app in this project and ofcourse CommonFilter is defined in models.py. Why is the function process_template_response function not being executed? Thanks for your time and kind concern. A: from the docs: process_template_response() will only be called if the response instance has a render() method, indicating that it is a TemplateResponse.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List using Nodes we are learning about linked list using nodes and I'm not sure if i'm doing this right. We are suppose to just make a simple list but when I go to run the program, I'm getting nullpointerException pointing to showList() method but when I try to not use that method, then nothing prints out at all. Please any help is greatly appreciated. public class node { public int dataitems; public node next; node front; public void initList(){ front = null; } public node makeNode(int number){ node newNode; newNode = new node(); newNode.dataitems = number; newNode.next = null; return newNode; } public boolean isListEmpty(node front){ boolean balance; if (front == null){ balance = true; } else { balance = false; } return balance; } public node findTail(node front) { node current; current = front; while(current.next != null){ //System.out.print(current.dataitems); current = current.next; } //System.out.println(current.dataitems); return current; } public void addNode(node front ,int number){ node tail; if(isListEmpty(front)){ front = makeNode(number); } else { tail = findTail(front); tail.next = makeNode(number); } } public void printNodes(int len){ int j; for (j = 0; j < len; j++){ addNode(front, j); } showList(front); } public void showList(node front){ node current; current = front; while ( current.next != null){ System.out.print(current.dataitems); current = current.next; } System.out.println(current.dataitems); } public static void main(String[] args) { node x = new node(); x.printNodes(50); } } A: You do this node current; current = front; but you never initial front, so when you call current.next, current is null. So you can't get the next... As an aside, why not clean up the code and do node current = front; Also, class names in Java should be capitalized, so node should be Node. A: The problem has to do with the variable scoping of your addNode method. public void addNode(node front ,int number){ node tail; if(isListEmpty(front)){ front = makeNode(number); //reassigns the node front parameter } else { tail = findTail(front); tail.next = makeNode(number); } } Your assignment of "front" only assigns the makeNode(number) value to the local variable. You need to use this.front to assign the makeNode(number) to the instance variable of your node class or refactor your variable name. public void addNode(node front ,int number){ node tail; if(isListEmpty(front)){ //assigns a value to the member variable "front" of your node instance this.front = makeNode(number); } else { tail = findTail(front); tail.next = makeNode(number); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7591046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do you iterate over all values produced by a function? I am new to go, and I have found myself writing a few for loops which look like this: for element, err := producer.Produce(); err == nil; element, err = producer.Produce() { process(element) } where producer.Produce() is a function like reader.ReadString('\n') or fmt.Fscan(Reader, &token). I would much rather like to write for element := range elements { process(element) } but for now, I would be satisfied to know if there is a cleaner way to iterate over the output of these kinds of functions in go. In particular, is there a nice way to get rid of this annoying duplication in the init statement and the post statement of the for statement? A: I don't think there's anything quite as clean as what you're looking for. The idiomatic way to write it is: for { element, err := producer.Produce() if err != nil { break } process(element) } A: Here's a way to create a channel from such a method: elements := make(chan elementType) val send func() send = func() { if element, err := producer.Produce(); err == nil { elements <- element go send() } else { close(elements) } } go send() for element := range elements { process(element) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7591050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rails 3.0.9 auto_link linking text infront of http:// So when I use the auto_link function on this text also saw this on yammer...http://techcrunch.com/2011/09/27/former-facebook-vp-chamath-palihapitiya-leads-17m-round-in-enterprise-social-networking-platform-yammer "yammer...http://techcrunch.com/2011/09/27/former-facebook-vp-chamath-palihapitiya-leads-17m-round-in-enterprise-social-networking-platform-yammer" gets auto_linked the "yammer..." gets inside the href link. Any one else having issues with this and is there a solution? A: I'm not sure why this particular behavior is exhibited, but I would guess that it has to do with auto_link trying to be protocol agnostic. Aaron Patterson has indicated that this method is inherently difficult to secure and requires a faster release cycle than Rails has, so they have removed it from Rails 3.1 and put it in a separate gem that adds the method back into ActionView::Helpers::TextHelper. You can probably use this gem for Rails 3.0.9 and it might behave differently in this situation. https://github.com/tenderlove/rails_autolink Edit: A quick and dirty hack to fix this for you would be to do the following in a helper: def your_auto_link(content) auto_link content.gsub(/([^ ])http:/, '\1 http:') end
{ "language": "en", "url": "https://stackoverflow.com/questions/7591053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Classes of referenced EJB project not found in (the referencing) Web project I'm learning J2EE and EJB and I've run into a strange problem. This is my project setup: I'm using Glassfish 3.1 and Eclipse 3.7. I have two projects in Eclipse: * *An EJB 3.0 compliant project, myEjbProject *A Dynamic Web Project, myWebProject I'm injecting an EJB session bean mySessionBeanPackage.mySessionBean from myEjbProject into a servlet myServletPackage.myServlet in myWebProject and then (in the servlet) calling a simple method defined in the session bean. I've provided myWebProject with a reference to myEjbProject (using the Properties -> Project References dialog). However, for some reason, the server is unable to find the session bean. The exact error I get is: SEVERE: Class [ LmySessionBeanPackage/mySessionBean ] not found. Error while loading [ class myServletPackage.myServlet ] Note that both the EJB project and the web project have been published to the server and I've double-checked that the class file generated for the bean is, in fact, present on the server (so I can't think of a reason why the server isn't able to find them). Can anyone tell me what I'm doing wrong? I've also tried * *adding the classes folder of myEjbProject explicitly to the Java Build Path -> Libraries list of myWebProject. This is in addition to the project reference (although I think adding a project reference should have sufficed in the first place). Anyway, it makes no difference (same error message as before). *creating a JAR file from myEjbProject using the Export -> EJB Jar File option (I don't want to get into writing an Ant script at the moment). I then put this JAR in the Java Build Path -> Libraries section of myWebProject. This approach does not solve the problem either (same error message as before). *modifying the session bean to have * *no interface *a local interface *a remote interface and modifying the injection accordingly. E.g., for a bean with only a local interface, I used: @EJB mySessionBeanPackage.mySessionBeanLocal myBean This approach did not solve the problem either (same error message as before). *doing away with myEjbProject altogether and adding the session bean to myWebProject as myServletPackage.mySessionBean (same package as the servlet). In this case, I can inject the session bean successfully into the servlet using @EJB mySessionBeanPackage.mySessionBean myBean *doing away with myEjbProject altogether and adding the session bean to myWebProject as mySessionBeanPackage.mySessionBean (a new package). In this case also, I can inject the session bean successfully into the servlet using @EJB mySessionBeanPackage.mySessionBean myBean A: I would recommend taking a look at the actual EAR that Eclipse packages and deploys to the server. You can do this by exporting the EAR project (right click on EAR project -> export -> Java EE -> EAR file) I think the step you are missing is to add the EJB project to the WEB project's MANIFEST file. But just in case you are missing a few more steps I would check the following: * *EJB and WEB projects are modules of the EAR project. Right click the EAR project -> properties -> Deployment Assembly -> Add -> Project -> select the EJB and the WEB project. If you export your EAR project now you will notice that the EJB and the WEB project is packaged with the EAR. *Add EJB project to MANIFEST of WEB project. Right click the WEB project -> properties -> Deployment Assembly -> Manifest entries -> Add -> select the EJB project. You can open the MANIFEST.MF file and see that it now includes the EJB project. Also I like adding the EJB project to the WEB project build path just so that it is included in the WEB's classpath: Right click WEB project -> properties -> Java Build Path -> Projects -> Add -> Select the EJB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Converting between LINQ expression types Does anyone know of a tool which converts between the 'types' of linq query expression? ie: a) var foo = from c in customers select... b) var foo = customer .Where(... I'm more familiar with a), but to use dynamic linq b) is required so it'd be nice to easily convert all my existing queries. I've had a bit of a look at Linqer and LinqPad but can't see such a function - perhaps its in there somewhere. Thanks A: It's definitely in LINQPad - but you only see it when querying against databases: You even get the SQL and IL that was created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7591061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java: Get group names using Pattern class? I am trying to use Pattern and Matcher class to extract matches out of a string. My string is as follows: $abc$12def$def$$11$ I want to get $abc$, $def$ and $11$ from this string. I thought of using the following regex: \$(.*)\$ (This works fine in normal pattern matching). My java program is unable to get these. All it returns me is the entire string. Here is my program: import java.util.regex.Matcher; import java.util.regex.Pattern; public final class dollar { private static String REGEX = "\\$(.*)\\$"; private static String INPUT = "$12f$$555$button button$abc0$"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object boolean found = m.find(); while (found) { System.out.println("TEST:" + m.start()); System.out.println("TEST:" + m.end()); found = m.find(); } } } I also tried the following: m.matches() m.groupCount() m.group(1) m.group(2) But this does not work too. How to get this done? Can it be done on jdk6 or something is available in jdk7? Appreciate all the help!!! A: your problem is that * is greedy. Try \$(.*?)\$ instead $abc$12def$def$$11$ = $ followed by 0 or more [anything] (which happens to be abc$12def$def$$11 in this case) followed by $ using *? makes the regex engine stop consuming characters as early as possible
{ "language": "en", "url": "https://stackoverflow.com/questions/7591063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do Java programs run without defining the main method? I was looking through some Java source and noticed that the main method wasn't defined. How does Java compile source code without knowing where to start? A: There is a difference between running and compiling. Java code can be compiled incrementally. You only need a main somewhere to run the code. Java "knows where to start" because the compiler is smart enough to arrange all the dependencies when you compile. Indeed, if you are building a web application in some sort of standard container, your code probably won't have a main method. The container does, but you just write components that plug in. A: The main method is only used when the Java Virtual Machine is executing your code. Code cannot be executed without a main method but it can still be compiled. When compiling code, you usually specify a set of files on the command line e.g. javac MyClass1.java MyClass2.java The Java compiler (javac) examines each class you passed to it and compiles it into a .class file. One reason Java source code may be missing a main method is because it is designed to be used as a library, instead of being executed. Something you may find interesting: although the source code compiled by the Java compiler does not need a main method, the source code for the Java compiler itself does have a main method. A: // works only on java 1.6 or less versions public class Test{ // this is static block static{ System.out.println("This is static block"); } } In Java (while running): * *all static members are identified. *all variables and methods are initialized *static block is executed A: how does Java compile run your source without knowing where to start? I assume you meant run (instead of compile), since you don't need a main() to compile. In which case, an explicitly declared main() method is only one of the ways to run a program. You can use some frameworks to execute your code. They have got the main() (talking about console applications only) and require you to declare an entry point only. This is how you run unit tests, for example. A: Every single Java class you write isn't intended to be an entry point for running, that's why. I'd say that's the rule rather than the exception. A: Yes, we can run a java program without main method, for this we will use static function Following is the code: class Vishal { static { System.out.println("Hi look program is running without main() method"); } } This will output "Hi look program is running without main() method" A: public class Test{ // this is static block static{ System.out.println("This is static block"); System.exit(0); } } This will run fine in JDK version 1.6 or earlier. In version 1.7 and later it is necessary to include a main() function. A: We can compile a program without main method. Actually running a program differs from compiling it.Most of the libraries do not contain a main method. so for compiling there is no problem whether the program contains main method or not. A: package com.test; public class Test { static { System.out.println("HOLAAAA"); System.exit(1); } } //by coco //Command line: //java -Djava.security.manager=com.test.Test A: One of the way is static block but in previous version of JDK not in JDK 1.7. class A3{ static{ System.out.println("static block is invoked"); System.exit(0); } } A: This will execute without any error and without main() method abstract class hello extends javafx.application.Application { static { System.out.println("without main method"); System.exit(0); } } A: If you don't want to use static block too, it can be done following way public class NoMain { private static final int STATUS = getStatus(); private static int getStatus() { System.out.println("Hello World!!"); System.exit(0); return 0; } } However, please note that this is for Java 6 version. This doesn't seem to work in Java 7 and above A: Yes, We can Compile and Execute a java program without Main function. Instead of that we can use static block to compile and Execute the program. It is supported only for previous versions of java. But now it is not supported...
{ "language": "en", "url": "https://stackoverflow.com/questions/7591064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: I want to call 20 UIView files random and non-repeating in xcode I have a game where each click of the "next" button is supposed to call one of 20 subviews in at random order without repeating any of the UIViews. At count 20 the code should call a new UIView for scores. Can someone pls. help. LasloV in San Francisco
{ "language": "en", "url": "https://stackoverflow.com/questions/7591065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create a thumbnail from only part of an image I'm creating a thumbnail right now like this: // create thumbnail and save var image = Image.FromFile(Server.MapPath(imageFilename)); var thumb = image.GetThumbnailImage(image.Width / 10, image.Height / 10, () => false, IntPtr.Zero); thumb.Save(Server.MapPath(Path.ChangeExtension(imageFilename, "thumb" + Path.GetExtension(imageFilename)))); All it does is take the image, create a thumbnail 1/10th of the size, and save it. I'd like to be able to create a thumbnail out of only part of the image. So say I have an image that is 200px by 200px. How can I take a 100px by 100px crop out of the middle of the image, and create a thumbnail out of it? A: Check out the code here for cropping an image: https://web.archive.org/web/20141006051530/http://bobpowell.net/changing_resolution.aspx using(Bitmap bitMap = (Bitmap)Image.FromFile("myimage.jpg")) // assumes a 400 * 300 image from which a 160 * 120 chunk will be taken { using(Bitmap cropped = new Bitmap(160,120)) { using(Graphics g=Graphics.FromImage(cropped)) { g.DrawImage(bitMap, new Rectangle(0,0,cropped.Width,cropped.Height),100,50,cropped.Width,cropped.Height,GraphicsUnit.Pixel); cropped.Save("croppedimage.jpg",ImageFormat.Jpeg); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7591067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amazon Web Services + ASP.NET MVC 3 + MySql I have an application built on ASP.NET MVC 3 that uses Entity Framework to connect to MySql for its data store. I am looking at hosting options, and Amazon looks like a very tempting place for me to host as the userbase will be shifting between both extremes (massive audience and no audience). 1) Is this possible? 2) Is it a bad idea? 3) If it is possible, what do I need from AWS to make it work? Any help would be extremely helpful, I'm looking at setting the host up this week. Thanks in advance! A: The issue with AWS is that administration and configuration of the server is on you, you will have to configure the server and IIS, I would suggest you to use appharbor instead, it's a PaaS hosting that uses Git for deployments and it's extremely pleasant to use, it's been in beta for almost a year and I find it very reliable, I have a production app on it without issues. Its infrastructure runs under AWS and you get to scale when you have to by adding more web servers on the control panel, and you dont have to configure the server yourself. A: I would like to second the appharbor vote with the following two cents of advice... I first tried to use MySql with appharbor using their MySql integrated service, but I found that it was difficult to use with multiple apps on the same database. I like to keep the admin app separate from the user app and I found that couldn't be done using appharbor best practices. I instead opted to use Amazon RDS directly from my appharbor app. You need to make sure they are in the same availability zones for performance, but this is working well for me. I also keep an Amazon EC2 instance for worker processes that I run directly with the Task Scheduler on Windows b/c appharbor doesn't have support for worker processes yet. This setup is working well for us... My other gripe was some down time they had this past weekend... but this is bound to happen with any service, and they got it back up very quickly. They also now have integrated add-on StillAlive which I haven't used yet but am excited about. EDIT MAY 2012 : AH now has options for background workers, check this blog post http://blog.appharbor.com/2012/4/18/scheduled-tasks-using-quartz-and-appharbor-background-workers
{ "language": "en", "url": "https://stackoverflow.com/questions/7591074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }