text
stringlengths
8
267k
meta
dict
Q: How to add data dynamically into the spinner from xml Hello I'm downloading XML and parsing data. I want to add data to the spinner. The data updates every time I run the application. public class Main extends ListActivity { TextView valueTextView; HashMap<String, String> name=null; private HashMap<String, String> array_spinner[]; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main) ArrayList<HashMap<String, String>>mylist = new ArrayList<HashMap<String, String>>(); String xml = XMLfunctions.getXML(); Document doc = XMLfunctions.XMLfromString(xml); NodeList nodes = doc.getElementsByTagName("Table"); Toast.makeText(Main.this, "ID '" + nodes.getLength(),Toast.LENGTH_LONG).show(); for (int i = 0; i < nodes.getLength(); i++) { HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element)nodes.item(i); map.put("id", XMLfunctions.getValue(e, "id")); map.put("name", "Name:" + XMLfunctions.getValue(e, "name")); map.put("Score", "Score: " + XMLfunctions.getValue(e, "score")); mylist.add(map); } valueTextView = (TextView)findViewById(R.id.selected); Spinner s = (Spinner)findViewById(R.id.spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } Its incomplete code I don't know how to apply SpinnerAdapter Please anyone help me Thank you Abhishek A: I would take your Hashmap and create an Array instead, without knowing how you want your Spinner to work I would combine Name and Score. Then make the call to the adapter like this: String[] nameScore = (xml name score data in string array) ArrayAdapter adapter= new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameScore); s.setAdapter(adapter); Anything more complex than that then you will have to make a custom adapter. Answer::: Here is what you do. Create a Class called NameData then set properties with ID, name and score. public class NameData { public int id; public String name; public int score; public NameData(int i, String n, int s) { this.id = i; this.name = n; this.score = s; } } Next create a method to connect to your data parse it and put each item into this NameData Object public List<NameData> getNameData() { List<NameData> list = new LinkedList<NameData>(); //get data from url and parse it to your namedata object // /.....for loop (psuedo coding here... list.add(new NameData(id, name, score)); // end for loop return list; } then you will need to make a custom List adapter that uses a layout you design for the rows.: private class ItemsAdapter extends BaseAdapter { NameData[] items; public ItemsAdapter(Context context, int textViewResourceId, NameData[] md) { this.items = md; } @Override public View getView(final int position, View convertView, ViewGroup parent) { TextView text1; View view = convertView; if (view == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = vi.inflate(R.layout.yourRowForListlayout, null); } text1 = (TextView) view.findViewById(R.id.yourRowForListlayoutTextView); text1.setText("" + (position+1)); return view; } @Override public int getCount() { return this.items.length; } @SuppressWarnings("boxing") @Override public Object getItem(int p) { return p; } @Override public long getItemId(int p) { return p; } } then in your creation code you can take this list and add it directly to the adapter: List<NameData> list = getNameData(); adapter = new ItemsAdapter(this, R.layout.yourRowForListlayout, list.toArray(new NameData[list.size()]) ); setAdapter(adapter); And thats the way I would do it for a custom list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to reference a C# Class Library project in Visual Studio 2010? I am new to visual studio and was wondering how to setup visual studio 2010 so that I can reference my C# windows class library project? I currently have a solution with 2 projects - C# library project and a unit test project. What is the best way to create multiple clients that will use this library? Should they be their own solution or just another project in the library solution? How do I use the classes in the library function from the project that references the library project? A: You can add a reference to a library by doing a rightclick on the references node in the solution explorer and selecting the req. lib... When all you consuming apps are located within the same solution I would prefer to place the lib also inside the sln, otherwise I would use an extra sln A: Right click on the Client project "References" - > Add Reference Go to the Projects tab if the class library is in the same solution. Else Browse and select the dll of the class library. If Class library is not going to release as common dll for multiple projects, it's better to add them all to the same solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to retrieve data from MarketDataIncrementalRefresh message? How can I retrieve the following values from a MarketDataIncrementalRefresh? * *Symbol/Instrument *Offer *Bid *OfferSize *BidSize I'm familiar with Quote message handling, for example: If quote.isSetOfferPx Then Offer = quote.getOfferPx.getValue Tried the same approach on MarketDataIncrementalRefresh, but there are no such methods, and isSetField always returns false although the field does exist. MarketDataIncrementalRefresh Example message: 8=FIX.4.29=22535=X34=349=ABC52=20110928-12:47:53.31656=TARGETCOMPID262=634528216663837491268=2279=0269=0278=155=AUD/CAD270=1.0126515=AUD271=1000000346=1279=0269=1278=255=AUD/CAD270=1.0130715=AUD271=1000000346=110=094 A: Problem solved. In order to retrieve data from MarketDataIncrementalRefresh, is build of Groups. Hence, I needed to get each group and retrieve its' data individually. Method is: Public Overrides Sub onMessage(message As QuickFix42.MarketDataIncrementalRefresh, session As SessionID) Try If message IsNot Nothing Then Dim group As New MarketDataIncrementalRefresh.NoMDEntries() For i = 1 To message.getNoMDEntries.getValue group = message.getGroup(i, group) If group.isSetSymbol Then Dim l_symbol As String = group.getSymbol().getValue If group.getMDEntryType().getValue() = "0"c Then SetBid(l_symbol, group.getMDEntryPx().getValue()) If group.isSetMDEntrySize Then SetBidSize(l_symbol, group.getMDEntrySize().getValue) End If End If If group.getMDEntryType().getValue() = "1"c Then SetOffer(l_symbol, group.getMDEntryPx().getValue()) If group.isSetMDEntrySize Then SetOfferSize(l_symbol, group.getMDEntrySize().getValue) End If End If End If Next End If Catch ex As Exception End Try End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7606218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i give pager to drupal_add_tabledrag i am using the function drupal_add_tabledrag. Now i want pager also in that. Is there any option? Thanks A: That won't work, tabledrag will only work if all items are on the same page. Adding a pager is illogical as it will become impossible to manage the weights of the items when spread over 2 or more pages. A: drupal_add_tabledrag is js script, work with special form elements and doesn't depend on pager_query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create a cookie with a non url encoded value using JQuery and the Cookie plugin I am creating a cookie on the client side and adding 3 string values in it separated by commas. The string have special characters. The problem is when I am fetching the value of the cookie in my code behind, the cookie has value as follows:- 4%2CHealth%20Related%2C%2Fmysite%2FYourKB%2FHealth-Related I want to get rid of these % signs and values.. Is replacing these characters the only way? How can I make my cookie not have these values and just simple text with some special characters? edit 1 I am creating cookie like this now but still the problem persists. Please help me out. $.cookie('MyCookie', unescape(myString), { path: '/' }, { expires: 30 }); A: I know this thread is ancient, but I just ran into this and came across the raw setting. Setting it to true fixed the issue for me. A: For completeness those %xx characters are url encodings of certain characters that are not allowed in URLs. So: %2C is a comma and %2F is a forward slash. Taking that into account, where are you checking the value of the cookie again? This code works and gives you the correct value as an alert: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> </script> <script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script> </head> <body> <script language="javascript"> <!-- $(function(){ var myString = '4%2CHealth%20Related%2C%2Fmysite%2FYourKB%2FHealth-Related'; $.cookie('MyCookie', unescape(myString) ); alert($.cookie('MyCookie')); }); --> </script> </body> </html> So basically your code above should work, but if you are checking on the server make sure your server-side technology decodes the value as well. In ASP.NET this is done automatically when you call Request.Cookies["MyCookie"].Value but AFAIK the browser will transmit it only as a url encoded value so it has to be decoded again on the server. HTH Alex
{ "language": "en", "url": "https://stackoverflow.com/questions/7606230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to view item in browser based on its key in Python GAE I'm using python GAE with webapp. I have a form for a user to create a object in the database, something like: class SpamRecord(db.Model): author = db.ReferenceProperty(Author, required=True) text = db.StringProperty() After it's created, the user is redirected to a page whose URL contains that object's key... using code such as: spam = SpamRecord(author=author, text=text) spam.put() new_spam_key = spam.key() self.redirect("/view_spam/%s" % new_spam_key) And this mostly works, with me being able to view items at: sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQYy8oJDA sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY_boJDA However, there's an occasional key that won't work. Here are 2 recent examples of pages that won't load and return HTTP 404 not found errors: sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-5MJDA sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-boJDA My html-mappings.py contains the following mapping: (r"/view_spam/(\w+)", ViewSpamPage) And the ViewSpamPage looks something like: class ViewSpamPage(webapp.RequestHandler): def get(self, spam_id): self.response.out.write("Got here") Can anyone offer any insight as to why this is occurring and how it may be prevented? Thanks very much! A: In regular expressions, \w doesn't match hyphens. (It will match underscores.) For that second pair of keys, this'll result in only passing part of the key to your handler. In your URL pattern, try r"/view_spam/(.*)" instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Message sent to deallocated instance -- short and simple This has to be very basic, but I don't see the problem. The program crashes whenever the following code block is executed. Analyzer reports a possible memory leak: if (anImage) { eventImageView.frame = defaultEventImageFrame; UIImage *scaledImage = [anImage scaleToFitWithin:defaultEventImageFrame.size interpolationQuality:kCGInterpolationHigh]; eventImageView.backgroundColor = [UIColor colorWithPatternImage:scaledImage]; } The message is -[UIImage release]: message sent to deallocated instance 0x1129d920* Instance 0x1129d920 is scaledImage I tried adding retains and releases, like this if (anImage) { eventImageView.frame = defaultEventImageFrame; UIImage *scaledImage = [[anImage scaleToFitWithin:defaultEventImageFrame.size interpolationQuality:kCGInterpolationHigh] retain]; eventImageView.backgroundColor = [UIColor colorWithPatternImage:scaledImage]; [scaledImage release]; } and still get the error message. So I tried replacing the assignment with a copy, like this if (anImage) { eventImageView.frame = defaultEventImageFrame; UIImage *scaledImage = [anImage copy]; eventImageView.backgroundColor = [UIColor colorWithPatternImage:scaledImage]; } And the problem is gone. Checking the scaleToFitWithin method, I see it returns an autoreleased object: - (UIImage *) scaleToFitWithin:(CGSize) newSize interpolationQuality:(CGInterpolationQuality)quality{ CGSize originalImageSize = self.size; CGSize newImageSize; if (originalImageSize.width <= originalImageSize.height) { newImageSize.width = self.size.width * newSize.width / self.size.width; newImageSize.height = self.size.height * newSize.width / self.size.width; } else { newImageSize.width = self.size.width * newSize.height / self.size.height; newImageSize.height = self.size.height * newSize.height / self.size.height; } return [[[self normalize] resizedImage:newImageSize interpolationQuality:kCGInterpolationHigh] autorelease]; } So there is something about memory management that I'm not understanding. What is the problem likely to be? A: The problem is most likely that the scaleToFitWithin:interpolationQuality: method is calling autorelease on an object which has already previously been autoreleased. This can occur if you initialise the UIImage using a temporary constructor, like +[UIImage imageWith...], earlier in the same method you call the scaling method from. The reason it works when you use [anImage copy] is because the behaviour of the copy constructor is such that the object returned to you has already had retain called on it (so it has a local retain count of 1 and zero autoreleases). What happens at the end of the current run loop is: the autorelease pool which is currently in use is drained, and as a part of that two release messages will be sent to the UIImage. When the first one is sent, the application then runs off and calls dealloc on the image, because the retainCount has decreased to zero. When the second one is sent, the application throws an exception because a message is being sent to an object which was previously deallocated. Try removing the autorelease message from the scaleToFitWithin:interpolationQuality: method. Even if your resizedImage:interpolationQuality: method IS returning a new object, you should only be calling autorelease in that method rather than the scaling method. A: It seems that the method resizedImage:interpolationQuality: itself returns an autoreleased object and you are again autoreleasing it in the reutun statement. Just remove the autorelease from the return statement, return [[self normalize] resizedImage:newImageSize interpolationQuality:kCGInterpolationHigh]; Then you don't have to retain/release or copy the returned object in if (anImage) {...} block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should my Rails before_validation callbacks handle bad data? I have several before_validation callbacks that operate on the attributes being set on my model. I run into trouble when I have a situation like this: class Foo < ActiveRecord::Base before_validation :capitalize_title validates :title, :presence => true def capitalize_title title.upcase end end I write a test to ensure that 'nil' title is not allowed, but the test gets an error because the nil.upcase is not defined. I'd like to handle this error, but I already have error handling that runs after before_validation callbacks. I don't want to put checks around all of my before_validation callbacks to make sure the data exists, if I can avoid it. Is there a clean or accepted way to deal with this type of situation? A: Just check if you have a title. And don't forget to save the modified title. def capitalize_title title = title.upcase if title end If you need to patch things up with a before_validation hook then you're stuck with taking care of invalid data in two places. If your validation was complicated you could factor it into two pieces: one piece that has to be true before the before_validation can run and one piece that has to be true after the before_validation has run: before_validation :mangle_data validate :data_is_okay #... def mangle_data return if(!data_is_mangleable) #... mangle away end def date_is_okay if(!data_is_mangleable) # complain end if(!data_is_properly_mangled) # complain some more end end def data_is_mangleable return false if(thing.nil?) # etc. end def data_is_properly_mangled # check that stuff that the before_validation hook doesn't # have to care about. end
{ "language": "en", "url": "https://stackoverflow.com/questions/7606244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get the value of a disabled text field in jsp I am having a dropdown box and a 5 textfields( all disabled). I am entering data into textfield by using javascript, from the dropdown(what ever value is present in the dropdown, goes into the text fields). Now, when the submit button is clicked, I want to get the value from this text field in the action class(java). On testing, I was getting "null" [getParameterValues("textfieldname") is what I have done]. When I removed the disabled, I was getting the value. So, how can I get the value while the disabled, is applied to the text field ? A: Instead of disable them make them readonly. <input type="text" name="nameOfTextField" readonly="readonly" /> A: if you want the field to be disabled you can use an hidden input like this: <input type="text" id="nameVisible" disabled="disabled" /> <input type="hidden" name="nameObj" id="nameObj"/> when you load page, you set value in both fields via DOM in this way you'll see the input disabled on the page, and you'll get the hidden value when you submit it. A: If you still want text fields to be disabled, double them: one with disabled, other with hidden type. Example: <select name="selectedItem"> <option value="1" selected>A</option> <option value="2" selected>B</option> </select> <input name="iname" value="${selectedItem}" disabled /> <input name="inameh" value="${selectedItem}" type="hidden" /> Now the iname field will be visible at site (disabled), and you can get the choosen value from inameh (hidden) with: javascript: getParameterValues("inameh") java: request.getParameterValues("inameh")
{ "language": "en", "url": "https://stackoverflow.com/questions/7606251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why RewritePath changes the Browser Url? I have an ASP.NET 4 HttpModule (see code below). When the url path starts with "/1.0" I want Cassini/IIS to go to MyService.svc. However, I don't want to show "MyService.svc" to the user (i.e. no update to the url in the browser). I want the user to see "www.something.com/1.0". I was pretty sure that RewriteUrl isn't supposed to change the browser url, but in my case it does. Any idea why? public void Init(HttpApplication context) { context.BeginRequest += delegate { HttpContext ctx = HttpContext.Current; const string BasePath = "~/1.0"; if (path.StartsWith(BasePath, StringComparison.OrdinalIgnoreCase)) { ctx.RewritePath("~/MyService.svc", "this/is/a/path", string.Empty, false); } }; } P.S. I cannot use ASP.NET Routing because of the period/dot in the Url (see ASP.NET MVC Route IDs with a period). A: Looks like you have the same problem as described here: ASP.NET RewritePath not working as expected / URL in browser changing Add the trailing slash to the url: ctx.RewritePath("~/MyService.svc/", "this/is/a/path", string.Empty, false); Also, I'm not sure if WCF engine would preserve PathInfo for you. Possibly you'll have to pass parameters with the URL as QueryString. A: You need url routing of ASP.NET, and it's available since .NET 3.5 SP1. For your case, I think it's easier to "route" instead of rewriting, and it's simpler to use. Why? MSDN said this: In ASP.NET routing, you define URL patterns that contain placeholders for values that are used when you handle URL requests. At run time, the pieces of the URL that follow the application name are parsed into discrete values, based on a URL pattern that you have defined. For example, in the request for http://server/application/Products/show/beverages, the routing parser can pass the values Products, show, and beverages to a handler for the request. In contrast, in a request that is not managed by URL routing, the /Products/show/beverages fragment would be interpreted as the path of a file in the application. You can also use the URL patterns to programmatically create URLs that correspond to the routes. This enables you to centralize the logic for creating hyperlinks in your ASP.NET application. ASP.NET Routing versus URL Rewriting ASP.NET routing differs from other URL rewriting schemes. URL rewriting processes incoming requests by actually changing the URL before it sends the request to the Web page. For example, an application that uses URL rewriting might change a URL from /Products/Widgets/ to /Products.aspx?id=4. Also, URL rewriting typically does not have an API for creating URLs that are based on your patterns. In URL rewriting, if you change a URL pattern, you must manually update all hyperlinks that contain the original URL. With ASP.NET routing, the URL is not changed when an incoming request is handled, because routing can extract values from the URL. When you have to create a URL, you pass parameter values into a method that generates the URL for you. To change the URL pattern, you change it in one location, and all the links that you create in the application that are based on that pattern will automatically use the new pattern. See ASP.NET Routing in MSDN Library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to use handler to run a task in background I am using the following code to to access web service and it's showing me an error. The application is not responding. package com.android.webservice; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class WebServiceActivity extends Activity { private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; private static final String METHOD_NAME = "HelloWorld"; private static final String NAMESPACE = "http://tempuri.org/"; private static final String URL = "http://192.168.1.19/TestWeb/WebService.asmx"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button getquote = (Button) findViewById(R.id.getquote); getquote.setOnClickListener(new OnClickListener() { public void onClick(View v) { TextView result1; result1=(TextView)findViewById(R.id.result1); try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); EditText CompanyName = (EditText) findViewById(R.id.CompanyName); String val1 = (CompanyName.getText().toString()); request.addProperty("passonString", val1); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet=true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = (Object)envelope.getResponse(); result1.setText(result.toString()); } catch (Exception e) { result1.setText(e.getMessage()); } } }); } } May be because this is running in UI thread, I want to run it in background using handler. I am new in this field so I'm having problems to write it in background thread. Can anyone please give me directions on how to write the code inside handler? Thanks A: try this:: AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute private class xyz extends AsyncTask<Void, Void, Void> { private final ProgressDialog dialog = new ProgressDialog(tranning.this); @Override protected void onPreExecute() { this.dialog.setMessage("Please Wait..."); this.dialog.show(); // put your code which preload with processDialog } @Override protected Void doInBackground(Void... arg0) { // put your code here return null; } @Override protected void onPostExecute(final Void unused) { if (this.dialog.isShowing()) { this.dialog.dismiss(); } } } and use this in main :: new xyz().execute(); For more Elaboration . . . . . . . . . . . . . . . . . . . . . . . A: You should Use AysncTask to do this work in background http://labs.makemachine.net/2010/05/android-asynctask-example/
{ "language": "en", "url": "https://stackoverflow.com/questions/7606254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to have a "Create View" with multiple dynamic fields? I need to be able to have multiple so-called "create" forms in my view. I need advice as to how to go about achieving it. My form basically allows a user to create passenger details / book for several passengers depending on the number they have selected from a dropdownlist. Using javascript, more div's a displayed to cater to their selection, up to a maximum of 3. How would I go about creating these passengers on my model through a single submit button though? How would I collect these values? There are a total of 3 divs, and the more passenger details the user wants to book for, the more divs are shown.My view currently looks like so: <h2>Booking</h2> <div class="editor-label"> <%=Html.Label("Select number of passengers") %> </div> <div class="editor-field"> <%=Html.DropDownList("PassengerNumber", new List<SelectListItem> { new SelectListItem{Text="1", Value="1"}, new SelectListItem{Text="2", Value="2"}, new SelectListItem{Text="3", Value="3"} })%> </div> <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div id="div1"> <h2>Passenger Details 1</h2> <div class="editor-label"> <%= Html.LabelFor(model => model.flight_number) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.flight_number, ViewData["Flight_Number"]) %> <%= Html.ValidationMessageFor(model => model.flight_number) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.title) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.title) %> <%= Html.ValidationMessageFor(model => model.title) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.first_name) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.first_name) %> <%= Html.ValidationMessageFor(model => model.first_name) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.last_name) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.last_name) %> <%= Html.ValidationMessageFor(model => model.last_name) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.date_of_birth) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.date_of_birth) %> <%= Html.ValidationMessageFor(model => model.date_of_birth) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.passport_number) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.passport_number) %> <%= Html.ValidationMessageFor(model => model.passport_number) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.address) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.address) %> <%= Html.ValidationMessageFor(model => model.address) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.phone) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.phone) %> <%= Html.ValidationMessageFor(model => model.phone) %> </div> </div> <br /> <div id="div2"> <h2>Passenger Details 2</h2> <div class="editor-label"> <%= Html.LabelFor(model => model.flight_number) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.flight_number, ViewData["Flight_Number"]) %> <%= Html.ValidationMessageFor(model => model.flight_number) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.title) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.title) %> <%= Html.ValidationMessageFor(model => model.title) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.first_name) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.first_name) %> <%= Html.ValidationMessageFor(model => model.first_name) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.last_name) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.last_name) %> <%= Html.ValidationMessageFor(model => model.last_name) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.date_of_birth) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.date_of_birth) %> <%= Html.ValidationMessageFor(model => model.date_of_birth) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.passport_number) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.passport_number) %> <%= Html.ValidationMessageFor(model => model.passport_number) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.address) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.address) %> <%= Html.ValidationMessageFor(model => model.address) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.phone) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.phone) %> <%= Html.ValidationMessageFor(model => model.phone) %> </div> </div> <br /> <div id="div3"> <h2>Passenger Details 3</h2> <div class="editor-label"> <%= Html.LabelFor(model => model.flight_number) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.flight_number, ViewData["Flight_Number"]) %> <%= Html.ValidationMessageFor(model => model.flight_number) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.title) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.title) %> <%= Html.ValidationMessageFor(model => model.title) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.first_name) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.first_name) %> <%= Html.ValidationMessageFor(model => model.first_name) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.last_name) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.last_name) %> <%= Html.ValidationMessageFor(model => model.last_name) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.date_of_birth) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.date_of_birth) %> <%= Html.ValidationMessageFor(model => model.date_of_birth) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.passport_number) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.passport_number) %> <%= Html.ValidationMessageFor(model => model.passport_number) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.address) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.address) %> <%= Html.ValidationMessageFor(model => model.address) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.phone) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.phone) %> <%= Html.ValidationMessageFor(model => model.phone) %> </div> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%= Html.ActionLink("Back to List", "Index") %> </div> <script type="text/javascript"> $(document).ready(function () { $("#div2").hide(); $("#div3").hide(); }); $("#PassengerNumber").change(function () { if ($("#PassengerNumber").val() == "1") { $("#div2").hide(); $("#div3").hide(); } if ($("#PassengerNumber").val() == "2") { $("#div2").show(); $("#div3").hide(); } if ($("#PassengerNumber").val() == "3") { $("#div2").show(); $("#div3").show(); } }); </script> A: Your code indicates that your model is a single instance - instead, you have to choose a model that is a collection of instances. So that your mark-up will be something like <% for (int i = 0; i < 3; i++) { %> <div id="div1"> <h2>Passenger Details <%: i %></h2> <div class="editor-label"> <%= Html.LabelFor(model => model[i].flight_number) %> </div> ... ASP.NET MVC does support model binding to a list/collection. See this blog post where author has explained in detail (along with demo project) how to edit a variable length list and provide a link to add one more item etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to fetch file informations and md5 checksum using 1 command in linux I want to fetch all the file information viz: "permission","hardlink","owner","group","fsize","month","date","time","filename" and MD5 Sum information in one line command. How can I do this? currently I get the 1st one by running ls -latr /home/asimon and 2nd 1 by md5sum /home/asimon/filename.sh (it fetches me info for only 1 file) but instead i want all the information like below drwxr-xr-x 2 asimon support 4096 Sep 27 11:59 lib de1d8cd98f00b204e9800998ecf842qw -rwxrwxrwx 1 asimon support 924 Sep 27 12:00 run.sh dqtd8cd98f00b204e9800998ecf84a7a drwxr-xr-x 6 asimon support 4096 Sep 27 18:13 plugins d41d8cd98f00b204e9800998ecf8427s -rw-r--r-- 1 asimon support 2572 Sep 28 10:06 servicesFramework.log d51d8cd98f00b204e9800998ecf8427f A: you can do it with find very easily: find . -printf "%m %n %u %g %s %t" -exec md5sum \{\} \; Instead of the printf and the options you could also do a -ls but that would print the file name twice (and the ouput from md5sum delimited with a newline char) A: Looks rather clumsy, but here you go: ls -lAtr /home/asimon |grep -v total|awk '{printf($ARGV[1]);printf(" ");system("md5sum $9");}'|tr -d "-" [EDIT] note the upper case A in the ls command [EDIT2 and 3] Upated command, not spoiling the '-' characters in file names: ls -lAtr /home/asimon|egrep -v "^d|total"|awk '{printf($ARGV[1]);printf(" ");system("md5sum $9");}'|awk '{$11="";print $ARGV[1]}' A: One of the many ways would be to use a for loop as follows: for ls_entry in `ls`;do [ -f $ls_entry ] && ls_out=`ls -alth $ls_entry` && md5_out=`md5sum $ls_entry|awk '{print $1}'` && echo "$ls_out $md5_out"; done Hope this helps! A: try: ls -latr /home/asimon; md5sum /home/asimon/* the semicolon lets you do two commands on one line, and the * will run md5sum for everything in that directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: can not get html inside iframe , and can not fire events of elements inside iframe i am using Facebook graph API to invite Facebook friends to my codeigniter application , i want to fire a click event inside an element of iframe , but it is not firing , my code is $("iframe").contents().find('input[name="login"]').live('mouseover',function(){ alert("log in"); }); alert is not shown , no errors in firebug . but if i do this $("iframe").live('mouseover',function(){ alert("log in"); }); this works and give the alert . but if i try to get html inside iframe $("iframe").live('mouseover',function() { alert($('.fb_ltr').contents().find('.request').html()); }); it gives an error in firebug Permission denied to access property 'ownerDocument' [Break On This Error] shift(),i.sort());if(!!e&&!f.event.cus...is).get();f(e[h])[b](j),d=d.concat(j how to use elements inside iframe , i saw similar questions , but could not get a help . please help , thanks .............................. A: You are unable to access/manipulate any content via iframe if it's from a different domain. jQuery/JavaScript: accessing contents of an iframe A: The Iframe is treated as a single element. Thats why your code: $("iframe").live('mouseover',function(){}); works but accessing its element won't see this jQuery - Trying to select element from iFrame (point and click)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala/Lift - Cannot access image uploaded until jetty is restart I created a file upload form, the form will take an image file from user then save it in the webapp/images/ directory. The problem is I cannot access the image uploaded by user until jetty is restarted. Is there anything I should add to the code? Do I need to add anything on the sitemap? Thanks for the help A: try '~jetty-run' instead of 'jetty-run' when running the jetty server from sbt
{ "language": "en", "url": "https://stackoverflow.com/questions/7606270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cant store Hash table in session - Asp.net MVC3 In my application I want to store a hash table in session and retrieve later from session. The code is shown below Hashtable ht = new Hashtable(); DateTime fromDate = Convert.ToDateTime(dt.Rows[0]["FromDate"]); DateTime toDate = Convert.ToDateTime(dt.Rows[0]["ToDate"]); ht["StartTime"] = fromDate; ht["EndTime"] = toDate; Session["RuleSearchParameterForArchive"] = ht; While debuggin i can see that hashtable ht hold two values (StartTime and EndTIme) .. But when i retrieving ,that always give null .. code is shown below Hashtable hts = (Hashtable)Session["RuleParametersForArchive"]; DateTime dd = Convert.ToDateTime(hts["EndTime"]); While debugging i can see that hastable hts holds null value. Why i cant retrieve value from session. Any ideas?? A: The hashtable is stored with a different key (RuleSearchParameterForArchive) than you use when attempting to retrieve it (RuleParametersForArchive).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joyent no.de: cant ssh/git push into my node.js machine I get: ssh: connect to host switchboard1.no.de port 34726: Bad file number fatal: The remote end hung up unexpectedly As the instructions say my config file in .ssh looks like: Host switchboard1.no.de Port 34726 User node ForwardAgent yes And I'm running on windows and using git bash Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7606275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone:How to change default delete button's frame in UITableViewCell I have facing problem is that Is there any way to change default frame of delete button in UITableView and one more thing is that delete button is always display in center of cell of UITableViewcell so any way to change frame of delete button. // Update the data model according to edit actions delete or insert. - (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { [appDelegate.categories removeObjectAtIndex:indexPath.row]; [categoryTableView reloadData]; } } #pragma mark Row reordering // Determine whether a given row is eligible for reordering or not. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { return YES; } // Process the row move. This means updating the data model to correct the item indices. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { NSString *item = [[appDelegate.categories objectAtIndex:fromIndexPath.row] retain]; [appDelegate.categories removeObject:item]; [appDelegate.categories insertObject:item atIndex:toIndexPath.row]; [item release]; } Thanks in advance. A: in ios 6.1 i was not able to use the above code. I've seen several answers that suggests subclassing the cell class and providing a custom -willTransitionToState. Changing the subview/buttonview frame does not affectively change it's displayed position. However if you override the layoutSubviews method it will work. Here is the code: //below i moved the delete button to the left by 10 points. This is because my custom tableview has lef - (void)layoutSubviews { [super layoutSubviews]; for(UIView *subview in self.subviews) { if([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) { CGPoint o = subview.center; subview.center = CGPointMake(o.x - 10, o.y); } } } A: You can use your own view by setting the cell's editingAccessoryView property. This can have whatever frame you like, though you'll need to supply a gradient if you want it to look like the standard delete button. In the xib file of your custom cell, add a new button of whatever size you like (as long as it is smaller than the cell!). This button should not be a subview of your cell, but a separate item in the file. Connect this button to the editingAccessoryView outlet of your cell and it will replace the standard delete button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: call function in class i want to change the "value" when run my app. but when i call RS232::PackageRecived in "RS232.cpp" i revived This Error : Error 1 error C2352: 'RS232::PackageRecived' : illegal call of non-static member //////////////////////////////////////////// RS232.cpp FILE #include "RS232.h" void RS232::PackageRecived() { value =123; } void TryCallPackageRecived() { RS232::PackageRecived(); // my compiler error is here } int RS232::Connect() { TryCallPackageRecived(); } RS232::RS232(void) { } RS232::~RS232(void) { } //////////////////////////////////////////// RS232.h File class RS232 { public: int value; int Connect(); void PackageRecived(); RS232(void); ~RS232(void); }; //////////////////////////////////////////// Main.cpp File #include "RS232.h" RS232 RS; int main() { RS.Connect(); } A: Your function, "TryCallPackageRecived()" is not a member of the RS232 class. It's trying to call a member function of RS232 that is not static. This is not allowed. When you want to call a non-static member function you need to call it on a particular object. In this case, you could do: RS.PackageRecived(); If you want to allow for multiple objects, you could modify your TryCallPackageRecived function to take a pointer to the RS232 object: void TryCallPackageRecived(RS232 *ptr) { if(ptr != 0) ptr->PackageRecived(); } ... more code ... int RS232::Connect() { TryCallPackageRecived(this); } A: That's because PackageRecived is not a static method and you can't call non-static methods without an object. Either make it a static method (but it depends on your logic) or Call it directly since you are inside this class anyway. void TryCallPackageRecived() { PackageRecived(); // my compiler error is here } A: The obvious way to fix this would be to add TryCallPackageRecived() to your RS232 class: //////////////////////////////////////////// RS232.h File class RS232 { public: int value; int Connect(); void PackageRecived(); void TryCallPackageRecived(); RS232(); ~RS232(); }; //////////////////////////////////////////// RS232.cpp // [...] void RS232::TryCallPackageRecived() { PackageRecived(); } // [...]
{ "language": "en", "url": "https://stackoverflow.com/questions/7606277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to draw a vertical scale bar with css i want to draw a vertical scale bar with css for my project. please help me. here u can see the image. http://www.google.co.in/imgres?q=vertical+scale+bar&um=1&hl=en&sa=N&biw=1024&bih=578&tbm=isch&tbnid=FJiiXsutIEBcKM:&imgrefurl=http://www.anychart.com/products/anychart/docs/users-guide/gauge-linear-scale-bar-v.html&docid=3x5FkAAE7L13NM&w=150&h=500&ei=EFOFTu2HPMjxrQei8Y3tAw&zoom=1&iact=hc&vpx=236&vpy=43&dur=1&hovh=400&hovw=120&tx=78&ty=217&page=1&tbnh=128&tbnw=38&start=0&ndsp=18&ved=1t:429,r:1,s:0 like above diagram i have to draw with css and html. A: You could try something like this I suppose. Just need to add in some scale marks. Can set the height of the inner bar dynamically with javascript / or server side output. <div id="container"> <div id="therm"> <div id="inner"> <div id="bar">&nbsp;</div> </div> </div> </div> #container{ width:60px; height: 350px; } #therm{ background-color: green; width: 100%; height: 100%; position: relative; } #inner{ position: absolute; left:0; bottom: 0; width: 100%; } #bar{ background-color: black; width: 15px; height: 250px; margin: 0px auto; } related fiddle: http://jsfiddle.net/sUeCn/ A: You can try something like this, that shows scale and fills the scale bar with a nice gradient color <div id="scale"> 200 -<br /> .<br /> .<br /> .<br /> 175 -<br /> .<br /> .<br /> .<br /> 150 -<br /> .<br /> .<br /> .<br /> 125 -<br /> .<br /> .<br /> .<br /> 100 -<br /> .<br /> .<br /> .<br /> 75 -<br /> .<br /> .<br /> .<br /> 50 -<br /> <div> <div id="outer"> <div> </div> </div> and the following CSS #scale { width: 30px; font-size: 0.6em; text-align: right; } #outer { position: absolute; left: 42px; top: 10px; width: 50px; height: 300px; background: -webkit-gradient(linear, left top, left bottom, from(#0f0), to(#fa0)); background: -moz-linear-gradient(top, #0f0, #fa0); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0f0', endColorstr='#fa0'); } #outer > div { position: absolute; left: 35%; bottom: 0px; width: 30%; height: 90%; background-color: black; } jsfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7606280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Parameter query run hyperlink & open webpage, for tracking UPS package I have a parameter query that looks up the tracking # for a given customer_order_ID and outputs the tracking# as a website link, as a single record. Please advise me how I can have the link run automatically when the user inputs the customer_order_ID into the parameter query , in order that the user can immediately track the package on the UPS Worldship website. I do not know VBA nor do I know SQL, but I can make macros. Thank you very much in advance SELECT T.order_ID, "http://wwwapps.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_us&InquiryNumber1=" & [T].[tracking_number] & "&track.x=0&track.y=0" AS link FROM tblShipmentDataFromAllCarriers AS T WHERE (((T.order_ID)=[Please enter customer order ID])); A: If you don't need to parse the return data and just want to open the web page, you can use Application.FollowHyperlink. But you don't need to do the concatenation with the URL in the SQL: SELECT T.order_ID, [T].[tracking_number] FROM tblShipmentDataFromAllCarriers AS T WHERE (((T.order_ID)=[Please enter customer order ID])); Then you could store the rest of the URL as constants: Const c_strURL1 = "http://wwwapps.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_us&InquiryNumber1=" Const c_strURL2 = "&track.x=0&track.y=0" ...and then execute it like this: Public Sub DisplayTrackingNumber(ByVal strOrderID As String) Dim strTrackingNumber As String strTrackingNumber = DLookup("tracking_number", "tblShipmentDataFromAllCarriers", "[order_ID]=" & strOrderID) Application.FollowHyperlink strUrl1 & strTrackingNumber & strUrl2 End Sub You'd then have to have a UI to collect the OrderID from the user (I'd suggest a form with a combo box) and then call this sub.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to put XDocument elements into Comboboxes (second box dependent on first) (C# .net 3.5) I'm trying to take XML and display two comboboxes. The first combobox will contain a distinct list (i.e., no duplicates) from the provinceCode elements. The second combobox will show only nameEN elements matching the provinceCode. Here is a sample of my XML: <siteList> <site code="s0000001"> <nameEn>Edmonton</nameEn> <provinceCode>AB</provinceCode> </site> <site code="s0000002"> <nameEn>Vancouver</nameEn> <provinceCode>BC</provinceCode> </site> ... </siteList> I have my XDocument from this: XDocument loaded = XDocument.Parse(strSiteList); I'm struggling with how to extract the unique list of provinces. It's something like: var list = loaded.Descendants("provinceCode").Distinct; but I'm new to C# and XDocument and I don't know what type of variable to use so I get "Cannot assign method group to an implicitly-typed local variable". And I'm totally in the dark on how do to the comboboxes. I've done a quick search on stackoverflow and google, but there doesn't seem to be anything relevant on both XDocument and dependent comboboxes in C#. Is using XDocument the wrong approach? Thanks! A: The problem is that you're not actually calling the method. You could write: var list = loaded.Descendants("provinceCode").Distinct(); Note the brackets. but I don't think that actually does what you want. I suspect you want: List<string> list = loaded.Descendants("provinceCode") .Select(x => x.Value) .Distinct() .ToList(); That will give you a list of distinct province codes as a list of strings. It's not quite clear what you mean about the second list - is that meant to match just a single province code? If so: List<string> names = loaded.Descendants("site") .Where(x => x.Element("provinceCode").Value == provinceCode) .Select(x => x.Element("nameEn").Value) .ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7606283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mongo: Selecting X elements from an array placed in an object I have the following collection for a user in a MongoDB: { "_id" : 1, "facebook_id" : XX, "name": "John Doe", "points_snapshot" : [{ "unix_timestamp" : 1312300552, "points" : 115 }, { "unix_timestamp" : 1312330380, "points" : 110 }, { "unix_timestamp" : 1312331610, "points" : 115 }] } Is it possible to write one query which by which I can get the user for id 1 along with the snapshots after a particular day. eg: 1312330300? Basically limit the snapshots to X numbers matching some criteria? So far, I have tried in C#: Query.And( Query.EQ("facebook_id", XX), Query.GTE("points_snapshot.unix_timestamp", sinceDateTimeStamp))) .SetFields("daily_points_snapshot", "facebook_id") which I soon realised will not work for what I want. Any help will be appreciated! Thanks! EDIT: My Solution to this If anyone is looking to get a quick fix to this, this is what I ended up doing: var points = MyDatabase[COLLECTION_NAME] .Find(Query.EQ("facebook_id", XX)) .SetFields("points_snapshot", "facebook_id") .FirstOrDefault(); if (points != null) { var pointsArray = points.AsBsonDocument["points_snapshot"].AsBsonArray .Where(x => x.AsBsonDocument["unix_timestamp"].AsInt32 > sinceDateTimeStamp) .ToList(); return pointsArray; } A: Is it possible to write one query which by which I can get the user for id 1 along with the snapshots after a particular day. eg: 1312330300? Not possible. The problem here is that MongoDB queries return all matching Documents. Your Document contains an array of objects, but MongoDB does not treat these as "Documents". Now, you can limit the fields that are returned, but in your case you actually want to limit the "portions of an array" that are returned. This is a long-outstanding issue, the JIRA ticket is here. The ticket is dated about 18 months ago and it continues to get pushed back. So if this type of query is critical to your architecture, you may have to re-design the architecture.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sqlite in a textview Is it possible to display a sqlite values in a textview?I have made it in a tableviewcontroller,but i am not able to display the same in a textview. appdelegate.biblearray is the array that holds the sqldata.I have the same qustion in another forom .please look at this link for that question [here is the link]: How to show sqlite datas in a textview? Please help me to do this. Thanks. A: Instead of doing bible *jesus = (bible *)[appDelegate.biblearray objectAtIndex:indexPath.row]; use string variable or the type of value that biblearray contains NSString *str = [appDelegate.biblearray objectAtIndex:indexPath.row]; For only displaying in textview, you dont need to use class object jesus.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monomac An Exception as thown by the type initializer for System.Net.WebRequest I'm writing a program in monomac to ftp files to a server. I used the FtpWebRequest as FtpWebRequest request =(FtpWebRequest)WebRequest.Create("ftp://serverip/filename"); When I'm running this code in monodevelop its running properly. But when I release this and runs outside monodevelop I get the error "An Exception as thrown by the type initialize for System.Net.WebRequest. I researched for this error and found it has problem with the library libc.dylib. If I change the DYLD_FALLBACK_LIBRARY_PATH in launch script of the app(AppBundle/MacOs/AppName edit with TextEdit) as export DYLD_FALLBACK_LIBRARY_PATH="$MONO_FRAMEWORK_PATH/lib:$DYLD_FALLBACK_LIBRARY_PATH:/usr/lib" (added /usr/lib) then it is sending the files. But I have to install mono framework in all system to run this app. Once i create a mac installer package i cannot edit the the launch script. I tried copying libc.dylib file from /usr/lib to Appbundle(App/MonoBundle/) but still the error exists. Can anyone help me? A: I had this issue. Are you adding monomac dll's to the app bundle? It tries to be clever and remove unused methods and classes. I found that it would often not include methods it thought were not being used by mistake. I'm not sure how to force it to include the missing methods, however you can solve this by turn off linking in the package settings. Unfortunately this makes the app much bigger.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can i write join query in android sqlite? Hi, I am new to android. I want to write query for join in sqlite. My code is - public Cursor SearchCategory(SQLiteDatabase db){ //return db.query("category_master", null, "status = 'Active'", null, null, null, null); String Category_Sql = " select category_master.*,count(*) as cnt from product_master " + " left join category_master on product_master.category_id = category_master.category_id " + " where category_master.status = 'Active' group by category_master.category_id having cnt > 0 "; return db.query(Category_Sql); } but it generate error. Where am I wrong? A: It would have helped more if you could cite the error description. Try running the query first in Portable SQLite explorer A: you can use rawQuery db.rawQuery("Select a.column1,b.column1 FROM table1 a JOIN table2 b ON a._id=b._id", null); it should work
{ "language": "en", "url": "https://stackoverflow.com/questions/7606298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I edit the bytes code of a JPG file preserving still its header and footer? (in Java) I already have successfully coded my Steganography program in a PNG file using Java. My program works very well in both PNG and BMP files. But when I tried running my program in a JPG file, the revealed data is not the same as the original data. Certainly, the headers of each file type isn't the same. And so now I wonder; Do the data structures of PNG and JPG files aren't the same? I need to know exactly how to manipulate the bytes of a JPG file without affecting its header and the footer. Thanks. A: First of all you need to tell the exact method you are using for image steganography e.g. hiding the secret data in the lsb's of the pixels of the image, reading the file in a binary format etc. If working with lsb's is your procedure then I hope the following answer satisfies your query- 'PNG' and 'BMP' are actually lossless file formats. After manipulating the bits of pixels of these formats when you create the new image no data is lost. This is the reason you are able to retrieve all the hidden data. 'JPG' formats however use a lossy compression technique due to which the data hidden in the pixels is lost. Even I faced this problem and the solution to this exists in handling the image in transform domain. You need to use the Direct Cosine Transform method for its implementation. The transform domain involves manipulation of the algorithms and image transforms such as discrete cosine transformation (DCT) and wavelet transformation. These methods can hide information in more significant areas of the image and may also manipulate the properties of the image like luminance. These kinds of techniques are more effective than image domain bit-wise steganographic methods. The transform domain techniques can be applied to image of any format. Also, the conversion between lossless and lossly formats may survive. How DCT works in steganography? The image is broken down into 8x8 blocks of pixels. DCT is applied to each block from left to right, top to bottom. The quantization table compresses each block to scale the DCT coefficients and the message is embedded in the scaled DCT coefficients. A lot of reasearch is still required in this method. I am working on its code and will post it ASAP. It will be a pleasure to hear of other methods or different efficient techniques from other developers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Postgres select all columns but group by one column I have a simple table with a unit_id oid, time timestamp, diag bytea. The primary key is a combination of both time and unit_id. The idea behind this query is to get the latest row (largest timestamp) for each unique unit_id. However the rows for each unit_id with the latest time are not always returned. I really want to group by just the unit_id, but postgres makes me use diag also, since I am selecting that. SELECT DISTINCT ON(unit_id) max(time) as time, diag, unit_id FROM diagnostics.unit_diag_history GROUP BY unit_id, diag A: Any time you start thinking that you want a localized GROUP BY you should start thinking about window functions instead. I think you're after something like this: select unit_id, time, diag from ( select unit_id, time, diag, rank() over (partition by unit_id order by time desc) as rank from diagnostics.unit_diag_history ) as dt where rank = 1 You might want to add something to the ORDER BY to consistently break ties as well but that wouldn't alter the overall technique. A: You can join the grouped select with the original table: SELECT d.time, d.diag, d.unit_id FROM( SELECT unit_id, max(time) as max_time FROM diagnostics.unit_diag_history GROUP BY unit_id ) s JOIN diagnostics.unit_diag_history d ON s.unit_id = d.unit_id AND s.max_time = d.time
{ "language": "en", "url": "https://stackoverflow.com/questions/7606305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Can XAML tag names be bound? I have a simple Question.. Is it possible to use binding like this: <my:{Binding Path=Foo} /> The reason why I want to do this is I need the foo to change by using conditional compilation, for Example: #if BAR var foo = "FooBar" #endif A: As far as I know having dynamic changes to the XAML markup itself is not possible in WPF. If you do need to have something like this I would suggest that you use one of your possible classes in XAML to keep design support and to have a valid XAML file and then write a little tool that runs through all your xaml files before compilation and exchanges Foo with Bar if a certain condition is met. Obviously you would need to make sure that Foo and Bar are interchangeable too. Effectively your XAML would look like this <my:Foo .../> and your tool would check a condition and then exchange Foo with Bar in all your xaml files. A: You want to bind to a different property based on a pre-processor directive? That doesn't sound easy to do to me. Wouldn't it be better to have the the Xaml use the same property but for the property to use a different body/field: public string MyDebugFoo { get; set; } public string MyOtherFoo { get; set; } public string Foo { #if DEBUG get { return MyDebugFoo; } } set { MyDebugFoo = value; } } #else get { return MyOtherFoo; } } set { MyOtherFoo = value; } } #endif }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cutting out the middle portion of an image (example shown)? This is something I've seen done by Grooveshark, which removes the need to use multiple images for expandable buttons and such. Basically, an image like this is used to produce buttons of any width smaller than the image itself. I assume this is done by somehow trimming out the middle, but I'm not sure how. I've looked over the CSS properties for it's usage here but can't seem to find out what's done aside from a 15px padding on either side. Does anyone know how to replicate the same effect? Edit: Just for clarity, I'm talking about cutting out the middle of a single button (I do realize I've given a picture of a sprite for 4 button styles, so it might be confusing when I say "cutting out the middle portion of an image"). A: What you're talking about is known as the sliding doors technique. By applying the background image to a container element to show the left edge, you can then apply the same image to another element that only shows the right edge. For example: .menu li { background: url(button-sprite.png) 0 0 no-repeat; padding-left: 10px; } .menu li a { background: url(button-sprite.png) 100% 0 no-repeat; display: block; } The list item shows the left edge of the image. The padding allows the left edge to show when another element is laid on top. The anchor element shows the right edge of the image, and it is cropped to the required width of the text content. A: I know of no way to manipulate images like that in CSS, I think you'll find what they do is have the top image and bottom image always top and bottom, and just fill the rest with a middle image. This can also be applied to each side, i'll add the CSS3 code, the CSS2 code should be easy to determine. This would look like (CSS3): .button_horizontal { background: url(topimage) top left no-repeat, url(bottomimage) bottom left no-repeat, url(middleimage) top left repeat-y; } .button_vertical { background: url(left.png) top left no-repeat, url(right.png) top right no-repeat, url(middle.png) top left repeat-x; } This would look like (CSS2): .top { background: url(top.png) top left no-repeat; width:100%; height:10px; } .middle { background: url(bottom.png) bottom left no-repeat; width:100%; height:180px; } .button{ background: url(middle.png) top left repeat-y; width:500px; height:200px; } <div class="button"> <div class="top">&nbsp;</div> <div class="middle"><p>stuff goes in here :D</p></div> </div> A: CSS allows to move background image to any position. In order to display part of the background you need to define CSS like the following: .button { background: transparent url(sprite.png) left top no-repeat; display: block; height: 40px; width: 160px; } .button:hover { background-position: left bottom; } .button:focus { background-position: left center; /* or background-position: left -50%; background-position: left -40px; */ } A: @Pixelatron; i know you accept the answer but check this example may be that's help you & easy solution as well http://jsfiddle.net/sandeep/CQmJz/ css: a{ text-decoration:none; display:inline-block; background:url(http://i.stack.imgur.com/gYknG.png) no-repeat 0 0; position:relative; padding:8px 0 8px 10px; height:17px; } a:after{ content:""; display:block; background:url(http://i.stack.imgur.com/gYknG.png) no-repeat -490px 0; position:absolute; height:33px; width:10px; top:0; right:-10px; } a:hover{ background-position:0 -34px; } a:hover:after{ background-position:-490px -34px; } A: That is called border-image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ReadDirectoryChangesW and determining which process caused the change How can I determine which processes are making changes to which files. I did find this: FileSystemWatcher: how to know which process made the change? But I'm curious if anything has changed lately? Is it possible yet to determine which process is making changes to the file system, either using ReadDirectoryChangesW or anything else? I'd prefer not to have to write or use a kernel driver. A: Create a security audit on the files you want to track. The information will be recorded in the security event log. A: While it may be possible to find out the process that changes a file using kernel drivers (for example, process monitor), there will always be a problem identifying the process in case the folder is shared on the network, and a process on another computer modifies the file over the network. Even the kernel drivers would in this case identify the network share process as the one accessing the file, not the process on the other computer. A: I can't seem to comment yet. I would be interested in your Python code that creates a security audit on files or paths. It's a bit of a shame if it messes with the system security event log, but you can't have everything! :-) Up until this point, I have been using GetForegroundWindow at the time of the change to eventually get the associated process. It only works well for changes initiated by the user, but that is primarily what I've been interested in. Besides background processes, the only minor issue is that sometimes a process is spawned just to accomplish a task (like a batch file) and it is non-existent by the time you want to learn more about it (like what process spawned it). I imagine that is a problem even with a security audit, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fscopyobjectasynch : be asked for decision where file is going to be overwritten I am developping a small file copy utility and I am using fscopyobjectasynch to copy files. When a file already exists in the destination, I would like to ask the user if he want to keep the original file or to overwrite it. I am trying to find a way to achive this whith fscopyobjectasynch Thanks for your help A: As stated in the documentation, FSCopyObjectAsync will overwrite an existing object at the destination if you give it the kFSFileOperationOverwrite flag. If you don't, it won't. You can present an NSAlert to determine whether you should pass that flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting date string to date I'm trying to use strtotime to convert date strings in the format Jan 14th 2011 to the format 2011-01-14 but it's not working. Is this format not suitable for strtotime and if so, how can I convert it. The month is always in 3-letter format, like Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec A: $date_str = "Jan 14th 2011"; $date = date_parse_from_format('M jS Y', $date_str); echo $date->format('Y-m-d'); A: Please, refer to here: http://www.php.net/manual/en/datetime.formats.date.php AFAIK, strtotime parses an English textual date or time into a Unix timestamp. A: strtotime or solutions like that would need a little bit of changes for each use case. If you want to go a little bit further and have a permanent solution to convert raw string dates into time formats you can check this project I did https://github.com/raimonbosch/date.extraction I'm using regular grammars to detect all kind of date formats.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Confusing PHP/AJAX timeout after 900 secs(15 mins) all of the below is based on Linux, recent Apache, recent PHP module for Apache. I am experiencing an unexpected behavior for my AJAX+PHP based web-application. It is quite a simple AJAX approach, basically involving a request to a PHP-script (execute.php) that runs for some time (few seconds to several minutes). As a test-setup, the PHP-script (execute.php) basically just sleeps for a certain amount of time. When this amount is 899 seconds, it works, but when I set it to 900, the answer of the PHP-script (simple echo() ) seems to expire or something like this (what is exactly the cause or reason is actually unknown to me) as the request is not taking notice of it and thus not responding and the respective innerHTML is not updated, as expected. Please find the code below. I am now wondering where this "timeout" of 900 seconds comes from and even more important, how can I prevent that from happening? After all, I thought that this was, at least, one general idea of AJAX to handle asynchronous calls and notify the client as soon as a request has changed its state?! process.php <?php session_start(); include("functions.php"); include("env.php"); html_head("Processing..."); $sid = $_SESSION['my_sid']; ?> <script type="text/javascript"> function run_analyses(params){ <?php print "var sid = \"". $sid ."\"; "; ?> // Use AJAX to execute the programs independenantly in the background // Allows for the user to close the process-page and come back at a later point to the results-link, w/o need to wait. if (window.XMLHttpRequest) { http_request = new XMLHttpRequest(); } else { //Fallback for IE5 and IE6, as these don't support the above writing/code http_request = new ActiveXObject("Microsoft.XMLHTTP"); } //Is http_request still false if (!http_request) { alert('Ende :( Kann keine XMLHTTP-Instanz erzeugen'); } http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ // Maybe used to display the progress of the execution document.getElementById("output").innerHTML=http_request.responseText; } }; http_request.open("POST","execute.php",true); //Send the proper header information along with the request http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http_request.setRequestHeader("Content-length", params.length); http_request.setRequestHeader("Connection", "close"); http_request.send(params); }; </script> <?php $params "some_params"; print " Starting AJAX-call<br> <div style=\"width:400px; border: 1px black solid;\" id=\"output\">Use this to display an information about the progress</div> <script type=\"text/javascript\"> run_analyses('".$params."'); </script> <form action=\"./usersets/". $sid ."/results.html\" id=\"go_to_results\" method=\"POST\"> <input type='hidden' name=\"session_id\" value=\"" .$sid. "\"> </form> "; html_foot(); ?> and execute.php: <?php session_start(); include("functions.php"); include("env.php"); $sid = $_SESSION['my_sid']; // Used to get the time at start of processing $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; session_write_close(); sleep(900); //899 here works session_start(); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 3); //echo 'Page generated in '.$total_time.' seconds.'."\n"; // Make it accessible for the results $_SESSION['process_time'] = $total_time; echo("none"); ?> So the text after "Starting AJAX call" is updated to "none" when the PHP-script sleeps for 899 seconds, but stays "Use this to display an information about the progress" if that value is 900 seconds. I am really looking forward to your suggestions. Best, Shadow EDIT Doing grep max_execution $(locate php.ini ) gives: /etc/php5/apache2/php.ini:max_execution_time = 30 /usr/share/doc/php5-common/examples/php.ini-development:max_execution_time = 30 /usr/share/doc/php5-common/examples/php.ini-production:max_execution_time = 30 /usr/share/php5/php.ini-production:max_execution_time = 30 /usr/share/php5/php.ini-production-dist:max_execution_time = 30 /usr/share/php5/php.ini-production.cli:max_execution_time = 30 EDIT2 When calling the scripts locally (apache webserver running on my local linux machine) in my browser interestingly it behaves as expected and respectes the return of the request. But it exhibits the above unexpected behavior when run on a webserver running on a different machine. Any clues on that? Because I don't have any... Sorry. A: In your php.ini there is a max_execution_time, the default is 30 seconds, so it seems somewhere it has been set to 900. So I would check there first. Info: http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time As for solving it, you can edit the php.ini to set that value really high (or 0 for unlimited), or alternatively you might be able to use this function: http://php.net/manual/en/function.set-time-limit.php to reset it after say 300 seconds. Hope this helps! Edit: added Lee's suggestion of 0 value max_execution_time Edit 2: Just found something interesting here http://www.php.net/manual/en/function.set-time-limit.php#75557 Please note that, under Linux, sleeping time is ignored, but under Windows, it counts as execution time. So, that could be why its allowed to execute for longer than 30 seconds, but still cutting it off eventually. A: I tried your example and place it in a different host (not localhost). In my case it ran fine and got the "none" value after 900 seconds. I removed the SESSION calls to simplify the example... Try it without session. If that changes something, then maybe "session.cookie_lifetime" value could be related. A: Search for the value 900 in all your php.ini and .htaccess: grep -HR 900 $(locate php.ini ) $(locate -e .htaccess ) also search for 900 and fractions of 900 in your source code: cd /var/www/ #path_to_yoursite grep --color=auto -HR "=\s*900\b" grep --color=auto -HR "=\s*20\s*\*\s*45\b" grep --color=auto -HR "=\s*15\s*\*\s*60\b" ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Function returning 2 types based on input in Perl. Is this a good approach? i have designed a function which can return 2 different types based on the input parameters ex: &Foo(12,"count") -> returns record count from DB for value 12 &Foo(12,"details") -> returns resultset from DB for value 12 in hash format My question is is this a good approach? in C# i can do it with function overload. A: Please think what part of your code gets easier by saying Foo(12, "count") instead of Foo_count(12) The only case I can think of is when the function name ("count") itself is input data. And even then do you probably want to perform some validation on that, maybe by means of a function table lookup. Unless this is for an intermediate layer that just takes a command name and passes it on, I'd go with two separate functions. Also, the implementation of the Foo function would look at the command name and then just split into a private function for every command anyway, right? A: additionally you might consider the want to make foo return the details if you wanted a list. return wantarray ? ($num, @details) : $num;
{ "language": "en", "url": "https://stackoverflow.com/questions/7606332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where Is gcvt or gcvtf Defined in gcc Source Code? I'm working on some old source code for an embedded system on an m68k target, and I'm seeing massive memory allocation requests sometimes when calling gcvtf to format a floating point number for display. I can probably work around this by writing my own substitute routine, but the nature of the error has me very curious, because it only occurs when the heap starts at or above a certain address, and it goes away if I hack the .ld linker script or remove any set of global variables (which are placed before the heap in my memory map) that add up to enough byte size so that the heap starts below the mysterious critical address. So, I thought I'd look in the gcc source code for the compiler version I'm using (m68k-elf-gcc 3.3.2). I downloaded what appears to be the source for this version at http://gcc.petsads.us/releases/gcc-3.3.2/, but I can't find the definition for gcvt or gcvtf anywhere in there. When I search for it, grep only finds some documentation and .h references, but not the definition: $ find | xargs grep gcvt ./gcc/doc/gcc.info: C library functions `ecvt', `fcvt' and `gcvt'. Given va lid ./gcc/doc/trouble.texi:library functions @code{ecvt}, @code{fcvt} and @code{gcvt }. Given valid ./gcc/sys-protos.h:extern char * gcvt(double, int, char *); So, where is this function actually defined in the source code? Or did I download the entirely wrong thing? I don't want to change this project to use the most recent gcc, due to project stability and testing considerations, and like I said, I can work around this by writing my own formatting routine, but this behavior is very confusing to me, and it will grind my brain if I don't find out why it's acting so weird. A: Wallyk is correct that this is defined in the C library rather than the compiler. However, the GNU C library is (nearly always) only used with Linux compilers and distributions. Your compiler, being a "bare-metal" compiler, almost certainly uses the Newlib C library instead. The main website for Newlib is here: http://sourceware.org/newlib/, and this particular function is defined in the newlib/libc/stdlib/efgcvt.c file. The sources have been quite stable for a long time, so (unless this is a result of a bug) chances are pretty good that the current sources are not too different from what your compiler is using. As with the GNU C source, I don't see anything in there that would obviously cause this weirdness that you're seeing, but it's all eventually a bunch of wrappers around the basic sprintf routines. A: It is in the GNU C library as glibc/misc/efgcvt.c. To save you some trouble, the code for the function is: char * __APPEND (FUNC_PREFIX, gcvt) (value, ndigit, buf) FLOAT_TYPE value; int ndigit; char *buf; { sprintf (buf, "%.*" FLOAT_FMT_FLAG "g", MIN (ndigit, NDIGIT_MAX), value); return buf; } The directions for obtain glibc are here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there some way for networking data to be directed to two applications simultaneously? I'm developing an application that processes a real time data feed across the internet. There are 2 fundamentally different things I want to do with it: one extremely simple but critical that it never is interrupted. Another much more complex but interruption is not such a horrible problem. Given that the second would have higher risk of the application crashing due to its complexity... I'm asking if there is some way that both can be receiving the data feed at the same time? I could have both functions in a single application but if it crashes, that's very bad. I was thinking by separating the two functions into two applications, it might provide more robust handling for the critical simple processing. But if I separate into two applications, is it possible for both of them to receive the identical data at the same time? Some type of OS networking voodoo or something? A: It depends on the stream and on the way you want to implement it - some general ideas to achieve what you describe: * *make a receiver app this has the only purpose in receiving the feed and dispatching it to any apps/consumers who register to receive... if the receiving apps are on the same system you can use shared memory (MemoryMappedFile in .NET for example) which is really fast... this would help regarding future requirements - for example if you need to implement another processing app it just needs to register with the receiver app... another nice side-effect: the receiver app can capture the feed to some persistence and thus allow a "replay" for testing purposes etc. *make the "critical" one multiplex the feed this would mean only your critical app receives the feed and sends a copy to the other app (for example on a different thread)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scatter.smooth R function - color How can I change the color of the scatter.smooth in R? I can add a "col" parameter, but that only changes the color of the data points (the dots), not the actual line that is on the screen. How do I change the color of the actual line. A: As an alternative, you can use lattice::xyplot with type=c('p', 'smooth'): xyplot(dist~speed, data=cars, type=c('p', 'smooth'), col.line='green') A: If you read the source code for scatter.smooth, you'll find that the prediction line is plotted without a col parameter. This means you will have to modify the code. Here I add a lcol argument for line colour: scatter.smooth <- function (x, y = NULL, span = 2/3, degree = 1, family = c("symmetric", "gaussian"), xlab = NULL, ylab = NULL, ylim = range(y, prediction$y, na.rm = TRUE), evaluation = 50, lcol="red", ...) { xlabel <- if (!missing(x)) deparse(substitute(x)) ylabel <- if (!missing(y)) deparse(substitute(y)) xy <- xy.coords(x, y, xlabel, ylabel) x <- xy$x y <- xy$y xlab <- if (is.null(xlab)) xy$xlab else xlab ylab <- if (is.null(ylab)) xy$ylab else ylab prediction <- loess.smooth(x, y, span, degree, family, evaluation) plot(x, y, ylim = ylim, xlab = xlab, ylab = ylab, ...) lines(prediction, col=lcol) # <<-- Note the edit here invisible() } with(cars, scatter.smooth(speed, dist, col="blue", lcol="green")) A: There is no need to hack scatter.smooth() to achieve the desired result. Notice on ?scatter.smooth that there is another function documented; loess.smooth(). This latter function is used by scatter.smooth() to compute the x an y coordinates of the fitted loess smoother. The desired plot can be produced by two calls; i) to plot(), and ii) a second call to loess.smooth() to draw the line. Using @Andrie's example, this would be: plot(dist ~ speed, data = cars, col = "blue") with(cars, lines(loess.smooth(speed, dist), col = "green")) The loess.smooth() step returns a list with x and y components that can be plotted easily using lines(): > with(cars, loess.smooth(speed, dist)) $x [1] 4.000000 4.428571 4.857143 5.285714 5.714286 6.142857 [7] 6.571429 7.000000 7.428571 7.857143 8.285714 8.714286 [13] 9.142857 9.571429 10.000000 10.428571 10.857143 11.285714 [19] 11.714286 12.142857 12.571429 13.000000 13.428571 13.857143 [25] 14.285714 14.714286 15.142857 15.571429 16.000000 16.428571 [31] 16.857143 17.285714 17.714286 18.142857 18.571429 19.000000 [37] 19.428571 19.857143 20.285714 20.714286 21.142857 21.571429 [43] 22.000000 22.428571 22.857143 23.285714 23.714286 24.142857 [49] 24.571429 25.000000 $y [1] 4.962236 6.132561 7.294531 8.451282 9.605949 10.761666 [7] 11.921569 13.088792 14.266472 15.457742 16.646268 17.788187 [13] 18.916270 20.068806 21.284085 22.534880 23.776272 25.020014 [19] 26.277859 27.554763 28.793605 30.039834 31.287544 32.541662 [25] 33.982881 35.706712 37.262771 38.683122 40.080683 41.491404 [31] 42.951233 44.438569 45.860202 47.361200 49.023137 50.730452 [37] 52.619626 54.852390 57.325596 59.936095 62.580738 65.156375 [43] 67.559859 69.876282 72.248492 74.659973 77.094212 79.534692 [49] 81.964898 84.368316 The plot produced looks like this: A: See the documentation: with(cars, scatter.smooth(speed, dist, lpars = list(col = "red", lwd = 3, lty = 3)))
{ "language": "en", "url": "https://stackoverflow.com/questions/7606342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Create multidimensional array from csv I am having trouble generating a multidimensional array from a csv file. I need to have the output 'grouped' by country as each country may have multiple networks. Some rows do not have a value for country or zone as they are related to the row above it. Unfortunately this is how i receive the csv file and there is no way of changing the output. Any feedback or pointers would be appreciated. Snippet of csv file... Country|Zone|Network|Video|Voice Afghanistan,5,Afghan Wireless,No,Yes ,,Roshan,No,Yes Antigua,4,Digicel,No,Yes Argentina,5,Telecom Personal,Yes,Yes ,,Movistar,No,Yes ,,Movistar2,Yes,Yes Aruba,4,Digicel,No Ideal Output Array ( [0] => Array ( [country] => Afghanistan [zone] => 5 [network] => Array ( [0] => Array ( [name] => Afghan Wireless [video] => No [voice] => Yes ) [1] => Array ( [name] => Roshan [video] => No [voice] => Yes ) ) ) [1] => Array ( [country] => Antigua [zone] => 4 [network] => Array ( [0] => Array ( [name] => Digicell [video] => No [voice] => Yes ) ) ) etc... ) A: <?php $csvArray=array();//to store final data $networkArray=array();//to serve as temporar buffer if (($handle = fopen("file.csv", "r")) !== FALSE) { fgetcsv($handle, 1000, ",");//skip the first line cause contains labels only //iterate all ther line while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { //if a new country if($data[0]!=='') { /*get last key assigned to the previous country*/ $key=array_pop(array_keys($csvArray)); /*store the buffer, at the very begining no last country exists so this network will be stored in a null key, will delete it later*/ $csvArray[$key]['network']=$networkArray; //emty the buffer $networkArray=array(); //now we are done with previous country and will store the new one $csvArray[]=Array('country'=>$data[0],'zone'=>$data[1]); }//@if ends //Put to buffer network, video and voice $networkArray[]=Array('name'=>$data[2],'video'=>$data[3],'voice'=>$data[4]); }//@while ends fclose($handle); }//@outer if ends //store the last network buffer $key=array_pop(array_keys($csvArray)); $csvArray[$key]['network']=$networkArray; //delete the null key set in the begining array_shift($csvArray); //show the array echo '<pre>'; print_r($csvArray); ?> A: Just a simple solution (not e complete tested one) <?php // Initialize the final result $result = array(); // Read the file line by line $handle = @fopen("test.csv", "r"); if ($handle) { $country = null; while (($buffer = fgets($handle, 4096)) !== false) { $line = explode(',', $buffer); if($line[0] == null) { $network['name'] = $line[2]; $network['video'] = $line[3]; if(isset($line[4])) $network['voice'] = $line[4]; $country['network'][] = $network; $network = null; } else { if($country != null) { $result[] = $country; $country = null; } $country['country'] = $line[0]; $country['zone'] = $line[1]; $network['name'] = $line[2]; $network['video'] = $line[3]; if(isset($line[4])) $network['voice'] = $line[4]; $country['network'][] = $network; $network = null; } } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); print_r($result); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is a timer mandatory for drawing OPENGL ES I have a method called startAnimation: -(void)startAnimation{ 1: self.animationTimer=[NSTimer scheduledTimerWithTimeInterval:1/60 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES]; 2: //[self gameLoop] { The gameLoop method is like this: -(void)gameLoop{ [self updateModel]; [self render] { Now, a very strange thing happens. If I comment the line 1 and uncomment the line 2 in startAnimation method I will not get the objects rendered to my screen. I thought rendering might require continuously calling the gameLoop metod. But even if I set the timer to not repeat (so repats:NO) objects are drawn. It means calling the gameLoop method just once, but from an NStimer object is enough. But if I call the gameLoop method manually I do not get the objects drawn. I tried calling the method inside a loop which executes 100 times. It did not help either. Is there something special with the timers in regards with OPENGL?Sorry for the question if it's too immature. A: A timer is not needed for OpenGL ES. For my drawing app the render method is called everytime the user touches the screen. However, for games most developers use CADisplayLink to call the render or gameloop method instead of NSTimer, as CADisplayLink will call the render method each time the screen refreshes. Setting up a CADisplayLink is done like the example below. - (void)setupDisplayLink { //this sets up the game loop to be called once each time the screen refreshes CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(gameLoop:)]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } Then the gameLoop should be setup as: - (void)gameLoop:(CADisplayLink *)displayLink { [self updateModel]; [self render]; } A: It´s been some time since you asked but the problem there is that the time interval is set to 1/60, which is 0 because it´s using the integer division. You should use 1.0/60.0 instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tilde or accent on Rails 3 I have this piece of code to make a consult: text = 'pestañas' text.split(' ').each do |word| @dictionary = Dictionary.where('spanish_word LIKE ?', "%#{word}%").first end But if I see on the debugger, I have this consult: Dictionary Load (0.3ms) SELECT `dictionaries`.* FROM `dictionaries` WHERE (spanish_word LIKE '%pestaas%') LIMIT 1 I have this problem with ñ,á,é,í,ó,ú or latin characters. My MySQL DB encoding is UTF-8 Unicode (utf8), Ruby 1.9.2p0 A: Which MySQL gem are you using? You should use the ruby-mysql or the mysql2 gem. See Reads for Rubyists for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JTable Header contains Image and on top of that image I want to place 3 buttons in a single header JTable Header contains Image and on top of that image I want to place 3 buttons in a single header. My requirement is to Create a "Play List" table in which user can add their favourite songs. So in the header I want to put a "Play List" title and "+" button to insert new playlists and "Export" and "Import" buttons. How I can do that? Thanks in Advance. A: I doubt(1) this use-case actually calls for cramming extra components into a JTable header. E.G. Take the UI of DukeBox. We can see the play list on the left (a JTable) with a Filter text field and Random check-box above it, and the Enqueue & History buttons below. This was created with a nested layout. The 'outer layout' is BorderLayout, that panel has the table in the CENTER, and nested panels in the NORTH & SOUTH. The NORTH panel has another BorderLayout, while the SOUTH uses a GridLayout. If using a nested layout does not give you some ideas, I suggest you post a drawing or better, ASCII art, of the UI as it should appear at the smallest size, as well as a representation of it when it is resized (where is the extra width/height assigned?). 1) I have that suspicion every time I hear words to the effect "Wouldn't it be great if we had a component that..?". Of course, there are some classic counter-examples where the standard widget tool-kit seems lacking (e.g. a date picker or switch list), but these are common components to which a name can be put. If the person asking cannot put a 'catchy name' to the custom component, there is a good chance they are over (or under) thinking the matter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bots - detecting JavaScript Events Can Bots figure out JavaScript sections of a webpage? Would it be possible for them to parse through the source code of a webpage (I am guessing the dynamic scripts will show up in the source code) and determine javascript events. Also, I am curious if bots can do this in any other way apart from merely parsing the source code. For example, say there is a script which populates a text field with a random string, whenever a user clicks on a button. By merely parsing the page source, a bot cannot determine what the string will be (since there is just a rand() function). So can the bot in any way guess the actual contents of the string that is entered into the text field. P.S: I am a grad student researching on web bot detection techniques. A: First of all bots are very unlikely to even execute any javascript on your page. With so many zillions of web pages on the internet, it's generally easier to just go scan more web pages than linger trying to solve issues on web pages that only expose content via javascript. Second, a generic bot is not going to know how your web page works and is not going to know what needs to be where before doing some operation on your page. They scrape and parse what they find looking for things of interest. If a URL was in your script as a full URL, they might be smart enough to find that. But, if a URL was built from pieces in your script, it's extremely unlikely than any generic bot would be able to figure out that your code was putting together a URL and what it would be. Third, a specific attacker could analyze your page, figure out how it works and design a way to circumvent certain user operations. But, that's only if some attacker decides to specifically attack/circumvent your site. No generic bot that hasn't been specifically code to your site is going to be able to do that. That's where captcha type operations come into the picture because it's very hard for a script to "read" images to get codes out of them that have to then be submitted to a server - so even bots built for a specific purpose can't really solve captcha-type problems. They can use real people to solve captcha problems, but now it's starting to cost them money and few sites would be worth that. The idea with a lot of these obstacles is to just make the cost of circumventing them more than the benefit of getting in. The snoops are in it to make money so they run the other way when it costs more than they can make. Fourth, you asked about "events". Keep in mind that there are programmatic events (timers, page load events, etc...) and there are user events. Programmatic events will occur only if there is a browser to cause them or if javascript code is executed in a browser-like environment. User events (keys, clicks, mouse movements, etc...) will only occur if there is a browser-like environment in which to interact with the web page and if there is an actual user to create those events. None of these are typically present when a bot reads your page. They use a server-side script to fetch the page and they parse it. They could programmatically drive a browser to load your page and create some of the programmatic events, but there still wouldn't be a user present to create any user events. If a bot knew what user events it was supposed to simulate (button click, for example), it could drive the controlled browser to do that, but at that point, this is not a generic bot in any fashion, but a bot designed specifically to attack your site. If one wants to go to that trouble, it's probably far easier to just engineer how one requests the desired content from your site (so it can just request it direction) rather than try to simulate an actual browser page that does so. If you want to try to detect (from your web server) if something accessing your web page is likely a bot or human, all you can do is to study their access patterns from one page to the next. Bots will "crawl" your site in some programmatic fashion. * *Bots will typically have fairly regular access patterns (a certain amount of time between each page access). Real users are likely to have very different access patterns. *Bots will typically not interact with controls on your page (buttons, fields, etc...) and not cause things to happen that only happen when those controls are used, so no URLs that you might create programmatically when those controls are used would be accessed. *Bots will not know to follow written directions on the page. They will just try to access direct links that they find in the page. *Bots will likely follow links that are never visible - humans usually don't. So, if you see a quick access pattern from your main page to a link that is in your page, but always invisible (CSS style rule display: none), then it's unlikely a human did that. It's probably some programmatic agent (e.g. a bot). So, you can set traps for bots like this that humans won't go to. A: No bots cannot guess the random string generated by javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to release the objects which are in Xib in iphone In my .h file create 3 objects like below IBOutlet UIScrollView *scrollView; IBOutlet UITextView *txtMessage; IBOutlet UIWebView *webView; In xib make Connection for all 3 objects hierarchy in xib like **View ---UIScrollView ---UITextView ---UIWebView** then I am printing retainCount in dealloc method NSLog(@"scrollView retainCount:%d",[scrollView retainCount]); [scrollView release];scrollView=nil; NSLog(@"txtMessage retainCount:%d",[txtMessage retainCount]); [txtMessage release];txtMessage=nil; NSLog(@"webView retainCount:%d",[webView retainCount]); [webView release];webView=nil; on console i am getting like below scrollView retainCount:3 txtMessage retainCount:2 webView retainCount:2 I want to know why its happens like this ,and one more thing how can release this objects in dealloc method... A: I don't think you need to do anything in dealloc. In Objective-C, if you haven't alloc/retain anything, you don't need to worry. A: The answer is: you don't release them. You didn't alloc] init] then, they're not your responsibility memory-wise. The only case where they're somehow your responsibility, is when you retain them using a @property (retain) for the IBOutlets. In that case, you'll release them in [dealloc] Answering to your comment in another answer about instruments and releasing the outlets that the xib creates: if you release them, then the view will be unload sometime and the responsible for releasing the elements in the .xib (which it wasn't you) will release them again, and it will crash ;) The reason why you go back to another view and the memory doesn't decrease is because when a view disappears, it's not unloaded, that only happens when either the view controller is deallocated, or when the application gets a memory warning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java's HttpServletResponse doesn't have isClientConnected method I'm implementing a long poll http connection using java servlet. How can I know that the http client is still active at any instance? Currently, what I do is to write a byte to the output stream and flush data. If there's an IO exception then the client is dead. But in ASP.NET there is a property, Response.IsClientConnected which can find out if the client is active without writing anything to the output stream. I want to know how if it is possible to develop in java servlet. I do not want to keep writing data into the http response stream as it may cost network. Thanks in advance. A: It will be difficult to achieve that using Servlet APIs. Though the low level Socket APIs provide this functionality (Socket.isConnected() ), but same functionality is not available through any higher level APIs. Not sure if you any compulsions of using Servlet APIs or you can use low level socket APIs. A: Maybe you've taken the wrong approach? HTTP protocol is developed to be used in a request-response style, it is not suited to be used for a long polling. In fact, there should be lowest possible delay before client gets a server response. The case you've described looks like a job for a good old Socket.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: In PHP, does suppressing error output of a function (via @) affect performance if no error occurs? Like most of our code base, our mysql handling functions are custom built. They work very well and include a number of logging forks. A simplified version of our query execution function looks like this: if(!$result=mysql_query($query)){ file_put_contents(QUERYLOG,'Query '.$query.' failed execution'); } This is overly simplified, but you get the basic idea: If queries fail, they will be logged to a separate query log. This is a great way of keeping track of any queries that need to be looked at. My question is as follows: With the above, the tiny problem is that if a query fails both our query log, AND our php log will be stamped with the error as a mysql_query (... or mysql_connect, mysql_select_db, etc ...) will produce a php error. What we want to do is surpress the php error via: .... $result=@mysql_query($query .... So, as far as the question goes: Does using the @ error suppression mechanism in php cause any performance impacts if no error is produced? Or does it only affect performance if an error is produced? I know I know, micro optimization, but as you can guess, or query execution function is used millions of times a day, so even a small performance hit is worth examining. A: made a little "research" $s = microtime(true); $a = array('1','2'); $b = $a[1]; echo microtime(true)-$s; gives 1.1205673217773E-5 and if i use $b = @$a[1]; i get a bit more: 1.5974044799805E-5 so: yes, there is a difference, but no, you should not bother.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comparing two ids from two tables in php using mysql This is the SQL statement I have written. $result_array = mysql_query("SELECT * FROM pl_fixtures WHERE id = pl_divisions.id", $con1); It is written to compare values of dbfix.id with dbdiv.id. Can someone please tell me what is my error in comparing these two "id"s? dbfix and dbdiv are two different tables in a same database. Both have id as primary keys. I am using PHP 5. Any help will be appreciated. Thank you :) Regards, BG A: You aren't including the pl_divisions table in your select. Try the following: $result_array = mysql_query("SELECT * FROM pl_fixtures, pl_divisions WHERE pl_fixtures.id = pl_divisions.id", $con1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7606370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: I can find() but I can't save(), why? I'm using CakePHP with SQLite3 DB in Windows 7 x64 with PHP 5.3.8. I've a controller and when do a find("all") the records are retrieved but when I try to save() nothing hapens also when I try to read() and not understand where the problem is. This the code: http://pastebin.com/VNYSh5j3, can any help me to find where the problem is? A: If you're not getting any PHP errors, you should check file permissions. Both your SQLite database file and the directory enclosing it must be writable by PHP. Just having the file be writable is not enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parsingproblem in android saxparsing @Override public void characters(char ch[], int start, int length) throws SAXException { super.characters(ch, start, length); String strCharacters = new String(ch,start,length); if (itemFound==true){ // "item" tag found, it's item's parameter switch(currentState){ case state_title: item.setTitle(strCharacters); break; case state_description: item.setDescription(strCharacters); break; case state_link: item.setLink(strCharacters); break; case state_pubdate: item.setPubdate(strCharacters); break; default: break; } } else { // not "item" tag found, it's feed's parameter switch(currentState){ case state_title: feed.setTitle(strCharacters); break; case state_description: feed.setDescription(strCharacters); break; case state_link: feed.setLink(strCharacters); break; case state_pubdate: feed.setPubdate(strCharacters); break; default: break; } } currentState = state_unknown; } Please tell me how to parse (&) I am not able to parse & in this A: Try it.. it ll help you. private StringBuffer curTag = new StringBuffer(); public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if(localName.equalsIgnoreCase("Test_tag")){ System.out.println(curTag.toString()); } } public void characters(char ch[], int start, int length) { curTag.append(CharBuffer.wrap(ch, start, length)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to process JSON output from WCF in View( MVC3) I have a scenario where the WCF returns the follwing data ( in the function given below) to a VIEW. private List<KeyDatesCalendar> GetKeyDatesCalendarData() { //Dummy Data for BrandsCalendar CheckList var keyDatesCalendar = new List<KeyDatesCalendar>() { new KeyDatesCalendar() { EventText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", EventDate = new DateTime(2011, 02, 09), EventType = 3 }, new KeyDatesCalendar() { EventText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", EventDate = new DateTime(2011, 03, 05), EventType = 3 }, new KeyDatesCalendar() { EventText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", EventDate = new DateTime(2011, 03, 06), EventType = 4 }, }; The processing of the data in view is done by the following code: initCalendars({ from : '02/01/2011', to : '01/31/2013', dates : [ @for(int i=0, l=@Model.KeyDatesCalendar.Count; i<l; i++) { @Html.Raw("['" + @Model.KeyDatesCalendar[i].EventDate.ToString("yyyy/MM/dd") + "'," + @Model.KeyDatesCalendar[i].EventType + ",'" + @Model.KeyDatesCalendar[i].EventText + "']" + (i < (l-1) ? "," : "")); } ] }); Instead of the hardcoded values in WCF method, how Do i recieve a JSON output and process the same in View. I am a beginner here, appreciate your detail answers. Thanks, Adarsh A: I would agree with many of the previous comments, if you're using ASP.NET MVC you might as well do the JSON conversion from there (have a look at JsonResult class). However, if you really want the WCF service to return the result in JSON format, this blog post I wrote a while back might help. Iain
{ "language": "en", "url": "https://stackoverflow.com/questions/7606379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Consuming non-asmx SOAP 1.1 Web Service in C# with Header Security First time poster so please take it a bit easy on me if I break any posting rules - I have read them and I think I'm right. I've been searching for a while before posting and can't seem to find a guide on what I am trying to do so I thought I would post here. I need to write a C# .NET 3.5 program to consume a web service developed in Java. I have practice consuming ASMX web services in .NET using Web References from my experience writing Dynamics CRM plugins and software but this has me stumped. My first attempt was to use a Web Reference (yes, I know - not WCF) however the web service requires a PasswordDigest (SHA-1 with nonce and created), a username token and timestamp token in the SOAP header and I couldn't find a way to add these to the SOAP header using the Web Reference. My second attempt was to use a Service Reference (I believe, but I am probably wrong haha, that this is WCF) however I don't have much practice with this and any tutorials I found online were not much help. Each time when I try to use the WS, I get a rejection from the server for being unable to authenticate. My question is how do I consume a Web Service with these requirements in C# .NET 3.5? Thanks. A: IIRC, Microsoft WSE (either 2.0 or 3.0) had something called UsernameToken, which you need to stuff somewhere in the outgoing SOAP message and you're all set. Granted, this answer leaves a lot to be desired, so I'll throw a couple links at you and hope you'll wade through: http://www.codeproject.com/KB/webservices/WS-Security.aspx http://www.reliablesoftware.com/articles/WSESecurity.html http://www.devx.com/security/Article/15634 (And this all shows yet again how flawed SOAP and WSDL actually are).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TFS query Column option not showing all the columns I have a column in WIT (work item template) named " Planned end date" and Reference as "SV.Deadline" . But when i create a query, and want to add this column to appear in query through "Column Options" , i do not find this column in the list. Can anybody help ? Also how can i delete a work item from TFS in VS2010 A: Did you choose the correct work item type in the column dialog? Did you refresh your cache? To delete a work item type use witadmin destroywitd To delete a work item use witadmin destroywi
{ "language": "en", "url": "https://stackoverflow.com/questions/7606382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are some examples of problems well suited for Integer Linear Programming? I've always been writing software to solve business problems. I came across about LIP while I was going through one of the SO posts. I googled it but I am unable to relate how I can use it to solve business problems. Appreciate if some one can help me understand in layman terms. A: First, read a linear programming example from Wikipedia Now imagine the farmer producing pigs and chickens, or a factory producing toasters and vacuums - now the outputs (and possibly constraints) are integers, so those pretty graphs are going to go all crookedly step-wise. That's a business application that is easily represented as a linear programming problem. I've used integer linear programming before to determine how to tile n identically proportioned images to maximize screen space used to display these images, and the formalism can represent covering problems like scheduling, but business applications of integer linear programming seem like the more natural applications of it. SO user flolo says: Use cases where I often met it: In digital circuit design you have objects to be placed/mapped onto certain parts of a chip (FPGA-Placing) - this can be done with ILP. Also in HW-SW codesign there often arise the partition problem: Which part of a program should still run on a CPU and which part should be accelerated on hardware. This can be also solved via ILP. A: ILP can be used to solve essentially any problem involving making a bunch of decisions, each of which only has several possible outcomes, all known ahead of time, and in which the overall "quality" of any combination of choices can be described using a function that doesn't depend on "interactions" between choices. To see how it works, it's easiest to restrict further to variables that can only be 0 or 1 (the smallest useful range of integers). Now: * *Each decision requiring a yes/no answer becomes a variable *The objective function should describe the thing we want to maximise (or minimise) as a weighted combination of these variables *You need to find a way to express each constraint (combination of choices that cannot be made at the same time) using one or more linear equality or inequality constraints Example For example, suppose you have 3 workers, Anne, Bill and Carl, and 3 jobs, Dusting, Typing and Packing. All of the people can do all of the jobs, but they each have different efficiency/ability levels at each job, so we want to find the best task for each of them to do to maximise overall efficiency. We want each person to perform exactly 1 job. Variables One way to set this problem up is with 9 variables, one for each combination of worker and job. The variable x_ad will get the value 1 if Anne should Dust in the optimal solution, and 0 otherwise; x_bp will get the value 1 if Bill should Pack in the optimal solution, and 0 otherwise; and so on. Objective Function The next thing to do is to formulate an objective function that we want to maximise or minimise. Suppose that based on Anne, Bill and Carl's most recent performance evaluations, we have a table of 9 numbers telling us how many minutes it takes each of them to perform each of the 3 jobs. In this case it makes sense to take the sum of all 9 variables, each multiplied by the time needed for that particular worker to perform that particular job, and to look to minimise this sum -- that is, to minimise the total time taken to get all the work done. Constraints The final step is to give constraints that enforce that (a) everyone does exactly 1 job and (b) every job is done by exactly 1 person. (Note that actually these steps can be done in any order.) To make sure that Anne does exactly 1 job, we can add the constraint that x_ad + x_at + x_ap = 1. Similar constraints can be added for Bill and Carl. To make sure that exactly 1 person Dusts, we can add the constraint that x_ad + x_bd + x_cd = 1. Similar constraints can be added for Typing and Packing. Altogether there are 6 constraints. You can now supply this 9-variable, 6-constraint problem to an ILP solver and it will spit back out the values for the variables in one of the optimal solutions -- exactly 3 of them will be 1 and the rest will be 0. The 3 that are 1 tell you which people should be doing which job! ILP is General As it happens, this particular problem has a special structure that allows it to be solved more efficiently using a different algorithm. The advantage of using ILP is that variations on the problem can be easily incorporated: for example if there were actually 4 people and only 3 jobs, then we would need to relax the constraints so that each person does at most 1 job, instead of exactly 1 job. This can be expressed simply by changing the equals sign in each of the 1st 3 constraints into a less-than-or-equals sign. A: A sample ILP problem will looks something like: * *maximize 37∙x1 + 45∙x2 where * *x1,x2,... should be positive integers ...but, there is a set of constrains in the form * *a1∙x1+b1∙x2 < k1 *a2∙x1+b2∙x2 < k2 *a3∙x1+b3∙x2 < k3 *... Now, a simpler articulation of Wikipedia's example: * *A farmer has L m² land to be planted with either wheat or barley or a combination of the two. *The farmer has F grams of fertilizer, and P grams of insecticide. *Every m² of wheat requires F1 grams of fertilizer, and P1 grams of insecticide *Every m² of barley requires F2 grams of fertilizer, and P2 grams of insecticide Now, * *Let a1 denote the selling price of wheat per 1 m² *Let a2 denote the selling price of barley per 1 m² *Let x1 denote the area of land to be planted with wheat *Let x2 denote the area of land to be planted with barley *x1,x2 are positive integers (Assume we can plant in 1 m² resolution) So, * *the profit is a1∙x1 + a2∙x2 - we want to maximize it *Because the farmer has a limited area of land: x1+x2<=L *Because the farmer has a limited amount of fertilizer: F1∙x1+F2∙x2 < F *Because the farmer has a limited amount of insecticide: P1∙x1+P2∙x2 < P a1,a2,L,F1,F2,F,P1,P2,P - are all constants (in our example: positive) We are looking for positive integers x1,x2 that will maximize the expression stated, given the constrains stated. Hope it's clear... A: ILP "by itself" can directly model lots of stuff. If you search for LP examples you will probably find lots of famous textbook cases, such as the diet problem Given a set of pills, each with a vitamin content and a daily vitamin quota, find the cheapest cocktail that matches the quota. Many such problems naturally have instances that require varialbe to be integers (perhaps you can't split pills in half) The really interesting stuff though is that actually a big deal of combinatorial problems reduce to LP. One of my favourites is the assignment problem Given a set of N workers, N tasks and an N by N matirx describing how much each worker charges for the each task, determine what task to give to each worker in order to minimize cost. Most solution that naturally come up have exponential complexity but there is a polynomial solution using linear programming. When it comes to ILP, ILP has the added benefit/difficulty of being NP-complete. This means that it can be used to model a very wide range of problems (boolean satisfiability is also very popular in this regard). Since there are many good and optimized ILP solvers out there it is often viable to translate an NP-complete problem into ILP instead of devising a custom algorithm of your own. A: You can apply linear program easily everywhere you want to optimize and the target function is linear. You can make schedules (I mean big, like train companies, who need to optimize the utilization of the vehicles and tracks), productions (optimize win), almost everything. Sometimes it is tricky to formulate your problem as IP and/or sometimes you meet the problem that your solution is, that you have to produce e.g. 0.345 cars for optimum win. That is of course not possible, and so you constraint even more: Your variable for the number of cars must be integer. Even when it now sounds simpler (because you have infinite less choices for your variable), its actually harder. In this moment it gets NP-hard. Which actually means you can solve ANY problem from your computer with ILP, you just have to transform it. For you I would recommend an intro into reading some basic (I)LP stuff. From my mind I dont know any good online site (but if you goolge you will find some), as book I can recommend Linear Programming from Chvatal. It has very good examples, and describes also real use cases. A: The other answers here have excellent examples. Two of the gold standards in business of using integer programming and more generally operations research are * *the journal Interfaces published by INFORMS (The Institute for Operations Research and the Management Sciences) *winners of the the Franz Edelman Award for Achievement in Operations Research and the Management Sciences Interfaces publishes research that uses operations research applied to real-world problems, and the Edelman award is a highly competitive award for business use of operations research techniques.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to restart id counting on a table in PostgreSQL after deleting some previous data? I'm using PostgreSQL database on Rails 2.3.8 and I need to restart auto increment ID on my table. How can I do that? A: You can do it directly in PostgreSQL using "alter sequence": http://www.postgresql.org/docs/current/static/sql-altersequence.html Particularly "restart with" I don't know how you would do it via the rails abstraction. A: Try: ActiveRecord::Base.connection.reset_pk_sequence!(table_name) and check this answer for more details: https://stackoverflow.com/a/7814519/1392282 A: Check out setval SELECT setval('foo', 42); Next nextval will return 43 SELECT setval('foo', 42, true); Same as above SELECT setval('foo', 42, false); Next nextval will return 42 A: If you want to delete all data from table and want to reset id as well then try below code. ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY") But if some relationship is present with table and you want to delete all data from table as well as related table data then try below code. ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY CASCADE") Thanks and please suggest if correction needed. A: If you truncate the table you can use the RESTART IDENTITY clause on the end. Example: TRUNCATE TABLE foo RESTART IDENTITY; TRUNCATE DOCUMENTATION A: You could do it in the following way: ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY") A: You can use ActiveRecord in Rails. You can easily do it from your rails console by running the following command: Table_name.reset_primary_key You can also use SQL : TRUNCATE TABLE foo RESTART IDENTITY;
{ "language": "en", "url": "https://stackoverflow.com/questions/7606386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What is the use of "lenient "? Here lenient is used in Java DateFormat. I checked the doc, but didn't get what it was saying. Can any body please tell me what is the use of this lenient, with one real time example where we use it? A: DateFormat object is lenient by default. Leniency (Javadoc - Calendar) Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1. When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set. A: The javadoc clearly states: Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format. So, if you have a pattern and create a date object that strictly matches your pattern, set lenient to false. Also, DateFormat is lenient, by default. Basically, DateFormat sets Calendar.setLenient and the Javadoc states: Specifies whether or not date/time interpretation is to be lenient. With lenient interpretation, a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient. A: You can set the date parser as not lenient if you want it to accept strictly a date format you provided. It is well explained in the doc: By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false). A: For example this: SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy"); System.out.println(simpleDateFormat.parse("0")); simpleDateFormat.setLenient(false); System.out.println(simpleDateFormat.parse("0")); results in: Thu Jan 01 00:00:00 CET 1 Exception in thread "main" java.text.ParseException: Unparseable date: "0" at java.text.DateFormat.parse(Unknown Source) at net.java.quickcheck.generator.support.X.main(X.java:28) A: My advice is to always turn lenient off. I cannot think of a case where you want lenient on, and this setting should never have been the default for classes like SimpleDateFormat. Lenient processing can interpret garbage as valid time strings and opens up errors that may be difficult to catch in testing. Also, if you are using lenient to tolerate variations in time format you are going to get burned. For example: System.out.println(new SimpleDateFormat("yyyyMMdd").parse("2010-12-30")); Yields this (your time zone may vary): Mon Nov 02 00:00:00 EST 2009 This absurd result appears to be the minus one month ("-1"), second day ("2-") of 2010. The zeroth month is December! Unfortunately, using setLenient(false) does not lead to strict interpretation of the pattern. SimpleDateFormat will tolerate garbage following the pattern match, as discussed here: SimpleDateFormat.parse() ignores the number of characters in pattern Also, it is not strict about the number of pattern characters, such as "d" instead of "dd": SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d"); sdf.setLenient(false); System.out.println("For 5: " + sdf.parse("2010/01/5")); System.out.println("For 05: " + sdf.parse("2010/01/05")); System.out.println("For 15: " + sdf.parse("2010/01/15")); Yields: For 5: Tue Jan 05 00:00:00 EST 2010 For 05: Tue Jan 05 00:00:00 EST 2010 For 15: Fri Jan 15 00:00:00 EST 2010 Also with setLenient(false) "2010/01/5" is accepted with the pattern "yyyy/MM/dd". And data disagreement is ignored, like "1999/2011" with the pattern "yyyy/yyyy" (answer is 2011). Using SimpleDateFormat to validate date/time strings is sadly unreliable. If you follow the link above you will see some solutions, including a stricter version of SimpleDateFormat written by me! A: If date is not lenient it will throw error if you pass out of range date but if is not then it will accept is and fix it . e.g August 61st from comment above will become September 30th. Java doc on how to set it . Default is true. A: Leniency refers to whether or not a strict rule will be applied at parsing. If a DateFormat object is lenient, it will accept Jan 32, 2005. In fact, it will take the liberty of converting it to Feb 1, 2006. By default, a DateFormat object is lenient. import java.text.DateFormat; import java.text.ParseException; import java.util.Date; public class MainClass { public static void main(String[] args) { DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM); DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG); DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(shortDf.format(new Date())); System.out.println(mediumDf.format(new Date())); System.out.println(longDf.format(new Date())); System.out.println(fullDf.format(new Date())); // parsing try { Date date = shortDf.parse("Jan 32, 2005"); } catch (ParseException e) { } } } And the result: 1/26/07 Jan 26, 2007 January 26, 2007 Friday, January 26, 2007
{ "language": "en", "url": "https://stackoverflow.com/questions/7606387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: TFS query not opened properly in Microsoft project When open a query in Microsoft project, the start date changes. Please note that, the start date is a custom field. A: I found the answer, update the mappingfile of your project to map the custom tfs field to Project's start field like : the mapping file can be upload, downloaded using "TFSfieldmapping" command on vs command prompt. I am still facing a problem, that is when the task has child items, the start date is not reflected. Only for a task that has no child items, the date is reflected properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Free online php pastebins that "interpret" your code? I used to use: http://codepad.viper-7.com However it seems like it's down atm. Are there any other php pastebins that "interpret" code? EX. typing in this: <?php echo "Hello, World!"; ?> Would print Hello, World! A: When I need to quickly test a php string, I always use the command line, like this: php -r "var_dump((bool) null);" php -r "var_dump((bool) '');" php -r 'echo "Hello, World!";' Protips©
{ "language": "en", "url": "https://stackoverflow.com/questions/7606391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move the textbox cursor to the last index of text? I have a text box where the user can enter details up to 140 characters after that a dialog box pop up which showing maximum limit reached .My problem is that after the message box is shown the cursor is blinking at the beginning of the text.and also further typing is possible.I have to do two things one is the cursor should blinking at the end of text after message box shown.and next is when the user hit characters more than 140 it should not be entered in the text box.?Please give me a solution for this Here is my code. private void tbMessage_TextChanged(object sender, TextChangedEventArgs e) { string txt = tbMessage.Text; Regex regx = new Regex("\\(?\\b(http|https)://([-A-Za-z0-9+&@#/%?=~_()|!:,.;\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]*[-A-Za-z0-9+&@#/%=~_()|])"); regx.Matches(txt); MatchCollection mactches = regx.Matches(txt); foreach (Match match in mactches) { txt = txt.Replace(match.Value, "<--------------------->"); } textBlockNumberLimit.Text = txt.Length.ToString() + "/140"; if (txt.Length > 140) { try { MessageBox.Show("Maximum limit reached", "SPRINKLR", MessageBoxButton.OK); tbMessage.Text = tbMessage.Text.Substring(0, tbMessage.Text.Length - 1); } catch { } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to animate my view? Recently I saw a mobile "Karbonn Tornado" has one one application that shows applications on loading page in device as Tornado model.Means how tornado action goes in the same way here animates.Is it possible in iPhone.Please support with an example or supporting materials to do it. A: possible with openGL but even than the layout of the apps is looked out by the OS .. there is nothing you can do about it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to use google Authorization service in our android application? i am making google calendar application in android and i don't know how to use google Authorization service in our android application? A: This project describes google auth and this tutorial for calendar. A: check the OAuth concept in this you can implement by this OAuth. check this post links Android Google Calendar Authorization Problem Synchronising Google Calendar to my application in Android Google calendar: how to access it on android http://code.google.com/p/google-api-java-client/wiki/Android A: HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("<URL HERE>"); try { List<NameValuePair> parameters = new ArrayList<NameValuePair>(2); parameters.add(<name_value_pair>); parameters.add(<name_value_pair>); httppost.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse response = httpclient.execute(httppost); StatusLine returned_status = response.getStatusLine(); int status_code = returned_status.getStatusCode(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Access VBA: enter expression in user form, store calculated result in table? I've got a form that I'd like users to be able to enter simple maths into, with the calculated value stored in the table. For example: * *User enters "1+5" into a text box. *The answer 6 is stored in the database table. Currently, entering "1+5" in my numeric form field results in an error re: 'entering text into a numeric field'. Is there any way to do this? A: You can write a VBA script to parse the input and perform any needed calculations. This could be triggered by an unbound form field's BeforeUpdate event. Steps: * *Create a field named Field1 for the calculated value (bound to the appropriate database field). *Add an unbound field to your form and name it Input1. *In Design view, right-click on Input1 and choose Properties. Under Events -> Before Update, click the "..." button. *Insert the VBA code that I have written (below). *Save your changes and close the VBA editor. *Return to Form view and enter an expression into your Input1 field. When you tab out of the field, the expression will be evaluated and the value will appear in Field1. Note that, for reasons of security and/or data integrity, you may need to sanitize your user input before evaluating it as an expression. The details of "how" and "why" fall outside the scope of the original question. Private Sub Input1_BeforeUpdate(Cancel As Integer) ' TO-DO: Validate/sanitize input as necessary for security & validity; ' Exit Sub prior to the Eval() if we see something we don't like Dim result As Variant result = Eval(Input1.Value) ' Evaluate the contents of Input1 If IsNumeric(result) Then Field1 = result ' Save any numeric result to Field1 End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7606407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Interpreting gprof output with I am trying to find a performance issue in my program and thus instrumented the code with profiling. gprof creates a flat profile like this: Flat profile: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls ms/call ms/call name 27.97 4.10 4.10 std::_Deque_iterator<char, char&, char*>::_Deque_iterator(std::_Deque_iterator<char, char&, char*> const&) 6.96 5.12 1.02 std::_Deque_iterator<char, char&, char*>::difference_type std::operator-<char, char&, char*>(std::_Deque_iterator<char, char&, char*> const&, std::_Deque_iterator<char, char&, char*> const&) 5.12 5.87 0.75 std::__deque_buf_size(unsigned int) 4.23 6.49 0.62 std::_Deque_iterator<char, char&, char*>::operator+=(int) 3.41 6.99 0.50 std::deque<char, std::allocator<char> >::begin() 1.91 7.27 0.28 7896 0.04 0.04 std::vector<MyClass, std::allocator<MyClass> >::_M_insert_aux(__gnu_cxx::__normal_iterator<MyClass*, std::vector<MyClass, MyClasst> > >, MyClassconst&) 1.91 7.55 0.28 std::deque<char, std::allocator<char> >::size() const 1.91 7.83 0.28 std::_Deque_iterator<char, char&, char*>::_S_buffer_size() followed by many lines with less time. First question: is it a valid assumption to believe that there seems to be a problem with a std::deque? The problem is: I know we are using std::deque, but I am not aware of a usage with <char>. If this assumption is true, it seems to make sense to look at the call stack and see where this deque is used. Howevre all entries concerning the deque<char> stuff are only called by <spontaneous>! Just one example: index % time self children called name <spontaneous> [1] 28.0 4.10 0.00 std::_Deque_iterator<char, char&, char*>::_Deque_iterator(std::_Deque_iterator<char, char&, char*> const&) [1] Is there any way to find out more about this deque? Thanks for any hints! A: Apparently, spontaneous is what gprof uses when it can't work out the calling function. I would try recompiling all code with -pg (is it possible you missed some files?). Also, make sure you have optimisation turned on. Inlining will typically make these little functions disappear into the calling function which is generally more useful. A: The accepted answer is corret. Another reason you might find a lot of <spontaneous> entries is if you pass gprof the wrong executable. Make sure you pass the same compiled binary you generated the gmon.out file to gprof to generate the analysis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to parse a stream as it's been fed to MediaPlayer? I'm tinkering with a very simple streaming web radio player, using MediaPlayer's (relatively new) stream URL methods, something like: MediaPlayer mp = new MediaPlayer(); mp.setDataSource("http://stream.infowars.com"); mp.prepare(); mp.start(); (exception handling omitted here for simplicity) This works real well (and even better after recent upgrade to 2.3.4 - no more drop-outs :-) It is my understanding that many web radio streams have embedded song titles. I want to be able to parse the steam as it goes by and pick off the song title text so as to display it on-screen. I know I could probably do this the old-fashioned way (pre Android 2) - by manually opening the file and parsing it as I manually feed to MediaPlayer, but this would entail a whole lot of work that I'd rather avoid (unless there's no other way). I'm guessing I could probably also get to these embedded tags by opening a second instance of the same stream, just for reading, but of course this is way inefficient and too much overhead. Can anybody point me in the right direction? Is this even possible?? TIA
{ "language": "en", "url": "https://stackoverflow.com/questions/7606411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP - Include inside Include (Not passing variables) Lets say we have 3 files: File1.php, File2.php, File3.php I want to have it where in File1.php I include() File2.php. Then in File2.php I include() File3.php. I tested it out by writing test text in File3.php, and when I viewed File1.php I could see that test text. Now my problem is that if I make a variable, say '$test = "Success!";', in File3.php and then I try to call it in File1.php with 'echo $test;' it outputs nothing. It's not transferring the variables, but it is transferring standard text. What's going on here? (P.S. The reason I'm doing it like this is because of organization.) EDIT Here's my exact code: (also forgot to mention that I'm grabbing the url of the site first) file3.php <?php $test = "Success!"; file2.php <?php include 'http://' . $_SERVER['SERVER_NAME'] . '/file3.php'; file1.php <?php include 'http://' . $_SERVER['SERVER_NAME'] . '/file2.php'; echo $test; A: echo "$test"; //with double quotes :) // or echo $test; Can you provide more code? Per http://php.net/manual/en/function.include.php : When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. Check Example #1 Edit: Per http://php.net/manual/en/features.remote-files.php : In addition, URLs can be used with the include(), include_once(), require() and require_once() statements (since PHP 5.2.0, allow_url_include must be enabled for these) So, you cannot include files with the URL, instead, as stated in my comment, use local path. Unless you have allow_url_fopen enabled. This should work. A: If your files have these lines, then echo would print out your message: File1.php: <?php include 'File2.php'; echo $test; ?> File2.php: <?php include 'File3.php'; ?> File3.php: <?php $test='success!'; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php foreach values assign into while loop rows I have two tables which stored question and answer, as below script is used to fetch serialize answers and would unserialize each of it into an array as following: while($ans_row = mysql_fetch_array($q_chkans)){ $answer = unserialize($ans_row["a_answered"]); foreach($answer as $val){ for($i=0; $i<=3; $i++){ $r[$i] = $answer[$i]; } } for example, let said after an unserialize process, I get each array elements as below: $r[0] = a $r[1] = b $r[2] = c with those a, b and c, I want to assign each of them into another table loop, which was fetch it question, like below: 1) question a? answer a. 2) question b? answer b. 3) question c? answer c. but my code was always return all answer like 1) question a? answer a b c. 2) question b? answer a b c. 3) question c? answer a b c. Full code as below: $ques_data = array(); $q_ques = mysql_query("SELECT * FROM ".$tb03." WHERE ques_section='".$sectid."' AND ques_status='1' ORDER BY ques_id") or die(mysql_error()); while($rows = mysql_fetch_assoc($q_ques)){ $ques_data[] = $rows; } $q_chkans = mysql_query("SELECT * FROM ".$tb08." WHERE a_usrid='".$_COOKIE["loggedId"]."' AND a_section='".$sectid."'") or die(mysql_error()); $numrows = mysql_num_rows($q_chkans); $q_sect = mysql_query("SELECT * FROM ".$tb02." WHERE sect_id='".$sectid."' LIMIT 0, 1") or die(mysql_error()); $r_sect = mysql_fetch_array($q_sect); $section = $r_sect["sect_id"]; echo "<div class='sect_list'><b style='color:#000;'>".sprintf("%1\$.1f",$no)."&nbsp;&nbsp;".ucwords($r_sect["sect_title"])."</b></div>".$staff_txt; foreach($ques_data as $ques_rows){ echo "<div class='ques_list'> <div><b>".$sectid.".".$no."</b>&nbsp;&nbsp;".ucwords($ques_rows["ques_title"])."</div> <div class='ques_rmk'>".ucwords($ques_rows["ques_rmk"])."</div> <div class='answer'>"; if($numrows <= 0){ $q_ans = mysql_query("SELECT * FROM ".$tb04." WHERE input_ques_id='".$ques_rows["ques_id"]."'") or die(mysql_error()); if($ques_rows["ques_type"] == 1){ echo "<select name='txtOpt_".$section."_".$no."'>"; while($ans_rows = mysql_fetch_array($q_ans)){ echo "<option value='".$ans_rows["input_mark"]."'>".$ans_rows["input_title"]."</option>"; } echo "</select>"; }else{ echo "<input type='text' name='txtbox_".$section."' value='' style='width:500px;height:18px;' />"; } }else{ while($ans_row = mysql_fetch_array($q_chkans)){ $answer = unserialize($ans_row["a_answered"]); foreach($answer as $val){ for($e=0; $e<=count($answer); $e++){ $r[$e] = $answer[$e]; } } } } echo " </div> </div>"; $no += 1; } How can I make each of the answer could proper assign into its own question? Please advise, Thanks! A: Try this: while($ans_row = mysql_fetch_array($q_chkans)){ $answer = unserialize($ans_row["a_answered"]); foreach($answer as $i => $val){ $r[$i] = $val; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tsql substring or string manipulation i have an nvarchar(max) column and i need to extract everything between the opening a href tags and the closing a href tag. for example if the contents of my column where the following: Here you can visit <a href="http://www.thisite.com">this link</a> or this <a href="http://www.newsite.com">new link</a>. this is just a test to find the right answer. then my results of my query should be: "<a href="http://www.thisite.com">this link</a>" "<a href="http://www.newsite.com">new link</a>" any help would be greatly appreciated! A: You have to use CLR User-defined function (supported in Sql Server 2005+): Regular Expressions Make Pattern Matching And Data Extraction Easier A: declare @a varchar(max) = 'Here you can visit <a href="http://www.thisite.com">this link</a> or this <a href="http://www.newsite.com">new link</a>. this is just a test to find the right answer. ' ;with cte as ( select cast(1 as bigint) f, cast(1 as bigint) t union all select charindex('<a href=', @a, t), charindex('</a>', @a, charindex('<a href=', @a, t)) from cte where charindex('<a href=', @a, t) > 0 ) select substring(@a, f, t-f)+'</a>' from cte where t > 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7606418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mem_func and for_each usage How to call class member function using std::for_each Here is what my class is. template <typename _TyG> class Graph { private: public: typedef typename Vertex<_TyG> VertexType; typedef typename std::set<VertexType> GraphStorage; typedef typename GraphStorage::iterator GraphStorageItr; typedef typename GraphStorage::const_iterator GraphStorageConstItr; typedef typename std::list<VertexType *> AdjListType; typedef typename AdjListType::iterator AdjListTypeItr; typedef typename AdjListType::const_iterator AdjListTypeConstItr; typedef typename std::map< VertexType*, AdjListType, CompareIterator<VertexType*> > GraphType; typedef typename GraphType::iterator GraphTypeItr; typedef typename GraphType::const_iterator GraphTypeConstItr; void _init_not_visited(GraphTypeItr inItr) { } void DepthFirstSearch() { std::for_each(m_Graph.begin(), m_Graph.end(), std::bind2nd(std::mem_fun(&Graph::_init_not_visited),this)); } } What I want is to pass iterator to _init_not_visited. But I am confuse on how to use std::for_each, current code is giving me compilation error. A: I do not think you can do what you want to do with std::for_each. As std::for_each calls the given function on each value in the sequence and not each iterator position in the sequence. std::for_each might look like: template <class iter_t, class fn_t> fn_t for_each(iter_t first iter_t const last, fn_t fn) { for (; first != last; ++first) fn(*first); return fn; } You can either write your own for_each_iter such as: template <class iter_t, class fn_t> fn_t for_each_iter(iter_t first, iter_t const last, fn_t fn) { for (; first != last; ++first) { fn(first); } return fn; } Or change _init_not_visited() to take GraphType::value_type instead of GraphTypeItr. Assuming that you can still write the function with that argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: minesweeper java I am working on a minesweeper program in Java. I have my bombs distributed throughout the field, and I have my actionlisteners responding to clicks and mouselistener, responding to right clicks. I also have each square that is clicked check to see how many bombs are adjacent to it and print the number on the square just like in the game. The only part I don't understand is how minesweeper opens up field when clicking a square whether it be a number or a blank square. Please help me understand how this works. A: The only part I don't understand is how minesweeper opens up field when clicking a square whether it be a number or a blank square. If any of its neighboring squares has a mine, it will show a number with the number of mines around it. It's blank if there are no mines around it (ie: it would show the number 0 if it had to). When it's blank it also recursively opens all its neighbors (eg: opens all neighbors and their neighbors if they are blank too, and so forth). And if it's a mine you lose of course. An example: X 2 . . X 2 . . 2 2 1 . 1 X 1 . (let X denote a mine). If you open any of the squares with marked as . (blank), automatically expand all of them and the numbers next to them: - 2 . . - 2 . . - - 1 . - - 1 . (let - denote a hidden square). A: If it's a bomb, you lose. If it's a number then it just reveals that number. If it's a null square, that is to say, one with no adjacent bombs, then it is a blank square and upon being revealed the game reveals all other squares in contact with it that are blank ( this process continues until all squares which are adjacent to the newly created null field are ones which are them selves adjacent to at least one bomb ( that is to say, have a number ))
{ "language": "en", "url": "https://stackoverflow.com/questions/7606427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make Google oAuth remember user approval for permissions? While using Google OpenID, there is an already selected option for "remember approval". How can the same be achieved for a login with OAuth 2.0 ? It seems to ask permission everytime for the defined scope settings, whereas in facebook Oauth 2.0, it asks only once. OpenID example from Stack Exchange, with "remember this approval" option A: http://googleappsdeveloper.blogspot.com/2011/10/upcoming-changes-to-oauth-20-endpoint.html see Change #3: Server-side auto-approval
{ "language": "en", "url": "https://stackoverflow.com/questions/7606432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I automatically minify my webpages? All of my .html and .php webpages should be minified. That means I would like to get all HTML-comments and more than one whitespace-character stripped. Does an Apache-module exist for minification? (Or perhaps another method to automatically add a script directly before the output gets sent to the user?) (I could add a function like the following, but if an Apache-module or another automatic solution existed, I could not forget to do so.) <? function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', //strip whitespaces after tags, except space '/[^\S ]+\</s', //strip whitespaces before tags, except space '/(\s)+/s' // shorten multiple whitespace sequences ); $replace = array( '>', '<', '\\1' ); $buffer = preg_replace($search, $replace, $buffer); return $buffer; } ?> A: Try mod_pagespeed which may be of some use to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: get application path codeigniter with out contents after last slash hi i am using codeigniter in my application . for my application i need application path only before the last slash like this if application path is http://localhost/elephanti/connections/fb_connection/invite_friends i want to get http://localhost/elephanti/connections/fb_connection it is for a plae like this echo "<script type='text/javascript'>top.location.href = '"+APPPATH+"'testapp';</script>"; i tried to use '"+APPPATH+"'../testapp' but could not , please help ................... A: If you know the last part will always be the 4th, you can use a "dirty way" like this: $url = site_url($this->uri->segment(1).'/'.$this->uri->segment(2).'/'.$this->uri->segment(3)); And then: echo "<script type='text/javascript'>top.location.href = '".$url."'/testapp';</script>"; // here, though, I don't understan how "testapp" goes into the url..as a segment? This will create a valid CI url using only the first 3 segments. Alternatively, you can use the uri_string() function, wich returns only the segment part of the url. On this, you can explode/str_replace/array_pop/do whatever you need to and pass the new elaborated string on the site_url() function wichi will build the correct URL for you. I don't understand what "testapp" is there or, do you want to substitute the last segment of your url with that? So that you have, in your example, http://localhost/elephanti/connections/fb_connection/testapp ? Keep in mind that both uri_string() and site_url() are functions from the URL helper so you need to load it. A: * *In Codeigniter APPPATH referes to the location on the disk and not the url of the application. What you are looking for is base_url(). base_url() return the base location of your site, which usually is the domain. *Concatenation in php is done with the dot operator: "." echo "top.location.href = '".base_url()."'testapp';";
{ "language": "en", "url": "https://stackoverflow.com/questions/7606435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mapping letters to integers in MATLAB The function arithenco needs the input message to be a sequence of positive integers. Hence, I need convert a message into a sequence of numbers message_int, by using the following mapping. ‘A’→1, ‘C’→2, ‘G’→3, ‘T’→4. A: From what I understand, the alphabet you are using contains only four values A,C,G,T (DNA sequences I suppose). Simple comparison would suffice: seq = 'TGGAGGCCCACAACCATTCCCTCAGCCCAATTGACCGAAAGGGCGCGA'; msg_int = zeros(size(seq)); msg_int(seq=='A') = 1; msg_int(seq=='C') = 2; msg_int(seq=='G') = 3; msg_int(seq=='T') = 4; A: Oh, just reread your question: your mapping is not so simple. Sorry. (since darvidsOn wrote the same I won't delete this answer - it might give you a start - but it doesn't answer your question completely). Have a look at http://www.matrixlab-examples.com/ascii-chart.html You can use d = double('A') to convert a char into a double- you will then need to subtract 64 to get the mapping that you want (because A is ascii code 65).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Imail Server Express 11.5 Server APi for .Net : Unable to load DLL 'IMailsec.dll': The handle is invalid I am writing a custom application for IMAIl express 11.5 using IMAIl Server API for .Net I am using the following code: Dim DomData As New DomainData() DomData.Aliases = "TestALias" DomData.HostName = "TestImailDomain.com" DomData.TopDir = IMailAPI_NET.IMailSystem.TopDir & "\TestImailDomain.com" DomData.UserDBType = DomainData.DBTYPES.IMail DomData.UserDB = "TestUserDB" DomData.IPAddress = "192.168.1.12" DomData.IMEnabled = True DomData.MaxSize = 100 DomData.MaxOutboundSize = 100 DomData.MaxSingleMessageSize = 100 DomData.MaxMsgs = 20 DomData.MaxUsers = 0 DomData.AllowedLoginAttempts = 20 DomData.AllowedLoginLockouts = 10 DomData.DefaultWebReqPwdLevel = 0 DomData.SaveHost(True) I get the following error (in api logs created by imail): 9/30/2011 - 10:47 AM : Error : IMailAPI_NET.DomainData.SaveHost-2 : Unable to load DLL 'IMailsec.dll': The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE)) Please advise. Thanks. A: Likely as not, you added IMailAPI_NET.dll as a project dependency, but Visual Studio is not copying over IMailAPI_NET.dll's dependencies. I would recommend copying the following files from IMail into your project's binary directory: imailsec.dll, mailbox.dll and IpswitchLicense.dll
{ "language": "en", "url": "https://stackoverflow.com/questions/7606443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: try-catch slowness for static methods in Java I was checking out this discussion: How slow are Java exceptions? and while experimenting, found out that if I run static methods instead of instance methods, the normal path actually takes more time than try-catch path. What I'm doing is: create a no-op static foo() method, create static method method1() that calls foo() 100000000 times normally, and another static method method2() which calls foo() 100000000 times in a try-catch block. What I see is, method2 actually takes less time than method1. Any thoughts? public class ExceptionsStatic { public static void main(String... args) { withNormal(); withTry(); } static void foo() { } static void foo2() throws Exception { } static void withTry() { long t1 = System.currentTimeMillis(); for(int i = 0; i < 100000000; i++) { try { foo2(); } catch(Exception e) { } } long t2 = System.currentTimeMillis(); System.out.println("try time taken " + (t2 - t1)); } static void withNormal() { long t1 = System.currentTimeMillis(); for(int i = 0; i < 100000000; i++) { foo(); } long t2 = System.currentTimeMillis(); System.out.println("normal time taken " + (t2 - t1)); } } A: I have attempted to re-create your test code and then run it through javap. These are given at the end so that you don't have to scroll through a large text block. Note that when there is no absolutely no optimisation performed by the VM, the bytecode is executed as per the javap dump below. Thus, assuming no other external factors, execution of method2() should always take longer as it includes an additional instruction (line 11: goto 15). Of course, as Joachim mentions below, 'the bytecode says very little about performance'. There are a lot of flags available for profiling and enabling/disabling JVM optimisations. Have a look around online. For 1.4.2, I found this link which may work with newer JREs also. Edited to add: In supported VMs, you can enable JIT trace output by using the following VM flag -XX:-PrintCompilation. javap output: Ryan-Schippers-MacBook-Pro-2:Miscellaneous work$ javap -c -classpath ./src SlowTryCatch Compiled from "SlowTryCatch.java" public class SlowTryCatch extends java.lang.Object{ public SlowTryCatch(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: return public static void foo(); Code: 0: return public static void method1(); Code: 0: iconst_0 1: istore_0 2: iload_0 3: ldc #2; //int 100000000 5: if_icmpge 17 8: invokestatic #3; //Method foo:()V 11: iinc 0, 1 14: goto 2 17: return public static void method2(); Code: 0: iconst_0 1: istore_0 2: iload_0 3: ldc #2; //int 100000000 5: if_icmpge 21 8: invokestatic #3; //Method foo:()V 11: goto 15 14: astore_1 15: iinc 0, 1 18: goto 2 21: return Exception table: from to target type 8 11 14 Class java/lang/Exception } A: I have modified your code a bit so the optimizer does not remove code. By running it several times in Sun/Oracle JVM the things I have found are: * *Execution time is not deterministic. This is usual in HotSpot JVMs, especially in multicore systems *Differences between withNormal() and withTry are minimal. This is to be expected as no actual exception is ever thrown and there are no finally blocks. *The version that is run first tends to be slower. It might be something related to the HotSpot compiler "warming up", but I am not an expert in HotSpot internals To summarize, I would not expect any significant difference between code using exceptions or not, when running in Sun/Oracle JVM it is most likely noise from HotSpot. UPDATE I have run it with both -server and -client flags and apart from execution being an order of magnitude faster in my machine, the observations above apply. Modified code below: public class ExceptionsStatic { public static void main(String... args) { withNormal(); withTry(); } static int fooVar; static void foo() { fooVar++; } static int foo2Var; static void foo2() throws Exception { foo2Var++; } static void withTry() { long t1 = System.currentTimeMillis(); foo2Var = 0; for(int i = 0; i < 100000000; i++) { try { foo2(); } catch(Exception e) { } } long t2 = System.currentTimeMillis(); System.out.println("try time taken " + (t2 - t1) + "; " + foo2Var); } static void withNormal() { long t1 = System.currentTimeMillis(); fooVar = 0; for(int i = 0; i < 100000000; i++) { foo(); } long t2 = System.currentTimeMillis(); System.out.println("normal time taken " + (t2 - t1) + "; " + fooVar); } A: Here is a micro benchmark which sucks less. Use 1 or 2 as program parameters and -XX:+PrintCompilation -verbose:class -verbose:gc as JVM parameters. public class TryBlockBenchmark { private static final int MEASUREMENTS = 100; private static int dummy = 0; public static void main(String[] args) { boolean tryBlock = args[0].equals("1"); System.out.println(tryBlock ? "try block" : "no try block"); for (int i = 0; i < MEASUREMENTS; i++) { long start = System.currentTimeMillis(); if (tryBlock) { benchmarkTryBlock(); } else { benchmarkNoTryBlock(); } long end = System.currentTimeMillis(); System.out.println((end - start) + " ms"); } System.out.println("(" + dummy + ")"); } private static void benchmarkTryBlock() { for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) { try { staticMethod(); } catch (Exception e) { } } } private static void benchmarkNoTryBlock() { for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) { staticMethod(); } } private static void staticMethod() { dummy++; } } With Java 1.6.0_24 64-bit HotSpot Server VM on a C2Q6600 @ 3GHz, after the first couple of measurements, the time for both versions stabilizes at 266 ms (+/- 1 ms). The time is the same also when the staticMethod() is inlined manually, which is to be expected from HotSpot. Removing the dummy++ line reduces the time to 0 ms, when HotSpot optimizes it away. I also tested using Java 1.6.0_24 32-bit and with it the HotSpot Server VM had the same results, but the HotSpot Client VM had both versions producing results around 8660 ms (+/- 20 ms). So we can conclude that the Server VM has better optimizations than the Client VM and that a try-catch which does nothing is either optimized away by HotSpot or that it does not affect the performance. To find which it is, print the assembly code produced by HotSpot. Overall, measuring things which do nothing is pretty pointless.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: right way of testing for optional field values While writing a method in my app which uses playframework,I need to get user input for Address fields and search db for a matching one.If I can't find a matching address ,I have to create a new Address. Here only addressLine1 and country are the required fields. A user can ignore the addressLine2. while taking input from the html form ,the textfields for optional fields return an empty string.So,to test the creation of Address ,I decided to create a Map<String,String> to be passed to the POST method.. I tried addrparams = new Map<String,String>(); addrparams.put("addressline1","clayton st"); addrparams.put("country","US"); This caused nullpointer exception when the jpql query tried to bind values fro the map for the missing options fields. String query="select distinct a from Address a where a.addressLine1=:addressline1 and a.addressLine2=:addressline2 and a.country=:country"; Address address = Address.find(query).bind("addressline1",addressline1).bind("addressline2",addressline2).bind("country", country).first(); .. I solved this by putting empty strings for all optional fields addrparams = new Map<String,String>(); addrparams.put("addressline1","clayton st"); addrparams.put("addressline2",""); addrparams.put("country","US"); I hope this is the correct way to do this..If someone can point out better approach at testing such situations,it would help me a lot The Address class @Entity public class Address extends Model { @Required String addressLine1; String addressLine2; @Required String country; ... } update: The stacktrace is here The Account.java:207 where nullptr exception occurs,is this line Address address = Address.find(query).bind("addressline1",addressline1).bind("addressline2",addressline2).bind("country", country).first(); A: Your query is wrong. You missed the alias and the equal signs in your where clause: where a.addressline1 = :addressline1 ... The way you're building your map is also wrong. You put "clayton st" as addressline1, and then replace it with an empty string. If those corrections don't work, then edit your question, paste the stack trace of the exception, and tell us which line in your code throws it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to change widget name at runtime in GWT I have a label which i need to create as per the size of my record like if there are 2 records from database , my method should check and create 2 new labels at runtime , if 10 records there should be 10 labels to be created at run time I am able to create 10 new labels at run time but how can i name them differently some thing like for (int i =0;i<array.size();i++) { Label lbl = new Label(); } in this way there are 10 labels and showing perfectly , but all ten have the same name i.e lbl can this name could also be change like lbl1,lbl2,lbl3... is it possible in GWT Thanks A: The thing you want to do isn't poosible in any programming language. The solution you are searching for is storing them inside a list and then access the labels via the index. Eg. if you want the first label you say List[0] GWT supports such list, the easiast for you to use ist the ArrayList! here is some more or less pseudo code: ArrayList<Label> labelList = new ArrayList<Label>(); for (int i =0;i<array.size();i++) { Label lbl = new Label(); labelList.add(lbl); } ... //the first item has the index 0! Label lbl1 = labelList.get(0); .. //doing stuff with the first label ... //getting the secont label Label lbl2 = labelList.get(1); ... //you get the idea right ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the uploaded file information using jquery-ajax I'm using jquery-ajax to check whether the file already exist in my server. I have this code: Upload an Event Photo <br> <input type='file' name='imageSrc' id='imageSrc' /><br> <a href='#' class='uploadPhoto'>Upload Image</a><br> <div class='uploadMessage'></div> <span>Maximum size: 1MB (jpg,png,gif)</span> This is my jquery code: jQuery(document).ready(function() { jQuery('.uploadPhoto').click(function(){ // alert(1); jQuery.ajax({ type: "POST", url: "index.php?option=com_eventsandrsvp", data: "task=uploadEventPhoto&format=raw", success: function(data) { jQuery(".uploadMessage").html(data); } }) }); }); I want to get the information that was there in the <input type='file' name='imageSrc' id='imageSrc' /> I know that that is a file type so there are information such as: name,type,size, and tmp_name. How would I do that using ajax? I am trying to use a GET method but it doesn't work. maybe because it only works on <input type='text' /> Any help would be greatly appreciated. Thanks! A: You can't upload files using just jQuery.ajax(), to upload files via ajax, you can resort to: * *Flash *Iframe trick Above methods have their own drawbacks though. Fortunately, there exists nice script uploadify you can use to upload files via ajax easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to stop Browserfield requestContent() method when back to mainScreen on blackberry When i click a button, in next screen i've loaded browserfield requestcontent() using thread. and i've added browserfield listener. when click back button , i came to first screen. But in background, requestContent is executing. how to stop it.? i write the code on onClose() method public boolean onClose() { for(int i=0;i<=Thread.activeCount();i++) { if(Thread.currentThread().isAlive()) { Thread.currentThread().interrupt(); } } return super.onClose(); } My code is., new Thread(new Runnable() { public void run() { loadWebContent(path); } }).start(); private void loadWebContent(String path) { final VerticalFieldManager vfm = new VerticalFieldManager(HORIZONTAL_SCROLL|VERTICAL_SCROLL) { protected void sublayout(int maxWidth, int maxHeight) { super.sublayout(maxWidth, (Display.getHeight()-47)); setExtent(maxWidth, (Display.getHeight()-47)); } }; BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig(); myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER); myBrowserField = new BrowserField(myBrowserFieldConfig); myBrowserField.addListener(new BrowserFieldListener() { public void documentLoaded(BrowserField browserField,Document document) throws Exception { UiApplication.getApplication().invokeLater(new Runnable() { public void run() { try { mainlayout.delete(spinner); mainlayout.add(myBrowserField); myBrowserField.setZoomScale(1.0f); } catch (Exception e) { System.out.println("++ "+e); } } }); } }); myBrowserField.requestContent(path); } Pls help how to stop execution when back to first screen. A: I think this is Enough: public class LoadingScreen extends MainScreen { ButtonField click; String url; BrowserField browserField; public LoadingScreen() { url="http://www.google.com"; browserField=new BrowserField(); add(browserField); browserField.requestContent(url); } } In onClose method: public boolean onClose() { return super.close(); } If you have any doubbts come on chat room named "Knowledge sharing center for blackberry and java" to clarify your and our doubts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perfmon counter for web services request queued Is there any performance counter for web services which give the number of web service request queues? There is one for Asp request queue, is there one for web services? These are not wcf web services these are classic web services with asmx extension.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does serving MIME type images improves loading speed, what benefits I am wondering if including MIME types images, instead of the images themselves, helps improve the loading speed in the page? What are advantages of serving encoded MIME types instead of original files? Thank you,
{ "language": "en", "url": "https://stackoverflow.com/questions/7606466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamic array in delphi I have created an packaged object (TMyComponent) of TLabel and TCombobox in delphi 7. I have created an dynamic array(MyArray) of TMyComponent. Now on Add button click I have increamented length of MyArray and create object of TLabel and TCombobox and displayed on screen. If I have added 5 components, How we can get current selected component of Myaaray means if i selected 3rd component from screen then how can i get value 3 in return? thanks for help A: I think you are looking for a function like this: function FindMyComponentIndex( Selected: TMyComponent; const Components: array of TMyComponent ): Integer; begin for Result := low(Components) to high(Components) do if Components[Result]=Selected then exit; Result := -1; end; I trust it will be obvious how to call this function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android : Change App Label programmatically How can I change application label to change app name shown from java code in android? I'm refering to: <application android:icon="@drawable/icon" android:label="@string/app_name"> in the Android Manifest Is there any way to update values in strings.xml file? A: in the activity, i tried this.setTitle("your text"); and it worked. I hope it's a common solution A: In Launcher Activity,Before setContentView() write this, setTitle("Your Title"); I don't know how it's possible, But it's surely works. A: Yes, Its possible, In this question everyone mentioned like this.setTitle("your text"); this will change only your activity name not app logo here I show you how to change the app logo and appname dynamicly First add your dynamic app icons in the mipmap folder , after that add the below code in your AndroidManifest.xml file Add <activity-alias> for your app icon <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <!-- Disable the original activity app icon in launcher --> <!-- <category android:name="android.intent.category.LAUNCHER" /> --> </intent-filter> </activity> <activity-alias android:label="Anand" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:name=".MainActivityAlias1" android:enabled="true" android:targetActivity=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity-alias> <activity-alias android:label="Anand 1" android:icon="@mipmap/ic_launcher2" android:roundIcon="@mipmap/ic_launcher2_round" android:name=".MainActivityAlias2" android:enabled="false" android:targetActivity=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity-alias> </application> After doing these methods on your activity, just do below things on button click import android.content.ComponentName import android.content.pm.PackageManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button1.setOnClickListener{ packageManager?.setComponentEnabledSetting( ComponentName(applicationContext.packageName, applicationContext.packageName + ".MainActivityAlias1"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) packageManager?.setComponentEnabledSetting( ComponentName(applicationContext.packageName, applicationContext.packageName + ".MainActivityAlias2"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ) } button2.setOnClickListener{ packageManager?.setComponentEnabledSetting( ComponentName(applicationContext.packageName, applicationContext.packageName + ".MainActivityAlias1"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ) packageManager?.setComponentEnabledSetting( ComponentName(applicationContext.packageName, applicationContext.packageName + ".MainActivityAlias2"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) } } } for more details refer this github project A: It's not possible by the moment. It is a fixed string in the AndroidManifest.xml file which cannot be changed at runtime. A: Using <activity-alias> you can change App icon and name to few predefined by you. Create such config in Mannifest.xml <activity android:name="package.name.MainActivity" android:screenOrientation="portrait" android:label="@string/app_name" android:theme="@style/CustomTheme" android:launchMode="singleTask"> <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity-alias android:label="@string/app_name_default" android:icon="@drawable/icon_default" android:name=".MainActivity-Default" android:enabled="true" android:targetActivity=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity-alias> <activity-alias android:label="@string/app_name_flavor_one" android:icon="@drawable/icon_flavor_one" android:name=".MainActivity-Flavor-One" android:enabled="false" android:targetActivity=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity-alias> Now you can switch between those two aliases, therefore we will change app icon or/and name. To switch from Default to Flavor-One use this code. getPackageManager().setComponentEnabledSetting( new ComponentName("package.name", "package.name.MainActivity-Flavor-One"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); getPackageManager().setComponentEnabledSetting( new ComponentName("package.name", "package.name.MainActivity-Default"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); Keep in mind that you have to track that only one alias will be enabled at a time A: Application's android:label is a fixed resource referrer. But the string under this referrer could have multiple values, depending on configuration qualifier names (values-en, -large, -land, etc.), according to Providing Alternative Resources. A: To anyone interested: Android How to change the application title But it's not clear if it changes the "application label" (that is, the name of the icon in the application list) or only the window title. A: If you are extending the firmware, you can actually accomplish this by changing IconCache.java file and make it show a string with some internal value of the phone. For example if you want the SIM Toolkit to show the name of the carrier, you can do that this way. But for regular apps, as it's been said, it's currently not posible. A: As Mister Smith said, it is not possible, but you could use multiple ActivityAlias, which can be enabled/disabled dynamically and point to the same targetActivity. Therefore create your chooser for the app name - let the user select one and enable the ActivityAlias via the packageManager: ComponentName componentName = new ComponentName(context, context.getPackageName() + "." + aliasName); context.getPackageManager().setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); To hide the old alias, use the same code with the flag : COMPONENT_ENABLED_STATE_DISABLED You can also add the possibility to directly add a shortcut to the home launcher, after you enabled the alias. There are plenty ways described here on sow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Making google analytics ID a variable My app serves multiple domains which I understand should be done by namespaces which I'm researching. Since multiple domains should have multiple analytics ID:s I get the analytics ID from the code but I want to make it even more configurable: if os.environ.get('HTTP_HOST').endswith('.br') \ or os.environ['SERVER_NAME'].endswith('.br'): data[u'analytics'] = 'UA-637933-12' else: data[u'analytics'] = 'UA-637933-18' self.response.out.write(template.render(os.path.join(os.path.dirname(__file__), 'templates', name + '.html'), data)) The above sets analytics ID to ..-12 if it's my brazilian domain and to the other ID ...-18 if it is my dot com. But this is only for 2 domains and it's not easiliy generalizable. How can I achieve this function in a more scientific and scalable way so that it becomes easy to add my application to a domain without manually adding the domain to my application? I suppose namespaces is the way to go here since the domains are google apps domains but I don't understand how to use namespaces: def namespace_manager_default_namespace_for_request(): """Determine which namespace is to be used for a request. The value of _NAMESPACE_PICKER has the following effects: If _USE_SERVER_NAME, we read server name foo.guestbook-isv.appspot.com and set the namespace. If _USE_GOOGLE_APPS_DOMAIN, we allow the namespace manager to infer the namespace from the request. If _USE_COOKIE, then the ISV might have a gateway page that sets a cookie called 'namespace', and we set the namespace to the cookie's value """ name = None if _NAMESPACE_PICKER == _USE_SERVER_NAME: name = os.environ['SERVER_NAME'] elif _NAMESPACE_PICKER == _USE_GOOGLE_APPS_DOMAIN: name = namespace_manager.google_apps_namespace() elif _NAMESPACE_PICKER == _USE_COOKIE: cookies = os.environ.get('HTTP_COOKIE', None) if cookies: name = Cookie.BaseCookie(cookies).get('namespace') return name I suppose I should use the namespace manager, get the namespace and set the analytics ID according to the namespace but how? Thank you A: The simplest way to do this is with a Python dict: analytics_ids = { 'mydomain.br': 'UA-637933-12', 'mydomain.com': 'UA-637933-18', } data['analytics'] = analytics_ids[self.request.host] If you have other per-domain stats, you may want to make each dictionary entry a tuple, a nested dict, or a configuration object of some sort, then fetch and store it against the current request for easy reference. If you want to be able to reconfigure this at runtime, you could use a datastore model, but that will impose extra latency on requests that need to fetch it; it seems likely to me that redeploying each time you add a domain isn't likely to be a problem in your case. Namespaces are tangential to what you're doing. They're a good way to divide up the rest of your data between different domains, but they're not useful for dividing up configuration data. A: I presume you have two instances of the same application running. Instead of fiddling with namespaces, I suggest you turn the Analytics ID into a configuration variable. That is, either store it in a config file or a database your web is using. Then set one ID for each deployment (in each place your web is running from) and fetch it in the runtime. For example: Config file: analyticsId="UA-637933-12" Code: data[u'analytics'] = getValueFromConfig("analyticsId") where getValueFromConfig is a function you define to read the appropriate value. (To use configuration files effortlessly, you may use the ConfigParser module.) Now you've gained a lot more flexibility - you don't have to do any checking and switching at runtime. You only have to define the value once per web site and be done with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQUERY focusout fire at every time when i press keys at on screen keyboard <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript" src="jquery-fieldselection.js"></script> <script> $(document).ready(function(){ var CurrentTextBoxID = ""; // toggles the keyboard to show or hide when link is clicked $(":text").focus(function(e) { CurrentTextBoxID = this.id; var top = ($(window).height() - $('#keyboard').height()) - 25; var left = ($(window).width() - $('#keyboard').width()) / 2; //alert(CurrentTextBoxID + " focus In"); $('#keyboard').css( { "left": left+"px", "top": top+"px" } ).toggle(); }); $(":text").focusout(function() { $('#keyboard').hide(); }); // function thats called when any of the keys on the keyboard are pressed $("#keyboard input").bind("click", function(e) { $('#'+CurrentTextBoxID).replaceSelection($(this).val(), true); }); }); </script> <style type="text/css"> #keyboard { position: fixed; background: #eee; display: none; border: 1px solid #ccc; border-radius:7px; width: 700px; height: 240px; padding: 5px; cursor: move; box-shadow: -5px -5px 5px 5px #888; -moz-border-radius: -5px -5px 5px 5px #888; -webkit-border-radius: -5px -5px 5px 5px #888; } </style> </head> <body> <form id="frmOnScreenKeyboard" name="frmOnScreenKeyboard"> <table border="0" cellpadding="0" cellspacing="0" > <tr> <td> <input type="text" name="txtTest1" id="txtTest1"/> </td> </tr> <tr> <td> <input type="text" name="txtTest2" id="txtTest2"/> </td> </tr> <tr> <td> <input type="text" name="txtTest3" id="txtTest3"/> </td> </tr> <table> <table height="900px"> </table> <div id="keyboard"> <table border=1 cellpadding=0 cellspacing=0> <tr> <td> <div id="row2_shift"> <table border=1 cellpadding=0 cellspacing=0> <tr> <td><input name="a" type="button" value="A" /></td> <td><input name="s" type="button" value="S" /></td> <td><input name="d" type="button" value="D" /></td> <td><input name="f" type="button" value="F" /></td> <td><input name="g" type="button" value="G" /></td> <td><input name="h" type="button" value="H" /></td> <td><input name="j" type="button" value="J" /></td> <td><input name="k" type="button" value="K" /></td> <td><input name="l" type="button" value="L" /></td> <td><input name=";" type="button" value=":" /></td> <td><input name="'" type="button" value='"' /></td> </tr> </table> </div> </td> </tr> </table> </div> </form> </body> </html> At the upper code, I make on screen keyboard to display and to allow user to put key by just clicking. This keyboard will show automatically when user click at each and every text boxes. Firstly, my requirement is I want to make my keyboard hide and re-display whenever user change focus to each text boxes. I mean user can navigate through each and every text boxes. When I make focus to txtTest1 , it show keyboard. It is correct. But when I press any buttons at on-screen keyboard, the on-screen keyboard gone away(hide event fire). It is the place where problem start. So, please let me know is there any nicer way to modify my upper code. A: Try this: $(":text").focusout(function() { var $obj = $( document.activeElement, "#row2_shift table" ); if ( $obj.length == 0 ) { $('#keyboard').hide(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7606486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Host name validation in php How to validate the host name in PHP? That is if suppose am running my application server on IP:192.168.1.77 and if the request contains the Host name other than 192.168.1.77 it should not allow the further processing. Any help or suggestion would be appreciated. A: I'll throw a unauthorized page. With error stating that there is mismatch in host name What for? This is something the web server will already deal with if it's set up properly: If you are using name-based virtual hosts, the ServerName inside a section specifies what hostname must appear in the request's Host: header to match this virtual host. There's no need to additionally check for this in the PHP script. It will be an additional security na? Thats what my clients requirement is It is entirely pointless and will not add any security whatsoever. However, I guess there's no harm in doing it, either. A: I guess you mean address, not hostname. if ($_SERVER['REMOTE_ADDR'] !== '192.168.1.77') die(header("Location: /")); if you really wan't to check the users hostname, use this if ($_SERVER['REMOTE_HOST'] !== '192.168.1.77') die(header("Location: /")); More info http://php.net/manual/en/reserved.variables.server.php A: I think this is something you will have to do server side from within your web server's configuration. (.htaccess) order deny, allow deny from all allow from 192.168.1.77
{ "language": "en", "url": "https://stackoverflow.com/questions/7606491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: releasing object created in getter and setter I have some doubt regarding retain in .h file. I know that if we alloc/copy/retain than we need to release it, but in following case @property (nonatomic, retain) IBOutlet UITableView *myTable; Do I need to release this table view object in my dealloc. I have created this tableview using xib. Thanks. A: Yes you will have to as you would be creating an object in the .h file and allocating it memory.. The only thing you are doing in XIB is creating a link between the two (XIB just acts as an outlet for the inner tableview) , but if you posted a button using the xib and did not link it via the code then you don't have to release it... A: First of all you are not retaining anything in .h file. The purpose of @property declaration in the .h file (it can also be don in .m file) is to tell the compiler how to handle the getters and setters for this property when you use (dot syntax). Example: Declaring property in the following way: @property (nonatomic, retain) IBOutlet UITableView *myTable; Tells the compiler that when you create a UITableView in your .m file like so: - (id)initWithTable:(UITableView *)table { self = [super init]; if (self) { self.myTable = table; } return self; } Compiler will automatically know to retain it, and so you would also need to release it. But if you would declare your property in the following way: @property (nonatomic, assign) IBOutlet UITableView *myTable; and created the tableView as in the previous example - (id)initWithTable:(UITableView *)table { self = [super init]; if (self) { self.myTable = table; } return self; } The compiler would only assing the value of myTable to point to table. You would not own it and should not release it. A: So sayeth the docs: Objects in the nib file are created with a retain count of 1 and then autoreleased. As it rebuilds the object hierarchy, however, UIKit reestablishes connections between the objects using the setValue:forKey: method, which uses the available setter method or retains the object by default if no setter method is available. If you define outlets for nib-file objects, you should always define a setter method (or declared property) for accessing that outlet. Setter methods for outlets should retain their values, and setter methods for outlets containing top-level objects must retain their values to prevent them from being deallocated. And: When a low-memory warning occurs, the UIViewController class purges its views if it knows it can reload or recreate them again later. If this happens, it also calls the viewDidUnload method to give your code a chance to relinquish ownership of any objects that are associated with your view hierarchy, including objects loaded with the nib file, objects created in your viewDidLoad method, and objects created lazily at runtime and added to the view hierarchy. Typically, if your view controller contains outlets (properties or raw variables that contain the IBOutlet keyword), you should use the viewDidUnload method to relinquish ownership of those outlets or any other view-related data that you no longer need. So basically, when being loaded from a NIB/XIB, the property is used. Meaning, if you specify retain properties on your IBOutlets (which you should), you need to release them. The preferred way to do this is in viewDidUnload, using the property. @property (nonatomic, retain) IBOutlet UITableView *myTable; ... - (void) viewDidUnload { self.myTable = nil; } A: No u dont need to u only need to release object which you have allocated. since the table view is allocate in the xib it's release should be none of your concern hope this helps A: it should be release. if you want to see difference then run your application in instruments and check it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: End animation event android I have a fadeout animation in a view (which is inside a fragment), and everytime the animation happens, after it finishes the view redraws itself again. I found a work around doing view.SetVisibility(View.GONE) . But it doesn't wait for the animation to finish. I would like to execute this setVisibility code only after the animation has finished. What is the best way to do that? A: You can also achieve this using Animation.setFillAfter A: Example for Kotlin var fadeOutImage = findViewById<ImageView>(R.id.fade_out_Image) val fadeOutAnimation = R.anim.fade_out_animation val animation = AnimationUtils.loadAnimation(this, fadeOutAnimation) fadeOutImage.startAnimation(animation) animation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(p0: Animation?) { // not implemented } override fun onAnimationRepeat(p0: Animation?) { // not implemented } override fun onAnimationEnd(p0: Animation?) { fadeOutImage.visibility = View.INVISIBLE } }) A: Functionally the same as the accepted answer but in a much more concise way: // Add/Remove any animation parameter theView.animate() .alpha(0) .setDuration(2000) .withEndAction(new Runnable() { @Override public void run() { theView.setVisibility(View.GONE); } }); Enjoy :) A: You can add Animation listener to your animation object like anim.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { } }); A: Simply take your animation object and add animation listener to it. Here is the example code : rotateAnimation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animation animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animation animation) { // TODO Auto-generated method stub **// WRITE HERE WHATEVER YOU WANT ON THE COMPLETION OF THE ANIMATION** } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7606498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "101" }
Q: Rich text apostrophes aren't printing right I'm echoing text and all the apostrophes look like this â so the word it's is printed as Itâs. Is there something I need to do to the text, like encode it or decode it or something. How can I fix this? note: actually, it seems even stackoverflow wouldn't print the characters I see. The apostrophes are changed to the â you see above, and 2 boxes next to it which contain the numbers 0080 and 0099. But stackoverflow deletes them from here. A: I am not a php guy but it might be possible that development IDE would not support UTF-8 or encoding other than ANSI. Workaround is to copy the original text and paste it into the text file which has ANSI encoding. Fix your missing characters manually and then copy the text from that file into your development IDE. If you don't want to do this then you have to enter the actual decimal or hex values of those problem characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get dynamic TextInput field values in Actionscript 3 Hi creating dynamic TextInput fields in a function. Need to get the values of those fields in another function. Can anyone throw some light on this. for(var i:int=0;i<answers.length;i++) { txtbox = new spark.components.TextInput(); var lblBox:spark.components.Label = new spark.components.Label(); lblBox.id = "lbl"+i.toString(); lblBox.text = String(answersLabel.getItemAt(i) ); lblBox.width = 10 lblBox.x = xPos-15; lblBox.y = yPos; QuestionAnswer.addElement(lblBox); txtbox.id = "text"+i.toString(); txtbox.x = xPos; txtbox.y = yPos; QuestionAnswer.addElement(txtbox); xPos += 200; } A: var txt:TextField; var i:uint; var ary:Array = new Array(); function txtCreation ():void { for( i=0;i<5;i++) { txt = new TextField(); txt.text = "txt"+i; addChild(txt); txt.x = 50 + txt.width *i; txt.y = 20; ary.push(txt); } } txtCreation(); for(i=0;i<ary.length;i++) { trace("array values : " +ary[i].text); } A: Just look at the text variable for the textfield. var textFromField : String = myInputText.text;
{ "language": "en", "url": "https://stackoverflow.com/questions/7606501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Whats the point of Tuple(Of T) Possible Duplicate: What's the purpose of the Tuple(T1)/Singleton in .net? Trying to mimic a Tuple as implemented in .Net 4 (For .Net 3) I just realized there is a Tuple(Of T)? This was quite a surprize! Why would anyone do this Tuple<string> result = new Tuple<string>("Data"); Instead of this return "Data"; Isn't the whole point of a tuple that its a container for "loosely related data that isnt cohesive enough to make another class"? Am I missing something? A: There are a finite number of tuple-arities in the library, so to define an 8-tuple, you use the kind with 7-elements whose 'rest' argument is a one-tuple. See http://msdn.microsoft.com/en-us/library/dd383325.aspx A: This is a carry over from set theory that might not have much use for a software developer. Tuples are simply ordered lists of elements. An N-tuple has n elements, and n can be one, which is called a singleton. You probably won't have much use for a 1-tuple in code, but I'm guessing the C# team put it in there for completeness. http://en.wikipedia.org/wiki/Tuple#Etymology
{ "language": "en", "url": "https://stackoverflow.com/questions/7606506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Error: Could not find or load main class <<< Why do I get this error? I can't seem to get this code to work correctly. This is the error I keep getting: Error: Could not find or load main class. What causes this? Payroll3.java // A program to calculate and print the department, name, and pay of an employee. import java.util.Scanner; //program uses the Scanner class import java.io.*; class main { public class Payroll3 { // main method begins execution of Java program. public void main(String args[]) { // create Scanner to obtain input from the command window Scanner input = new Scanner (System.in); double number1; // first number to multiply double number2; // second number to multiply double product; // product of number1 and number2 while(true){ // infinite loop System.out.print("Enter Department name: "); //prompt String name = input.nextLine(); // read name from user if(name.equals("stop")) // exit the loop break; System.out.print("Enter number of employees: "); // prompt number1 = input.nextDouble(); // read first number from user input.nextLine(); while( number1 <= -1){ System.out.print("Enter positive number of employees:"); // prompt number1 = input.nextDouble(); // read first number from user input.nextLine(); } /* while statement with the condition that negative numbers are entered user is prompted to enter a positive number */ System.out.print("Enter average salary: "); // prompt number2 = input.nextDouble(); // read second number from user input.nextLine(); while( number2 <= -1){ System.out.print("Enter positive number for average salary:"); // prompt number2 = input.nextDouble(); // read first number from user input.nextLine(); } /* while statement with the condition that negative numbers are entered user is prompted to enter a positive number */ // make department object Department dept = new Department(name,number1,number2); product = number1 * number2; // multiply numbers System.out.println("Department name:" + name); // display Department name System.out.printf("Payroll is: $%.2f\n", product); // display product } // end while method } // end method main }/* end class Payroll3 */ } // Stores data about an department class Department { //fields String name; double number1; double number2; // constructor public Department(String name, double number1, double number2) { this.name = name; this.number1 = number1; this.number2 = number2; } // returns the pay: public double getPay() { return number1*number2; } // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public double getnumber1() { return number1; } public void setNumber1(double number1) { this.number1 = number1; } public double getNumber2() { return number2; } public void setNumber2(double number2) { this.number2 = number2; } } A: Class must be public and main must be static public static void main(String argv[]) And you can't have nested main class. At least it's probably not what you expect. Why don't you start with simple tutorial and expand it with your code? A: while Running the program just type java program_name but NOT java program_name.java A: more detail is required did you complied it? Error: Could not find or load main class.? it seems that you just run the java with the source file java test.java # wrong Exception in thread "main" java.lang.NoClassDefFoundError: test/java Caused by: java.lang.ClassNotFoundException: test.java at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) Could not find the main class: test.java. Program will exit. # correct javac yourfile.java java yourfile Also you need to changed your file as Alex Gitelman told. A: I simplified your code to reveal the problem inside. // Payroll3.java class main { public class Payroll3 { public void main(String args[]) { } } } First, we can see that the outmost suspicious class main hide your needed class and the main function. You need to remove the class main. Second, main function need to be declared as class-function instead of instance-function, because it is not bound to any instance. In java, we use static to declare a class-variable/class-function. So you need to declare the main as public static void main(String argv[]) After the changes, you can get: // Payroll3.java public class Payroll3 { public static void main(String argv[]) { } } A: The problem is that the main function needs to be declared as public static void main(String[] args), not public void main(String[] args). A: the name of the file should be used when compiling it i.e. javac test.java where test.java is the file name. And when running the file the name of the class is the file should be used for example if it is class Test{} then java test
{ "language": "en", "url": "https://stackoverflow.com/questions/7606507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get feed titles from any RSS feed with php I'm attempting to build an RSS reader at the moment I'm using php's simplexml using For example $xml->item->title But however this is dependent on the structure of the rss feed itself if the structure is different it won't work so I was wondering if theres a more broader and less specific way to grab all the titles from a RSS feed. Thanks a lot A: There is a RSS Specification document out there. You can find it at http://cyber.law.harvard.edu/rss/rss.html Therefore, a RSS file always looks the same, but be carefull. There is always something like Atom. You could use xPATH for searching within the RSS: http://nl.php.net/manual/en/simplexmlelement.xpath.php A: maybe it´s an option for you using a contribution like this instead of invent the wheel again: http://www.phpclasses.org/package/3724-PHP-Parse-and-display-items-of-an-RSS-feed.html A: You can use some Regex to filter the RSS files and split them into titles, etc. Whatever you want. As you will define which tags to grab data from. Using something like: $regex = '/<(w+)[^>]*>(.*?)</\1>/s'; preg_match_all($reg_exp, $text, $match); A: There are lot of feed formats. Writing code to comply all, is a bit difficult task. so.. I recommend using simple pie. http://simplepie.org/ or you can use google feed api also. here is a example using simple pie. http://simplepie.org/wiki/setup/sample_page
{ "language": "en", "url": "https://stackoverflow.com/questions/7606508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Downloading bar in android I have a problem that I want to create a downloading Bar means it increases as Downloading percentage increases in the background of a list row. I don't know How to implement this in Android. Please suggest me for right result. Thanks in advance. A: Check out for Linq Tutorials... FROM Source:What are some good LINQ resources? msdn.microsoft.com/en-us/vcsharp/aa336746.aspx www.linqtutorial.net FROM [ScottGu's blog] * *Part 1: Introduction to LINQ to SQL *Part 2: Defining our Data Model Classes *Part 3: Querying our Database *Part 4: Updating our Database *Part 5: Binding UI using the ASP:LinqDataSource Control *Part 6: Retrieving Data Using Stored Procedures *Part 7: Updating our Database using Stored Procedures *Part 8: Executing Custom SQL Expressions *Part 9: Using a Custom LINQ Expression with the <asp:LinqDatasource> control
{ "language": "en", "url": "https://stackoverflow.com/questions/7606509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set Grouped table view background colour how can i set the background color of a grouped table view to clear color so that is get the image of the underlying Image View. i tried to set the view color to clear view in the xib it works fine in case of a normal table view but doesnt work for a grouped table view i also tried it programmatically but in vain is there any work around A: Check this code for clear the background color of grouped table view.. UIView *backView = [[UIView alloc] init]; [backView setBackgroundColor:[UIColor clearColor]]; [yourTableView setBackgroundView:backView]; Thanks..
{ "language": "en", "url": "https://stackoverflow.com/questions/7606514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to build Python into a C++ .exe I have a c++ application and would like to take advantage of one of pythons libraries. I have seen info on how to run the python interpreter inside the program, however I want the program to be self-sufficient, so I can run it on any windows computer, even if it does not have python. How can i compile the python into the c++ .exe? Thanks A: You can't. You must have the DLL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select entries in "joined" table matching specific data and/or non-existing data I created two tables to manage a multi language article system : * *table1 is a table which is used as an index of all the articles registered table1 = (ART_ID, ART_AUTHOR, ART_DATE) *table2 is a table which is used to store all languages versions of an article table2 = (LOC_ID, LOC_TITLE, LOC_TEXT, LOC_LANG, ART_ID) My goal is the following: If I select English as language; * *I need to see the articles with an existing English localisation so I can edit them,[if there is a localisation matching the selected language then it returns this one as table2 data's]. *I also need to see the articles without any localisation yet (but the article index exists in the table1 already) so I can write the English version,[if there is no localisation at all for the article, then it returns null data's as table2 data's]. *And finally, I need to see the articles that already have a localisation in another language so I can write the English version.[if there is no localisation matching the selected language but there is another localisation, then it returns null data's as table2 data's.] but I was unable to write the good query until now... If I use: SELECT table1.ART_AUTHOR, table1.ART_DATE, table2.LOC_TITLE, table2.LOC_TEXT FROM table1 LEFT JOIN table2 ON ( table1.ART_ID = table2.ART_ID ) it returns all the article in all languages, but I need null data's if the selected language is not yet localized. So it's not good. If I use: SELECT table1.ART_AUTHOR, table1.ART_DATE, table2.LOC_TITLE, table2.LOC_TEXT FROM table1 LEFT JOIN table2 ON ( table1.ART_ID = table2.ART_ID ) WHERE table2.LOC_LANG = 'en' it returns all the article written in English, but not those without any localisation neither those with localisation in another language. So it's not good. If I use: SELECT table1.ART_AUTHOR, table1.ART_DATE, table2.LOC_TITLE, table2.LOC_TEXT FROM table1 LEFT JOIN table2 ON ( table1.ART_ID = table2.ART_ID ) WHERE table2.LOC_LANG = 'en' OR table2.LOC_LANG IS NULL it returns all the article written in English and all article without localisation at all, but not those with localisation in another language. So it's not good. I tried with some sub-queries and exists or not exists but nothing was reaching the goal. Does anybody knows something I could use in order to get this working ? Is this is even possible ? Thank you. A: Try to put the condition in the left join: SELECT table1.ART_AUTHOR, table1.ART_DATE, table2.LOC_TITLE, table2.LOC_TEXT FROM table1 LEFT JOIN table2 ON table1.ART_ID = table2.ART_ID and table2.LOC_LANG = 'en'
{ "language": "en", "url": "https://stackoverflow.com/questions/7606526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ Function appearing to not return anything when it should I currently have a function that is meant to return T (templated function). So I always assumed it MUST return a value, but I recently stumbled across something. #define PRINTERROR(msg) \ std::cout << msg << "\n\tFILE: " << __FILE__ << "\n\tLINE: " << __LINE__ << "\n\tTIME: " << __TIME__ << std::endl << std::endl; and this... template<class T> T& Container_Vector<T>::GetFirstItem() { #ifdef CONTAINER_VECTOR_ERROR_CHECKING_ON if (m_iCurrentSize > 0) { return m_pItems[0]; } else { PRINTERROR("ERROR: Attempting to retrieve item from an empty vector container"); } #else return m_pItems[0]; #endif } When I step through the code trying to test if the msg gets outputted and error checking is on the first check(m_iCurrentSize > 0) fails, the message is printed and then it appears to jump to the end of the function "}" and return nothing? Usually I'd get a compile error saying it has to return something. What's going on here and is it ok? While it doesn't actually step through onto anything that returns T it does return something, a random memory address maybe. A: You are missing a return after the PRINTERROR in the #ifdef block. Not doing so results in an undefined behavior. You must return an appropriate value at the end of the function. (Such logical error can be caught at compile time with appropriates flags set. For example, in g++ you can use -Wall.) A: First of all, the preprocessing takes place before the compilation. To your compiler, the code looks like - If CONTAINER_VECTOR_ERROR_CHECKING_ON is defined: template<class T> T& Container_Vector<T>::GetFirstItem() { if (m_iCurrentSize > 0) { return m_pItems[0]; } else { PRINTERROR("ERROR: Attempting to retrieve item from an empty vector container"); } } if CONTAINER_VECTOR_ERROR_CHECKING_ON is NOT defined: template<class T> T& Container_Vector<T>::GetFirstItem() { return m_pItems[0]; } Your first case doesn't have a return on all branches, you should get a warning at least. MSVS doesn't report a compilation error, but it does return a warning. The random number you're getting is simply the last value present in the return register before the function exits. A: That's undefined behavior, if CONTAINER_VECTOR_ERROR_CHECKING_ON is defined and !( m_iCurrentSize > 0 ) then you are not returing anything. You may get a warning, but not an error since you do have one conditional return. In such case the function returns garbage, and the stack is probably corrupted after that. A: Omitting to return a value from a function unfortunately is not a compile error. A compiler may emit a diagnostic message (for example g++ does if compiling with -Wall option) but it's not mandatory. Omitting to return a value is something that compiler writers are free to assume a programmer will never do, and if a program does it the standard says that the compiler is free to ignore the problem and whatever happens happens (undefined behavior). It's always a programmer fault. On x86 architecture normally the net effect is just that you will get some strange value if the function is returning a true "native" type (e.g. a char or an int) that fits in a register and you may instead get memory corruption or a crash if the function is for example returning a class instance (e.g. std::string). Note however that any speculation about what happens in case of undefined behavior is just that... i.e. pure speculation as indeed anything may happen for the C++ language specification.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create website specific configuration files while running multiple ASP.NET websites on a single code base? I want to create 2 websites on a single code base in asp.net. lets for say : www.domain1.com www.domain2.com I need to keep all the appsetting key name sames but with different values for each of the websites.So i need to maintain two web.config files in my code base. After exploring on internet , i found to keep both of the web.config files in different folders in the code base. Bow the problem is, how can i link each of the different web.config file with its corrosponding Virtual directory for each the website because both of the Virtual directories will target the same folder of code base. I really neede it as i have to finish this work within this week. Thanks A: If you really want to serve both site from one application/virtual directory, the only solution I can come up with is as follows: <appSettings> <add key="setting[www.domain1.com]" value="foo" /> <add key="setting[www.domain2.com]" value="bar" /> ... And then access these accordingly: var setting = ConfigurationManager.AppSettings["setting[" + request.Domain + "]"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7606532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: *curious behavoir* why is font-size over width/height <html> <head> <style type="text/css"> ul {font-size: 25px; list-style: none;} li{margin-left:0; padding: 0px 5px;} li a {width: 300px; height: 300px; height:300px; background:url(whatever) bottom left;} li a span{visibility: hidden;} </style> </head> <body> <ul><li> <a href="#"><span>some txt</span></a> </li></ul> </body> </html> why is here the ul's font-size making the width/height and not the witdth/height of the a ? A: @remy; a & span are inline element so it's not take the height , width , vertical margin & padding so give a , span{ display:block } A: Because an anchor tag is inline by default. Try adding li a { display: block; } to convert it to a block; this will mean you can assign it a width & height.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Page transitions for slow page load silverlight Windows Phone I have a silverlight page with around 250 elements on it. The page load time is around 2.5 seconds on average. I have tried to cut down on the data part, but I don't think it helps that much. Even loading without any data takes around 2 seconds. I'm guessing it's the UI elements load time that cause the slowness. my current navigation structure is: app load --- main page --- game page. The problem is in the game page load time. other pages loads very snappily. the current "slowness" happens when I press the navigating button (start game button), and the app freeze, and then load the next page. my questions are: is there anyway to "pre-load" the page? failing that, is there anyway to run some sort of animation for the perception of snappiness? I tried page transition based on silverlight toolkit, but I don't think it helps at all. the animation starts after the "freezing" after navigation button is pressed. thanks Alvin A: If the app appears to "freeze" then you are performing a long-running task (in processor cycle terms) on the UI thread, which you should be able to offload onto a background thread to let the page load quicker. If you are using the WP 7.1 SDK tools and targeting Mango, then you can use the built-in performance analysis tools to locate the source of the bottleneck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }