text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Minimum number of element required to make a sequence that sums to a particular number Suppose there is number s=12 , now i want to make sequence with the element a1+a2+.....+an=12.
The criteria is as follows-
*
*n must be minimum.
*a1 and an must be 1;
*ai can differs a(i-1) by only 1,0 and -1.
for s=12 the result is 6.
So how to find the minimum value of n.
A: Algorithm for finding n from given s:
1.Find q = FLOOR( SQRT(s-1) )
2.Find r = q^2 + q
3.If s <= r then n = 2q, else n = 2q + 1
Example: s = 12
*
*q = FLOOR( SQRT(12-1) ) = FLOOR(SQRT(11) = 3
*r = 3^2 + 3 = 12
*12 <= 12, therefore n = 2*3 = 6
Example: s = 160
*
*q = FLOOR( SQRT(160-1) ) = FLOOR(SQRT(159) = 12
*r = 12^2 + 12 = 156
*159 > 156, therefore n = 2*12 + 1 = 25
and the 25-numbers sequence for
159: 1,2,3,4,5,6,7,8,9,10,10,10,9,10,10,10,9,8,7,6,5,4,3,2,1
A: Here's a way to visualize the solution.
First, draw the smallest triangle (rows containing successful odd numbers of stars) that has a greater or equal number of stars to n. In this case, we draw a 16-star triangle.
*
***
*****
*******
Then we have to remove 16 - 12 = 4 more stars. We do this diagonally starting from the top.
1
**2
****3
******4
The result is:
**
****
******
Finally, add up the column heights to get the final answer:
1, 2, 3, 3, 2, 1.
A: The maximum possible for any given series of length n is:
n is even => (n^2+2n)/4
n is odd => (n+1)^2/4
These two results are arrived at easily enough by looking at the simple arithmetic sum of series where in the case of n even it is twice the sum of the series 1...n/2. In the case of n odd it is twice the sum of the series 1...(n-1)/2 and add on n+1/2 (the middle element).
Clearly you can generate any positive number that is less than this max as long as n>3.
So the problem then becomes finding the smallest n with a max greater than your target.
Algorithmically I'd go for:
Find (sqrt(4*s)-1) and round up to the next odd number. Call this M. This is an easy to work out value and will represent the lowest odd n that will work.
Check M-1 to see if its max sum is greater than s. If so then that your n is M-1. Otherwise your n is M.
A: There are two cases: s odd and s even. When s is odd, you have the sequence:
1, 2, 3, ..., (s-1)/2, (s-1)/2, (s-1)/2-1, (s-1)/2-2, ..., 1
when n is even you have:
1, 2, 3, ..., s/2, s/2-1, s/2-2, ..., 1
A: Thank all you answer me. I derived a simpler solution. The algorithm looks like-
First find what is the maximum sum that can be made using n element-
if n=1 -> 1 sum=1;
if n=2 -> 1,1 sum=2;
if n=3 -> 1,2,1 sum=4;
if n=4 -> 1,2,2,1 sum=6;
if n=5 -> 1,2,3,2,1 sum=9;
if n=6 -> 1,2,3,3,2,1 sum=12;
So from observation it is clear that form any number,n 9<n<=12 can be
made using 6 element, similarly number
6<n<=9 can be made at using 5 element.
So it require only a binary search to find the number of
element that make a particular number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to subclass UIApplication in Monotouch? EDIT:
A couple of years later, things are easier. It is now possible to omit the
Register() attributes, both on the application and the app delegate and instead use:
UIApplication.Main(args, typeof(CustomApp), typeof(CustomAppDelegate));
In order to be able to override UIApplication.SendEvent() I want to subclass UIApplication:
public class UIApplicationMain : UIApplication
{
public UIApplicationMain () : base()
{
}
public override void SendEvent (UIEvent uievent)
{
base.SendEvent (uievent);
}
}
In the main.cs I use this code:
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args, "UIApplicationMain", "AppDelegateBase");
}
}
But it fails with:
Objective-C exception thrown. Name:
NSInternalInconsistencyException Reason: Unable to instantiate the
UIApplication subclass instance. No class named UIApplicationMain is
loaded.
So I'm missing some attributes I guess. But what and where?
A: Add a [Register] attribute to your new type, like:
[Register ("UIApplicationMain")]
public class UIApplicationMain : UIApplication {
...
That will allow the native side to instantiate the right type when Main gets executed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Subview behaves strangely in navigation-based app I'm currently developing an app for iphone (my first) and I used several UITableViewController for navigation.
I then used a subview attached to self.view.superview to get a non-scroll image at the top.
The subview is created in IB, simple UIView with an UIImageView in it.
I'm adding the subview in viewDidAppear and this functions well.
But as soon as I'm tapping a cell and the navigationController pushes the next View animated, the previous view (scrolling out of sight) becomes completely white and my subview moves animated to the center. It's only for a half second or so, because then it's gone due to the next view arriving, but it's really unnerving.
I tried removing the subview in viewWillDisappear, that removes the UIImageView, but the screen still becomes completely white.
Does anybody how to fix this?
Oh, and PS: I'm working only on the Simulator, because I have no Developer Account yet. And I cannot change everything to a ViewController because I have a deadline to meet.
A: You shouldn't be surprised that things go wrong when you mess with the views of view controllers that don't belong to you. Rather than using a table view controller, you should replace it with a custom UIViewController whose view acts as a container view for both the table view and the non-scrolling view above it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook Like button og:image needs to be scraped to be displayed I've got a Drupal website with articles on them which have Facebook like buttons.
Now I've got all the OpenGraph metatags added on the pages and it's all working perfectly except for one thing.
Site visitors can share a page URL or like a page URL.
When a new article is added and the first person who presses the like button will not see the image added in the og:image tag.
If another person afterwards presses the like button, the og:image however is visible so it seems to me Facebook needs to scrape the page first before the og:image is added in the 'Facebook Like window'.
The Facebook share doesn't seem to suffer from this problem and does it right from the first time.
Now whenever somebody adds a new article, I'd need the URL of the article to be scraped automatically by Facebook using some PHP code or some other fix...
Anyone who knows if autoscraping a URL is possible or does anyone have an idea for a workaround?
A: You can use the graph API with scrape=true to force Facebook to scrape you right when you create your contents
https://developers.facebook.com/docs/beta/opengraph/objects/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: mapview working in india but not in switzerland I am making an android app in which i am using google maps which are working perfectly in India but the same build is not working in Switzerland i.e. in switzerland the maps are not loading in.
Is ther anything that is country orregion specific in generating google api key or debug.keystore.
A:
Is ther anything that is country orregion specific in generating google api key or debug.keystore.
No. The debug.keystore, by default, is developer-specific. Hence, the Google Map API key is developer-specific. Geography has nothing to do with it.
If this is the same exact APK file being used by both devices, then either:
*
*The Swiss device lacks an Internet connection, or
*The Swiss device is having difficulty reaching the Google Maps servers (e.g., they are on WiFi and there is some firewall or proxy issue), or
*The Swiss device does not have really have Google Maps (e.g., it is a device with a pirated Maps app and lacks a working Google Maps API add-on for Android), or
*The Alps were bulldozed and replaced by large black gridlines, so the map is being shown accurately
The first two should be testable by the user (e.g., try opening the native Maps application or browser). The last one should be testable by having the user look out a window. :-)
If, however, the APK file was built by one developer in India and a different APK file was built by a developer in Switzerland, and the app is working in India, then the Swiss developer needs to supply his or her own Maps API key into the source code, or use the same debug.keystore as is being used by the developer from India.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pull files from FTP using SSIS package and save to folder? I have FTP location having 2-3 folders from there i need to pull some files on daily bases using SSIS package please help.
for example:
FTP Detail
Server: ftp.abc.com:21
User: user1
Pwd: pass1
then there is a folder called Mydata and file named price(Date)
now i what to pull that file on my local machine C:\
how can I do this using SSIS?
A: I'd start with adding an FTP Connection Manager to your package. You will most likely want to create two variables in your package, User and Password and configure the FTP connection manager's expressions tab to use them. Reason being, you may run into issues with running the package via SQL Agent and you will need to supply those values via external configuration. Example 1 of said issue but it's a common problem
Click test and verify the connection manager is working fine.
Next step is to drop an FTP task on your control flow and see if you can master pulling 1 file down. That operation will be "Receive files"
While looking for a good image, I stumbled across this article and that should more than cover everything you will need to know about Using the FTP Task in SSIS 2008
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Setting Theme.Holo.Light changes everything except checkboxes in list <style name="CustomTheme" parent="@android:style/Theme.Holo.Light">
I made my own theme and added a reference to it in my manifest. Everything looks perfect (buttons, textboxes etc) except for the checkboxes in my custom list.
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
The checkbox in my listitem is the default checkbox from Theme.Holo and I can't figure out why.
Grateful for any help!
A: I am having the same problem. I have no idea why it isn't choosing the correct checkbox - you can barely see it on the light background. For now, I copied the appropriate holo light checkbox images out the of the android drawable folders and into my project. I then created my own that referenced these images. I then set the android:button attribute to my new selector xml. My selector xml looks like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_check_on_focused_holo_light" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_check_off_focused_holo_light" />
<item android:state_checked="false"
android:drawable="@drawable/btn_check_off_holo_light" />
<item android:state_checked="true"
android:drawable="@drawable/btn_check_on_holo_light" />
</selector>
Make sure you copy all of the different density images (xhdpi, hdpi, etc.) into your project.
A: The same thing happened to me but with radio buttons, as henry000 wrote.
I downloaded the original holo-light themed radiobuttons images and XML layouts from
http://android-holo-colors.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error from debugger failed to launch simulator error 4294956467 I am getting this error when I try to run the application on simulator. What might be the reason?
A: I had this problem because I had another user on the same machine running the iOS simulator. Logging in as the other user and quitting the simulator (and Xcode) solved it in my case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using 'IF.. ELSE' to change variable and use it in 'form action...' I've created a test form that uses IF.. ELSE to validate data in a simple form. This works ok and any validation messages or errors are posted to the same page (userform.php) to inform the user of success or otherwise.
What I want to do now is take the user to a different page on successful completion of the form. Here's my code so far:
<?php
if (isset($_POST['email'], $_POST['password'])) {
$errors = array ();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form";
}
if (empty($email)) {
$errors [] = "You must enter an email address";
}
if (empty($password)) {
$errors [] = "You must enter a password";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
}
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
$result = "userform.php";
}
} else {
$result = "confirm.php";
}
?>
<form action="<?php echo $result ?>" method="post">
The idea is that the users success or otherwise in completing the form changes the $result variable which is used in the form action. The above code doesn't work, so how would I do it?
Is it even possible?
A: instead of "form action=" at the bottom:
<?php
include($result);
?>
A: As I understand it you want it to work like so:
*
*User fills form
*User submits form
*Form submission goes to userform.php
*
*If all values validate, continue to confirm.php
*If not, return to userform.php
If that's the case, I don't think you want to change the form action: that would require that the user re-submit the form. Instead, use a HTTP redirect to send them to confirm.php:
header("Location: confirm.php");
... or if you wanna be really by-the-book about it:
header("Status: 303 See Other");
header("Location: http://exampel.com/confirm.php"); // according to the protocol,
// `Location` headers should be full URLs
<?php
/* ... */
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
}
?>
<form action="userform.php" method="post">
<?php
} else {
header("Location: confirm.php");
// if you need to pass additional information to confirm.php, use a query string:
// header("Location: confirm.php?var1=".$var1);
}
?>
A: The way you're doing it now, will redirect the user to confirm.php if they submit the form for a second time. You could change your code to this:
} else {
// $result = "confirm.php";
header("Location: confirm.php");
exit();
}
That way, if everything has been entered, the user will be redirected to confirm.php. But what do you do with the variables if everything is allright? They won't be taken to the new page.
A: } else {
$result = confirm.php;
foreach($_POST as $key => $val){
$input.="<input type='hidden' name='$key' value='$val' />";
}
$form = "<form method='post' name='confirm' action='confirm.php'>".$input."</form>";
$script = "<script type='text/javascript'>document.confirm.submit();</script>";
echo $form.$script;
}
A: empty ($errors)
will ALWAYS return empty. That's why you always get:
$result = 'confirm.php';
Check return values here
Also, I don't think you can do this easily. Instead, why don't you just create a check.php or whatever to check the variables/check for errors, etc. Then do whatever you want (redirect back to the form-filling page or proceeding to confirm.php page.
A: The whole idea is wrong. You have to fix 2 issues in your code.
1. A major one. Learn to properly indent nested code blocks!
It's impossible to read such an ugly mass with no indents.
2. A minor one.
I see no use of confirmation page here. What are you gonna do on that page? And from where you're going to get form values?
It seems you have to either use just simple Javascript code to show a confirmation or store entered data into session
And, I have to say, that show a confirmation page for simply a feedback form is quite uncommon practice.
So, I think you really need only one form action and only thing to ccare is properly filled form
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$errors = array();
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form. All fields required.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
if (!$errors) {
// do whatever you wish to this data
// and then redirect to whatever address again
// the current one is a default
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['fiestname'] = $form['lasttname'] = $form['email'] = $form['password'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($errors): ?>
<? foreach($errors as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form method="POST">
<input type="text" name="firstname" value=<?=$form['firstname']>
... and so on
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android How to pass real time data up the stack from local service to the activity? I have a local service that will need to wait for a response and when it gets the response immediately update the activity with that information. So the activity will not poll a service method but the moment the local service gets some data it has to inform that activity immediately somehow.
So Activity--binds-->LocalService <------>(RemoteService separate process). So I know I could just package it up in an intent and pass it up to the activity ... but is that the best/only option. How else might one communicate up the stack from the local service to the activity thats invoking the local service? Keep in mind I already have the local service binding to a remote separate process service which runs forever in the background and periodically sends realtime data to the local service. Thanks
A: you can pass the handler object of the activity to service thru setter() and using this object you can update the change in the activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Store huge amount of data in memory I am looking for a way to store several gb's of data in memory. The data is loaded into a tree structure. I want to be able to access this data through my main function, but I'm not interested in reloading the data into the tree every time I run the program. What is the best way to do this? Should I create a separate program for loading the data and then call it from the main function, or are there better alternatives?
thanks
Mads
A: I'd say the best alternative would be using a database - which would be then your "separate program for loading the data".
A: If you are using a POSIX compliant system, then take a look into mmap.
I think Windows has another function to memory map a file.
A: You could probably solve this using shared memory, to have one process that it long-lived build the tree and expose the address for it, and then other processes that start up can get hold of that same memory for querying. Note that you will need to make sure the tree is up to being read by multiple simultaneous processes, in that case. If the reads are really just pure reads, then that should be easy enough.
A: You should look into a technique called a Memory mapped file.
A: I think the best solution is to configure a cache server and put data there.
Look into Ehcache:
Ehcache is an open source, standards-based cache used to boost
performance, offload the database and simplify scalability. Ehcache is
robust, proven and full-featured and this has made it the most
widely-used Java-based cache.
It's written in Java, but should support any language you choose:
The Cache Server has two apis: RESTful resource oriented, and SOAP.
Both support clients in any programming language.
A: You must be running a 64 bit system to use more than 4 GB's of memory. If you build the tree and set it as a global variable, you can access the tree and data from any function in the program. I suggest you perhaps try an alternative method that requires less memory consumption. If you post what type of program, and what type of tree you're doing, I can perhaps give you some help in finding an alternative method.
Since you don't want to keep reloading the data...file storage and databases are out of question, but several gigs of memory seem like such a hefty price.
Also note that on Windows systems, you can access the memory of another program using ReadProcessMemory(), all you need is a pointer to use for the location of the memory.
A: You may alternatively implement the data loader as an executable program and the main program as a dll loaded and unloaded on demand. That way you can keep the data in the memory and be able to modify the processing code w/o reloading all the data or doing cross-process memory sharing.
Also, if you can operate on the raw data from the disk w/o making any preprocessing of it (e.g. putting it in a tree, manipulating pointers to its internals), you may want to memory-map the data and avoid loading unused portions of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What does iOS do when an app is "Installing" and is it possible to programmatically control it? I understand it may be unpacking some sort of compressed package into the file system (and due to the mobile nature I suppose it may be quite aggressive compression to reduce download time). But does it run any sort of preflight scripts? I suppose it does stuff like register the info.plist, add a pane in Settings.app if you've specified one, and the app's global URL and file type reception registration.
The reason why I'm interested is twofold: curiosity (would there be a way of seeing precisely what's going on? Has anyone investigated this?) and making an installation script. I'm constructing a dictionary app using Core Data (I've thought about this a lot, trust me, I want to use Core Data) and I'd like to have a way of nicely generating the Core Data store from the original XML without degrading the user experience by having some kind of "initializing app". Furthermore I'd like to deploy the dictionary compressed and then uncompress it on the device, to keep it under the 20 mb over the air download limit.
I suppose I could generate the Core Data store on my simulator or dev phone and then add it to the bundle, though that way still seems less than neat. Hence why it would be nice for iOS to handle it for me
Anyway, thoughts?
A: Whatever the OS does during install, you can be certain that Apple does not offer developers any hook into the operation. There is no way to run any code of your own (install script etc.) until the user first launches your app manually. So do whatever initialization needs to be done on first launch.
The .ipa packages you submit to Apple are already compressed (they are just ZIP files with another file extension) so it should not be necessary to compress a text file yourself to stay under the 20 MB limit. Compressing it twice probably won't help much in terms of file size.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android client and server using servlet I'm running my servlet program on a localhost, and my android code is running on emulator in the same system, I want to send some requests from an android client to the servlet and the servlet program should also send back some data to android after getting the request and it should send using response. Please let me know the code.
This is my android code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.util.Log;
public class CheckHttpClint {
public static void executeHttpPost() throws IOException {
BufferedReader bufferedReader = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
String details = "details";
pairs.add(new BasicNameValuePair("pid", details));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse httpResponse = client.execute(httpPost);
bufferedReader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separater");
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line + NL);
System.out.println(buffer);
Log.i("data send.", null);
}
bufferedReader.close();
String page = buffer.toString();
System.out.println(page);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
}
}
servlet code:
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DBConnection extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
String pid1 = request.getParameter("pid");
out.print(pid1);
out.println("</body></html>");
out.close();
}
}
A: You can find a tutorial for android describing GET, POST and MULTIPART POST here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ASP.NET Routing Regex to match specific pattern I am trying to write a regular expression for ASP.NET MapPageRoute that matches a specific type of path.
I do not want to match anything with a file extension so I used this regex ^[^.]*$ which worked fine except it also picked up if the default document was requested. I do not want it to pick up the default document so I have been trying to change it to require at least one character. I tried adding .{1,} or .+ to the beginning of the working regex but it stopped working alltogether.
routes.MapPageRoute("content", "{*contentpath}", "~/Content.aspx", true, new RouteValueDictionary { }, new RouteValueDictionary { { "contentpath", @"^[^.]*$" } });
How can I change my regex to accomplish this?
Unfortunately my brain does not seem capable of learning regular expressions properly.
A: ^[^.]+$
zero is to * as one is to +
A: You want to change your * quantifier to +. * matches zero or more times, whereas + matches one or more. So, what you are asking for is this:
^[^.]+$
The regex is accomplishing this: "At the beginning of the string, match all characters that are not ., at least one time, up to the end of the string."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CV_8U opencv's matrixes on no 8 bit systems I've read that the signed char and unsigned char types are not guaranteed to be 8 bits on every platform, but sometimes they have more than 8 bits.
If so, using OpenCv how can we be sure that CV_8U is always 8bit?
I've written a short function which takes a 8 bit Mat and happens to convert, if needed, CV_8SC1 Mat elements into uchars and CV_8UC1 into schar.
Now I'm afraid it is not platform independent an I should fix the code in some way (but don't know how).
P.S.: Similarly, how can CV_32S always be int, also on machine with no 32bit ints?
A: Can you give a reference of this (I've never heard of that)? Probably you mean the padding that may be added at the end of a row in a cv::Mat. That is of no problem, since the padding is usually not used, and especially no problem if you use the interface functions, e.g. the iterators (c.f.). If you would post some code, we could see, if your implementation actually had such problems.
// template methods for iteration over matrix elements.
// the iterators take care of skipping gaps in the end of rows (if any)
template<typename _Tp> MatIterator_<_Tp> begin();
template<typename _Tp> MatIterator_<_Tp> end();
the CV_32S will be always 32-bit integer because they use types like those defined in inttypes.h (e.g. int32_t, uint32_t) and not the platform specific int, long, whatever.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Offline comparison of two arrays iphone sdk I have two arrays containing string variables. In one array, it contains the values from a web service, it will be updating in every 5 seconds. So, i need to run this app offline and also compare the array with another array that contains some sample values. If any matches occur, should generate a PushNotification. Is that possible?? If yes how can I implement that? If no, is there any other way?
Please help...
Thanks....
A: Hey I can just give you an idea.
register your app for background app
in did enter background make a background handler and you will get approximately 10 mins to finish the task, after the time is over the handler will call finishing block and in this block again create the background handler you will get again 10 mins and so on, in this way your application will reamin in background. But be aware of watchdog.
P.S. This is just an idea, i dont know the apple's view on this. Hope you will succeed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing a form's control from a separate thread I'm practising on threading and came across this problem. The situation is like this:
*
*I have 4 progress bars on a single form, one for downloading a file, one for showing the page loading status etc...
*I have to control the progress of each ProgressBar from a separate thread.
The problem is I'm getting an InvalidOperationException which says
Cross-thread operation not valid: Control 'progressBar1' accessed from
a thread other than the thread it was created on.
Am I wrong in this approach or can anybody tell me how to implement this?
A: A Control can only be accessed within the thread that created it - the UI thread.
You would have to do something like:
Invoke(new Action(() =>
{
progressBar1.Value = newValue;
}));
The invoke method then executes the given delegate, on the UI thread.
A: You need to call method Invoke from non-UI threads to perform some actions on form and other controls.
A: You can check the Control.InvokeRequired flag and then use the Control.Invoke method if necessary. Control.Invoke takes a delegate so you can use the built-in Action<T>.
public void UpdateProgress(int percentComplete)
{
if (!InvokeRequired)
{
ProgressBar.Value = percentComplete;
}
else
{
Invoke(new Action<int>(UpdateProgress), percentComplete);
}
}
A: The UI elements can only be accessed by the UI thread. WinForms and WPF/Silverlight doesn't allow access to controls from multiple threads.
A work-around to this limitation can be found here.
A: private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
}
Maybe this will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Mapping POCO Class to Dynamically Created Tables I have a script running every hour that stores log data in a logging database. Every month a new table is created, and the logging information from this month is stored in that table.
Every table that is created is identical and match a simple POCO class
class IISLog
{
SystemRef,
date,
s-sitename,
//etc
}
I've only found a single way to access these tables using a code-first approach:
var result = this.Database.SqlQuery<WebLog>("select * from " + table + "_" + month);
However, it appears that I lose the lazy loading in the process since SqlQuery returns an IEnumerable of the type.
Is there any way to let lazy loading prevail as well as allow the data context to track the elements? (Main priority on the first point).
A: You will lose everything by using SqlQuery - that is direct SQL execution without any EF features involved. It will just materialize objects for you.
There is no way to use EF with this type of database tables. EF demands that type can be mapped only to single table (or set of tables in case of inheritance or splitting). Entity cannot be mapped to multiple tables even if they are exactly same.
If you want to use EF you should look for solution on database side and map only single database view or table to your entity or use stored procedure to correctly select table which will be queried.
A: I think this is very possible. Of course I have not developed it but here is where I would start. First you can make two queries to find basic information regarding your database:
SELECT * FROM INFORMATION_SCHEMA.TABLES
SELECT * FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'MyTableName'
EDIT: From this you will have a list of tables and their respective attributes by cycling through.
You may not need this step if you use convention over configuration.
From here you can create your custom objects at runtime using reflections TypeBuilder and FieldBuilder. An example would be http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-%28C%29.aspx.
Next, use EF Code First with a custom DbContext and override OnModelCreating(...) to map your dynamic objects. Using the Fluent API you could loop through your dynamic types to create your reoccurring mapping pattern. However use caution to not perform this step with every instantiation. I think that might be the crux of your issue.
Never the less I'm very intrigued by your question and curious to what your end solution is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: context depended scan-component filter My SpringMVC based webapp uses typically 2 contexts: the webapplication context for the MVC dispatcher servlet and the parent/root application context.
<!-- the context for the dispatcher servlet -->
<servlet>
<servlet-name>webApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
....
<!-- the context for the root/parent application context -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:root-context.xml</param-value>
</context-param>
Within these contexts, I use component scanning for loading all beans.
My packages are named according their usecase (e.g. com.abc.registration, com.abc.login etc.) rather then based on the technological tier (e.g. com.abc.dao, com.abc.services etc.)
Now my question: in order to avoid duplicate scanning of some classes, is it a good practice, to filter the candidate component classes for both contexts, e.g. include only the MVC Controller for web context scan and include all other components (services, dao/repositorie) in the root application context ?
<!-- servlet-context.xml -->
<context:component-scan base-package="com.abc.myapp" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- root-context.xml -->
<context:component-scan base-package="de.efinia.webapp">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
Or is it neither important nor necessary to avoid such duplication for the component scan ?
A: I like your solution in two areas:
*
*You divide classes based on uses cases rather than layers. If you would have a single web package with all controllers then you wouldn't have problems. But still I found such an approach much better.
*Yes, you should filter classes. Obviously it's not a problem with increased memory footprint, as this is marginal (but increased startup time might be significant).
However having duplicated beans (both controllers and service beans) might introduce subtle bugs and inconsistencies. Some connection pool has been initialized two times, some startup hook runs two times causing unexpected behavior. If you use singleton scope, keep that it way. Maybe you won't hit some problems immediately, but it's nice to obey the contracts.
BTW note that there is an <mvc:annotation-driven/> tag as well.
A: It is a good practice, indeed. The parent application context should not have controllers in it.
I can't add more arguments to justify the practice, but it certainly is cleaner that way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to store images in the sqlite database in iphone
Possible Duplicate:
Reading and writing images to an SQLite DB for iPhone use
How to store a images file in database in blob type in sqlite database and how to retrieve a image from the database.
A: save image in your nsdocument directory. in database save the path of this image. this is a good approach. if u save blob in data base database will so heavy. it take time to load.
A: First convert image into NSData
Then NSData into bytes
Then store that bytes...
Sorry I don't know the method that should be called, because I use core data which is far better than sqlite c api
A: The easiest way is to use an Objective-C sqlite wrapper such as fmdb. Then you can pass an NSData handle from UIImagePNGRepresentation() into the wrapper as a blob.
Alternatively, you could do something like this:
NSData *rawImage = UIImagePNGRepresentation(myUIImage);
sqlite3_bind_blob(mySavedSQLStatement, 2, [rawImage bytes], [rawImage length], SQLITE_TRANSIENT);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: App Release Version crashes Debug Version works, no idea why So I have this app I'm working on and after building running the App from XCode on the device everything works fine. However after installing the same App from the App Store (no changes only the provisioning profile is different) the App crashes shortly before it starts.
Console errors:
Fri Sep 30 12:48:42 unknown locationd[540] <Notice>: MS:Notice: Installing: (null) [locationd] (550.32)
Fri Sep 30 12:49:47 itess Ola Portugal[556] <Notice>: MS:Notice: Installing: com.mindovertech.olaportugal [Ola Portugal] (550.32)
Fri Sep 30 12:49:47 itess kernel[0] <Debug>: launchd[556] Builtin profile: container (sandbox)
Fri Sep 30 12:49:47 itess kernel[0] <Debug>: launchd[556] Container: /private/var/mobile/Applications/13E9B45C-84ED-4FD3-BDAA-8527BA34CB3F [69] (sandbox)
Fri Sep 30 12:49:47 itess Ola Portugal[556] <Notice>: MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Activator.dylib
Fri Sep 30 12:49:47 itess Ola Portugal[556] <Notice>: MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/PDFPatch_CVE-2010-1797.dylib
Fri Sep 30 12:49:49 itess locationd[557] <Notice>: MS:Notice: Installing: (null) [locationd] (550.32)
Fri Sep 30 12:49:51 itess Ola Portugal[556] <Warning>: Warning: Libinfo call to mDNSResponder on main thread
Fri Sep 30 12:49:56 itess ReportCrash[559] <Notice>: Formulating crash report for process Ola Portugal[556]
Fri Sep 30 12:49:57 itess com.apple.launchd[1] (UIKitApplication:com.mindovertech.olaportugal[0xeace][556]) <Warning>: (UIKitApplication:com.mindovertech.olaportugal[0xeace]) Job appears to have crashed: Bus error
Fri Sep 30 12:49:57 itess SpringBoard[28] <Warning>: Application 'Olá Portugal' exited abnormally with signal 10: Bus error
Fri Sep 30 12:49:57 itess ReportCrash[559] <Error>: Saved crashreport to /var/mobile/Library/Logs/CrashReporter/Ola Portugal_2011-09-30-124953_itess.plist using uid: 0 gid: 0, synthetic_euid: 501 egid: 0
Device log:
Incident Identifier: B2ABCA98-7942-4FF2-968A-F5FE4AFDDE4D
CrashReporter Key: fd9745556d91de13e834ad1bbd0bee6c29b17976
Hardware Model: iPod2,1
Process: Ola Portugal [556]
Path: /var/mobile/Applications/13E9B45C-84ED-4FD3-BDAA-8527BA34CB3F/Ola Portugal.app/Ola Portugal
Identifier: Ola Portugal
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]
Date/Time: 2011-09-30 12:49:53.028 +0100
OS Version: iPhone OS 4.0 (8A293)
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x00816a00
Crashed Thread: 0
Thread 0 Crashed:
0 ??? 0x00816a00 0 + 8481280
(Didn t copy the other threads because they seems to be fine)
Here's one more detail, the device where it crashes is an iPod touch running 4.0
The same App (from the App Store) works perfectly on an iPhone4/iPad2 running 4.3.3
I'm not sure if the problem is with the device or with the OS and what I can do to fix it.
Like I said before If I run the debug version on the device from XCode it works fine.
Any ideas?
A: Generally this kind of error occurs when we are updating new version on store because of coredata.
If you have changed any thing related to coredata then you need to delete old .Sqlite file at first launch of new version. remember not every time to delete .squlite but only once the application starts and old file exist.
A: I forgot about this thread. I eventually found out it had to do with iAD, I was using an instruction available on 4.1 but not 4.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Framework MVC 3 in C#. Refuses to add values to table 'Person' and People is generated(?) One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'Person' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: The EntitySet People is based on type Person that has no keys defined.
---> Person.cs ( in models )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Portal.Models
{
public class Person
{
[Required]
public int UserId;
[Required]
public string FirstName;
[Required]
public string LastName;
}
}
-- > PersonDB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Portal.Models
{
public class PersonDB : DbContext
{
public DbSet<Person> Person { get; set; }
}
}
-- > web.config connectionstring.
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ASPNETDB.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="PersonDB"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ASPNETDB.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
-- > AccountController ( trying to add values if account creation succeded )
PersonDB db = new PersonDB();
Person p = new Person {UserId = 1, FirstName = "hej", LastName = "padig"};
db.Person.Add(p);
db.SaveChanges();
Here I'm just trying to add some test values to the table, the table consists of UserId with is int, and nvarchar FirstName, LastName.
Where does this People come from in the validation error?
"The EntitySet People is based on type Person" << This is driving me insane.
Don't get this, I've spent way too much time with this which essentially just is an insert into query...
A: First, every entity type needs a key. If you got the property named Id or 'EntityClassName'Id, it is chosen as the key by default (that's the convention in other words). As you do not have property named Id or PersonId - you've got only UserId, you get first validation error that Person has got no key. Add the [Key] attribute on UserId, or use the fluent interface code
//Inside PersonDB class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>().HasKey(x => x.UserId);
}
PluralizingEntitySetNameConvention is one more example of conventions. Entity Framework uses this convention by default and makes entity set names plural. If you do not wish to use this convention, you can remove it. Here is the list of all the default conventions. You can remove undesired convention by calling
//Inside PersonDB class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().HasKey(x => x.UserId);
....
modelBuilder.Conventions.Remove<ConventionTypeNameFromTheLinkAbove>();
}
If you look carefull, you can see that KeyAttributeConvention is also one of default builtin conventions.
A: "People" is the name that was automatically assigned to the EntitySet when your model was generated. EntityFramework tries to do some slick automatic pluralization of table/entity names so it decided a row in the Person table was a "Person" and the entire table itself should be referred to by a repository named "People."
You need to do db.People.Add(p);
You also need to revisit the Person table in your database, because EntityFramework wasn't able to easily determine the keys defined in that table (which EntityFramework needs for maintaining state of your repository/table when changes are being made to its internal ObjectStateManager etc).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Application won't end VideoStreams and Exit I've got an application what's working with two video streams.
When the form is being closed, it runs this function:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (FinalVideoDevice.IsRunning) { FinalVideoDevice.Stop(); }
if (streamMJPEG.IsRunning) { streamMJPEG.Stop(); }
Application.Exit();
}
But in reality it doesn't kill the application, only hides the form, but still is seen from TaskManager/Processes.
Any ideas what I might be doing wrong?
Thanks!
A: Assuming you are in Windows Forms you can call Application.ExitThread();
in general one of the reasons why you still see the process in TaskManager could be that you still have some background / worker threads active.
Roger check this question/answers as well: Application.Exit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get rows and count using PDO UPDATE 1:
I've just noticed PDO::MYSQL_ATTR_FOUND_ROWS in the manual, but I'm not sure how to integrate it with the code below in the original question and/or if this will answer my question?
ORIGINAL QUESTION:
I currently have the following which works, it returns rows of data:
function my_function()
{
$DBH = new PDO( "mysql:host=server;dbname=database", "user", "pass" );
$DBH -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH -> prepare( "select * from table 1" );
$STH -> execute();
$ROWS = $STH -> fetchAll();
foreach($ROWS as $ROW) {
$output .= $ROW["col1"] . " - " . $ROW["col2"] . "<br />";
}
$DBH = null;
return $output;
}
How do I get a count of the number of rows returned? I've looked into PDO's rowCount() function, but that returns rows effected on update, insert, or delete. I would like to get a count of the number of rows return from a select.
I understand I can increment an integer i.e. i++ in the loop, but that seems a little primitive. I'm guessing there is a nicer way?
A: rowCount returns the number of rows matched when used with a SELECT statement.
A: count($ROWS);
?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Magento: Put "product list pager"-block in I have the following problem:
I want develop Pagination with rel=“next” and rel=“prev” for magento product lists.
http://googlewebmastercentral.blogspot.com/2011/09/pagination-with-relnext-and-relprev.html
How can I access the pager in ? The head-block has been already rendered when the pager-block will be rendered...
Is there any solution for my problem?
A: Yes, you can do edit the following file:
/app/design/frontend//default/template/page/html/pager.phtml
There you see for example:
<?php if (!$this->isFirstPage()): ?>
<li>
<a class="previous<?php if(!$this->getAnchorTextForPrevious()): ?> i-previous<?php endif;?>" href="<?php echo $this->getPreviousPageUrl() ?>" title="<?php echo $this->__('Previous') ?>">
<?php echo $this->__("Previous");?>
</a>
</li>
<?php endif;?>
Where you can easily add the rel="..." you want to the link, same goes for the "Next" link ;)
A: I added this code into the head.phtml file...
<?php
$actionName = $this->getAction()->getFullActionName();
if($actionName == 'catalog_category_view') // Category Page
{
$id = Mage::app()->getRequest()->getParam('id', false); //cat id
$category = Mage::getModel('catalog/category')->load($id);
$prodCol = $category->getProductCollection();
$tool = $this->getLayout()->createBlock('catalog/product_list_toolbar')->setCollection($prodCol);
$linkPrev = false;
$linkNext = false;
if ($tool->getCollection()->getSize()) {
if ($tool->getLastPageNum() > 1) {
if (!$tool->isFirstPage()) {
$linkPrev = true;
$prevUrl = $tool->getPreviousPageUrl();
}
if (!$tool->isLastPage()) {
$linkNext = true;
$nextUrl = $tool->getNextPageUrl();
}
}
}
?>
<?php if ($linkPrev): ?>
<link rel="prev" href="<?php echo $prevUrl ?>" />
<?php endif; ?>
<?php if ($linkNext): ?>
<link rel="next" href="<?php echo $nextUrl ?>" />
<?php endif; ?>
<?php
}
?>
A: From version 1.5 this solution doesn't work anymore, this is my solution:
$actionName = $this->getAction()->getFullActionName();
if($actionName == 'catalog_category_view') // Category Page
{
$id = Mage::app()->getRequest()->getParam('id', false); //cat id
$category = Mage::getModel('catalog/category')->load($id);
$prodCol = $category->getProductCollection()->addAttributeToFilter('status', 1)->addAttributeToFilter('visibility', array('in' => array(2, 4)));
$tool = $this->getLayout()->createBlock('page/html_pager')->setLimit($this->getLayout()->createBlock('catalog/product_list_toolbar')->getLimit())->setCollection($prodCol);
$linkPrev = false;
$linkNext = false;
if ($tool->getCollection()->getSize()){
if ($tool->getLastPageNum() > 1){
if (!$tool->isFirstPage()) {
$linkPrev = true;
if($tool->getCurrentPage()==2){
$url = explode('?',$tool->getPreviousPageUrl());
$prevUrl = $url[0];
}
else $prevUrl = $tool->getPreviousPageUrl();
}
if (!$tool->isLastPage()){
$linkNext = true;
$nextUrl = $tool->getNextPageUrl();
}
}
}
if ($linkPrev) echo '<link rel="prev" href="'. $prevUrl .'" />';
if ($linkNext) echo '<link rel="next" href="'. $nextUrl .'" />';
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I turn transactions off in MySQL/InnoDB? I have a Django app where the default "REPEATABLE READ" transaction isolation level in InnoDB is causing different processes to have different views of the data than that current in the database.
e.g. Process 1 has made a change but Process 2 isn't seeing it.
I don't need transactional integrity in the app; can I just turn off transactions altogether so that all processes doing a SELECT see the same data?
Any downside to doing this?
Is this what is meant by "READ UNCOMMITTED"?
Any pointers welcome
Rachel
A: I'd suggest that you just convert the InnoDB tables to myISAM. If your criteria is speed, you are wasting alot of potential by using a transaction oriented table type (InnoDB) and just disabling transactions. You would gain alot if you just converted the tables to myISAM. It's designed with lack of transactions in mind, while still being able to lock changes (i.e. table locks).
A clean
ALTER TABLE table_name ENGINE = MyISAM;
can do the trick for a single table, dumping, changing type and loading the table does the trick as well.
A: Autocommit is on by default in InnoDB. Transactions are still used for updates (which is necessary), but they are committed immediately after each statement.
The READ UNCOMMITTED isolation level allows a transaction to read rows which have been written by other transactions but haven't yet been committed. This point is irrelevant however if you're not explicitly using transactions and autocommit is on.
Unfortunately, I'm not too familiar with Django, but from the documentation I see:
How to globally deactivate transaction management
Control freaks can totally disable all transaction management by setting
DISABLE_TRANSACTION_MANAGEMENT to True in the Django settings file.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to use Min,max and average with Solr.net I found http://code.google.com/p/solrnet/wiki/Stats link.
But i cannot understand properly.
I want to use min,max kind of function with solr query.
My query(Display min, max and average price of Round shape and color D and clarity FL and caratweight.(This query will be genarated based on user's selection dynamically)
(Shape:"Round") AND (Color:"D") AND (Clarity:"FL") AND (CaratWeight:[1 TO 10])
But how can i use such kind of function and select specific column.
Now i am somewhat nearer...
By using following url, i am getting min,max,count and mean..things those i want.
But its in xml format. Now i want to cusomize. I want to use this result in my asp.net code behind and want to do further computation.
http://localhost:8983/solr/coreMikisa/select/?q=*%3A*&version=2.2&start=0&rows=10&indent=on&stats=true&stats.field=Price
So please reply.. how can i get???
A: http://localhost:8983/solr/coreMikisa/select/?q=*%3A*&version=2.2&start=0&rows=10&indent=on&stats=true&stats.field=Price
This can be expressed in SolrNet as:
var statsParams = new StatsParameters();
statsParams.AddField("Price");
var results = solr.Query(SolrQuery.All, new QueryOptions {
Rows = 10,
Start = 0,
Stats = statsParams
});
// use results.Stats...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to override window show operation? I have a class derived from window to show message to user. The problem is in some places in my application it is throwing an exception saying
The calling thread must be STA, because many UI components require
this.
I came to know i need to introduce the Dispatcher to invoke the messagebox to get rid of the error. Since the messagebox is used in numerous locations the fastest fix i can think about is to override the show and showwindow and create and display the message box from there.
Please tell me how can i override the Show and ShowWindow events of a wpf window
A: I would make a static utility class that has a method (and maybe some overloads) to show this form for you. A bit like MessageBox in Windows.Forms. Within that class you can code anything that is required to show the window properly without ever having to repeat yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make maven versions:use-latest-versions step up import scoped entry in dependencyManagement? We use the maven versions plugin to keep our versions up to date by regularly mvn versions:use-latest-versions. In our poms we have an import scoped dependency to another POM that looks like this:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>se.company.maven</groupId>
<artifactId>maven-third-party-dependencies</artifactId>
<version>0.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
When we run mvn versions:use-latest-versions all our dependencies (and other entries in dependencyManagement) get stepped up except this one. Is there a way to get the versions plugin to step up this kind of entry?
A: It does work when you put the version of the import-scoped dependency in a property, and use the versions:update-properties goal.
Your example pom would then look like this:
<properties>
<my.dependency.version>0.0.1</my.dependency.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>se.company.maven</groupId>
<artifactId>maven-third-party-dependencies</artifactId>
<version>${my.dependency.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
A: Could you be hitting one of the problems mentioned in the FAQ?
To rephrase it here, is the artifact which is not getting stepped a local artifact, which is not deployed to a repository manager? If so, you can resolve this by setting up a repository manager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: php/regex - Extract proper nouns from text I want to extract proper nouns (e.g Micheal Jackson) from a text with PHP regex but my regex is not right.
The text:
My friend Micheal Jackson was the King of Pop. The Game Album sold little.
What I want:
A regex that is able to extract proper nouns of multiple words e.g Micheal Jackson or The Game Album.
My regex:
/(?<=\s)([A-Z][a-z]+).*(?=\s)/
Thanks.
P.S. Posted via a mobile device. Apologies if format is poor.
A: Try to use word boundaries instead of your lookbehind/lookahead
/\b([A-Z][a-z]+)\b/
I don't understand your .* part this will match anything after the first word till the last whitespace, so I removed it from my regex.
If you want to match multiple words at once (Maybe you wanted to achieve this with your .*?) try this:
(?:\s*\b([A-Z][a-z]+)\b)+
See it here on Regexr
A: The Stanford Parser can help you here. It will tokenize your phrase and extract proper nouns and all other pieces according to the sentence structure.
It's available as a jar download or you can try it out online here: http://nlp.stanford.edu:8080/parser/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Delete duplicate string with PowerShell I have got text file:
1 2 4 5 6 7
1 3 5 6 7 8
1 2 3 4 5 6
1 2 4 5 6 7
Here first and last line are simmilar. I have a lot of files that have double lines. I need to delete all dublicate.
A: To get unique lines:
PS > Get-Content test.txt | Select-Object -Unique
1 2 4 5 6 7
1 3 5 6 7 8
1 2 3 4 5 6
To remove the duplicate
PS > Get-Content test.txt | group -noelement | `
where {$_.count -eq 1} | select -expand name
1 3 5 6 7 8
1 2 3 4 5 6
A: All these seem really complicated. It is as simple as:
gc $filename | sort | get-unique > $output
Using actual file names instead of variables:
gc test.txt| sort | get-unique > unique.txt
A: If order is not important:
Get-Content test.txt | Sort-Object -Unique | Set-Content test-1.txt
If order is important:
$set = @{}
Get-Content test.txt | %{
if (!$set.Contains($_)) {
$set.Add($_, $null)
$_
}
} | Set-Content test-2.txt
A: Try something like this:
$a = @{} # declare an arraylist type
gc .\mytextfile.txt | % { if (!$a.Contains($_)) { $a.add($_)}} | out-null
$a #now contains no duplicate lines
To set the content of $a to mytextfile.txt:
$a | out-file .\mytextfile.txt
A: $file = "C:\temp\filename.txt"
(gc $file | Group-Object | %{$_.group | select -First 1}) | Set-Content $file
The source file now contains only unique lines
The already posted options did not work for me for some reason
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Use SQL Server for file queue storage We are developing file processing system where several File Processing applications pick up files from queue, do processing and put back file to queue as response. Now we use Windows file system(share a folder on network) as queue. We share one folder and put files in it, the File Processing Servers applications pick up files from it and put back after processing.
We are thinking to move the whole queue engine system from windows file system to SQL Server. Is it good idea to store files into SQL Server and use SQL Server as file queue backend? The files are about 1-20mb in size and our system process about 10 000 files per day.
A: You can do that, but I'd prefer a queue - either a remote instance or an in-memory object. I would prefer a real queue because I could pool listeners and have the queue hand off requests to them and manage their life cycle. You'll have to write all that code if you put them in a database.
10,000 files per day means you need to process one every 8.64 seconds for 24 hours a day. What are your typical processing times for a 1-20MB file?
The processing of the files should be asynchronous.
If you have 50 listeners, each handling one 20MB file, your total memory footprint will be on the order of 1GB.
As far as speed goes, the worst case is the 15 minutes for processing time. That's four per hour, 96 per day. So you'll need at least 104 processors to get through 10,000 in a single day. That's a lot of servers.
You're not thinking about network latency, either. There's transfer time back and forth for each file. It's four network hops: one from the client to the database, another from the database to the processor, and back again. 20MB could introduce a lot of latency.
I'd recommend that you look into Netty. I'll bet it could help to handle this load.
A: The file size is quite nasty - unless you can e.g. significantly compress the files, the storage requirements in SQL might outweigh any benefits you perceive.
What you might consider is a hybrid solution, i.e. modelling each incoming file in SQL (fileName, timestamp, uploadedby, processedYN... etc), queuing the file record in SQL after each upload, and then use SQL to do the queueing / ordering (and you can then run audits, reports etc out of SQL)
The downside of the hybrid is that if your file system crashes, you have SQL but not your files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: filter text from list view in an edit text I have a list view and above that one edit text. In edit text, data is searched from the list view and show in edit text. In the list view some data are two words. For example, list view contains "car", "red car", "blue car" . Now if I type c in edit text, it shows only car, not the other two. How can I search all the above three, when c is typed. Here is my code...
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
wordlength = ed.getText().length();
editsort.clear();
for(int i=0;i<word.length;i++){
if(wordlength<=word[i].length()){
if(ed.getText().toString().equalsIgnoreCase((String) word[i].subSequence(0, wordlength))){
editsort.add(word[i]);
}
}
}
Thanks...
A: If word is the array of strings which you want to search in:
public void onTextChanged(CharSequence s, int start, int before, int count) {
String searchFor = ed.getText().toString();
editsort.clear();
for( String whole : word ){
for( String part : whole.split( " " ) ) {
if( part.startsWith( searchFor ) );
editsort.add( whole );
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Geocoder API or Places API for an address based map search I am trying to build an address based map search using PHP and Ajax. Typing in a term in the address field should bring up suggested addresses in a dropown and any address term not bringing up any suggested addresses in a dropown should present a 'Did you mean' section on the left of the page. For my internal functions I need the lat, lng and short country code, for example - 'GB'.
I have tried using both the Geocoder API and the Places API but both APIs lack some features which I would like.
Using the Geocoder API with jQuery UI to bring up suggested addresses in a dropown up and for the 'Did you mean' section' return multiple duplicate results. Is there any way to refine this even further so that distinct results are returned. Also for some countries like 'India' and 'Afghanistan' there seems to be no short country code.
Using the Places API Autocomplete I am able to get the lat, lng and short country code for almost all addresses but I don't seem to able to tell when the suggested addresses in the dropown have been populated. There doesn't seem to be an event for this. Also I can't seem to use the Places API to create my 'Did you mean' section'.
I know the APIs are experimental and are being constantly updated, but maybe I'm missing something. Any help would be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL Database Function to reduce value in other table by 1 I have a MySQL db. When a field in a table is updated can I write a function or by some other process get a field in another table to be automatically updated?
ie, and this is what I want to do, if table 1 field discount_code and discount code is 123456, then in table 2 can I have times_code_can_be_used (starts at say 20) automatically reduced by 1???
Not done this before and need some guidance.
Thank you.
A: yes you can do it using mysql trigger
example :-
delimiter |
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
|
delimiter ;
Note :Support for triggers is included beginning with MySQL 5.0.2
A: you can just use a trigger function. You can set it to run for a particular table if a field is updated or inserted or deleted. Inside that trigger function, you can put any kind of sql you want with whatever logic you need, in your example, just get data from the updated field and use it to update fields in another table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does pthread_exit kill a thread.. I mean free the stack allocated to it? I want to create a lot of threads for a writing into a thread, and after writing I call exit... But, when I call exit do I free up the stack or do I still consume it??
A: In order to avoid resource leaks, you have to do one of these 2:
*
*Make sure some other thread call pthread_join() on the thread
*Create the thread as 'detached', which can either be done by setting the proper pthread attribute to pthread_create, or by calling the pthread_detach() function.
Failure to do so will often result in the entire stack "leaking" in many implementations.
A: The system allocates underlying storage for each thread, (thread ID, thread retval, stack), and this will remain in the process space (and not be recycled) until the thread has terminated and has been joined by other threads.
If you have a thread which you don't care how the thread terminates, and a detached thread is a good choice.
For detached threads, the system recycles its underlying resources automatically after the thread terminates.
source article: http://www.ibm.com/developerworks/library/l-memory-leaks/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery doesn't work in page called by ajax If I have the following in a page:
$(document).ready(function () {
alert('moo');
});
It will show the alert when I view that page BUT if that page is called via Ajax then the alert will not show... Any ideas why? Or how to get around this?
Note: This is test javascript and i'm not actually showing an alert in my real app
Thanks
Ajax jazz as requested:
$(document).ready(function ()
{
$('ul#ui-ajax-tabs li a').click(function (e)
{
e.preventDefault();
$("ul#ui-ajax-tabs li").removeClass("selected");
$(this).parents('li').addClass("loading");
var url = $(this).attr("href");
var link = $(this);
$.ajax({
url: url,
success: function (responseHtml)
{
//$('div#ui-tab-content').html($(responseHtml));
$('div#ui-tab-content').html($(responseHtml).find('div#ui-tab-content > div#ui-ajax-html'));
$(link).parents('li').addClass('selected');
$("ul#ui-ajax-tabs li").removeClass("loading");
History.pushState(null, $(responseHtml).filter('title').text(), url)
},
error: function (responseHtml)
{
$('div#ui-tab-content').html('<div class="message error"><p><strong>Something went wrong...</strong> Please contact the Administrator!</p></div>');
$(link).parents('li').addClass('selected');
$("ul#ui-ajax-tabs li").removeClass("loading");
History.pushState(null, $(responseHtml).filter('title').text(), url)
},
statusCode:
{
404: function (responseHtml)
{
$('div#ui-tab-content').html('<div class="message error"><p><strong>Error 404 (Not Found)</strong> Please contact the Administrator!</p></div>');
$(link).parents('li').addClass('selected');
$("ul#ui-ajax-tabs li").removeClass("loading");
History.pushState(null, 'Error 404 (Not Found)', url)
},
500: function (responseHtml)
{
$('div#ui-tab-content').html('<div class="message error"><p><strong>Error 500 (Internal Server Error)</strong> Please contact the Administrator!</p></div>');
$(link).parents('li').addClass('selected');
$("ul#ui-ajax-tabs li").removeClass("loading");
History.pushState(null, 'Error 500 (Internal Server Error)', url)
}
}
});
});
});
A: Your web page is text. The browser you use happens to interpret it when you request it from your servers.
If you're doing an ajax request, the content will be on a variable as a string waiting for you to do something. It doesn't matter if it has scripts on it, it won't auto execute.
You would have to create a script element with that as innerText and append it to the DOM to have it executed by the browser.
A: Your remote js code is not executed when you call AJAX but you can return a js script as text and execute it on your page using the eval() function
A: When you say you are "calling" a page via Ajax, do you mean you are requesting some HTML(dynamic or otherwise) from the server that happens to contain this JavaScript with it?
If so, that snippet should run, but not until you insert it into the DOM.
If you are using jQuery, the most typical way of getting HTML from a server and replacing the contents of a DOM element with it is the "load" method:
jQuery .load()
A: The reason alert doesn't come up on ajax request is because the "document" has already executed the "ready" state.
Remove $(document).ready() from the js file (leave alert() on its on in there) and try loading it via ajax. It should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django: Custom 'clean' method on a Form that sets to self._errors, but isn't shown on the HTML? I have a Form in Django, I've added a custom clean() method since some of the fields depend on each other. When there's an error, I add things to self._errors['FIELDNAME'] (as the Django documentation says).
However I also need to customize the output of this form in the HTML, so I'm manually writing HTML, and using {{ form.FIELDNAME }} etc. However I can't get the error message for that field. form['FIELDNAME'].errors is empty (i.e. {{ form.FIELDNAME.errors }} in the termplate), but form.errors['FIELDNAME'] has the error message.
What's the Right Way™ to do this? Should I access {{ form.errors.FIELDNAME }} in the template, or should I set the errors in the clean method another way? Is this a bug in Django?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hive Dynamic Partition table issue with altering partition I Have table with dynamic partition "campaign" and static partitions year and month(that means I am giving there value while inserting/creating partitions).
'ABC' Partition by (year='2011', month='08', campaign)
As dynamic partition is only supported when its followed by static partitions namesly year and month. But my use case is opposite
I want something like this -->
'ABC' Partition by (campaign, year='2011', month='08')
So that i can see for campaigns results per year and month.
By any chance, OR any other option by which I can do that? something like this??
ALTER TABLE ABC PARTITION (y='2011', m='08',campaign) RENAME/ALTER PARTITIONs (campaign,y='2011', m='08');
A: A partition isn't defined as static or dynamic in the metastore; Just INSERT/LOAD queries define partitions as static or dynamic. You can run an insertion that uses all-dynamic partitions by using SET hive.exec.dynamic.partition=nonstrict.
See: https://cwiki.apache.org/confluence/display/Hive/Tutorial
A: if you set your partition to strict mode you can perform it
SET hive.exec.dynamic.partition=strict
BUT IF you set to nonstrict mode and perform dynamically then
SET hive.exec.dynamic.partition=nonstrict
We cannot perform ALTER on the Dynamic partition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I turn Wifi on when my application runs in Android? When I start my twitter app, how can I turn on WiFi automatically through coding?
A: I have not tried this but it should work:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null)
wifiManager.setWifiEnabled(true);
Add this permission to the manifest file:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
A: if (text.indexOf("wi-fi") != -1) {
if (text.indexOf("on") != -1) {
WifiManager wifi = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()) {
Toast.makeText(MainActivity.this, "Already WiFi is Enabled", Toast.LENGTH_SHORT).show();
tts.speak("Already WiFi is Enabled", TextToSpeech.QUEUE_ADD, null);
}
else {
wifi.setWifiEnabled(true);
Toast.makeText(MainActivity.this,"Turning on",Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Turning on wifi", Toast.LENGTH_SHORT).show();
tts.speak("Turning on wifi", TextToSpeech.QUEUE_ADD, null);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Matlab: Optimize this? Im v new to matlab. Have been tasked with speeding up a procedure. Im sure there is a better way to do the following statements:
for i = 2:length(WallId)
if WallId(i) ~= WallId(i-1)
ReducedWallId = [ReducedWallId;WallId(i)];
ReducedWallTime = [ReducedWallTime;WallTime(i)];
GroupCount = [GroupCount;tempCount];
tempCount = 1;
else
tempCount = tempCount +1;
end
end
I can preallocate the various vars to 'length(WallId)' but what do I do with the extra after its done? Do I care?
A: idx = find([true diff(WallId) ~= 0]);
ReducedWallId = WallId(idx);
ReducedWallTime = WallTime(idx);
GroupCount = diff([idx numel(WallId)+1]);
Assuming what you want is a summary of the unique data in WallId and WallTime, then you should
make sure that WallId is sorted first. You can re-organise WallTime to match, as follows:
[WallId, ind] = sort(WallId);
WallTime = WallTime(ind);
Also, you'll only get the right answer if WallTime matches whenever WallId does.
A: Use vectorization.
ReducedWallId=WallId(find(diff(WallId)~=0));
and similarly for ReducedWallTime.
The explicit for-loops are extremely slow. Using vector-operations speeds everything up considerably. This is a general theme in optimizing MATLAB code and is covered in detail in various documents found in the web.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to send multiple inputs to the remote shell using subprocess.Popen I am trying to run multiple commands on a remote computer after doing ssh to that machine and then running commands on its terminal.
I want to use subprocess for this work. So I wrote the following command:-
import subprocess
process = subprocess.Popen(['ssh', '[email protected]'], shell=False, stdin=subprocess.PIPE)
Now I get the terminal of remote machine and I pass the following command which gets executed on that machine:-
print process.communicate('python test.py /home/rahul/vPath-dissector')
But when I am again calling the last called command, it gives an error:-
print process.communicate('python temp.py /home/rahul/vPath-dissector')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/subprocess.py", line 690, in communicate
self.stdin.write(input)
ValueError: I/O operation on closed file
So what command can I use to send multiple commands without closing the file???
A: Trying to find the answer to the same problem I ended up using pexpect instead of subprocess.
import pexpect
ssh = pexpect.spawn('ssh [email protected]')
prompts = [">", "#", "\$", "}", '%', pexpect.TIMEOUT]
ssh.sendline('echo Hello')
ssh.expect(prompts)
print ssh.before
For ssh specific there is even pxssh.
A: Not sure whether this is useful for you since you asked explicitely for subprocess.Popen
- still, you can simply execute your remote command from the shell using
ssh [email protected] python test.py /home/rahul/vPath-dissector
and of course from python with
os.system("ssh [email protected] python test.py /home/rahul/vPath-dissector")
You can also capture the output of this command.
Sorry if I missed your point, though...
A: When I had a similar problem years ago I ended up using this recipe from the Python Cookbook. Apparently it is now also available from Pypi, but I don't know if it's exactly the same code or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display array elements in smarty I have merged two mysql results :
while($rs_1 = mysql_fetch_array($r1))
{
$arr1[] = $rs_1;
}
while($rs_2 = mysql_fetch_array($r2))
{
$arr2[] = $rs_2;
}
$resN = array_merge($arr1,$arr2);
var_dump($resN) shows the following result :
array(5) {
[0] => array(4) {
[0] => string(6) "Petric"
["bz_pro_first_name"] => string(6) "Petric"
[1] => string(8) "Naughton"
["bz_pro_last_name"] => string(8) "Naughton"
}
[1] => array(4) {
[0] => string(6) "Nitish"
["bz_pro_first_name"] => string(6) "Nitish"
[1] => string(12) "Dolakasharia"
["bz_pro_last_name"] => string(12) "Dolakasharia"
}
[2] => array(4) {
[0] => string(6) "Martin"
["bz_pro_first_name"] => string(6) "Martin"
[1] => string(3) "Rom"
["bz_pro_last_name"] => string(3) "Rom"
}
[3] => array(4) {
[0] => string(5) "Steve"
["bz_pro_first_name"] => string(5) "Steve"
[1] => string(5) "Wough"
["bz_pro_last_name"] => string(5) "Wough"
}
[4] => array(4) {
[0] => string(3) "Liz"
["bz_pro_first_name"] => string(3) "Liz"
[1] => string(6) "Hurley"
["bz_pro_last_name"] => string(6) "Hurley"
}
}
I am supposed to display them in smarty so :
assign_values('rand_ad',$resN);
Now I tried to display in smarty like this :
{foreach name=outer item=pro from=$rand_pro}
{foreach key=key item=item from=$pro}
{$key}: {$item}<br />
{/foreach}
{/foreach}
It displays the results but serially. I need to extract the values in some positions . So how can I extract the values eg first name, last name etc ?
A: You didn't give an example output of what you wanted, so I'll take a guess. Assuming you are looking for the following output for the array above:
0: Petric Naughton<br />
1: Nitish Dolakasharia<br />
2: Martin Rom<br />
3: Steve Wough<br />
4: Liz Hurley<br />
You'd could do this:
{foreach from=$rand_pro item=pro key=pro_key}
{$pro_key}: {$pro.bz_pro_first_name} {$pro.bz_pro_last_name}<br />
{/foreach}
If I am assuming incorrectly, please update your question with the output you are expecting to be more clear.
A: Use {foreach} to display array in smarty.
and for database connection use ADODB.
In php file:
type $smarty->assign->("arrname",$aodDBconn->Execute($sql)).
It will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is Step 7 v5.5 compatible with v5.4? Does anyone know if a project that was originally created in step 7 v.5.4, then opened, edited, and saved in 5.5, can then be reopened in 5.4 again?
A: No, it can't be re-opened if it was saved in a later version.
A: It is not recommended that you open project with older version, but you can do it.
You may run into some anomalies when using project with different Step 7 versions. But I have not run into anything serious, yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I move the most recent few commits to my git repo to their own branch off a specific historical commit? I have this:
A -- B -- C -- D -- E -- F -- G (master branch)
Where F and G are my recent commits and E is the last commit from the origin.
What I need is to make F and G into a separate branch, which other questions cover, but based on commit B, leaving this:
A -- B -- C -- D -- E (master branch)
\
F -- G (my new branch)
The reason is that commit B is tagged as the stable release (in use on other systems not maintained using git) and I need to make a patch file of commits F and G against that release.
A: git checkout B
git branch my_new_branch
git checkout my_new_branch
That creates a new my_new_branch on B. Then you need to:
git cherry-pick F
git cherry-pick G
Note that [A-G] are the commits hash numbers
A: git checkout B
git branch my_new_branch
git checkout my_new_branch
git cherry-pick F
git cherry-pick G
But this creates only
A -- B -- C -- D -- E -- F -- G (master branch)
\
F -- G (my new branch)
now you need reset master history:
git checkout master
git reset --hard HEAD^^
this will make
A -- B -- C -- D -- E (master branch)
\
F -- G (my new branch)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Inserting text into a text file Alright, this maybe the simplest (or the stupidest) question, but I just got to know...
Suppose I have a text file containing account no. and balance. I am writing a program to search the file using entered account no. and update the balance field in the same text file with a new balance.
I am finding it surprisingly difficult to do so using file streams. The problem is that I am trying to overwrite the balance string in the said text file with a new balance string.
So, if the balance is 1000 (4 digits), I can overwrite it with another 4 digit string. But, if the new balance string is more than 4 digits, it is overwriting the data after the balance field (it is a simple text file mind you...).
For example, if the text file contains
Acc. No. balance
123456 100
123567 2500
The fields are separated by TAB '\t' character, and next record is separated by a newline '\n'. If I enter new deposit of 200000 for account 123456, the fwrite() function overwrites the data in the text file as...
Acc. No Balance
123456 2001003567 2500
You can notice that the '\n' after the balance field, and 2 digits from the next accounts' acc. no. is overwritten.
Of course, no-one wants that to happen :)
What I need is a way to insert text in that file, not just overwrite it. There are many results of doing this using Java, python or even SED, but nothing using FILE streams.
Please share your thoughts... thanks.
A: You'll have to move all data after the insertion point a few bytes up first. That's what Java, sed or python do as well, if they aren't writing a temporary file to begin with.
A: If you really want to manage your data in a plain text file:
While you are reading the file in, write a modified version of your data into a temporary file, then delete the original file and rename the temp file to the original filename. But be carefull that no other process accesses the same file concurrently.
Database systems were invented for such purposes. So I recommend to manage your data in a database table and dynamically create a text report when needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Storing data in memcache to be accessed by different languages I am working on a system that has components written in the following languages:
*
*C
*C++
*C#
*PHP
*Python
These components all use (infrequently changing) data that comes from the same source and can be cached and accesed from memcache for performance reasons.
Because different data types may be stored differently by different language APIs to memcache, I am wondering if it would be better to store ALL data as string (objects will be stored as JSON string).
However, this in itself may pose problems as strings (will almost surely) have different internal representations accross the different languages, so I'm wondering about how wise that decision is.
As an aside, I am using the 1 writer, multiple readers 'pattern' so concurrency is not an issue.
Can anyone (preferably with ACTUAL experience of doing something similar) advice on the best format/way to store data in memcache so that it may be consumed by different programming languages?
A: memcached I think primarily only understands byte[] and representation of byte is same in all languages. You can serialize your objects using protocol buffers or a similar library and consume it in any other language. I've done this in my projects.
A: Regardless of the back-end chosen, (memcached, mongodb, redis, mysql, carrier pigeon) the most speed-efficient way to store data in it would be a simple block of data (so the back-end has no knowledge of it.) Whether that's string, byte[], BLOB, is really all the same.
Each language will need an agreed mechanism to convert objects to a storable data format and back. You:
*
*Shouldn't build your own mechanism, that's just reinventing the wheel.
*Should think about whether 'invalid' objects might end up in the back-end. (either because of a bug in a writer, or because objects from a previous revision are still present)
When it comes to choosing a format, I'd recommend two: JSON or Protocol Buffers. This is because their encoded size and encode/decode speed is among the smallest/fastest of all the available encodings.
Comparison
JSON:
*
*Libraries available for dozens of languages, sometimes part of the standard library.
*Very simple format - Human-readable when stored, human-writable!
*No coordination required between different systems, just agreement on object structure.
*No set-up needed in many languages, eg PHP: $data = json_encode($object); $object = json_decode($data);
*No inherent schema, so readers need to validate decoded messages manually.
*Takes more space than Protocol Buffers.
Protocol Buffers:
*
*Generating tools provided for several languages.
*Minimal size - difficult to beat.
*Defined schema (externally) through .proto files.
*Auto-generated interface objects for encoding/decoding, eg C++: person.SerializeToOstream(&output);
*Support for differing versions of object schemas to add new optional members, so that existing objects aren't necessarily invalidated.
*Not human-readable or writable, so possibly harder to debug.
*Defined schema introduces some configuration management overhead.
Unicode
When it comes to Unicode support, both handle it without issues:
*
*JSON: Will typically escape non-ascii characters inside the string as \uXXXX, so no compatibility problem there. Depending on the library, it may be also possible to force UTF-8 encoding.
*Protocol Buffers: Seem to use UTF-8, though I haven't found info in Google's documentation in 3-foot-high letters to that effect.
Summary
Which one you go with will depend on how exactly your system will behave, how often changes to the data structure occur, and how all the above points will affect you.
A: Not going to lie you could do it in redis. Redis is a key-value database written to be high performance it allows the transfer of data between languages using a number of different client libraries these are the client libraries Here is an example in java and python
Edit 1: Code is untested. If you spot an error please let me know :)
Edit 2: I know I didn't use the prefered redis client for java but the point still stands.
Python
import redis
r = redis.Redis()
r.set('test','123')
Java
import org.jredis.RedisException;
import org.jredis.ri.alphazero.JRedisClient;
import static org.jredis.ri.alphazero.support.DefaultCodec.*;
class ExampleCode{
private final JRedisClient client = new JRedisClient();
public static void main(String[] args) throws RedisException {
System.out.println(toStr(client.get('test')))
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: StructureMap Error: No Default Instance defined for PluginFamily very new to Structure-Map. trying to figure it out how it works and how can i benefit from it.
i have got this so far..
Global.asax.cs:
IContainer container = new Container(x =>
{
x.For<IControllerActivator>().Use
<StructureMapControllerActivator>();
x.For<IUserRepo>().Use<UserRepo>();
});
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
StructureMapControllerActivator:
public class StructureMapControllerActivator : IControllerActivator
{
private readonly IContainer _container;
public StructureMapControllerActivator(IContainer container )
{
this._container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
return _container.GetInstance(controllerType) as IController;
}
}
StructreMapDependencyResolver:
private readonly IContainer _container;
public StructureMapDependencyResolver(IContainer container )
{
this._container = container;
}
public object GetService(Type serviceType)
{
object instance = _container.TryGetInstance(serviceType);
if(instance == null && !serviceType.IsAbstract)
{
_container.Configure(c => c.AddType(serviceType,serviceType));
instance = _container.TryGetInstance(serviceType);
}
return instance;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
}
My AccountController:
public class AccountController : Controller
{
private readonly IUserRepo _userRepo;
private AccountController()
{
_userRepo = ObjectFactory.GetInstance<IUserRepo>();
}
public ActionResult Login()
{
return View();
}
}
Error Code & Description:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily MBP_Blog.Controllers.AccountController
MBP-Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
I have a Interface Name : IUserRepo and a repository Name: UserRepo
please help as I try to google but dint find any solution within first 3 pages.
New error after using @Martin's code:
StructureMap Exception Code: 180
StructureMap cannot construct objects of Class MBP_Blog.Controllers.AccountController, MBP-Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null because there is no public constructor found.
A: Take out the StructureMapControllerActivator, I don't think you need it. If you keep it, you need to add a mapping for your AccountController.
Also, use Controller Injection instead, it will make unit testing easier:
public class AccountController : Controller
{
private readonly IUserRepo _userRepo;
public AccountController(IUserRepo userRepo)
{
_userRepo = userRepo;
}
public ActionResult Login()
{
return View();
}
}
Also again, for your Container, you can default the mappings. This will automatically map IService to Service :
IContainer container = new Container(
x =>
{
x.Scan(scan =>
{
scan.Assembly("MBP_Blog");
scan.Assembly("MBP_Blog.Data");
scan.WithDefaultConventions();
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adding external JS and CSS file dramatically slows the loading of the site a few line like these:
<link rel="stylesheet" href="style_base.css" type="text/css" />
<script type="text/javascript" src="fallings.js"></script>
dramatically slows my site loading down. This checks the files too?
A: Those references could be indeed slowing load times of the page if they are, for instance, referencing other external resources. Use a profiler to detect what is slowing down load times.
There's a nice addon for Firefox called YSlow that might help you in this matter.
Here you can find different tools that may also help you determining what is slowing down your page: 7 Tools To Optimize The Speed of Your Website
If you're having performace issues on account of referencing external resources, put them in your web app if possible. And minify your javascript/css resources (at least in production) if they are large. Here's a minification-related SO question that can help you Ways to compress/minify javascript files
A: If you put your external js at the bottom of the page (just before you close the body tag) it can help the perceived speed of the page load. Your html, css, and images will load before the javascript executes, so if it's your js taking the extra time the page will have at least rendered.
Depending on the size of your external files and how well your js is written we could probably help you more, but we'd need to see your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: can we see html localstorage content through client browser? supppose I use html5 local storage for my website.
1)can End user see my local storage values through browser using view source code etc?
2)How can we enter data for HTML5 local storage as domain level, i dont want to add my records manually when page loads everytime?
3where will HTML5 local storage content be saved?
I)in client side?
II)in server side(webserver)
anyhelp please?
A: *
*Not through view source, but many Developer Tools support this. So yes, a user could very easy figure out what the contents of their browser's localStorage is. For example, in Chrome, open the Developer Tools, and on the Resources tab select "Local Storage"
*I think what you are asking for is "How to I add local storage without writing the code in every page". You would typically then put that code in a common .js file - and reference it whenever you needed it. If you need it in every page, then depending on which platform you are using, they probably have some sort of "master". ASP.NET WebForms has Master Pages, ASP.NET MVC has ViewStart, etc.
*Client side. It's local storage - as in it is local to the browser.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Execute Lync 2010 extension code before user accepts call I'd like to execute some custom code every time Lync 2010 receives a call. I tried it with a Conversation Window Extension (CWE), which contains a Silverlight client, and the Silverlight client uses the Lync API, like this:
var lync = LyncClient.GetClient();
lync.ConversionManager.ConversionAdded += ...
The problem is, this code gets executed only when the user accepts an incoming call. How can I execute code like this exactly in the moment when the call comes in? Not after the user accepts the call, but while "the phone rings"?
Thank you
A: That's right, the extension will only be displayed when you have a conversation window to show it in - which means accepting the conversation first.
If you want to trap incoming calls you can do this with the Lync SDK - theres more info on exactly how to do this in the accepted answer to this question here
If you're trying to build a screen-pop type application, see this post
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Obtaining MAC address on windows in Qt I am attempting to obtain mac address on windows xp using this code:
QString getMacAddress()
{
QString macaddress="??:??:??:??:??:??";
#ifdef Q_WS_WIN
PIP_ADAPTER_INFO pinfo=NULL;
unsigned long len=0;
unsigned long nError;
if (pinfo!=NULL)
delete (pinfo);
nError = GetAdaptersInfo(pinfo,&len); //Have to do it 2 times?
if(nError != 0)
{
pinfo= (PIP_ADAPTER_INFO)malloc(len);
nError = GetAdaptersInfo(pinfo,&len);
}
if(nError == 0)
macaddress.sprintf("%02X:%02X:%02X:%02X:%02X:%02X",pinfo->Address[0],pinfo->Address[1],pinfo->Address[2],pinfo->Address[3],pinfo->Address[4],pinfo->Address[5]);
#endif
return macaddress;
}
The code was suggested here: http://www.qtforum.org/post/42589/how-to-obtain-mac-address.html#post42589
What libraries should i include to make it work?.
A: With Qt and the QtNetwork module, you can get one of the MAC addresses like that:
QString getMacAddress()
{
foreach(QNetworkInterface netInterface, QNetworkInterface::allInterfaces())
{
// Return only the first non-loopback MAC Address
if (!(netInterface.flags() & QNetworkInterface::IsLoopBack))
return netInterface.hardwareAddress();
}
return QString();
}
A: I was looking for the same and had some problems with virtual machines and different types of bearers, here's another approach that I found:
QNetworkConfiguration nc;
QNetworkConfigurationManager ncm;
QList<QNetworkConfiguration> configsForEth,configsForWLAN,allConfigs;
// getting all the configs we can
foreach (nc,ncm.allConfigurations(QNetworkConfiguration::Active))
{
if(nc.type() == QNetworkConfiguration::InternetAccessPoint)
{
// selecting the bearer type here
if(nc.bearerType() == QNetworkConfiguration::BearerWLAN)
{
configsForWLAN.append(nc);
}
if(nc.bearerType() == QNetworkConfiguration::BearerEthernet)
{
configsForEth.append(nc);
}
}
}
// further in the code WLAN's and Eth's were treated differently
allConfigs.append(configsForWLAN);
allConfigs.append(configsForEth);
QString MAC;
foreach(nc,allConfigs)
{
QNetworkSession networkSession(nc);
QNetworkInterface netInterface = networkSession.interface();
// these last two conditions are for omiting the virtual machines' MAC
// works pretty good since no one changes their adapter name
if(!(netInterface.flags() & QNetworkInterface::IsLoopBack)
&& !netInterface.humanReadableName().toLower().contains("vmware")
&& !netInterface.humanReadableName().toLower().contains("virtual"))
{
MAC = QString(netInterface.hardwareAddress());
break;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Lisp: Evaluation of quotes Which of the following expressions has correct lisp syntax?
(+ 1 (quote 1))
==> 1 (???)
(+ 1 (eval (quote 1))
==> 2
I'm currently writing my own lisp interpreter and not quite sure how to handle the quotes correct. Most lisp interpreters I've had a look at evaluate both expressions to "2". But shouldn't the quote be not evaluated at all and thereby only the second one be a legal expression? Why does it work then anyway? Is this some kind of syntactical sugar?
A: Barring special forms, most Lisps evaluate the arguments first, then apply the function (hence the eval-and-apply phrase).
Your first form (+ 1 '1) would first evaluate its arguments 1 and '1. Constant numerics evaluate to themselves, and the quote evaluates to what it quotes, so you'd be left applying + to 1 and 1, yielding 2.
eval: (+ 1 (quote 1))
eval 1st arg: 1 ==> 1
eval 2nd arg: '1 ==> 1
apply: (+ 1 1) ==> 2
The second form is similar, the unquoted 1 will just go through eval once, yielding 1 again:
eval: (+ 1 (eval '1))
eval 1st arg: 1 ==> 1
eval 2nd arg: (eval '1)
eval arg: '1 ==> 1
apply: (eval 1) ==> 1
apply: (+ 1 1) ==> 2
A: Numbers evaluate to themselves so (quote 1) is the same as 1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: external sorting: multiway merge In multiway merge The task is to find the smallest element out of k elements
Solution: priority queues
Idea: Take the smallest elements from the first k runs, store them into main memory in a heap tree.
Then repeatedly output the smallest element from the heap. The smallest element is replaced with the next element from the run from which it came.
When finished with the first set of runs, do the same with the next set of runs.
Assume my main memory of size ( M )less than k, how we can sort the elements, in other words,how multi way merge algorithm merge works if memory size M is less than K
For example if my M = 3 and i have following
Tape1: 8 9 10
Tape2: 11 12 13
Tape3: 14 15 16
Tape4: 4 5 6
My question how muliway merge will work because we will read 8, 11, 14 and build priority queue, we place 8 to output tape and then forward Tape1, i am not getting when Tape4 is read and how we will compare with already written to output tape?
Thanks!
A: It won't work. You must choose a k small enough for available memory.
In this case, you could do a 3-way merge of the first 3 tapes, then a 2-way merge between the result of that and the one remaining tape. Or you could do 3 2-way merges (two pairs of tapes, then combine the results), which is simpler to implement but does more tape access.
In theory you could abandon the priority queue. Then you wouldn't need to store k elements in memory, but you would frequently need to look at the next element on all k tapes in order to find the smallest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: weird grey square in extjs layout (ie7 & 8 only) I have weird grey square in extjs layout (ie7 & 8 only).
I applyed css code to all doc in hope to see borders of gray element but...
There are NO BORDER ON IT. please tell me what to do or check next.
*{
border:1px red solid !important;
}
ie7 & ie 8
normal browser
A: Looks like IE isn't rendering things correctly. Something was at that position and when the form was rendered, IE didn't keep up with the redraw.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AlternateView and čćžšđ when sending mail by C# MailMessage message = new MailMessage(email.From,
email.To,
email.Subject,
email.Body);
message.BodyEncoding = Encoding.GetEncoding("utf-8");
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">";
body += "</HEAD><BODY><DIV>";
body += email.Body.Replace("\r\n", "<br />");
body += "</DIV></BODY></HTML>";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(Regex.Replace(email.Body, @"<(.|\n)*?", string.Empty), null, "text/plain");
message.AlternateViews.Add(plainView);
ContentType mimeType = new ContentType("text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(email.Body, mimeType);
message.AlternateViews.Add(htmlView);
where email.Body and email.Subject is for example "čžćšđščžčžčšđš"
and when i get mail, Subject is ok but body is corrupted like Äžšđ
Problem is in AlternateView.
here:
ContentType mimeType = new ContentType("text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(email.Body, mimeType);
message.AlternateViews.Add(htmlView);
what to do?
A: According to the following question
*
*How do I set Encoding on AlternateView
the answer is to set the content type of the alternate view appropriately. You are passing null as the encoding, consider passing UTF-8 instead:
AlternateView plainView = AlternateView.CreateAlternateViewFromString(
Regex.Replace(email.Body, @"<(.|\n)*?", string.Empty),
Encoding.UTF8, "text/plain");
A: You're using null for AlternateView encoding in constructor, replace it with Encoding.GetEncoding("utf-8")
Update:
You've updated your question before it was using null in constructor, anyway there is constructor with encoding parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Phone 7.1: AutoResetEvent does not work with Service Methods? After adding Service Reference to my Phone Application (for example http://www.deeptraining.com/webservices/weather.asmx?op=GetWeather), I tried to use AutoResetEvent for emulation syncronous method calling. But after calling WaitOne, method Set is never called. Why? Is it a bug?
public partial class MainPage : PhoneApplicationPage
{
private readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
private string _result;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var weatherSoapClient = new WeatherSoapClient();
weatherSoapClient.GetWeatherCompleted += weatherSoapClient_GetWeatherCompleted;
weatherSoapClient.GetWeatherAsync("Pekin");
_autoResetEvent.WaitOne(); // Program stop hire
textBlock1.Text = _result;
}
void weatherSoapClient_GetWeatherCompleted(object sender, GetWeatherCompletedEventArgs e)
{
_result = e.Result;
_autoResetEvent.Set(); // Never invoke! Why???
}
}
A: In WP7, HTTP responses are processed on the UI thread. Bocking the UI thread prevents the response from being processed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cURL and an extern Tor relay I'm creating a tool and I wish to use the Tor network.
I am familiar with with both PHP and it's cURL extension but I just cant seem to use Tor as proxy. I keep getting no response from the server.
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->ch, CURLOPT_PROXY, $proxy_ip);
curl_setopt($this->ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
curl_setopt($this->ch, CURLOPT_NOSIGNAL, true);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_TIMEOUT, 1);
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->useragents[array_rand($this->useragents, 1)]);
$result = curl_exec($this->ch);
$httpcode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
if($httpcode >= 200 && $httpcode < 300) {
return $result;
}
return $httpcode; // Always returns 0
I'm rather clueless what the problem could be. Are my cURL settings incorrect?
Every extern relay doesn't work for me, but my local relay does work.
OS: OSX, but tested on Windows as well
PHP: 5.3.5
cURL: 7.21.3
A: Tor is usually really slow and needs much more than one sec to get the response, so first try changing CURLOPT_TIMEOUT to something like 30 or so and see if it helps, if not we'll dig further :)
P.S. Also set CURLOPT_CONNECTTIMEOUT to 0 (indefinitely)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Oracle Single-row subquery returns more than one row error I have a scenario. Can this be done using one query ?
*
*Table Company : Single Company information with CPK as primary key and one Manager,Lead,HR attached to it
*Table Employees : For every Company there are Employees (1 or more can be up to 500) with unique empID and Manager,Lead,HR attached to it
*Table Employees Information (for using Web application) : he is assigned with 1 or more Manager,Lead,HR (or can be ALL,ALL,ALL which means he can see everything)
So:
Company
--------
CPK (PK)
Manager
Lead
HR
Employees
--------
empID (PK)
CPK (FK)
Manager
Lead
HR
EmployeesInfo
-------------
USER_ID (FK)
Manager
Lead
HR
Web --> When a user login he should get all company information.If he has access to that company or any employee within that company then that row is enabled else its greyed out(disable) if its "All" then he can edit every record
For Example:
User1 is assigned to Manager1, Lead1 and HR1.
Then he can edit all records from Company where Manager = Manager1, Lead = Lead1 and HR = HR1.
Also records in Company which has employees with Company.CPK = Employee.CPK and Employee.Manager = Manager1 and Employee.Lead = Lead1 and Employee.HR = HR1
My query till now But
select t2.MANAGER from Employees t2 where t2.CPK = t1.CPK
returns Multiple record which is expected what should i do ???
SELECT t1.*,
--All condition
CASE WHEN (SELECT MANAGER FROM EmployeesInfo WHERE USER_ID=44) = 'All' then 1
ELSE(
--Check for Company
CASE
WHEN t1.MANAGER in (SELECT MANAGER FROM EmployeesInfo WHERE USER_ID=44) then 1
WHEN t1.LEAD in (SELECT LEAD FROM EmployeesInfo WHERE USER_ID=44) then 1
WHEN t1.HR in (SELECT HR FROM EmployeesInfo WHERE USER_ID=44) then 1
ELSE(
--Check Employee M,L,HR for that Company
CASE
WHEN (SELECT t2.MANAGER FROM Employees t2 WHERE t2.CPK = t1.CPK) in
(SELECT MANAGER FROM EmployeesInfo WHERE USER_ID=44) then 1
WHEN (SELECT t2.LEAD FROM Employees t2 WHERE t2.CPK = t1.CPK ) in
(SELECT LEAD FROM EmployeesInfo WHERE USER_ID=44) then 1
WHEN (SELECT t2.HR FROM Employees t2 WHERE t2.CPK = t1.CPK ) in
(SELECT HR FROM EmployeesInfo WHERE USER_ID=44) then 1
ELSE 0 END
)
END
)
END AS Grey_Out
FROM Company t1
WHERE t1.CPK ='1234'
Finally I should get all Company with grey_out field as (1 or 0) , then I will use the Grey_Out field for finding whether it should be made editable.
A: I got a headache just to understand your table design.
Have you heard about joins?
SELECT DISTINCT c.*,
CASE WHEN e.empid IS NOT NULL OR ei.USER_ID IS NOT NULL
THEN 1
ELSE 0
END AS Grey_Out
FROM Company c
LEFT OUTER JOIN EmployeesInfo ei
ON c.MANAGER = ei.MANAGER
OR c.LEAD = ei.LEAD
OR c.HR = ei.HR
LEFT OUTER JOIN Employees e
ON e.CPK = c.CPK
AND (
e.MANAGER = ei.MANAGER
OR e.LEAD = ei.LEAD
OR e.HR = ei.HR
)
WHERE c.CPK = '1234'
AND ei.USER_ID = 44
A: Change
case
when (select t2.MANAGER from Table2 t2 where t2.CPK = t1.CPK) in
(Select MANAGER from Table3 where USER_ID=44) then 1
to
case
when exists
(select *
from
Table3 t3
inner join table2 t2 on t2.manager = t3.manager
where
t3.USER_ID=44 and t2.CPK = t1.CPK) then 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unxpected result when iterating nested arrays for merging content in PHP I have 2 nested arrays over which I intent to iterate over one and insert into it a portion of a match in the other based on a key->value.
The idea is to iterate for each element of arrayA and nested iterate for each key->value of arrayB. When arrayA element equals to arrayB key->value i want to insert into arrayB a key->value of arrayA.
The problem I am having is that for some reason in the loop of arrayB it should iterate 78 times but is doing it only 2.
I know there is something messed up with the iterations but can't pin point.
Here is a sample of arrayA, arrayB and my code.
arrayA
arrayB
Here is my code
foreach($premiumContent as $prem_key => $targets)
{
$totCat = 0;
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$totCat = $totCat + 1;
$totFeatures = 0;
foreach($category as $features) //features = 1 designers, restaurants
{
$totFeatures = $totFeatures + 1;
//*********HERE IS THE PROBLEM IS NOT ITERATING BY THE LIST OF ALL FEATURES
$totFeature = 0;
foreach ($features as $feature) //stores
{
$totFeature = $totFeature + 1;
$properties = $feature[0]->properties;
if ($feature[0]->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}
return $result;
Could someone explain me what am I doing wrong? I am sure there is a better approach to this.
Here is the fix.
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$name = $category->dispName;
//echo $name;
foreach($category->list as $features) //features = 1 designers, restaurants
{
foreach ($features as $featureKey => $featureVal) //stores
{
$properties = $featureVal->properties;
if ($featureVal->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Animation Listener OnTouch of an ImageView I'm starting a fade in animation:
myImageView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
v.startAnimation(fadeInAnimation);
I know it's need an animation listener to find out when the animation is complete but how do I attach this so that I can get the view that the animation has just completed on... I want to set the visibility of the view after the animation is done.
Thanks
A: In case someone needs the solution in kotlin:
fadeInAnimation.setAnimationListener(object: Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onAnimationEnd(animation: Animation?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onAnimationStart(animation: Animation?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
A: Using Kotlin
//OR using Code
val rotateAnimation = RotateAnimation(
0f, 359f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
)
rotateAnimation.duration = 300
rotateAnimation.repeatCount = 2
//Either way you can add Listener like this
rotateAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
val rand = Random()
val ballHit = rand.nextInt(50) + 1
Toast.makeText(context, "ballHit : " + ballHit, Toast.LENGTH_SHORT).show()
}
})
ivBall.startAnimation(rotateAnimation)
A: My function setAnimation
private Animation animateRoationLayout(Animation.AnimationListener animationListener) {
Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.level_expand_rotation);
anim.setInterpolator(new LinearInterpolator()); // for smooth animation
anim.setAnimationListener(animationListener);
return anim;
}
Define Animation Listener :
final Animation.AnimationListener animationListener =new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Toast.makeText(getActivity(),"Animation Have Done", Toast.LENGTH_LONG).show();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
Set Animation For View :
view.startAnimation(animateRoationLayout(animationListener));
A: If you only need an end-action it would suffice to use .withEndAction(Runnable)
fadeInAnimation.withEndAction(new Runnable() {
@Override
public void run() {
... do stuff
}
})
A: I think you need this.
fadeInAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
A: If you are using kotlin and androidx. There are some event methods
Animator.doOnEnd
Animator.doOnStart
Animator.doOnCancel
Animator.doOnRepeat
Animator.doOnPause
Animator.doOnResume
Example
val animator = ObjectAnimator.ofFloat(progressBar, View.ALPHA, 1f, 0.5f)
animator.doOnEnd {
//
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: Skeptical behavior of MoveWindow function MoveWindow(int x, int y, int nWidth, int nHeight,false) even used SetWindowPos(&wndTopMost, m_iLeft, m_iTop, m_iWidth, m_iHeight, false);
as i do not want to repaint my window, i am passing repaint parameter of MoveWindow with false. but it repaints the window.
This behavior works fine if i use LeadTool v 16, but in v16.5 MoveWindow function loose its functionality. do not know how it relates to LeadTool.
Looking forward for any help regarding of this issue
A: It's not (only) your call when a window should be repainted. When you get an WM_PAINT, windows tells you that a window must be painted. "I don't want to" is not enough reason.
A: Are you changing the width or height of the window? If so, and if the target window has the CS_HREDRAW or CS_VREDRAW class style bits set, then resizing will cause a full repaint. (A simple move likely won't cause a repaint unless moving it uncovers part of the window that was previously hidden by some other window.)
BTW, last parameter to SetWindowPos is a set of bits, not a true/false, and the first parameter looks odd, it should be a plain HWND, not the address of a variable. See MSDN on SetWindowPos for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: jQuery - function with custom callback I'm trying to execute a specific function once some processes finished executing.
My specific example refers to a number of animate() methods after which I want to call another function, however this function should only be called once the animate() methods finished processing:
var testObject = {
methodOne : function(callbackMethod) {
$('#item').animate({ 'paddingLeft' : '20px'}, { duration: 200, queue: false });
$('#item2').animate({ 'paddingLeft' : '30px'}, { duration: 200, queue: false });
$('#item3').animate({ 'paddingLeft' : '40px'}, { duration: 200, queue: false });
testObject.callbackMethod();
},
run : function() {
alert('done');
}
};
$(function() {
testObject.methodOne(run);
});
Any idea how can I achieve this?
A: Provided you are using jQuery >= 1.5, then you should use the Deferred-functionality:
var testObject = {
methodOne : function($elements, callbackMethod) {
$elements.each(function (i) {
$(this).animate({ 'paddingLeft' : (10 + (10*i)) + 'px'}, { duration: 200 * i, queue: false });
});
$elements.promise().done(callbackMethod);
},
run : function() {
$('.wrapper').append('<span>Finished!</span>');
}
};
$(function() {
testObject.methodOne($('#item, #item2, #item3'), testObject.run);
});
jsFiddle for this example: http://jsfiddle.net/3Z4zu/
A cleaner/refactored version could look like this:
var testObject = {
methodOne : function($elements, callbackMethod) {
$elements.each(function (i) {
$(this).animate({ 'paddingLeft' : (10 + (10*i)) + 'px'}, { duration: 200 * i, queue: false });
});
$elements.promise().done(callbackMethod);
},
run : function() {
$('.wrapper').append('<span>Finished!</span>');
}
};
$(function() {
testObject.methodOne($('#item, #item2, #item3'), testObject.run);
});
http://jsfiddle.net/3Z4zu/1/
A: You can define a custom event to be fired when an animation stops, for example:
$("body").bind("animationsComplete", function() {
testObject.completed++;
if (testObject.completed == testObject.needToComplete) {
testObject.run();
}
});
In each of your functions you should trigger that event:
var testObject = {
needToComplete : 3,
completed : 0,
methodOne : function(callbackMethod) {
$('#item').animate({ 'paddingLeft' : '20px'}, { duration: 200, queue: false ,complete : function(){
trigger("animationsComplete");
}});
$('#item2').animate({ 'paddingLeft' : '30px'}, { duration: 200, queue: false ,complete : function(){
trigger("animationsComplete");
}});
$('#item3').animate({ 'paddingLeft' : '40px'}, { duration: 200, queue: false ,complete : function(){
trigger("animationsComplete");
}});
},
run : function() {
alert('done');
}
};
EDIT: I understand that I lost some functionality of your original code (defining which function to be called as callback) but I think you'll know basically what I had in mind.
A: You can count the animate function calls and decrement that number in each animation callback. In the callbacks, if all the other animations have finished you call the "master" callback :
var testObject = {
methodOne : function(callbackMethod) {
var animationsCount = 3;
$('#item').animate({ 'paddingLeft' : '20px'}, { duration: 200, queue: false ,complete : function(){
if(--animationsCount == 0)
testObject[callbackMethod]();
}});
$('#item2').animate({ 'paddingLeft' : '30px'}, { duration: 200, queue: false ,complete : function(){
if(--animationsCount == 0)
testObject[callbackMethod]();
}});
$('#item3').animate({ 'paddingLeft' : '40px'}, { duration: 200, queue: false ,complete : function(){
if(--animationsCount == 0)
testObject[callbackMethod]();
}});
},
run : function() {
alert('done');
}
};
$(function() {
testObject.methodOne('run');
});
A: You could have all of the success callbacks from each animate function increase a counter and call the same function (your callbackMethod).
In callbackMethod, you check to see if the counter has hit 3 and then only perform your desired code if it has.
Or work the opposite way from 3 down to 0, or 3 separate booleans, you've got many options to you at that point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Return a dynamic resource from a converter I want to change the color of a WPF control depending on the state of a bool, in this case the state of a checkbox.
This works fine as long as I'm working with StaticResources:
My control
<TextBox Name="WarnStatusBox" TextWrapping="Wrap" Style="{DynamicResource StatusTextBox}" Width="72" Height="50" Background="{Binding ElementName=WarnStatusSource, Path=IsChecked, Converter={StaticResource BoolToWarningConverter}, ConverterParameter={RelativeSource self}}">Status</TextBox>
My converter:
[ValueConversion(typeof(bool), typeof(Brush))]
public class BoolToWarningConverter : IValueConverter
{
public FrameworkElement FrameElem = new FrameworkElement();
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
bool state = (bool)value;
try
{
if (state == true)
return (FrameElem.TryFindResource("WarningColor") as Brush);
else
return (Brushes.Transparent);
}
catch (ResourceReferenceKeyNotFoundException)
{
return new SolidColorBrush(Colors.LightGray);
}
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
}
The problem is that I have several definitions of the Resource "WarningColor" dependant on setting day mode or night mode. These events does not trig the WarningColor to change.
Is there a way to make the return value dynamic or do I need to rethink my design?
A: You cannot return something dynamic from a converter, but if your only condition is a bool you can easily replace the whole converter with a Style using Triggers:
e.g.
<Style TargetType="TextBox">
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=WarnStatusSource}" Value="True">
<Setter Property="Background" Value="{DynamicResource WarningColor}" />
</DataTrigger>
</Style.Triggers>
</Style>
If now the resource with that key is changed the background should change as well.
A: The way to return a dynamic resource reference is pretty simple using a DynamicResourceExtension constructor and supplying it a resource key.
Usage:
return new DynamicResourceExtension(Provider.ForegroundBrush);
Definition of the Provider class should contains the key:
public static ResourceKey ForegroundBrush
{
get
{
return new ComponentResourceKey(typeof(Provider), "ForegroundBrush");
}
}
And the value for the key would be declared in the resource dictionary:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:theme="clr-namespace:Settings.Appearance;assembly=AppearanceSettingsProvider">
<Color x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type theme:Provider}, ResourceId=ForegroundColor}">#FF0000FF</Color>
<SolidColorBrush x:Key="{ComponentResourceKey {x:Type theme:Provider}, ForegroundBrush}" Color="{DynamicResource {ComponentResourceKey {x:Type theme:Provider}, ForegroundColor}}" />
</ResourceDictionary>
This way, the converter would dynamically assign a DynamicResource to the bound property depending on the resource key supplied.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Possible memory leak with malloc, struct, std::string, and free I've a situation like the following, and I'm not sure whether or not the std::string elements of the struct leak memory or if this is ok. Is the memory allocated by those two std::strings deleted when free(v) is called?
struct MyData
{
std::string s1;
std::string s2;
};
void* v = malloc(sizeof(MyData));
...
MyData* d = static_cast<MyData*>(v);
d->s1 = "asdf";
d->s2 = "1234";
...
free(v);
Leak or not?
I'm using the void-pointer because I have another superior struct, which consists of an enum and a void-pointer. Depending on the value of the enum-variable, the void* will point to different data-structs.
Example:
enum-field has EnumValue01 => void-pointer will point to a malloc'd MyData01 struct
enum-field has EnumValue02 => void-pointer will point to a malloc'd MyData02 struct
Suggestions for different approaches are very appreciated, of course.
A: That's undefined behavior - memory allocated by malloc() in uninitialized, so using it as a struct containing string objects can lead to anything; I'd expect crashing. Since no-one invokes the destructor before calling free(), string objects won't be destroyed and their buffers will almost definitely leak.
A: You shouldn't be using malloc() and free() in a C++ program; they're not constructor/destructor-aware.
Use the new and delete operators.
A: Yes, because the constructor and destructor are not called. Use new and delete.
A: There is a leak indeed. free doesn't call MyData destructor (after all it's a C function which doesn't know anything about C++ stuff). Either you should use new/delete instead of malloc/free:
MyData* d = new MyData;
d->s1 = "asdf";
d->s2 = "1234";
delete d;
or call destructor by yourself:
void* v = malloc(sizeof(MyData));
MyData* d = new (v) MyData; // use placement new instead of static_cast
d->s1 = "asdf";
d->s2 = "1234";
...
d->~MyData();
free(v);
as sharptooth noted you can't directly use memory allocated by malloc as a MyData struct without initialization, so you have to do it by yourself as well. To initialize MyData using already allocated memory you need to use placement new (see in the code above).
A: Even if you manage to initialize s1 and s2 properly, simply doing free(d) won't reclaim any memory dynamically allocated for s1 and s2. You should really create *d through new and destroy through delete, which will ensure proper destruction of s1 and s2 (and initialization as well).
A: Yes, you are probably leaking, and your strings aren't properly constructed, either. The program's behaviour is undefined, meaning everything is going to go wrong.
The closest valid way to do what you're doing is placement new. Still, you'd be better off with some common base class and proper C++ polymorphism.
If the possible types are unrelated, you can use Boost.Any or Boost.Variant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I resize the windows work area, and then update the other windows to reflect the change please? I have a toolbar application which changes the work area of the desktop and positions itself in the gap (either at the top or bottom of the screen). I need a function which will resize the other windows so that they are not left behind the toolbar after the resizing (the toolbar is always on top). I'm using the function below to change the work area:
private bool SetWorkspace(RECT rect)
{
bool result = SystemParametersInfo(SPI_SETWORKAREA,
0,
ref rect,
SPIF_change);
if (!result)
{
MessageBox.Show("The last error was: " +
Marshal.GetLastWin32Error().ToString());
}
this.minAll();
return result;
}
and the minAll() function is how I'm resizing the other windows:
public void minAll(){
IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero);
System.Threading.Thread.Sleep(10);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL_UNDO, IntPtr.Zero);
System.Threading.Thread.Sleep(10);
}
This method works, in that the workarea does get resized and no window keeps its old position outside it, but there are a few problems:
*
*Normal (ie. not maximised or minimized) windows are sometimes made so
small that they aren't displayed, and have to be maximised from the
taskbar (Vista) to be visible
*Sometimes the method makes other
windows 'always on top' when they shouldn't be
*It changes the z-order of the windows, seemingly at random
The first two of these problems are fixed if you close and reopen the affected windows, but it's hardly an ideal solution and I can't even manually correct the z-order (I tried saving the z-order before the method and then restoring it afterwards, but no luck).
So, can anyone see what's wrong with how I'm doing this, or does anyone know how it's supposed to be done please?
A: The correct way to do this is to create an AppBar. See SHAppBarMessage. There is a C++ sample in the Knowledge Base. There is a C# sample on CodeProject.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery execute script only for url and not this url but url has the same work in both url I would like to execute some script only for http://win-23ookphjfn0/Previsions/Pages/default.aspx and not for http://win-23ookphjfn0/abc/Pages/Les_Previsions.aspx
that script doesn't seem to function.
var url = location.pathname;
if (url.indexOf('Previsions') >= 0) {
//script here
}
how should i go?
A: var url = location.pathname;
if (url.indexOf('Previsions') >= 0) {
window.location = url;
}
u can relocate the url by this,
A: Give this a try:
var url = window.pathname;
if (url.indexOf('Previsions') >= 0) {
//script here
}
window.pathname should give you the url in the browser window, rather than the file where the script is housed.
Here is an alternative to window.pathname as well:
document.location.href
A: If your url is corrrect and '/Previsions/' should me there in the url so try this-
var url = location.pathname;
if (url.indexOf('/Previsions/') >= 0) {
alert();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bug with Ruby on Rails 3 tutorial, chapter 13 I updated to rails 3.1 the "sample application" from the Rails 3 Tutorial. Everything went smoothly except that when I'm using the site and a logged in user tries to follow/unfollow another user, I get the following message from the log:
Started POST "/relationships" for 127.0.0.1 at 2011-09-29 20:06:30 -0400
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Yn4XSU4RSEjGqpv1H/ZAxTAi/5JREDaBaa5UbPArRAo=", "relationship"=>{"followed_id"=>"7"}, "commit"=>"Follow"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "7"]]
SQL (3.5ms) INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Fri, 30 Sep 2011 00:06:30 UTC +00:00], ["followed_id", 7], ["follower_id", 101], ["updated_at", Fri, 30 Sep 2011 00:06:30 UTC +00:00]]
Relationship Load (0.2ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = 101 AND "relationships"."followed_id" = 7 LIMIT 1
Rendered users/_unfollow.html.erb (3.5ms)
(0.2ms) SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = 7
Rendered relationships/create.js.erb (6.7ms)
Completed 200 OK in 51ms (Views: 12.1ms | ActiveRecord: 4.7ms)
Started POST "/relationships" for 127.0.0.1 at 2011-09-29 20:06:31 -0400
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Yn4XSU4RSEjGqpv1H/ZAxTAi/5JREDaBaa5UbPArRAo=", "relationship"=>{"followed_id"=>"7"}, "commit"=>"Follow"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "7"]]
SQL (0.6ms) INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Fri, 30 Sep 2011 00:06:31 UTC +00:00], ["followed_id", 7], ["follower_id", 101], ["updated_at", Fri, 30 Sep 2011 00:06:31 UTC +00:00]]
SQLite3::ConstraintException: constraint failed: INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "updated_at") VALUES (?, ?, ?, ?)
Completed 500 Internal Server Error in 35ms
SQLite3::ConstraintException (columns follower_id, followed_id are not unique):
The operation should work since it's the first time that I'm creating that association. After that error, I need to do a restart of the server in order to get back to my user, otherwise, the server keeps on throwing. Here's a sample:
Rendered /Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.9ms)
Rendered /Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (3.7ms)
[2011-09-29 20:08:12] ERROR SQLite3::Exception: cannot use a closed statement
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb:110:in `close'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb:110:in `block in clear_cache!'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb:110:in `each'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb:110:in `clear_cache!'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb:104:in `disconnect!'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:214:in `block in clear_reloadable_connections!'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:213:in `each'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:213:in `clear_reloadable_connections!'
/Users/huguesjoly/.rvm/gems/ruby-1.9.2-p180 rails3tutorial/gems/activesupport-3.1.0/lib/active_support/core_ext/module/synchronization.rb:35:in `block in clear_reloadable_connections_with_synchronization!'
...
So, back to my user after a restart, I can see that the record has been created anyway. But if I try to delete that relation, I get the following error from that log file:
Started DELETE "/relationships/95" for 127.0.0.1 at 2011-09-29 20:11:59 -0400
Processing by RelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7YfmrROy4dqviuRakYSyWz2xZLbqIBwfU5McvqBWBrU=", "commit"=>"Unfollow", "id"=>"95"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
Relationship Load (0.1ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."id" = ? LIMIT 1 [["id", "95"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 LIMIT 1
Relationship Load (0.1ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = 101 AND "relationships"."followed_id" = 7 LIMIT 1
SQL (0.3ms) DELETE FROM "relationships" WHERE "relationships"."id" = ? [["id", 95]]
Rendered users/_follow.html.erb (2.0ms)
(0.2ms) SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = 7
Rendered relationships/destroy.js.erb (5.3ms)
Completed 200 OK in 68ms (Views: 32.5ms | ActiveRecord: 1.5ms)
Started DELETE "/relationships/95" for 127.0.0.1 at 2011-09-29 20:11:59 -0400
Processing by RelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7YfmrROy4dqviuRakYSyWz2xZLbqIBwfU5McvqBWBrU=", "commit"=>"Unfollow", "id"=>"95"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
Relationship Load (0.1ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."id" = ? LIMIT 1 [["id", "95"]]
Completed 404 Not Found in 28ms
ActiveRecord::RecordNotFound (Couldn't find Relationship with id=95):
app/controllers/relationships_controller.rb:24:in `destroy'
Again, if I get back to the user's page, I can see that the relation has been removed. It looks as if exceptions are thrown for no reason. And indeed, if I rspec-test the following/follower relations, everything works correctly. Furthermore, the version of the sample_app using rails 3.0 works perfectly.
Could it be possible that one of the gems has a bug in the context of rails 3.1? Here's a listing of my Gemfile in case that it would help:
source 'http://rubygems.org'
gem 'rails', '3.1.0'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'gravatar_image_tag', '1.0.0'
gem 'will_paginate', '3.0.1'
gem 'sqlite3', '1.3.4'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.1"
gem 'uglifier'
end
# Is replacing: gem 'prototype-rails'
gem 'jquery-rails'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'
group :development do
gem 'rspec-rails', '2.6.1'
gem 'annotate', '2.4.0'
gem 'faker', '1.0.0'
end
group :test do
gem 'rspec-rails', '2.6.1'
gem 'webrat', '0.7.3'
gem 'spork', '0.8.5'
gem 'factory_girl_rails', '1.2.0'
# Pretty printed test output
gem 'turn', :require => false
end
Thanks in advance,
A: I had this problem for the Ajax implementation part. The problem was because the tutorial is written for Prototype (pre Rails 3.1), but Rails 3.1 uses JQuery.
This is the JQuery code
create.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>");
$("#followers").html('<%= "#{@user.followers.count} followers" %>');
destroy.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>"");
$("#followers").html('<%= "#{@user.followers.count} followers" %>');
source
A: This is a late answer, I ran into the same problem when going through the tutorial.
Check if your Rsepc tests have AbstractController::DoubleRenderError failures. if so you probably forget to remove the line redirect_to @user in the RelationbshipsController after adding the respond_to block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to understand the workflow between latex, sweave and R Let's say I have written the following tiny .Rnw file:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{Sweave}
\usepackage{tikz}
\usepackage{pgf}
\begin{document}
<<>>=
sessionInfo()
@
\end{document}
I then can go to R and use sweave to translate the .Rnw file into a .tex file
Once this is done the latex interpreter can be called and because I used
\usepackage{Sweave} Latex knows how to handle the sweave specific code tags.
When I first did this procedure I got the common error that the Sweave.sty file could
not be found. I googled and could solve the problem by typing the following command
into the Mac OS Terminal:
mkdir -p ~/Library/texmf/tex/latex
cd ~/Library/texmf/tex/latex
ln -s /Library/Frameworks/R.framework/Resources/share/texmf Sweave
What I don't understand now is how does the latex package \usepackage{Sweave} know that it
has to look at ~/Library/texmf/tex/latex to find the symbolic link to the Sweave.sty file?
What happens if I change the following line:
ln -s /Library/Frameworks/R.framework/Resources/share/texmf Sweave
to
ln -s /Library/Frameworks/R.framework/Resources/share/texmf Sweave_Link
In the .Rnw file do I have to use then \usepackage{Sweave_Link}?
A: That path is set automatically when you install LaTeX; it's your personal texmf tree and you can put any style or class files you want LaTeX to find there. The directory names don't matter, it searches recursively in them for Sweave.sty. So changing the directory link to Sweave_Link shouldn't matter.
You can test this by running kpsewhich Sweave.sty which looks in all the texmf trees for the desired file.
Also, you don't need to have \usepackage{Sweave} in the Rnw file; Sweave will add it automatically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: android map not showing in signed app I have developed an app which uses google map. The problem is when I sign this app and then download it from some link say dropbox or any other, the map does not show up. I have created a new Google map key as well but not working at all. Any idea...???
A: Are you signing the app and getting the Google API key with the same keystore. If it is, then you should use the keystore with which you have signed your app for marketing/publishing...
A: You probably checked most of the things already (as I did).
My problem was solved when I created an Api Key (with debug key+project package name) in one google account to use during development time....
and I created another Signed Api Key (signed keystore+project package name) on another google account.
Apparently you cannot have more than one API key for the same package name (even if the keystore is different!) on the same google account.
I ended up with a development time Api key on one google account and another Publishing Api key on another account. Yet, another chapter closed on the Google Maps Googlemares.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Retain count and factory methods in Objective-C I have been in this forum before to find the best way of creating a factory function to construct a custom view from a nib (here is my previous post)
i am now using the following code:
+ (LoadingV *)loadingViewCopyFromNib
{
LoadingV *view = nil;
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"LoadingV" owner:self options:nil];
view = (LoadingV*)[nibViews objectAtIndex: 0];
// Setting up properties
CGRect frm = view.progress.frame;
frm.size.width *=1.5;
frm.size.height *=1.5;
view.progress.frame = frm;
view.waitLbl.text = NSLocalizedString(@"Please wait", @"");
return view; <------- warning is here
}
// In .h file
...
LoadingView* loadV;
@property (nonatomic, retain) LoadingView* loadV;
// in .m file
@synthesize loadV;
...
self.loadV = [LoadingV loadingViewCopyFromNib];
When i Build and Analyse i get the following warning about the factory function:
/LPAPP/Classes/LoadingV.m:34:5 Object with +0 retain counts returned
to caller where a +1 (owning) retain count is expected
Why is this happening? I understand that local variables allocated within a function do not live beyond its scope unless they are retained and autoreleased. But in my case i am not creating a new object am just returning a reference to an existing one. So why am i getting warning back? Is it safe to proceed like this :)
Cheers
AF
A: Although Mike is right, the warning has a completely different reason.
Your method name includes "copy" which is interpreted to return a +1 retain count (similar to alloc, init). Remember that once you transition to ARC this may cause problems!
A: When it comes to collection classes like NSArray, references returned by objectAtIndex: and other similar accessors are not guaranteed to stay valid when the parent container is deallocated. In other words, objectAtIndex: does not return an autorelease'd object.
This means the pointer you return will probably end up becoming invalid once the array it came from is deallocated.
To fix this, use a retain+autorelease in your return statement:
return [[view retain] autorelease];
UPDATE:
I'm unable to reproduce this warning in my version of Xcode. But perhaps Martin is correct that the 'copy' is being interpreted incorrectly by the version of GCC/clang that you are using. This warning doesn't appear with the latest Xcode and gcc/clang compilers, and the rules are that only a prefix of "copy" or "mutableCopy" is interpreted as returning a +1 retained object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the purpose of the -m switch? Could you explain to me what the difference is between calling
python -m mymod1 mymod2.py args
and
python mymod1.py mymod2.py args
It seems in both cases mymod1.py is called and sys.argv is
['mymod1.py', 'mymod2.py', 'args']
So what is the -m switch for?
A: I just want to mention one potentially confusing case.
Suppose you use pip3 to install a package foo, which contains a bar module. So this means you can execute python3 -m foo.bar from any directory. On the other hand, you have a directory structure like this:
src
|
+-- foo
|
+-- __init__.py
|
+-- bar.py
You are at src/. When you run python -m foo.bar, you are running the bar.py, instead of the installed module. However, if you are calling python -m foo.bar from any other directory, you are using the installed module.
This behavior certainly doesn't happen if you are using python instead of python -m, and can be confusing for beginners. The reason is the order how Python searches for modules.
A: It's worth mentioning this only works if the package has a file __main__.py Otherwise, this package can not be executed directly.
python -m some_package some_arguments
The python interpreter will looking for a __main__.py file in the package path to execute. It's equivalent to:
python path_to_package/__main__.py somearguments
It will execute the content after:
if __name__ == "__main__":
A: Since this question comes up when you google Use of "python -m", I just wanted to add a quick reference for those who like to modularize code without creating full python packages or modifying PYTHONPATH or sys.path every time.
Setup
Let's setup the following file structure
.
├── f1
│ ├── f2
│ │ ├── __init__.py
│ │ └── test2.py
│ ├── __init__.py
│ └── test1.py
└── test.py
Let the present path be m1.
Using python -m instead of python ./*
*
*Use . qualified module names for the files (because they're being treated as modules now). For example, to run the contents in ./f1/test1.py, we do
python -m f1.test1
and not
python ./f1/test1.py
*When using the module method, the sys.path in test1.py (when that is run) is m1. When using the ./ (relative file) method, the path is m1/f1.
So we can access all files in m1 (and assume that it is a full python package) using -m. This is because the path to m1 is stored (as PYTHONPATH).
*If we want to run deeply nested "modules", we can still use . (just as we do in import statements).
# This can be done
python -m f1.f2.test2
And in test2.py, we can do from f1.test1 import do_something without using any path gimmicks in it.
*Every time we do module imports this way, the __init__.py is automatically called. This is true even when we're nesting.
python -m f1.f2.test2
When we do that, the ./f1/__init__.py is called, followed by ./f1/f2/__init__.py.
A: The first line of the Rationale section of PEP 338 says:
Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts. The motivating examples were standard library modules such as pdb and profile, and the Python 2.4 implementation is fine for this limited purpose.
So you can specify any module in Python's search path this way, not just files in the current directory. You're correct that python mymod1.py mymod2.py args has exactly the same effect. The first line of the Scope of this proposal section states:
In Python 2.4, a module located using -m is executed just as if its filename had been provided on the command line.
With -m more is possible, like working with modules which are part of a package, etc. That's what the rest of PEP 338 is about. Read it for more info.
A: Despite this question having been asked and answered several times (e.g., here, here, here, and here), in my opinion no existing answer fully or concisely captures all the implications of the -m flag. Therefore, the following will attempt to improve on what has come before.
Introduction (TLDR)
The -m flag does a lot of things, not all of which will be needed all the time. In short it can be used to: (1) execute python code from the command line via modulename rather than filename (2) add a directory to sys.path for use in import resolution and (3) execute python code that contains relative imports from the command line.
Preliminaries
To explain the -m flag we first need to explain a little terminology.
Python's primary organizational unit is known as a module. Module's come in one of two flavors: code modules and package modules. A code module is any file that contains python executable code. A package module is a directory that contains other modules (either code modules or package modules). The most common type of code modules are *.py files while the most common type of package modules are directories containing an __init__.py file.
Python allows modules to be uniquely identified in two distinct ways: modulename and filename. In general, modules are identified by modulename in Python code (e.g., import <modulename>) and by filename on the command line (e.g., python <filename>). All python interpreters are able to convert modulenames to filenames by following the same few, well-defined rules. These rules hinge on the sys.path variable. By altering this variable one can change how Python resolves modulenames into filenames (for more on how this is done see PEP 302).
All modules (both code and package) can be executed (i.e., code associated with the module will be evaluated by the Python interpreter). Depending on the execution method (and module type) what code gets evaluated, and when, can change quite a bit. For example, if one executes a package module via python <filename> then <filename>/__main__.py will be executed. On the other hand, if one executes that same package module via import <modulename> then only the package's __init__.py will be executed.
Historical Development of -m
The -m flag was first introduced in Python 2.4.1. Initially its only purpose was to provide an alternative means of identifying the python module to execute from the command line. That is, if we knew both the <filename> and <modulename> for a module then the following two commands were equivalent: python <filename> <args> and python -m <modulename> <args>. One constraint with this iteration, according to PEP 338, was that -m only worked with top level modulenames (i.e., modules that could be found directly on sys.path without any intervening package modules).
With the completion of PEP 338 the -m feature was extended to support <modulename> representations beyond the top level. This meant names such as http.server were now fully supported. This extension also meant that each parent package in modulename was now evaluated (i.e., all parent package __init__.py files were evaluated) in addition to the module referenced by the modulename itself.
The final major feature enhancement for -m came with PEP 366. With this upgrade -m gained the ability to support not only absolute imports but also explicit relative imports when executing modules. This was achieved by changing -m so that it set the __package__ variable to the parent module of the given modulename (in addition to everything else it already did).
Use Cases
There are two notable use cases for the -m flag:
*
*To execute modules from the command line for which one may not know their filename. This use case takes advantage of the fact that the Python interpreter knows how to convert modulenames to filenames. This is particularly advantageous when one wants to run stdlib modules or 3rd-party module from the command line. For example, very few people know the filename for the http.server module but most people do know its modulename so we can execute it from the command line using python -m http.server.
*To execute a local package containing absolute or relative imports without needing to install it. This use case is detailed in PEP 338 and leverages the fact that the current working directory is added to sys.path rather than the module's directory. This use case is very similar to using pip install -e . to install a package in develop/edit mode.
Shortcomings
With all the enhancements made to -m over the years it still has one major shortcoming -- it can only execute modules written in Python (i.e., *.py). For example, if -m is used to execute a C compiled code module the following error will be produced, No code object available for <modulename> (see here for more details).
Detailed Comparisons
Module execution via import statement (i.e., import <modulename>):
*
*sys.path is not modified in any way
*__name__ is set to the absolute form of <modulename>
*__package__ is set to the immediate parent package in <modulename>
*__init__.py is evaluated for all packages (including its own for package modules)
*__main__.py is not evaluated for package modules; the code is evaluated for code modules
Module execution via command line with filename (i.e., python <filename>):
*
*sys.path is modified to include the final directory in <filename>
*__name__ is set to '__main__'
*__package__ is set to None
*__init__.py is not evaluated for any package (including its own for package modules)
*__main__.py is evaluated for package modules; the code is evaluated for code modules.
Module execution via command line with modulename (i.e., python -m <modulename>):
*
*sys.path is modified to include the current directory
*__name__ is set to '__main__'
*__package__ is set to the immediate parent package in <modulename>
*__init__.py is evaluated for all packages (including its own for package modules)
*__main__.py is evaluated for package modules; the code is evaluated for code modules
Conclusion
The -m flag is, at its simplest, a means to execute python scripts from the command line by using modulenames rather than filenames. The real power of -m, however, is in its ability to combine the power of import statements (e.g., support for explicit relative imports and automatic package __init__ evaluation) with the convenience of the command line.
A: In short, one of the best use case for 'python -m' switch is when you want to tell Python that you want to run a module instead of executing a .py file.
Consider this example: you have a Python script in a file named 'venv' (without '.py' file extension). If you issue this command:
python venv
then, Python will excute the 'venv' file in the current directory. However, if instead you want to create a new virtual environment using the 'python venv' module, you would run:
python -m venv
in which case, Python will run the 'venv' module, not the file 'venv'.
Another example, if you want to run Pyhton's built-in local http server and issue the command:
python http.server
you would get an error like:
python: can't open file '/home/user/http.server': [Errno 2] No such file or directory
That's because Python tried to execute a file called 'http.server' and didn't find it.
So instead, you want to issue the same command but with '-m' switch:
python -m http.server
so that Python knows you want the module 'http.server' not the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "304"
} |
Q: Injecting a bean from a different Jar in Weld I have two Jars A and B where A depends on B.
Jar B has a single class:
@ApplicationScoped
public class MyManagedBean {
private String user;
public MyManagedBean(){
//Constructor necesary for CDI
}
@Inject
public MyManagedBean(@Named("user") String user){
this.user = user;
}
...
}
Jar A (more precisely, an EJB jar) has a bean:
@ApplicationScoped
public class AnotherManagedBean {
public AnotherManagedBean(){
//Constructor necesary for CDI
}
@Inject
public AnotherManagedBean(MyManagedBean bean){
...
}
}
And a configuration bean with a @Produces method:
@ApplicationScoped
public class ConfigurationBean {
public ConfigurationBean(){
//Constructor necesary for CDI
}
@Produces
@Named("user")
public String getUser(){
return "myUser";
}
}
However, when I deploy an EAR with both Jars I'm getting this exception:
SEVERE: Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [String] with qualifiers [@Named] at injection point [[parameter 1] of [constructor] @Inject public com.example.MyManagedBean(String)]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [String] with qualifiers [@Named] at injection point [[parameter 1] of [constructor] @Inject public com.example.MyManagedBean(String)]
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:270)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:106)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:129)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:351)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:336)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:396)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:190)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:306)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:382)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1064)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1244)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1232)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:459)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:209)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:238)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Any idea?
Thanks
A: Make sure both jars are "bean archives" - i.e. they have META-INF/beans.xml
A: I was having this exact same problem and I was able to get it figured out but I use an ear to combine the jars.
Ear Layout
project.ear
|-- META-INF
| |-- MANIFEST.MF
| |-- application.xml*
|-- one.jar (bean archive)
| |-- META-INF
| | |-- beans.xml
| |-- <code>
|-- two.jar (ejb)
*
*application.xml
<application>
<display-name>test-application</display-name>
<module>
<ejb>two.jar</ejb>
</module>
<module>
<java>one.jar</java>
</module>
</application>
Doing that it made one.jar available to two.jar in the container.
-kurt
A: One thing, you have to create Qulifier annotation for specify exactly which should be injected.
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface UserConfiguration { }
and then..
@Produces
@UserConfiguration
@Named("user")
public String getUser(){
return "myUser";
}
for injection..
@Inject
public MyManagedBean(@UserConfiguration String user){
this.user = user;
}
see also http://docs.jboss.org/weld/reference/1.1.0.Final/en-US/html_single/#d0e1355
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: WPF warm AppDomain startup performance (Application.RunInternal, XamlReader.LoadBaml) I have relatively simple application, but warm (second, etc.) start-up time is awful 3-5 seconds. Profiler (VS2010, CPU Sampling) shows that more than 80% of time is spent in Application.RunInternal (~40%) and XamlRader.LoadBaml (~40%) functions.
The root of the problem is that Window is created in non-default AppDomain. If I move Window creation to default AppDomain or give AppDomain unrestricted permission set everything is as fast as expected.
I'm testing on:
*
*Windows Seven x64
*.Net 4.0
*4Gb RAM
*GeForce 9800GT 1Gb.
I'm creating AppDomain this way
var permissionSet = new PermissionSet(null);
permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.UnmanagedCode));
permissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
permissionSet.AddPermission(new UIPermission(PermissionState.Unrestricted));
permissionSet.AddPermission(new MediaPermission(PermissionState.Unrestricted));
permissionSet.AddPermission(new FileDialogPermission(PermissionState.Unrestricted));
var appDomainSetup =
new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName,
DisallowApplicationBaseProbing = false,
DisallowBindingRedirects = true,
DisallowCodeDownload = true,
DisallowPublisherPolicy = true,
LoaderOptimization = LoaderOptimization.MultiDomainHost
};
_appDomain =
AppDomain.CreateDomain(
name,
null,
appDomainSetup,
permissionSet,
new[]
{
// a few types I need
typeof(...).Assembly.Evidence.GetHostEvidence<StrongName>(),
});
The behavior remains the same even if I strip down XAML to empty window
<Window
x:Class="Rosmurta.Extensibility.WpfUI.RosmurtaWindow"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test"
Height="480"
Width="640"
WindowStyle="SingleBorderWindow">
<Grid>
</Grid>
</Window>
Not too much to parse by XamlRader.LoadBaml, but it spends more than 30% of startup time event for empty window.
I've tried (and it did not help)
*
*Adding <generatePublisherEvidence enabled="false"/> to App.config.
*Adding [LoaderOptimization(LoaderOptimization.MultiDomainHost)] atribute to Main method.
*Adding signatures to all assemblies.
What else can be done?
A: The question is very old, but probably my answer will help somebody. Sometimes XAMLReader definitely takes much time during startup, however this doesn't always mean that the issue is caused by parsing itself. When XAML is being parsed, XAMLParser executes several relatively heave operations except for parsing:
*
*Uses reflection to get unknown types and crate instances
*Initializes objects and creates instances. If your XAML (or XAML of the component library you are using) contains many custom classes, they are created by XAMLParser and jitting occurs.
*Searches resources in the resource dictionary hierarchy and moreover. If the hierarchy of resource dictionaries is really complex, this operation make take some time.
There are several general techniques that may help you decrease your WPF application startup time:
*
*Generate native images using the Ngen tool.
*Enable MultiCore JIT when Ngen is not applicable
*Use ReadyToRun in conjunction with MultiCore JIT for .NET Core projects, since there is no Ngen for them
*Load Data on Demand. I think is is not your case, but may be useful for the full picture. For example, DevExpress has Virtual Source and Server Mode features to do this asynchronously for you.
*You can also wrap "heavy" views in in controls that delay their loading without freezing the UI. For example, you can use DevExpress LoadingDecorator
*Make sure that your view controls are not expanded of outside the visible area. For example, if you have StackPanel with ListBox inside, ListBox will create all its elements at once, because StackPanel doesn't limit height for its children, and they "think" that they have infinite height. As a result, ListBox will create all visual elements at once and significantly decrease your performance.
*As simple way to determine bottlenecks, you can comment UI, you can comment our XAML parts and see how this affects startup
Here is a blog post that might be helpful: 9 Tips to Reduce WPF App Startup Time
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android geocode get nearest locations I have Geocoder in my application and I want to get location by street name.
But if try to get location of some, I've get a location of that street in other city.
Is there a way to range found locations by distance from some location?
A: You can add the city into string if you want to find that address which is in your city, simply get the cityname of your location and append that to string but it keep it invisible to the user and if you want to find the address more precisely then you should need more specific input...!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Applying box-shadow to in Safari I need to apply a box-shadow to the tbody-Element of an TABLE.
Example: http://jsfiddle.net/emqUd/1/
The shadow doesn't display in Safari, in FF does.
I found a solution to apply
display:block;
on the Table, but then I have to explicitely have to assign a width to each column.
And I want to have the second element to be autowidth.
Has someone a working suggest?
thanks
Felix
A: This is untested (I don't have Safari), but how about placing a div around the tbody and styling the div with the box-shadow?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Crashing at ABRecordCopyValue Following is the method:
-(id)getValueForProperty:(NSUInteger) propertyId{
if(personRec != NULL)
return (id)ABRecordCopyValue(personRec, (ABPropertyID)propertyId);
}
}
I am calling above method as follow:
NSString *lastName = (NSString *)[self getValueForProperty:kABPersonLastNamePhoneticProperty];
//or
NSString *lastName = (NSString *)[self getValueForProperty:kABPersonLastNameProperty];
NSString *firstName = (NSString *)[self getValueForProperty:kABPersonFirstNamePhoneticProperty];
//or
NSString *firstName = (NSString *)[self getValueForProperty:kABPersonFirstNameProperty];
NSString *orgName = (NSString *)[self getValueForProperty:kABPersonOrganizationProperty];
but when I run the application in device it's showing that it's crashing in line
return (id)ABRecordCopyValue(personRec, (ABPropertyID)propertyId);
in what case this can crash?
A: It might be that a ABMultiValueRef is returned for one of your propertyId when calling ABRecordCopyValue, but you try to stuff it in a NSString.
In that case what you should do (say you're trying to get the first email address and you're using ARC):
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
int no = ABMultiValueGetCount(emails);
if ( no > 0 )
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(emails, 0);
NSString* email = CFBridgingRelease(emailRef);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android tabhost with asynchronous HttpClient I have an application with tabs and every tab has HttpCLient that is triggered every time user clicks on the tab and a page is downloaded in a tabActivity thread. When user clicks on tab and then switches to another one, he must wait for a few seconds, so that the request will be sent to server and reply received. I want to make switching between the tabs asynchronous from the HttpClients. It did not work even when i put requests in threads and it even did not work when I introduced TabGroupActivity on every tab.
I have a separate class with all the requests to the server. SHould i extend this class with asyncTask? (This is actually the last thing i have been thinking about that could help)
EDIT:
On every tab onPause i am doing Thread.join() nad it seems that it is the action that slows down all the process of comming back to the same tab
A: to prevent UI from blocking, all potentially slow running operations (such as networking) should run in the background, e.g. via some way of concurrency such as Asynctask.
I think Asynctask is better choice (comparing with threading) because it encapsulate everything into a single class, and is native android. (e.g. you don't need to use RunOnUIThread when using this class)
read this article for more information: http://www.vogella.de/articles/AndroidPerformance/article.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: nginx only sending GET requests to unicorn I'm trying to run a Rails 3 app proxied through nginx to unicorn, using the following virtual host.
upstream nginx {
server unix:/tmp/nginx.socket fail_timeout=0;
}
server {
listen 80;
server_name nginx.domain.net;
rewrite ^(.*) https://nginx.mydomain.net$1 permanent;
}
server {
listen 443 ssl;
server_name nginx.mydomain.net;
root /home/me/nginx.mydomain.net/current/public;
access_log /home/me/nginx.mydomain.net/shared/log/access.log;
error_log /home/me/nginx.mydomain.net/shared/log/error.log;
ssl_certificate /etc/nginx/certs/my_crt_chain.crt;
ssl_certificate_key /etc/nginx/certs/my_crt_key.key;
rewrite_log on;
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_methods GET HEAD POST;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
if (!-f $request_filename) {
proxy_pass http://nginx;
break;
}
}
}
When I start unicorn and attempt to make a POST request, it's showing up in the Unicorn logs as a GET request.
I, [2011-09-30T12:38:05.036462 #19364] INFO -- : unlinking existing socket=/tmp/nginx.socket
I, [2011-09-30T12:38:05.036902 #19364] INFO -- : listening on addr=/tmp/nginx.socket fd=5
I, [2011-09-30T12:38:05.037435 #19364] INFO -- : Refreshing Gem list
master process ready
worker=0 ready
worker=1 ready
92.22.194.68 - - [30/Sep/2011 12:38:13] "GET /reset HTTP/1.0" 200 - 0.6486
I'm new to nginx but it seems that somehow the POST requests aren't being sent through. I can't find proxy_cache_methods set explicity anywhere (nginx config, virtual host) but I've also set it explicity to allow POST in this virtual host: proxy_cache_methods GET HEAD POST; Whether the virtual host includes this line or not doesn't make any difference.
I didn't think it was worth posting the unicorn.rb configuration file as it seems to be an issue with nginx's proxying, but I can do if needed.
A: It seems this also needs the following under the location block:
proxy_set_header X-FORWARDED_PROTO https;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i logout from my application I am new to android.
I want in my application logout facility.
How can i log out from my application. I want to clear shared preferences in logout button ,but i don't know How can I do this.
A: *
*keep android:noHistory for all of your activities
*See that you clear everything in onDestroy() or onStop() of your root activity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to flowplayer play while a mp4 file is buffering? It always play only when mp4 is fully loaded, i would like to it playing while video is buffering, it's possible to do?
thanks.
A: I use flowplayer with those settings and the video starts while it buffers
flowplayer("player", {
// our Flash component
src: "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf",
// we need at least this Flash version
version: [9, 115],
// older versions will see a custom message
onFail: function() {
document.getElementById("info").innerHTML =
"You need the latest Flash version to see MP4 movies. " +
"Your version is " + this.getVersion();
}
// here is our third argument which is the Flowplayer configuration
},
{
clip: {
url: "<?php echo($fileName); ?>",
autoPlay: false,
autoBuffering: true
}
});
I think that "autoBuffering" is what you are looking for
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Missing PropertyChanged event when BindingList elements has properties changed I have a class ViewModel that has a property MyList of type BindingList<Foo>.
ViewModel implements INotifyPropertyChanged.
Foo has the property FooProp.
Foo implements INotifyPropertyChanged
ViewModel has this property:
public bool IsButtonEnabled
{
get
{
return MyList.Any(x=> x.FooProp!=null);
}
}
I have a view with a button. The Enabled property of the button is bound to IsButtonEnabled.
But the button doesn't get enabled when an element of MyList has it's FooProp set. I've noticed that ViewModel doesn't fire a PropertyChanged event here. Why not? And how should I go about for the view model to notice that it's IsButtonEnabled property actually has changed?
A: EDITED: Didn't notice that this was a getter and not a setter. The point is still the same. Simply implementing the INotifyPropertyChanged interface doesn't automatically add everything you need. You need to create the method(below) that fires the event. Then you need to call that method in the SETTER of all of your properties.
Shouldn't you fire the PropertyChanged event yourself?
public bool IsButtonEnabled
{
get
{
return MyList.Any(x=> x.FooProp!=null);
// assuming you named the method this
OnPropertyChanged("IsButtonEnabled");
}
}
The INotifyPropertyChanged interface only creates the event for you. You need to fire the event from the ViewModel yourself.
If you haven't already created the method, this one normally works. You would call this method explicitly when a property of the ViewModel changes.
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
A: ViewModel will not fire any PropertyChanged here because ViewModel's properties are not changed. The actual property that was changed FooProp which is a property of class Foo, not ViewModel.
In order to enable/disable the button based on the IsButtonEnabled functionality you will have to track all the elements of MyList and see if any changes are done. So, the following should work:
public class Foo : INotifyPropertyChanged
{
void OnPropertyChanged(string propertyName) { /* ... */ }
public object FooProp
{
get { return _obj; }
set
{
_obj = value;
OnPropertyChanged("FooProp");
}
}
}
public class ViewModel : INotifyPropertyChanged
{
void OnPropertyChanged(string propertyName) { /* ... */ }
private List<Foo> _myList;
public List<Foo> MyList
{
get { return _myList; }
set
{
_myList = value;
foreach(var item in _myList)
{
HandleItem(item);
}
}
}
void AddItem(Foo item)
{
MyList.Add(item);
HandleItem(item);
}
void HandleItem(Foo item)
{
item.PropertyChanged += (s, e) =>
{
if(e.PropertyName == "FooProp")
};
}
void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertyName == "FooProp") OnPropertyChanged("IsButtonEnabled");
}
public bool IsButtonEnabled
{
get
{
return MyList.Any(x=> x.FooProp!=null);
}
}
}
Note that in this case you need to use ViewModel.AddItem() in order to add an item to MyList (you can use MyList.Add(), but it will not fire the correct notifications then).
Also the code above is not the best way to do it - it is just an illustration of how your case should work. After you understand that you are probably going to replace the List<> to ObservableCollection<> to be able to track/handle items in your list automatically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Make a build for ios3.1.3 through Xcode 4....? I'm using xcode 4 and making the build for ios4 and ios3.1.3 . I'm able to make the build for ios4 but when i made a build for ios3.1.3 it gives me "signcode error" at the time of sync can any one suggest me the proper way of making the build for ios3.1.3 through xcode 4 . As far as i know entitlements.plist is not required in Xcode 4.
Thanks In Advance
A: You can't build app for iOS 3.* in XCode4, you can however set the deployment target of you project to iOS 3.*.
Setting the deployment target will make your app run on iOS 3., but you will have to make sure that you are not calling nay methods that are not available on iOS 3..
Also user classes introduced in iOS 4 will not work.
A: First you need to set the deployment target to 3.* like rckoenes say.
The second, and more important is set in your target->Build Phases tab->Link Binary With Libraries the framework you need with weak link. This mean configure it from Required to Optional.
This can make you use it in old iOS. Now is obvious you can't use function of new iOS in the older iOS. This mean you can check like respondToSelector or only use function that run in your old iOS.
If you run a function that don't exist in old iOS, it will crash. But, at least, will run until it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pointer becomes null when constructor finishes running I have a camera class that has two pointers as parameters:
Camera::Camera(
float fOVDeg, float nearCull, float farCull,
float xPos, float yPos, float zPos,
D3DMATRIX* matProjection, D3DMATRIX* matView)
{
this->SetCamera(fOVDeg, nearCull, farCull);
this->AdjustCamera(xPos, yPos, zPos);
matProjection = &(this->projection);//gets the addresses of two private members
matView = &(this->view);
}
and this is the code that calls it:
D3DMATRIX* matProjection,* matView;
//called once
void Initialise(HWND hWnd)
{
camera = new Camera(
45.0f, 1.0f, 100.0f,
0.0f, 9.0f, 24.0f,
matProjection, matView);
...rest of code...
basically the problem is that I want the two pointers in the code that calls the camera constructor to retain the memory addresses of the camera classes two private members so I can do stuff with 'em! trouble is, this works fine, but as soon as the constructor is finished the pointers become null (0x00000000). I have no idea why! The camera's private members still have values because I was just grabbing their values with getters before and it worked fine.
A: You are passing matProjection by value, therefore, the assignments to it in the constructor assign to a local copy (which is not visible outside). Try using a reference:
Camera::Camera(
float fOVDeg, float nearCull, float farCull,
float xPos, float yPos, float zPos,
D3DMATRIX* &matProjection, D3DMATRIX* &matView)
---------------^ ------------------^
The rest of the code should stay the same.
Responses to your comments:
one more thing I don't quite understand is why I don't have to place an '&' in front of matProjection and matView in the call
Because when the function parameter is declared as a reference, the compiler figures that out and passes a reference (probably implemented as a pointer) instead.
am I right in thinking that you pass the value it points to.. therefore you need to reference is to get the address of the actual pointer?
Yes. Pointers are no different than ints, and under normal conditions, their value is passed. When you need the function to set your variable (of pointer type, but the same applies to ints), you have to either pass a pointer-to-pointer or a reference-to-pointer, which are similar, but the latter comes with neat syntactic sugar.
A: You are passing the pointers in by value. So the Camera constructor is assigning values to copies of those pointers. You need to pass the pointers in by reference...
Camera::Camera(
float fOVDeg, float nearCull, float farCull,
float xPos, float yPos, float zPos,
D3DMATRIX*& matProjection, D3DMATRIX*& matView)
A: See another today's question: Why is my pointer not null after free?
You need a reference type argument, or a pointer to pointer. By-value arguments won't do your task.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a jQuery plugin or JavaScript code to allow client-size image resizing/cropping in a circle? We're trying to allow the user to select the exact face of a person from a chosen photo and we want to achieve this by providing an oval shape into which the user has to fit the face by resizing the photo or the oval itself.
Is there any plugin I can use or will this need to be done from scratch?
A: Don't know of a plugin (and google is a better place for this) but it's not hard to develop one. Just create a overlay div with some opacity over the image the user sent. Then use jQuery UI draggrable and resizable for a smaller div with transparent background.
Send the div's position, width and height to the server and perform the cropping there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using jQuery to read a JSON file errors in Google Chrome I have a JSON file here:
http://dalexl.webs.com/products.json
I'm trying to read it on my site with Javascript/jQuery:
$.getJSON("http://dalexl.webs.com/products.json")
(Yes, I know that it isn't complete, I'm currently just trying to get it to load, I haven't worked on reading it yet)
I tried having in my own sites directory (I'm using Dreamweaver locally on my HD).
$.getJSON("json/products.json")
The problem is, in Chrome (I'm not sure about other browsers), the console gives me this error:
XMLHttpRequest cannot load http://dalexl.webs.com/products.json. Origin null is not allowed by Access-Control-Allow-Origin.
or:
XMLHttpRequest cannot load json/products.json. Origin null is not allowed by Access-Control-Allow-Origin.
At first, reading about the problem online suggested that it was Chrome thinking that a website was trying to read files on my computer. After moving the file online, however, the problem continues.
Does anybody have a solution to this? If it isn't supposed to be supported, why does jQuery have a native method of doing it?
Thanks!
A: you are trying to open cross domain? See:
http://en.wikipedia.org/wiki/Same_origin_policy
A: http://dalexl.webs.com/products.json does not return valid json. I like using http://jsonviewer.stack.hu/ for testing (when you press the "viewer" button you get an error).
You have three missing commas:
After: "url": "#1"
After: "url": "#2"
Before: "Cakes": {
A: Unless the page on which the script executing the line
$.getJSON("http://dalexl.webs.com/products.json")
is also on http://dalex1.webs.com, you're running afoul of the Same Origin Policy, a restriction on what resources you can load via XMLHttpRequest (e.g., "ajax"). See the link for details.
Your options for getting around the SOP are:
*
*JSON-P, which requires modifying the data you're returning, but in a trivial way.
*Cross-Origin Resource Sharing, a relatively recent standard which the server and browser would both need to support. (Recent versions of Firefox, Opera, and Chrome all support it with XMLHttpRequest; IE8 and above support it, but only via XDomainRequest object rather than the standard XMLHttpRequest. Details here.)
*In really tricky situations, you might look at using YQL as a cross-domain proxy.
Separately, note that the JSON you're returning is invalid (missing commas between properties), see jsonlint.com and others for validation tools. It is now you've fixed it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: REQUEST_TIME in C# Is there a similar function in C# that is akin to the PHP functionality of ("$_SERVER['REQUEST_TIME']")?
A: The following property returns the initial timestamp of the current HTTP request:
HttpRequest.RequestContext.HttpContext.Timestamp
In an ASP.Net-Page it can be accessed through the Request object like this:
Request.RequestContext.HttpContext.Timestamp
Hope I could help.
A: You can use the following extension method to convert a DateTime to a Unix timestamp (which is what I understand to be held in REQUEST_TIME):
public static class TimeTools
{
private static readonly DateTime StartOfEpoch =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long ToUnixTime(this DateTime dt)
{
return Convert.ToInt64(
(dt.ToUniversalTime() - StartOfEpoch).TotalSeconds);
}
}
so (borrowing from @Dennis` answer)
Request.RequestContext.HttpContext.Timestamp.ToUnixTime()
A: I think you're looking for DateTime.Now or DateTime.UtcNow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: ListView selection In a ListView control by default you select a row if you click on the content of a column but if you click on the row out of bounds of content then it wont select the row. Is there any quick way to do it expect specifying templates for each column?
I've tried (this actually works for ListBox ):
<Style TargetType="{x:Type ListViewItem}"
BasedOn="{StaticResource {x:Type ListViewItem}}">
<Setter Property="Background" Value="#01000000" />
</Style>
A: I had a similar problem with ListView (did not test it with ListBox). Hopefully this will apply. I know this is not a tested answer but I cannot post code in a comment. If it does not work please let me know and I will remove it.
<ListView ... >
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error with zoomStartTime and AnnotatedTimeLine I'm a bit of a beginner with Javascript, but last month I had a working Google chart linked to a Google Docs file, which uses a start date for the graph at 90 days before the current date.
I checked the page today and in Chrome I get the message "Object # has no method 'getTime'", and in Firefox I get the message "b.zoomStartTime[y] is not a function". Both stop the graph from loading.
I have simplified the code to help me with the error, but I'm not getting anywhere... Here's the code:
<script type="text/javascript">
var oldDate = new Date();
oldDate.setDate(oldDate.getDate() - 90);
</script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/static/modules/gviz/1.0/chart.js">
{
"dataSourceUrl": "//docs.google.com/spreadsheet/tq?key=0AkQH6d2CUv_qdDhwd3gtZzdTVFlNX3AwX2xUSUVuclE&transpose=0&headers=-1&range=A1%3AB2436&gid=0&pub=1",
"options": {
"zoomStartTime": oldDate,
"width": 650,
"height": 371
},
"chartType": "AnnotatedTimeLine",
}
</script>
Any ideas would be hugely appreciated.
David.
A: The getDate() call returns the day of the month (http://www.w3schools.com/jsref/jsref_obj_date.asp), which creates an invalid date and causes the error.
A solution for get another date than now:
function getDate(y, m, d) {
var now = new Date();
return new Date(now.getFullYear()+(y?y:0), now.getMonth()+(m?m:0), now.getDate()+(d?d:0));
}
You may use like this:
"options": {
"zoomStartTime": getDate(0, -90, 0),
"width": 650,
"height": 371
},
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: May UIComponent#getFamily() return null or not? I would like to know wether the method UIComponent#getFamily() may return null or not? Mojarra 2.1.3 will throw an exception when returning null but MyFaces 2.1.3 not.
Does a component really need a family?
A:
I would like to know wether the method UIComponent.getFamily() may return null or not?
This is nowhere explicitly documented. So I think this is a little oversight in the spec/javadoc. You may want to post an issue report about this at the spec guys.
Does a component really need a family?
I've always specified them, so I've never seen the exception you got with Mojarra. If your component is rather unique, you could consider to just let it return the same value as component type (the class name) or if there are more related components, then the component's package name.
What is the preferred way of implementing a component that has no renderer?
Return null on getRendererType(). You could prepare that by setRendererType(null) in the component's constructor:
public MyComponent() {
setRendererType(null); // This component doesn't have an renderer.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# Define custom UnmanagedType for the MarshalAs attribute class is it possible to define a custom UnmanagedType for the MarshalAs attribute class?
Specifically I want to convert a long int unix time into a DateTime type. Something like this:
[MarshalAs(UnmanagedType.LongTimeUnix)]
public DateTime Time;
Where do I have to put the custom LongTimeUnix enumeration type and where to put the time conversion code:
public static DateTime ConvertUnix2DateTime(long timeStamp)
{
DateTime DT = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DT = DT.AddSeconds(timeStamp);
return DT;
}
When transferring the data with
(SomeStruct)Marshal.PtrToStructure(
IntPtr,
typeof(SomeStruct));
I want that the long time unix is automatically converted with the code sinppet above.
Do I have to inherit from the MarshalAs class and write the conversion into this class?
Thanks, Juergen
Update
Here is the custom marshaller:
class MarshalTest : ICustomMarshaler
{
public void CleanUpManagedData(object ManagedObj)
{
throw new NotImplementedException();
}
public void CleanUpNativeData(IntPtr pNativeData)
{
throw new NotImplementedException();
}
public int GetNativeDataSize()
{
return 8;
}
public IntPtr MarshalManagedToNative(object ManagedObj)
{
throw new NotImplementedException();
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
long UnixTime = 0;
try
{
UnixTime = Marshal.ReadInt64(pNativeData);
}
catch (Exception e)
{
QFXLogger.Error(e, "MarshalNativeToManaged");
}
DateTime DT = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DT = DT.AddSeconds(UnixTime);
return DT;
}
}
Here is the class definition:
unsafe public struct MT5ServerAttributes
{
/// <summary>
/// Last known server time.
/// </summary>
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalTest))]
public DateTime CurrentTime;
//[MarshalAs(UnmanagedType.U8)]
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalTest))]
public DateTime TradeTime;
}
And finally the code to marshal the data from unmanaged memory:
try
{
MT5ServerAttributes MT5SrvAttributes = (MT5ServerAttributes)Marshal.PtrToStructure(mMT5Proxy.MT5InformationProxy.ServerData,
typeof(MT5ServerAttributes));
}
catch (Exception e)
{
QFXLogger.Error(e, "ConsumeCommand inner");
}
When running this the following excpetion is thrown(which is not a direct exception ot PtrToStructure!)
Cannot marshal field 'CurrentTime' of type 'QFX_DLL.MT5ServerAttributes': Invalid managed/unmanaged type combination (the DateTime class must be paired with Struct).
Any ideas?
A: You cannot add your own to the enumeration, but you can use UnmanagedType.CustomMarshaler. To specify that you want to marshal it using a custom type.
MSDN has an entire section dedicated to this.
You would end up doing something along these lines:
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MyCustomMarshaler))]
public DateTime Time;
Then implement MyCustomMarshaler as ICustomMarshaler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Binary Zero, NULL Byte and ASCII I am very confused. Is there any relationship between the following:
*
*Binary Zero.
*Null Byte.
*ASCII Character 0 (Decimal value is 48).
Your explanation is highly appreciated.
A: Technically, I suppose the first refers to a single bit. Eight bits make a byte, and eight binary zeros would thus comprise a "null byte", the byte with numeric value 0 which is used to terminate C strings. The ASCII value used to represent the text character 0 is, as you say, 48, and there is nothing special about that value -- it's just the more or less random number that was assigned to this duty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Get information about a SHA-1 commit object? I searched for a topic of interest in a commit log:
$ git log --pretty=oneline | grep -i ...
$SHA1 < ... commit message ... >
I now have a SHA1, and I want to know information about the files affecting that SHA1 and maybe later diff them with their parent. How can I get this done?
A: git show <SHA1> will show the commit date, author, parent, and diff of files that changed from parent commit.
A: git show --no-patch --oneline <SHA1>
git show --no-patch <SHA1>
This is an answer to
View a specific Git commit
which has no reply box as it has been marked as a duplicate of this question.
Some of the people looking for a reply to the above question are likely to follow the link and look for an answer here.
Both are questions about obtaining information about a commit from its SHA1 code.
Some of the time when you have identified a commit by its SHA1 code, you will want to know everything about it: all the changed files, what the actual changes are etc.
The other question is much more specific. Someone had a suspect line of software in a file and had tracked it to a particular SHA1 code using "git blame".
They then simply wanted to know which software change in human terms had introduced that line. There is no interest in knowing all the other changed files, no interest in getting a complete diff of the files, or even of getting a diff of that one file. It's simply about knowing which change introduced a line of code.
Instead of information like
c27feeaa9b2c6270ff559b21eaf9f1e0317676a7
we want information like
Humanitarian Aid Feature
or
Left handed Thread Fix
To do that, use
git show --no-patch --oneline <SHA1>
where git show --no-patch (i.e. with the --no-patch option) is the key to answering eykanal's question View a specific Git commit
Use
git show --no-patch <SHA1>
if you want author and date information too.
A: You can also get specific information about a commit object (using the SHA1) using cat-file command.
E.g. git cat-file -p <sha1>
Sample Output:
$ git cat-file -p xxxx
tree <sha1>
parent <sha1>
parent <sha1>
author <author> <unix timestamp>
committer <committer> <unix timestamp>
<commit message>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "72"
} |
Q: Bugzilla Apache server config I have installed Bugzilla on my dedicated server with Centos5.5.
I have already a website running on this server with Apache config
<VirtualHost *:80>
DocumentRoot /var/www/html/XXX
..
</VirtualHost>
and I have defined a new virtual host on Apache as
<VirtualHost *:8000>
DocumentRoot /var/www/html/bugzilla
<Directory /var/www/html/bugzilla>
AddHandler cgi-script cgi pl
Options +Indexes +ExecCGI
DirectoryIndex index.cgi
AllowOverride Limit
</Directory>
</VirtualHost>
However, I can't reach bugzilla anyway.. What is the right way to do that ?
Thanks
A: Is there any chance that the firewall is blocking port 8000?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: get out of memory exception when indexing files with solrj I write a simple program with solrj that index files but after a minute passed it crashed and the
java.lang.OutOfmemoryError : java heap space appears
I use Eclipse and my memory storage is about 2GB and i set the -Xms1024M-Xmx2048M for both my VM arg of tomcat and my application in Debug Configuration and uncomment the maxBufferedDocs in solrconfig and set it to 100 then run again the application but it crash soon when it reaches the files greater than 500MB
is there any config to index large files with solrj?
the detail my solrj is as below:
String urlString = "http://localhost:8983/solr/file";
CommonsHttpSolrServer solr = new CommonsHttpSolrServer(urlString);
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
req.addFile(file);
req.setParam("literal.id", file.getAbsolutePath());
req.setParam("literal.name", file.getName());
req.setAction(ACTION.COMMIT, true, true);
solr.request(req);
A: Are you also setting the heap size params when running the java class in eclipse ?
Run -> Run Configurations > <Class Name> > Arguments -> VM arguments
A: Is Solr also running on the same machine as solrj? There might be memory constraints on the machine where you are running Solr. How much free memory do you have once you start Solr? - you will probably need more memory available on that box.
Try to put a commit after every document and see if you can get around the problem temporarily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get id of merged JPA entity I have a little application where I store entity to DB. I do this in next way:
class Entity {
privete id;
String somePropertie;
// getters and setters
}
// In main class
Entity newEntity = new Entity();
newEntity.setSomePropertie("somePropertie");
Entity entity = entityManager.merge(newEntity);
System.out.println("This is id of stored entity:", entity.getId())
The didn't write the jpa annotations here. But the entity is stored to database, but the printed id is 0; I using transaction driven by spring, I need this entity for later updates of the entity id.
A: EntityManager.merge(..) gets an instance and returns an instance that is managed. And in case of transient instances it returns a new instance (does not modify the original)
So your mergeEntity(..) method should return em.merge(entity)
A: Correct me if I am wrong, but have you tried with
Entity entity = entityManager.merge(newEntity);
System.out.println("This is id of stored entity:", entity.getId())
in the same transaction?
Also try setting id to Long rather than long (or Integer rather than int; it is not clear from your definition)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find and replace strings using sed I am trying to replace strings in a document that enclosed in single quotes, to a string without.
'test' -> test
Is there a way using sed I can do this?
Thanks
A: This will remove single quotes from around any quoted word, and leave other quotes alone:
sed -E "s/'([a-zA-Z]*)'/\1/g"
When tested:
foo 'bar' it's 'OK' --> foo bar it's OK
Notice that it left the quote in it's intact.
Explanation:
The search regex '([a-zA-Z]*)' is matching any word (letters, no spaces) surrounded by quotes and using brackets, it captures the word within. The replacement regex \1 refers to "group 1" - the first captured group (ie the bracketed group in the search pattern - the word)
FYI, here's the test:
echo "foo 'bar' it's 'OK'" | sed -E "s/'([a-zA-Z]*)'/\1/g"
A: removing single quotes for certain word (text in your example):
kent$ echo "foo'text'000'bar'"|sed "s/'text'/text/g"
footext000'bar'
A: How about this?
$> cat foo
"test"
"bar"
baz "blub"
"one" "two" three
$> cat foo | sed -e 's/\"//g'
test
bar
baz blub
one two three
Update
As you only want to replace "test", it would more likely be:
$> cat foo | sed -e 's/\"test\"/test/g'
test
"bar"
baz "blub"
"one" "two" three
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add class for form label defined in cakephp and then add jquery event I have created a form in cakephp
<?php echo $form->create('User', array('action' => 'login'));?>
<?php
echo '<div class="loginbox">';
echo '<table width="200" border="0">';
echo '<tr>';
echo '<td>';
echo $form->input('username', array('label' => __('Username', true)));
echo '</td>';
echo '<td>';
echo $form->input('password', array('label' => __('Password', true)));
echo '</td>';
echo '<td>';
echo $form->end('Login');
echo '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
?>
I want to add a class for label and after that add focus event of jquery so that in the input for username the text username appears and when clicked in the input area the text disappears. How to make it work?
A: I would just bind the focus and blur events to your inputs. For each input, create a title attribute as your default text when the input is empty:
<script type='text/javascript'>
jQuery(document).ready(function() {
$(".forminput").focus(function() {
if ($(this).val() == $(this)[0].title) {
$(this).removeClass("active");
$(this).val("");
}
});
$(".forminput").blur(function() {
if ($(this).val() == "") {
$(this).addClass("active");
$(this).val($(this)[0].title);
}
});
$(".forminput").blur();
});
</script>
<input value="" title="Enter a username" name="screenname" type="text" class="forminput" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: portable AIR apps. Is that possible? is it possible to build a portable version of an air app? So that it's possible to put it on flash, and launch on any PC.
Thank you in advance!
A: In AIR 3, you can package the app as a captive runtime bundle. This is self contained and can be run without a special install. (A few features that require registry settings on windows won't work, like registering to handle file types.)
A: I suspect not. Adobe AIR makes extensive use of directories in the logged-in user's profile for things like local storage. I believe that that is also where it sets up the verification for the code-signing certificate. So it would likely not be possible for you to run an AIR application portably from a flash drive.
I am going to guess you have tried it. If not, then give it a try. Install the Application using one machine, and when prompted for the install location, sent it to a Flash drive. Then take that Flash drive to another machine that has AIR installed and try running it from there. See what happens, and see what kind of error you get. Like I said, I suspect it will not work.
A: It is quite possible. The only thing the developer(s) need to keep in mind is not to store anything in app-storage:// of the application. They should ask the user before storing any data from the user. Similarly, when referencing files the developers should try and put the same in the app:/ folder. Lastly, encrypted local storage should not be used.
If these guidelines are followed, an AIR application should easily work from a flash drive as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android compatibility Here is the thing, I'm developing an application that uses a lot of the screen space, I need to show 3 list views in certain times for example. At first I was testing on my Android 3.1 tablet, but then I decided I wanted to have it playing on Android 2.1 as well. When I tried to play the application the simulator, It looked awfully bad, things much more space on screen then it looked on the 3.1 (even testing it in big screens). Does anyone with experience in this knows if its possible to make an application like my (with lot's of things showing up in the screen at one time) to look good and be compatible to android 2.1?
If its possible, how hard would it be? Should I consider making two different applications?
Here are some example pictures:
Image missing http://dl.dropbox.com/u/2490888/android31.png
Image missing http://dl.dropbox.com/u/2490888/android21.png
The first one is how I want it to look like.
A: Check out the developer site on supporting different screen sizes, especially the part where they mention this:
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-small/my_layout.xml // layout for small screen size
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
Basicly you should be able to solve your problem by rearranging your layouts depending on screen size.
EDIT
If you don't have time to fit your layouts you could look into Fragments. I haven't worked with them that much myself, so I can't really give you any pointers on how best to use them, but from what I read in the documentation they might serve a purpose in your situtation.
A: Make different xml layout as per different range of devices and put them in different folder of layouts. For example if you have main.xml as your layout file designed for tablet, put it in layout-xlarge for tab devices and other version of main.xml which is compatable with handset like galaxy s2 you out it in layout folder and for smaller devices like galaxy pop you put main.xml which is designed for smaller devices in layout-small folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.