text stringlengths 8 267k | meta dict |
|---|---|
Q: Android Launcher Icon not working I have an Android app that I am currently developing. I have created icons (.png) and placed them in the /res/drawable-hdpi (and ldpi & mdpi) folders. In my manifest I have
<application android:icon="@+drawable/icon" android:label="@string/app_name">
my icons are all named icon.png.
I have compiled the source and when I run it on the emulator, the icon shows up in the desktop launcher. But when I copy the apk to my actual phone, the desktop launcher shows the default package icon rather than my custom icon. Although, funny enough when I am actually installing the app, the package manager does show the icon. But once it is installed, the icon does not show.
How do I make my application icon show up as the launcher icon?
Skip
A: remove the "+" in "@+drawable/icon"
A: I had the same problem, and I never used the "+" in the manifest.
Rebooting&wiping emulator or restarting Eclipse did not work for me.
I simply solved renaming all the icon.png files to something different (e.g. iconq.png).
A: I just had the same issue. I renamed my icon to launch_icon and restarted Eclipse. Not sure which one did the trick but it worked after that
A: It's possible to have different icons set for different components (ie Activity and Service). Make sure that you have the icon only defined for the application element, and nothing else. This will guarantee that all components will have a the same icon, the one defined in the application.
A: For some reason it was the ROM I had on my phone (it was a gingerbread MIUI ROM). I put a new ROM on my phone today and it works fine. Strange.
A: I had a similar problem. I am running a custom rom (Cyanogen mod 7), and my solution was to simply reboot my device. After that, the icon appeared.
A: Make sure that the Intent of your Launcher Activity is named MAIN
i.e,
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Moreover, add the icon to your Drawable folders and then refer it in the application block of Manifest.
<application
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
A: In my case, I was testing in a Nexus 5X device with the Android Nougat and the icon was correct, but in the emulator on the same android version but with the Pixel Launcher, the default icon were shown.
I saw that in my case I forgot to replace the android:roundIcon property in the manifest to use the new one.
Round Icon Resources
Apps can now define circular launcher icons, which are used on devices that support them. When a launcher requests an app icon, the framework returns either android:icon or android:roundIcon, depending on the device build configuration. Because of this, apps should make sure to define both android:icon and android:roundIcon resources when responding to launcher intents. You can use Image Asset Studio to design round icons.
You should make sure to test your app on devices that support the new
circular icons, to see how your circular app icons look and how they
are displayed. One way to test your resources is to run the Android
emulator and use a Google APIs Emulator System targeting API level 25.
You can also test your icons by installing your app on a Google Pixel
device.
For more information about designing app launcher icons, see the
Material Design guidelines.
https://developer.android.com/about/versions/nougat/android-7.1.html#circular-icons
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: dropdown menu stops working after page jump My head is about to explode as I try to figure out the reason why my dropdown menu stops working as soon as the page jumps to an anchor. There is some JS involved in the jump, too, but the same problem existed even with a plain html anchor jump.
The page is at http://mincovlawyer.com/doc/euro-excellence
As you load the page, please hover over "The Law", "About" and "The Goodies" and see how the dropdown is supposed to operate.
Then click any of the links in the sidebox to the right, for example Alt. #1.
Then hover over the menu items again and observe that no dropdowns emerge anymore.
I would immensely appreciate any guidance in this regard.
A: It looks like they're working, but they are above the top of the page. Before clicking on any of the links, scroll down just a little bit. Then hover over "The Law" and you'll see your menu shifted vertically.
A: The rollover breaks even if you just scroll down the page. The rollover menu is positioned absolute and the navigation is positioned fixed. You could add 'position:fixed' to your rollover menu or you could add the scroll offset in your drop down menu code.
To set 'position:fixed':
At line 8 of the anylinkmenu.css file, change the position:absolute to position:fixed.
A: Now that's a lot of code...
Where's your menu created? The mouse-over stuff
Question1:
Why even using any javascript for an inline-anchor? Using #links scrolls to said position anyways, even without JS?!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are people using for html form generation? There is a similar question from 2009 which mentions Wufoo and FormAssembly services. Are there any other services you would recommend for generating html forms?
I simply want to generate the code for the forms (some with a lot of fields) for my php application. I don't want a hosted solution or anything such as those mentioned above. What do you use for this tedious process?
Thanks.
A: You could check out Zend_Form. It generates HTML for you but you have to write quite a lot of php - with the reward of contained validation rules and decoration (container elements etc).
Or are you looking for a solution that let's you use a GUI to generate the form? In that case Wufoo seems like a good choice, I guess.
A: Just found what I was looking for. Must be newly indexed because it didn't turn up in my search the first time. In case anyone else is looking for something similar:
http://www.phpform.org/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: switched to ssl and devise tokens are invalid We just switched our rails 3 app over to SSL, and later noticed that password recovery tokens aren't working in production any longer. It says "invalid token" when a user tries to reset their password using the emailed link.
I'm using rails 3.0.0, devise 1.3.4, and our user model has:
devise :database_authenticatable, :invitable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
I'm not using anything like ssl_requirement, because we just did ssl universally across the app. I expired old tokens to make sure it wasn't somehow not expiring old tokens or something. I'm baffled.
A: This was a problem with our nginx config, and entirely unrelated to Devise. But in case anyone else ever finds themselves in a similar position, here's what went down. We set up nginx to redirect the plain http urls to https.. Specifically we had a double rewrite when someone went from domain.com to www.domain.com to https://www.domain.com, and the reset_code was getting added to the end a second time so that reset_code was coming through to the app as ?reset_code=12345?reset_code=12345.
So we changed our nginx config so:
# rewrite ^ https://$server_name$request_uri permanent;
rewrite ^(.*) https://$host$1 permanent;
and then just an optimization
rewrite ^(.*)$ https://www.domain.com$1 permanent;
and all better now.
A: The answer provided above is correct. But it is a temporary solution and it works only for devise. However the problem arises when you manually send a confirmation token via email.
You can fix this permanently.Go to environment/production.
and change this line
config.action_mailer.default_url_options = { :host => 'domainname', :protocol => "http"}
to
config.action_mailer.default_url_options = { :host => 'domainname', :protocol => "https"}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing parameter to load data from DB after login with Django Auth App I am new user of Django.
I want to use the built in Django Auth app for secure login. However, once a user logs in, based upon the username, I want to load it's data on the first page (lets call it welcome or home page). If I write my own login, I get stuck with URLs. All my pages become http://127.0.0.0.1:8000/login/..... I don't know where this /login/ comes from (it's written in settings file but who calls it I don't know) so after losing hope, I went for Auth login again.
I am sure there is a nice and easy way to retrieve the username but where should I write this code? in the login view of Auth app? would then that code will become part of my application?
A: Information about the user that's currently logged in is stored in the request.user object (request being the first parameter of every view function). request.user is an instance of the User class from django.contrib.auth. So, you can pass the user object to your templates and make all the information about the logged in user avalable that way (user.username, user.email, etc).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does -[NSURL length]: unrecognized selector sent to instance 0x1001c0360 mean I've been trying to get some example code interfaced with a Cocoa interface(It had been written using Carbon); however, when I attempted to replace
err = ExtAudioFileCreateNew(&inParentDirectory, inFileName, kAudioFileM4AType, inASBD, NULL, &fOutputAudioFile);
with
err = ExtAudioFileCreateWithURL(CFURLCreateWithString(NULL,(CFStringRef)inFileName,NULL),kAudioFileM4AType,inASBD, NULL,kAudioFileFlags_EraseFile, &fOutputAudioFile);
I started to get these exceptions
2011-09-25 10:27:31.701 tester[1120:a0f] -[NSURL length]: unrecognized
selector sent to instance 0x1001c0360
2011-09-25 10:27:31.701 tester[1120:a0f] -[NSURL length]: unrecognized selector sent to instance 0x1001c0360.
I've looked at several other questions and answers and in all of those cases the problem was related to a NSURL being passed when a NSString was expected; however, I can't find where/if I'm doing that. I've looked at the documentation and as far as I can tell with my extremely limited knowledge of Apple's APIs. I'm not doing anything wrong.
Any help would be greatly appreciated.
A: May be help you, i had same problem
I was trying to make UIImage from :
[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
Then its solved with by making string with [NSString stringWithFormat:]
NSString *urlStr =[NSString stringWithFormat:@"%@", [_photosURLs objectAtIndex:indexPath.row]];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
A: The error message is pretty clear. NSURL class does not have a -length instance method.
Have you tried to create the NSURL object with Objective-C syntax and cast it to CFURLRef?
A: I had the same issue while getting url from string like
[NSString stringWithFormat:@"%@Activity/GetBudget/%@",self.baseURL,activityID]
and I resolved it by calling absoluteString
like this
[[NSString stringWithFormat:@"%@Activity/GetBudget/%@",self.baseURL,activityID] absoluteString]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Different glob() results from local to server (Windows vs Linux) I'd like to select only files that starts with a number or a letter:
$files = glob($xsl_dir_path . "/[^a-zA-Z0-9]*.xsl");
$files = array_map('basename', $files);
There are 3 files: a.xsl, b.xsl, _functions.xsl. I don't want to select _functions.xsl file.
*
*Result: local (Windows): a.xsl, b.xsl
*Result: server (Linux): _function.xsl
A: *Edited (again) *
My bad, glob probably doesn't have regex as pattern match.
This won't work then: (?<![^/])[a-zA-Z0-9][^/]*\.xsl$
(just matches the filename.xsl preceeded with either a / or begining of string. )
However, for more control, use a glob '*.*' or something broad, then filter the list that glob produces with a regex like above. Its an extra step but will probably get uniform results across OS's
A: You are negating the class match, try:
$files = glob($xsl_dir_path . "/[a-zA-Z0-9]*.xsl");
$files = array_map('basename', $files);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with symfony2 schema yaml: unable to get relationships working I have two entities: User and Student. Following is the yaml schema:
ABC\UserBundle\Entity\User:
type: entity
table: abc_user
id:
id: { type: integer, generator: { strategy: AUTO } }
fields:
username: { type: string, length: 255, notnull: true, unique: true }
email: { type: string, length: 255, notnull: true, unique: true }
password: { type: string, length: 255, notnull: true }
enabled: { type: boolean }
ABC\UserBundle\Entity\Student:
type: entity
table: abc_student
id:
id: { type: integer, generator: { strategy: AUTO } }
fields:
first_name: { type: string, length: 255, notnull: true }
middle_name: { type: string, length: 255 }
last_name: { type: string, length: 255, notnull: true }
OnetoOne:
user:
targetEntity: ABC\UserBundle\Entity\User
My problem is that when I do "doctine:update:schema --dump-sql", user_id field is not added to the Student table and no relationship is created between the entities.
A: Yaml map is case-sensitive, use the proper name oneToOne for creating relations.
A: Your are missing the joinColumn option for the OneToOne association:
ABC\UserBundle\Entity\User:
type: entity
table: abc_user
id:
id: { type: integer, generator: { strategy: AUTO } }
fields:
username: { type: string, length: 255, notnull: true, unique: true }
email: { type: string, length: 255, notnull: true, unique: true }
password: { type: string, length: 255, notnull: true }
enabled: { type: boolean }
OnetoOne:
student:
targetEntity: ABC\UserBundle\Entity\Student
mappedBy: user
ABC\UserBundle\Entity\Student:
type: entity
table: abc_student
id:
id: { type: integer, generator: { strategy: AUTO } }
fields:
first_name: { type: string, length: 255, notnull: true }
middle_name: { type: string, length: 255 }
last_name: { type: string, length: 255, notnull: true }
OnetoOne:
user:
targetEntity: ABC\UserBundle\Entity\User
joinColumn:
name: user_id
referencedColumnName: id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image equalisation I have an image. I would like to equalize histogram using histeq. But, I want only certain portion of the image be equalized and the rest part be displayed as it is. I could display the whole image and equalized image in two different plots but I want them to be in the same image such that certain portion of the image is different.
figure
imshow(a)
figure
b = a(1:100, 1:100);
b = histeq(b)
imshow(b)
Now how do I merge both these figures into one.
A: Is the region to be equalized a(1:100, 1:100)?
If so, just set a(1:100, 1:100) = b.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: css overflow - only 1 line of text I have div with the following css style:
width:335px; float:left; overflow:hidden; padding-left:5px;
When I insert, into that div, a long line of text, it's breaking to a new line and displays all the text. What I want is to have only one line of text that will not line-break. When the text is long, I want this overflowing text to disappear.
I was thinking about setting the height but it seems to be wrong.
Maybe if I add height that is the same as the font, it should work and not cause any problems in different browsers?
How can I do that?
A: If you want to indicate that there's still more content available in that div, you may probably want to show the "ellipsis":
text-overflow: ellipsis;
This should be in addition to white-space: nowrap; suggested by Septnuits.
Also, make sure you checkout this thread to handle this in Firefox.
A: I was able to achieve this by using the webkit-line-clamp and the following css:
div {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
A: width:200px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
Define width also to set overflow in one line
A: You can use this css code:
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
The text-overflow property in CSS deals with situations where text is clipped when it overflows the element's box. It can be clipped (i.e. cut off, hidden), display an ellipsis ('…', Unicode Range Value U+2026).
Note that text-overflow only occurs when the container's overflow property has the value hidden, scroll or auto and white-space: nowrap;.
Text overflow can only happen on block or inline-block level elements, because the element needs to have a width in order to be overflow-ed. The overflow happens in the direction as determined by the direction property or related attributes.
A: I solved it by using:
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
.txt1{width:100px;}
.txt2{width:200px;}
.mytext{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<div class="txt1 mytext">
A B C D E F G H I K L M N O P Q R S T V X Y Z
</div>
<div class="txt2 mytext">
A B C D E F G H I K L M N O P Q R S T V X Y Z
</div>
<div class="txt3 ">
A B C D E F G H I K L M N O P Q R S T V X Y Z
</div>
A: If you want to restrict it to one line, use white-space: nowrap; on the div.
A: the best code for UX and UI is
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: inherit;
A: if addition please, if you have a long text please you can use this css code bellow;
text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;
make the whole line text visible.
A: Yea, If you want it to be one line tall, use white-space: nowrap; on the div or list. Whatever you are using it for it should work.
A: I had the same issue and I solved it by using:
display: inline-block;
on the div in question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "184"
} |
Q: Moving Picture Box depending on monitor size? C# I am using a picture box in my C# application, I want it to cover a certain portion of the web browser (the username part on youtube).
I have a 21.5" monitor and this is what it looks like to me:
But then this is what it looks like to one of my users with a 24" monitor:
As you can see the position of the picture box has moved up due to that persons screen size (I believe)
Is there a way to make sure that it will always be over that section of the web browser or moving it to that section of the web browser?
Thanks.
A: I am convinced your approach is wrong and would break anytime either for screen resolution or size changes, or for using the mouse-wheel to zoom in/out the page or whatever. it is just unreliable and patching this by overlapping another UI control like a picture box or a panel on top of what you want to hide is simply insecure and unreliable.
I think the tow real options you have are these:
*
*You try to interpret the page content and remove from the page's DOM the information you do not want to show to the user (eventually HTML Agility Pack could help for this DOM parsing and manipulation but I am not sure if you can read what the WebBrowser control is showing and inject changes into it);
*use the YouTube APIs and Tools - .NET APIs to load the videos and details you want to load and show but rendering this information with your specific UI elements in your windows forms application, without using a browser to show the normal YouTube site.
Probably the second option takes more work but is more secure, I am not sure 100%, as I said, if the first option is viable at all. You could search for HTML Agility Pack and web browser control to see if anybody has done this before already :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sorting string array in Java There is an example in my textbook for how to sort string arrays, but I am having a hard time understanding the logic of the code. We have the following array:
String[] words = {"so", "in", "very", "every", "do"};
The method itself is as follows:
public static void sortArray(Comparable[] compTab) {
for (int next=1; next < compTab.length; next++) {
Comparable value = compTab[next];
int this;
for (this = next; this > 0 && value.compareTo(compTab[this-1]) < 0; this--) {
compTab[this] = compTab[this-1];
}
compTab[this] = value;
writeArray(next + " run through: ", compTab);
}
}
This last writeArray call results in the following text being printed for first run through: "1. run through: in so very every do"
OK. Like I said, I have some problems with the logic in this code. If we go through the loop for the first time, this is what I see happening:
*
*We have: Comparable value = compTab[1]. This means that value = "in".
*We start the inner loop with this = next (which == 1). Thus, Java will only go through the inner loop once. It turns out that for this first run value.compareTo(compTab[this-1]) is indeed less than 0. Thus we have: compTab[1] = compTab[0]. This means that the word that used to be in position [1] is now replaced with the word that used to be in position [0]. Thus, we now have the word "so" in position [1] of the array.
*The next step in the method is: compTab[this] = value. This is where I get confused. This tells me that since this = 1, we here get compTab[1] = value. However, earlier in the method we defined value = "in". This tells me that position [1] in the array yet again assumes the word "in".
*The way I see this, the final print out should then be:
"1. run through: so in very every do".
In other words, the way I follow the logic of the code, the final print out of the array is just the same as it was before the method was implemented! Clearly there is some part of my logic here which is not correct. For instance - I don't see how the word that used to be in position [1] is now in position [0]. If anyone can help explain this to me, I would be extremely grateful!
A: The issue is within the following statement:
The next step in the method is: compTab[this] = value. This is where I
get confused. This tells me that since this = 1, we here get
compTab[1] = value. However, earlier in the method we defined value =
"in". This tells me that position [1] in the array yet again assumes
the word "in".
Since you ran through the loop once (see your statement 2), also the this-- was executed once and therefore this==0.
A: public class A {
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
public static void main(String[] args)
{
for(int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if(Array[i].trim().compareToIgnoreCase(Array[j].trim())<0)
{
String temp= Array[j];
Array[j]= Array[i];
Array[i]=temp;
}
}
System.out.print(Array[j]);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ For loop problem I have a loop that takes two inputs, a last name and an ID, then converts it to a user id. The code looks like this:
void User::setUserid(string ln, string id){
string temp = "0";
string temp2 = "0";
for (int k = 0; k < 6; k++){
temp += ln[k];
}
for (int i = id.length()-2; i<id.length(); i++){
temp2 += id[i];
}
userid = temp+temp2;
}
For some reason if I comment out the first for loop it will compile and build. Any ideas why the code crashes?
A: Is ln guaranteed to have at least six characters? You may be shooting past the end of the string.
In any event, you've chosen a slow and complicated way to copy parts of strings around. This should suffice:
void User::setUserid(string ln, string id){
userid = "0" + ln.substr(0, 6) + "0" + id.substr(id.size() - 2);
}
Note that this will produce a shorter userid if ln.size() < 6 and throw out_of_range if id.size() < 2.
A: The string ln might have less characters than 6 - ln[k] will be out of bounds.
Note that the code will crash if the id string contains less then two characters (i will be negative).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What exactly is a monkey doing messing with my Android phone? Looking through the Android apis I found a method call isUserAMonkey(),
says it returns true if the phone is being messed with by a monkey.
Is this a joke, or what is it used for?
A: Look at monkeyrunner, it will give you the answer.
Quote from the document:
The monkeyrunner tool provides an API for writing programs that
control an Android device or emulator from outside of Android code.
With monkeyrunner, you can write a Python program that installs an
Android application or test package, runs it, sends keystrokes to it,
takes screenshots of its user interface, and stores screenshots on the
workstation. The monkeyrunner tool is primarily designed to test
applications and devices at the functional/framework level and for
running unit test suites, but you are free to use it for other
purposes.
So if you are running a package using Monkeyrunner, then this function will return true.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: how to put search functionality in dataGridView in vb.NET How can I select a single cell from selected row in datagridView and after selecting that I want to put simple search functionality (like we have in our windows folders-typing any characters and search should work)?
A: I do not really understand your question. If you want to select one cell, you can use the celldoubleclick event for exemple. And the to get the selected cell, use e.rowindex and e.columnindex which will give you the row and the column where the cell is located.
A: You can try this as a possible solution.
Dim nwData as CustomersDataSet = CustomersDataSet.GetCustomers()
m_CustomersGrid.DataSource = m_CustomersBindingSource
m_CustomersBindingSource.DataSource = nwData.Customers
Then you can sort using the BindingSource.
CustomersBindingSource.Sort = "ContactName ASC"
And you can find using the BindingSource.
Dim index as integer = _
CustomersBindingSource.Find("CompanyName", CompanyNameTextBox.Text)
If index <-1 then 'it was found; move to that position
CustomersBindingSource.Position = index
End If
You could then populate:
CustomersBindingSource.Find("CompanyName", CompanyNameTextBox.Text)
with the keys pressed in the cell by capturing them by utilizing:
Private Sub DataGridView1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyUp
Dim dgv As DataGridView = TryCast(sender, DataGridView)
If dgv IsNot Nothing Then
'You will need some logic here to determine how long to wait between keyups
'Perhaps a timer that ticks every500 milliseconds and reset on keyup.
e.KeyData
End If
End Sub
I found the original Biding Source Logic at : This Location
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can Google's Dart get better performance? I've read the article about Google's upcoming DASH/DART language, which I found quite interesting.
One thing I stumbled upon is that they say they will remove the inherent performance problems of JavaScript. But what are these performance problems exactly? There aren't any examples in the text. This is all it says:
*
*Performance -- Dash is designed with performance characteristics in
mind, so that it is possible to create VMs that do not have the performance
problems that all EcmaScript VMs must have.
Do you have any ideas about what those inherent performance problems are?
A: This thread is a must read for anyone interested in dynamic language just in time compilers:
http://lambda-the-ultimate.org/node/3851
The participants of this thread are the creator of luajit, the pypy folks, Mozilla's javascript developers and many more.
Pay special attention to Mike Pall's comments (he is the creator of luajit) and his opinions about javascript and python in particular.
He says that language design affects performance. He gives importance to simplicity and orthogonality, while avoiding the crazy corner cases that plague javascript, for example.
Many different techiques and approaches are discussed there (tracing jits, method jits, interpreters, etc).
Check it out!
Luis
A: The article is referring to the optimization difficulties that come from extremely dynamic languages such as JavaScript, plus prototypal inheritance.
In languages such as Ruby or JavaScript, the program structure can change at runtime. Classes can get a new method, functions can be eval()'ed into existence, and more. This makes it harder for runtimes to optimize their code, because the structure is never guaranteed to be set.
Prototypal inheritance is harder to optimize than more traditional class-based languages. I suspect this is because there are many years of research and implementation experience for class-based VMs.
Interestingly, V8 (Chrome's JavaScript engine) uses hidden classes as part of its optimization strategy. Of course, JS doesn't have classes, so object layout is more complicated in V8.
Object layout in V8 requires a minimum of 3 words in the header. In contrast, the Dart VM requires just 1 word in the header. The size and structure of a Dart object is known at compile time. This is very useful for VM designers.
Another example: in Dart, there are real lists (aka arrays). You can have a fixed length list, which is easier to optimize than JavaScript's not-really-arrays and always variable lengths.
Read more about compiling Dart (and JavaScript) to efficient code with this presentation: http://www.dartlang.org/slides/2013/04/compiling-dart-to-efficient-machine-code.pdf
Another performance dimension is start-up time. As web apps get more complex, the number of lines of code goes up. The design of JavaScript makes it harder to optimize startup, because parsing and loading the code also executes the code. In Dart, the language has been carefully designed to make it quick to parse. Dart does not execute code as it loads and parses the files.
This also means Dart VMs can cache a binary representation of the parsed files (known as a snapshot) for even quicker startup.
A: One example is tail call elimination (I'm sure some consider it required for high-performance functional programming). A feature request was put in for Google's V8 Javascript VM, but this was the response:
Tail call elimination isn't compatible with JavaScript as it is used in the real
world.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: javascript/html: Replacing embedded videos memory leak? I was wondering how to best replace embedded videos on a webpage. I have a bunch of video files (avi) that a visitor will be able to select and watch.
I am pretty new to javascript and html, but what I am currently doing is embedding the videos on the webpage as objects, and when a new video is selected, I change the url param for the object. This changes the video correctly, however after a few videos the browser becomes unresponsive. Looking at the task manager, the memory usage goes up with each video opened.
I originally thought that since the object has the same id, it would delete the first video and load the next. However, it seems like the first video is still in memory. Is there a better way to do this?
I am using using Windows 7, Windows Media Player 12, IE8. I am also wondering if this could be related to these technologies, because it doesn't seem to leak memory when I run this on my older PC (Windows XP, WMP 9, IE8).
Here is basically what I am doing:
Video tags in html:
<object width="100%" height="100%" id="video"
classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param name="url" value="video1.avi">
<param name="autostart" value="1">
<param name="uiMode" value="full" />
</object>
Then when a user selects a new video (javascript - assume newVideoPath contains the path to the next video to play):
$("video").url = newVideoPath;
Is there any memory cleanup I should be taking care of?
A: First of all I want to mention that I don't have much experience with cross-browser video embedding. Perhaps the explanations help nevertheless.
There are basically 2 ways to play video: Using the browser to play video and using a plugin.
Using a browser means that you need to serve different video files for different browsers. There are WebM or OGV for Firefox, Chrome, Opera and H264 for IE9 and Safari. IE8 and below do not support video at all.
The plugin approach has the advantage that you can serve what the plugin needs. The problem is that you never know if a plugin such as Windows Media Player, Flash or another is present at all.
This leads to the conclusion that you need to serve different media files (different file formats) to get a reasonably high probability of working videos. John Dyer's tutorial list the important steps to take – however you should additionally serve WebM before trying to use a plugin. Serving AVI files does not make much sense since this format is only a container that could contain any video and audio codecs.
<video>
<source src="myfile.mp4">
<source src="myfile.ogg">
<object src="flashplayer.swf?file=myfile.mp4">
<embed src="flashplayer.swf?file=myfile.mp4">
</object>
</video>
This code tries to serve myfile.mp4 and if that fails myfile.ogg and if that fails, too, to serve myfile.mp4 using Adobe's Flash. You can add your files with as many source tags as you have file formats available. The browser will then use the first file it understands.
The tutorial has an extended version that uses JavaScript to detect video support in the first place and adds fallbacks to Flash when necessary. You would replace the Flash part with Windows Media Player.
A word on the classid attribute: This attribute refers to a specify ActiveX control. There are 2 problems with this. ActiveX is only available on Windows and will fail on all other platforms. Since the classid specifies a specific control it will also fail for Windows systems without the very plugin implementation – so avoid such things. Therefore I would recommend to use the HTML5 approach with the video tag first and just give some files. Doing so allows browsers to choose a suitable player which increases the change of your video playing. Then a bit of JavaScript needs to be added to provide fallbacks.
Finally we end up with something similar to:
<video id="video">
<source src="myfile.webm">
<source src="myfile.mp4">
<source src="myfile.ogg">
</video>
<script type="text/javascript">
(function(){
var dummy = document.createElement("video");
// See if native video support is not available
if(typeof(video.canPlayType)===undefined || video.canPlayType('video/webm') == '' || add other video types here corresponding to source tags){
var videoElement = document.getElementById('video');
var fallbackContainer = document.createElement('div');
// Insert your HTML string for Windows Media, Flash, MPlayer or whatever else here
var fallback = '…';
fallbackContainer.innerHTML = fallback;
// This replaces the native (not available) video player with the plugin
videoElement.parentNode.replaceChild(fallbackContainer, videoElement);
}
})();
</script>
You could also use something like MediaElement.js and save yourself from handling all the different environments yourself.
Now, let's come back to your questions regarding memory leaks and replacing videos. If there are memory leaks caused by your script then the implementation that you are using has some serious problems. But before blaming the implementation you should make sure that a leak is really present.
Garbage collection (the process of freeing memory) takes time and is thus done at “suitable” times and not as soon as possible. So it could well be that your browser (or plugin) cleans up but only after some time or when memory is low. You would then see increasing memory whenever you change the video but this would not be a leak because it would be cleaned up eventually. Try to trigger the garbage collection by changing the video a lot of times until you run out of memory – does a cleanup happen? Try changing tabs in your browser or closing a tab – does a cleanup happen? If you've seen a cleanup now, there is probably no leak to worry about. The implementation just thinks your test case did not need freeing of memory.
In case you found it is really a leak you could try to detach to video an use a new video instead of replacing the old video. To do so, use the same approach as before:
var oldVideoElement = document.getElementById('video');
// Add some video element creation here for the new video
var newVideoElement = …;
// Replace video but make the browser aware of the replacement by using DOM methods
oldVideoElement.parentNode.replaceChild(newVideoElement, oldVideoElement);
// Get rid of the reference to the old video (just in case IE8 has still problems with discarding references)
var oldVideoElement = null;
Using the DOM methods allow the browser to remove the plugins entirely from memory. With a bit of luck your leak is now gone. Use the same technique to switch between your files by creating a new video and use it to replace the old video (the whole element, not just the file name).
If this did not help you need to provide more information: Which operating systems and browsers are you targeting? Do you know that a specific plugin is present? What video and audio codecs are within your AVI files?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Running a "rundll32.exe" process at Win7 Logon, Lock, & Switch User screens? Before I start, another post for something similar to this request for help is located at Running a process at the Windows 7 Welcome Screen, but the responses were not quite what I believe I am looking for, and the post is over a year old so I thought it best to start a new thread for my needs.
In Windows 7 Ultimate, I am trying to create a script or task scheduler event that will run a Windows "rundll32.exe" process with arguments at the logon, lock, and switch user screens (basically any screen that is waiting for user to log into the machine).
I have tried using the startup script controls in group policy editor as well as creating a task scheduler event, but so far I am unable to get the process to display on the logon screens.
The command line I am using does work while logged into any account at any user level via the "Run.." dialog as well as via CMD prompt, and is only creating a popup that already exists in the Windows OEM Environment.
The hardest part is this: My friend just bought a new laptop. The new laptop came with this specific feature already enabled, but I have no idea what is making it happen and do not have access to the computer to check out gpedit.msc and task scheduler for possible solutions.
There are two reasons why I need this info: 1) I want the feature to work on my own laptop, and 2) my friend would like help disabling it on his as he doesn't like it.
I have been all over Google, posted at Microsoft Answers, and also posted on the laptop manufacturer's user forums. I have found very few pages that refer to the same question as I have, but none have answers that work, and since I have seen and know that this is possible, I am compelled to continue looking.
The laptop that this is currently working on was purchased with a fresh install of Win 7 Ultimate and no manufacturer bloatware/additional software added, so we know that the feature was made to happen by whomever it was that installed the OS and configured it for sale. Therefore I am certain it is just a matter of the right task or script in Windows itself before I see the results I need and then know how to direct my friend to disable his via phone.
The specific call is "rundll32.exe van.dll,RunVAN". In task scheduler I have set this to run as "SYSTEM" and set the triggers for startup, workstation lock, and local disconnect. I have tried using full path to rundll32.exe as well as the bare command. In gpedit startup scripts I have tried full path and bare command. Neither of which for either case is making this popup show on the logon screens.
Any and all help and/or advice on this would be greatly appreciated by both myself and my friend.
A: dynamic display of images for the credential provider
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use a header function in 'int main'? I am working on a project that has a class (Time) defined in a header file and the objective is to use that class in my main function to determine the difference between two times. I have gone over this is class and yet cannot wrap my head around the concept of using the class that has been defined for me and using it's accessor functions in main.
I will post the header and what I have done so far and hopefully somebody can clarify what I need to do because I understand the objective and what I need to do to accomplish it but I just cannot seem to translate that into usable code... Hopefully someone can put this in terms comprehensible to an novice programmer like myself better than both my teacher and my text.
Header:
#ifndef CCC_TIME_H
#define CCC_TIME_H
/**
A class that describes a time of day
(between 00:00:00 and 23:59:59)
*/
class Time
{
public:
/**
Constructs a time of day.
@param hour the hours
@param min the minutes
@param sec the seconds
*/
Time(int hour, int min, int sec);
/**
Constructs a Time object that is set to
the time at which the constructor executes.
*/
Time();
/**
Gets the hours of this time.
@return the hours
*/
int get_hours() const;
/**
Gets the minutes of this time.
@return the minutes
*/
int get_minutes() const;
/**
Gets the seconds of this time.
@return the seconds
*/
int get_seconds() const;
/**
Computes the seconds between this time and another.
@param t the other time
@return the number of seconds between this time and t
*/
int seconds_from(Time t) const;
/**
Adds a number of seconds to this time.
@param s the number of seconds to add
*/
void add_seconds(int s);
private:
int time_in_secs;
};
#endif
___________________
using namespace std;
int main()
{
int t;
string x;
cout<< "This program will test your typing speed."<< endl;
cout<< "Type the following:"<<endl;
cout<<" "<<endl;
cout<< "The quick brown fox jumped over the lazy dog"<< endl;
Time startTime;
getline(cin, x, '\n');
if(x == "The quick brown fox jumped over the lazy dog")
{
Time endTime;
int durationInSeconds = endTime.seconds_from(startTime);
t = durationInSeconds;
}
else{cout<<"Invalid text entered";}
cout<<"You finished in: " << t << "seconds." endl;
system ("pause");
return 0;
}
A: You're having some trouble with your object declarations for instances of Time, I gather. I'll admit that the C++ syntax fouls me up sometimes, but I think you need to replace the void Time(int hour, int min, int sec); with something like Time startTime;, and replace time_t now(); with something like Time stopTime;.
Then do int durationInSeconds = stopTime.seconds_from(startTime); and report durationInSeconds as the time spent typing.
A: Ok if I understand your question,what you should do is add an include at the top of your c class, so for this case you will add
#include "cccTime.h"
(or whatever the file name is, use "" and not <> as you normally use for includes)
and then you can call the methods, as you always do
A: You don't need to know what time it is. Just use the default constructor. The default constructor "Constructs a Time object that is set to the time at which the constructor executes." This makes it very easy to time how long something takes:
Time start_time;
do_lots_of_stuff ();
Time end_time;
Now you can use end_time.seconds_from(start_time) to determine how much time elapsed from start to finish.
A: #include<iostream>
#include<string>
#include "ccc_time.h"
using namespace std;
int main()
{
//Time start_time;
string x;
const string SAMPLE = "The quick brown fox jumped over the lazy dog";
cout<< "This program will test your typing speed."<< endl;
cout<< "Type the following:"<<endl;
cout<<" "<<endl;
cout<< SAMPLE << endl;
getline(cin, x, '\n');
//Time end_time;
if(x.compare(SAMPLE) == 0)
{
//int res = 0;
//res = end_time.seconds_from(start_time);
//cout << res << endl;
//return res;
} else {
cout << "Invalid text entered" << endl;
}
return 0;
}
Am I right?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get a Boolean value for whether an Object partially matches (Java) I think this is an easy question, if I could figure out search terms to describe it. It's similar to Finding all objects that have a given property inside a collection except I just want a Boolean "is it there" result.
Say I have a sorted TreeSet of Cats, each of which has a name, age, food, etc. I have something complicated to do for each potential cat name, but I want to skip it if there already a cat in my TreeSet with that name. I don't care if any of the other attributes match. I obviously can't do if (!AlltheCats.contains(candidateName))... because then I'll have a type mismatch between the string candidateName and the object Cat. But I don't think I can create an object to search for an identical match to, because I don't care about the values for age, food, etc.
What would be an efficient/elegant way to do this?
A: Create a HashSet of Strings containing names, every time you invoke your method on a cat, check first if it is already in the set, and if it is, skip this cat. Modify this set as you keep going.
(*)This answer assumes you want to invoke the method for one cat [and not 0] with identical name.
Should look something like that:
Set<String> names = new HashSet<String>();
for (Cat c : set) {
if (names.contains(c.getName())) {
continue;
}
names.add(c.getName());
c.foo(); //your method here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding description to RestEasy's web service parameters? Is there some way/annotation by which I can add the description to the parameters of a RestEasy web service? I went through the api-doc of the annotations, but found nothing there.
This is in order to add the descriptions so that they are reflected in the REST API documentation which I'll be auto-generating using some tool.
An example web service interface:
@Path("list-all")
@GET
@RBAC(type = { CRUDEnum.READ }, capability = { "PowerUser" })
@ParseContext
@Produces( {
"application/json",
"application/xml"})
public net.myapp.services getAllDevices(
@QueryParam("start") int param0, @QueryParam("limit") int param1);
A: Found the way for this. There is no REST annotation to add the parameter description.
The solution for this is to use the typical java-doc annotation.
e.g.
/**
* @param param0 Paging parameter
* @param param1 Paging parameter
* */
@Path("list-all")
@GET
@RBAC(type = { CRUDEnum.READ }, capability = { "PowerUser" })
@ParseContext
@Produces( {
"application/json",
"application/xml"})
public net.myapp.services getAllDevices(
@QueryParam("start") int param0, @QueryParam("limit") int param1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to extend WhitespaceTokenizer? I need to use a tokenizer that splits words on whitespace but that doesn't split if the whitespace is whithin double parenthesis. Here an example:
My input-> term1 term2 term3 ((term4 term5)) term6
should produce this list of tokens:
term1, term2, term3, ((term4 term5)), term6.
I think that I can obtain this behaviour by extending Lucene WhiteSpaceTokenizer. How can I perform this extension?
Is there some other solutions?
Thanks in advance.
A: I haven't tried to extend the Tokenizer, but i have here a nice (i think) solution with a regular expression:
\w+|\(\([\w\s]*\)\)
And a method that split a string by matched groups from the reg ex returning an array. Code example:
class Regex_ComandLine {
public static void main(String[] args) {
String input = "term1 term2 term3 ((term4 term5)) term6"; //your input
String[] parsedInput = splitByMatchedGroups(input, "\\w+|\\(\\([\\w\\s]*\\)\\)");
for (String arg : parsedInput) {
System.out.println(arg);
}
}
static String[] splitByMatchedGroups(String string,
String patternString) {
List<String> matchList = new ArrayList<>();
Matcher regexMatcher = Pattern.compile(patternString).matcher(string);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
return matchList.toArray(new String[0]);
}
}
The output:
term1
term2
term3
((term4 term5))
term6
Hope this help you.
Please note that the following code with the usual split():
String[] parsedInput = input.split("\\w+|\\(\\([\\w\\s]*\\)\\)");
will return you nothing or not what you want beacuse it only check delimiters.
A: You can do this by extending WhitespaceTokenizer, but I expect it will be easier if you write a TokenFilter that reads from a WhitespaceTokenizer and pastes together consecutive tokens based on the number of parentheses.
Overriding incrementToken is the main task when writing a Tokenizer-like class. I once did this myself; the result might serve as an example (though for technical reasons, I couldn't make my class a TokenFilter).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery qTip2 not displaying or linking properly I'm using jQuery qTip2 for tooltips in my Rails app. I want the tooltip to display a link, but I can't get that (or the tooltip itself) to show properly.
Here's my application.js qTip jQuery:
$(document).ready(function() {
$('.article span[alt]').qtip({
position: {
my: 'bottom center',
at: 'bottom center'
},
hide: {
fixed: true
},
style: {
width: 200
}
});
});
My html.erb to show the tooltip:
<li class="article"><span alt=<%= link_to article.name, article_path %>>
<%= article.body %>
</span></li>
And my header:
<link href="/stylesheets/jquery.qtip.css?1316753274" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/jquery.qtip.min.css?1316753274" media="screen" rel="stylesheet" type="text/css" />
<script src="/javascripts/jquery.js?1316133561" type="text/javascript"></script>
<script src="/javascripts/application.js?1316962938" type="text/javascript"></script>
<script src="/javascripts/jquery.qtip.js?1316753274" type="text/javascript"></script>
<script src="/javascripts/jquery.qtip.min.js?1316753274" type="text/javascript"></script>
EDIT - Here's the HTML that shows:
<li class="article"><span alt=<a href="/articles/2">Article Name</a>>
Testing
</span></li>
The goal is that hovering over testing shows the tooltip link "Article Name", which takes you to the article.
Can anyone help me fix this?
A: You are including the qTip2 JavaScript twice...
<script src="/javascripts/jquery.qtip.js?1316753274" type="text/javascript"></script>
<script src="/javascripts/jquery.qtip.min.js?1316753274" type="text/javascript"></script>
You only need one instance of qTip2; pick one to keep and remove the other one.
You are also including the qTip2 CSS file twice but, if identical, this would not cause a major problem... it's just wasteful and redundant. Remove one...
<link href="/stylesheets/jquery.qtip.css?1316753274" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/jquery.qtip.min.css?1316753274" media="screen" rel="stylesheet" type="text/css" />
EDIT:
This is not even close to being valid HTML...
<span alt=<a href="/articles/2">Article Name</a>>Testing</span>
*
*The alt attribute need to be followed by text within quotation marks. alt="my alternate text"
*You cannot use the alt tag without the quotation marks and AFAIK, you cannot put HTML within the alt attribute.
http://www.w3.org/QA/Tips/altAttribute
This might work...
<span alt="<a href='\/articles\/2'>Article Name<\/a>">Testing</span>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically creating a new user on Mac OS using Objective-C or any Cocoa API? I'm trying to create new user within my Application. I know that is possible using dscl and NSTask.But does anyone know how it is possbile to do with any Cocoa API , or programmaticaly using objective-c? within code , not using bash commands , like here
sudo niutil -create / /users/newuser
sudo niutil -createprop / /users/newuser uid 502
sudo niutil -createprop / /users/newuser gid 502
sudo niutil -createprop / /users/newuser realname "Longer Name"
sudo niutil -createprop / /users/newuser home "/Users/newuser "
sudo niutil -createprop / /users/newuser shell "/bin/tcsh"
sudo niutil -createprop / /users/sharedDir shell "Public"
sudo niutil -createprop / /users/newuser passwd "*"
sudo passwd newuser
sudo ditto /System/Library/User\ Template/English.lproj /Users/newuser
sudo chown -R newuser :group /Users/newuser
I was told that is possible to do using Open Directory Framework, but couldn't find usefull documentation. Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Pass data from popup to the opening form in rails 3.1 and jQuery I have a form to create a new post and inside this form I have a button that opens a popup form that create a new client.
The popup is a jquery dialog.
I want to do 2 things when I close the popup:
1) save the new client in the database.
2) re-render the select-box in the post form so the new client will be added to the selected box and be selected.
I'm new in the web world (JavaScript, Ajax, rails), so if anyone can please help me and tell me how to do this I'll be so grateful!! (I've spend more then 3 days for searching a solution)
BTW, I'm using rails 3.1
A: Try out http://defunkt.io/facebox/ to open popup & it will get closed after saving form
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OAuth 2.0 cookie not set with FB.ui on Page tab I am using FB.ui to authorize with application Facebook tab using simple:
FB.init({
appId : '<%= Facebook::APP_ID %>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://<%= request.host_with_port %>/channel.html', // Custom Channel URL
oauth : true //enables OAuth 2.0
});
FB.ui({
method: 'oauth'
},
function(response) {
// do some redirect stuff here
});
Authorization goes fine, but even when user confirms the application, the relevant fbsr_xxxxx cookie is not set. Is there any way to force it? Response object contains user_id, but I would rather use the standard flow with signed_request.
A: I'm having the exact same issue. There seems to be no way to get the access token without refreshing the page other than using FB.login, which pops out a new window.
What you may want to do is make an ajax call to another page to return the access token after the FB.ui response:
FB.ui({
method: 'oauth'
},
function(response) {
if(response.session){
$.get('return_token.php', function(response){
var access_token = response;
alert(access_token);
})
}
});
return_token.php:
<?
$config = array(
'appId' => $app_id,
'secret' => $secret
);
$facebook = new Facebook($config);
try {$access_token = $facebook->getAccessToken();}catch(FacebookApiException $e) {
$result = $e->getResult();
echo json_encode($result);
}
echo $access_token;
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ERROR/LocationManagerService(64): java.lang.IllegalArgumentException: provider=network I am create a simple web service.
but it generate an error like that shown below
09-25 20:42:56.732: ERROR/LocationManagerService(64): requestUpdates got exception:
09-25 20:42:56.732: ERROR/LocationManagerService(64): java.lang.IllegalArgumentException: provider=network
09-25 20:42:56.732: ERROR/LocationManagerService(64): at com.android.server.LocationManagerService.requestLocationUpdatesLocked(LocationManagerService.java:861)
09-25 20:42:56.732: ERROR/LocationManagerService(64): at com.android.server.LocationManagerService.requestLocationUpdates(LocationManagerService.java:831)
09-25 20:42:56.732: ERROR/LocationManagerService(64): at android.location.ILocationManager$Stub.onTransact(ILocationManager.java:79)
09-25 20:42:56.732: ERROR/LocationManagerService(64): at android.os.Binder.execTransact(Binder.java:287)
09-25 20:42:56.732: ERROR/LocationManagerService(64): at dalvik.system.NativeStart.run(Native Method)
java and XML code is shown below
package com.webview;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebApplicationActivity extends Activity {
WebView webView1,webView2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView1 = (WebView) findViewById(R.id.webView1);
webView1.loadUrl("http://google.com");
// webView2 = (WebView) findViewById(R.id.webView2);
// webView2.loadData("<html><head></head><body>Hello</body></html>", "text/html", null);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.webkit.WebView android:layout_width="fill_parent"
android:id="@+id/webView1" android:layout_height="300dp"
android:layout_weight="1"></android.webkit.WebView>
<!-- <android.webkit.WebView android:id="@+id/webView2"
android:layout_width="fill_parent" android:layout_height="300dp"
android:layout_weight="1">
</android.webkit.WebView> -->
</LinearLayout>
A: Your error comes from the location manager module trying to get the user current location from the cellular network, not from the code you posted.
A: check you this code
WebView mWebView = (WebView) findViewById(R.id.webview);
mWebView.setSaveFormData(false);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
In the xml file. there should be webview id.
android:id="@+id/webview"
It is also necessary to put this permission on AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
In the HelloAndroid Activity, add this nested class:
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Then towards the end of the onCreate(Bundle) method, set an instance of the HelloWebViewClient as the WebViewClient:
mWebView.setWebViewClient(new HelloWebViewClient());
if you want more about webView click this link1, link2 and link3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CultureInfo for Latin language I develop an app for working with multi-language resources.
In database, when I need colomn with language identifier, I use language LCID.
Now I need to add new language - Latin. It's LCID - 1142. But when I try to create new CultureInfo(1142) - exception thrown.
Is there any way to solve this problem? Somehow add Latin language to CultureInfo available languages.
Thank you for your answers.
A: I don't believe that is possible. Latin is not supported as a culture.
The .NET Framework has specific functionality for creating custom cultures, but you don't get to decide the LCID. The LCID is always 0x1000 for a custom culture.
For replacement cultures the culture identifier is mapped to the corresponding National Language Support (NLS) locale identifier. For user-defined custom cultures, the value of this property is always hexadecimal 0x1000.
Reference
You may be better off storing the name of the culture in the database, instead of the LCID. This would allow you to load custom cultures since they are always loaded by name. Once that is done, you can proceed to create your own culture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Get the contents after logging In in Java I want to login to a site(yahoo mail - https://login.yahoo.com/config/login?.src=fpctx&.intl=us&.done=http%3A%2F%2Fwww.yahoo.com%2F)
using HttpClient and after logging in I want retrieve the contents. (java). what's wrong with my code?
public class TestHttpClient {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.yahoo.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "Yahoo! ID"));
nvps.add(new BasicNameValuePair("IDToken2", "Password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
System.out.println("Response "+response.toString());
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str ="";
while ((str = br.readLine()) != null){
System.out.println(""+str);
}
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
httpclient.getConnectionManager().shutdown();
}
}
when I print the output from HttpEntity it's printing the login page contents. How do I get the contents of the page after I login using HttpClient?
A: If you see the yahoo login source page, you'll see that there are many other parameters you are not sending in your request.
<input type="hidden" name=".tries" value="1">
<input type="hidden" name=".src" value="fpctx">
<input type="hidden" name=".md5" value="">
<input type="hidden" name=".hash" value="">
<input type="hidden" name=".js" value="">
<input type="hidden" name=".last" value="">
<input type="hidden" name="promo" value="">
<input type="hidden" name=".intl" value="us">
<input type="hidden" name=".bypass" value="">
<input type="hidden" name=".partner" value="">
<input type="hidden" name=".u" value="a0bljsd77uima">
<input type="hidden" name=".v" value="0">
<input type="hidden" name=".challenge" value="sCm6Z8Bv1vy78LBlEd8dnFsmbit1">
<input type="hidden" name=".yplus" value="">
...
I suppose that is the reason why Yahoo understands the login has failed and sends you to the login page again. That login page is what you see as the response.
Many sites try to avoid programmatic logins (to avoid bots or other security issues), so it could be hard to do what you are trying. You could:
*
*Use official Yahoo public APIs, when possible.
*Try to use other Java libraries that simulates the user browsing (such as HTTPUnit or HtmlUnit, there are many others) and "fake" the user as if he was navigating Yahoo pages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get the REST response message in ExtJs 4? I'm building upon RESTFul Store example of ExtJs 4. I'd like my script to display errors provided by the REST server, when either Add or Delete request fails. I've managed to obtain the success status of a request (see the code below), but how do I reach the message provided with the response?
Store:
var store = Ext.create('Ext.data.Store', {
model: 'Users',
autoLoad: true,
autoSync: true,
proxy: {
type: 'rest',
url: 'test.php',
reader: {
type: 'json',
root: 'data',
model: 'Users'
},
writer: {
type: 'json'
},
afterRequest: function(request, success) {
console.log(success); // either true or false
},
listeners: {
exception: function(proxy, response, options) {
// response contains responseText, which has the message
// but in unparsed Json (see below) - so I think
// there should be a better way to reach it than
// parse it myself
console.log(proxy, response, options);
}
}
}
});
Typical REST response:
"{"success":false,"data":"","message":"VERBOSE ERROR"}"
Perhaps I'm doing it all wrong, so any advice is appreciated.
A: I assume that your service follows the REST principle and uses HTTP status codes other than 2xx for unsuccessful operations.
However, Ext will not parse the response body for responses that do not return status OK 2xx.
What the exception/response object (that is passed to 'exception' event listeners) does provide in such cases is only the HTTP status message in response.statusText.
Therefore you will have to parse the responseText to JSON yourself. Which is not really a problem since it can be accomplished with a single line.
var data = Ext.decode(response.responseText);
Depending on your coding style you might also want to add some error handling and/or distinguish between 'expected' and 'unexpected' HTTP error status codes. (This is from Ext.data.reader.Json)
getResponseData: function(response) {
try {
var data = Ext.decode(response.responseText);
}
catch (ex) {
Ext.Error.raise({
response: response,
json: response.responseText,
parseError: ex,
msg: 'Unable to parse the JSON returned by the server: ' + ex.toString()
});
}
return data;
},
The reason for this behavior is probably because of the REST proxy class not being a first class member in the data package. It is derived from a common base class that also defines the behavior for the standard AJAX (or JsonP) proxy which use HTTP status codes only for communication channel errors. Hence they don't expect any parsable message from the server in such cases.
Server responses indicating application errors are instead expected to be returned with HTTP status OK, and a JSON response as posted in your question (with success:"false" and message:"[your error message]").
Interestingly, a REST server could return a response with a non-2xx status and a response body with a valid JSON response (in Ext terms) and the success property set to 'true'. The exception event would still be fired and the response body not parsed.
This setup doesn't make a lot of sense - I just want to point out the difference between 'success' in terms of HTTP status code compared to the success property in the body (with the first having precedence over the latter).
Update
For a more transparent solution you could extend (or override) Ext.data.proxy.Rest: this will change the success value from false to true and then call the standard processResponse implementation. This will emulate 'standard' Ext behavior and parse the responseText. Of course this will expect a standard JSON response as outlined in your original post with success:"false" (or otherwise fail).
This is untested though, and the if expression should probably be smarter.
Ext.define('Ext.ux.data.proxy.Rest', {
extend: 'Ext.data.proxy.Rest',
processResponse: function(success, operation, request, response, callback, scope){
if(!success && typeof response.responseText === 'string') { // we could do a regex match here
var args = Array.prototype.slice.call(arguments);
args[0] = true;
this.callParent(args);
} else {
this.callParent(arguments);
}
}
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How to get value of the slider, when touchend or mouseup events are used? $('.ui-slider-handle').live('touchend', function(){
// how can I get slider's value here?
});
$('.ui-slider-handle').live('mouseup', function(){
// and here?
});
I don't want to use .change since it is called even when sliders are moving.
A: You could just use the event stop
http://jqueryui.com/demos/slider/#event-stop
A: Well, it's fairly simple to get the current value of a slider:
$('.ui-slider-handle').live('mouseup', function() {
var value = $(this).closest('.ui-slider').slider('value');
});
You'll have to experiment with this though, because I've found that often this is not the most-up-to-date value (it's usually one click less than the actual final value).
What you REALLY want to do is use the slidestop event built-in to the slider widget, but of course right now it is not supporting touchend for some reason. (Along with a few other issues on touch devices.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: On start-up of google tv, show live tv? Start service on boot? I am pretty new at android development and am working on an android app for google tv. my current hurdle is that i want to start the Live TV app as soon right after the GTV starts.
I am thinking that it would be a Service that loads on startup that tells the Live TV app to start, but i don't know if a Service at startup is possible, nor do i know how to target the Live TV app.
any ideas or suggestions?
A: My workaround was to make LiveTV be the start up application (Set up in the Google TV UI). Then, I set my service to start on boot, explained here.
http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/
A: A user can set the startup application from the UI. If setting LiveTV to be the startup app isn't enough (it's the default), you can have your app start, then launch Live TV.
You can also have services that start at launch do it, just as you can on any Android platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is Spring MVC so called, when it is not an MVC framework? MVC describes when the Observer pattern is used to allow a model to notify the views about changes.
This is not how Spring MVC works.
Spring MVC is a Model2 framework because it doesn't notify the views from the model - the controller simply passes the model data to the views and performs the html generation.
So why is it called "Spring MVC"?
A: Observers are not necessary in MVC--how the view gets updated is implementation-specific. A controller can just tell the view to render itself, or the view can request a new rendering, which is what happens in almost all web-oriented MVC frameworks.
That said, while most web-oriented MVC frameworks are an interpretation of the original idea of MVC, they're still pretty MVC since they have the separation of components, and operate as a synchronous version of it.
A: MVC is a design pattern in which there's a view, a model and a controller. Concerning how the view updates itself on model changes, there's no particula statement saying that there should be an Observer patter there from view to model. Having the view actively re-interrogate the model in order to update itself is in accordance with the MVC spec.
Model2 is one implementation of the MVC design. This is something released by the Java EE guys (as well as Model1 which is non MVC compliant). In short, while Model one said you only had a separation between model on the one side (the beans), and view plus controller on the other (both represented by JSP pages), in the Model2 paradigm you have JSP as the view, beans as the model and servlets as the controller.
Spring-MVC is called that and not Spring-Model2 becauese model2 is something related to specific Java EE components such as servlets, JSPs and beans, while Spring-MVC encompasses more than that: the controllers are not servlets, the view can be something else besides JSP, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get Employee's Attendance History on Crystal Report I have table with the following fileds:
AttendanceID bigint
EmployeeID bigint
AttendanceDate datetime
FiscalMonthID int
TimeIn datetime
TimeOut datetime
TimeIn1 datetime
TimeOut1 datetime
HoursWorked decimal(18, 2)
LateHours decimal(18, 2)
Status nvarchar(10) ('Present', 'Absent', 'Holiday', 'Sick Leave')
Remarks nvarchar(250)
Now i want to generate a crystal report for each employee's attendance history...that will show total number of 'Presents', 'Absent', 'Sick Leaves' for a specicif dates or month.
i.e. How i can get total Presnets and Absents or Sick Leaves of one employee during the month.
A: You could use a stored procedure to feed data to the report. It would take the EmployeeID and month (or a date range) as the input and probably return AttendanceDate and Status; you might be more interested in AttendanceDate, HoursWorked and Status, depending on what the actual data looks like.
You could then group the return values for the dates by either using a GROUP BY statement for the return data or by grouping the data itself in the Crystal Report.
A: Insert a group on Employee ID, then one on AttendanceDate (be sure to choose month as the period), then one on Status. Select the AttendanceId field, then Insert Summary and choose Count.
If you want to filter the report by date, add a date parameter (set the Range option to true), then create a record-selection formula that resembles:
//change values to reflect your situation
{table.AttendanceDate} IN {?data-range parameter}
Consider reading a book on the topic or attending a class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IOS: test app-purchase don't work I'm testing app purchase for my app.
I create an app in itunes-connect and I add an id for apppurchase ex: com.mycompany.puzzle.tree
then when I try my code I have the alert that ask me apple id and password, but aftera a few of seconds I have an other alert that say it's not possible connect to apple store, why?
A: There seems to be a lot of this going around in the sandbox environment.
Try these:
- Make sure your app bundle has a version number set in the info plist
- Create a new sandbox user
A: The test account was expired .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing margin of a div with javascript I'm making a webpage that contains a picture gallery. I've written a javascript function to display a larger version of an image when you click on the miniature. What the function does is that it changes the search path of an img tag within a div that is hidden. It then changes the top and left values of the div to position the div in the center of the screen and then it's supposed to adjust the top and left margin of the div depending on the image size to place its middle in the center of the screen.
This is where it fails. Or really, it works, but not when it's supposed to. If I open an image for the first time it has the wrong offset from the center (the negative margins for top and left are wrong). If I open it again however, it works! I get the same error if I open an image with a different width and height.
This is the code used to set the margins:
imagebox.style.marginLeft=(image.width/-2)+'px';
imagebox.style.marginTop=(image.height/-2)+'px';
This works just fine in google chrome and and in safari, but in other browsers it doesn't always use this code and sometimes it gives it a double call.
And in the end I of course set the div visibility to visible.
A: Try the jQuery functions .css() and .width()/.height(). They work fine in almost every browser.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: interview question printing a floating point number What's the output of the following program and why?
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}
My compiler prints 0 and 1095237632. Why?
A: The memory referred to by a holds a pattern of bits which the processor uses to represent 12.5. How does it represent it: IEEE 754. What does it look like? See this calculator to find out: 0x4148000. What is that when interpreted as an int? 1095237632.
Why do you get a different value when you don't do the casting? I'm not 100% sure, but I'd guess it's because compilers can use a calling convention which passes floating point arguments in a different location than integers, so when printf tries to find the first integer argument after the string, there's nothing predictable there.
(Or more likely, as @Lindydancer points out, the float bits may be passed in the 'right' place for an int, but because they are first promoted to a double representation by extending with zeros, there are 0s where printf expects the first int to be.)
A: In both cases you pass a bits representing floating-point values, and print them as decimal. The second case is the simple case, here the output is the same as the underlying representation of the floating-point number. (This assumes that the calling convention specified that the value of a float is passed the same way an int is, which is not guaranteed.)
However, in the first case, when you pass a float to a vararg function like printf it is promoted to a double. This mean that the value passed will be 64 bits, and printf will pick up either half of it (or perhaps garbage). In your case it has apparently picked up the 32 least significant bits, as they typically will be all zero after a float to double cast.
Just to make it absolutely clear, the code in the question is not valid C, as it's illegal to pass values to printf that does not match the format specifier.
A: This is because floating point representation (see IEEE 754 standard).
In short, set of bits, which makes 12.5 floating point value in IEEE 755 representation when interpreted as an integer will give you strange value which has not much in common with 12.5 value.
WRT to 0 from printf("%d\n", a) , this is internal undefined behavior for incorrect printf call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: case insensitive NSPredicate with single result in CoreData Here is my current NSPredicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UPC==%@ OR ItemID==%@", aUPCCode,aUPCCode];
How can I make this case insensitive?
And I do not want to do any partial matching.
Example if they enter 123 for aUPCCode I do not want to get 123, 123a, 123b, 123c, ect. I would only want an exact match.
I thought about doing this but it seems a little ridiculous:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UPC==%@ OR ItemID==%@ OR UPC==%@ OR ItemID==%@ OR UPC==%@ OR ItemID==%@", aUPCCode,aUPCCode,[ aUPCCode lowercaseString] ,[aUPCCode lowercaseString], [aUPCCode uppercaseString],[aUPCCode uppercaseString]];
A: As Sinetris said, the above works in Objective-C.
It works for case-insensitive. Fetches all results which have the "example" string value in it.
Update Swift 4.0/5.0
let predicateIsNumber = NSPredicate(format: "keywordContactNo contains[c] %@", example!)
Hope it helps
Thanks
A: As Dave DeLong said, you can use:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UPC ==[c] %@ OR ItemID ==[c] %@", aUPCCode,aUPCCode];
Edit:
Use ==[c] instead of ==[cd] or you get accents too (abcd == àbcd).
A: maybe this:
[NSPredicate predicateWithFormat:@"UPC MATCHES[cd] %@ OR ItemID MATCHES[cd] %@",aUPCCode,aUPCCode];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: How to open a page and activate specific JS? I have a jplayer on a website, which embeds several playlists.
To activate these playlists, I use this function :
jQuery("#playlist_french_baroque").click(function() {
...
});
This works very well.
Now, on other pages on the same website I want to load a specific playlist.
This doesn't work because I use the click() function.
What should I do for that ?
Thank you very much.
A: If what you need is to load something without user intervention, you can use the .ready() method provided by jQuery (see docs):
$(document).ready(function() {
// do whatever you need
});
Which is equivalent to:
$(function() {
// do whatever you need
});
The code is executed after the DOM is ready.
A: On your /listen page add this code
$(function () {
if (window.location.hash) {
$(window.location.hash).click();
}
});
This will execute when the page loads, and check if the hash has been set then call the click hander on the element with that hash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to determine if the requested directory is writable?
Possible Duplicate:
How do you check for permissions to write to a directory or file?
I'm trying to figure out if it is possible to determine if a requested file directory is writable and the current user have the right permissions to write into that folder.
Till now I'm making a test for the requested path by creating new directory, writing a temp file into it and remove it (the temp file and directory).
This operation is very problematic since that directory may be exist already and all of its old information can be lost (when the directory remove).
Any idea ??
Tx...
A: The best approach is to attempt the operation and let the system decide whether or not it is allowed. Duplicating the checks that the system performs would be terribly hard to get right. Just let the system decide, it is the ultimate arbiter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get first empty cell in a column? Google Spreadsheets API Hi is there a fast way (csharp) to get the first empty cell in a column in a Google Spreadsheet file?
Is there any alternative to scanning the entire column?
How long (ms) would it ~ take to scan about 200 one word columns?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JSON-WSP or JSON-RPC We're about to implement a webservice using JSON objects as the mode of transportation. We have an intent of having third-party organizations to connect to our network and for that we are planning to use a standarized protocol to ease integration in the future.
For JSON, there's two specifications at the moment: JSON-RPC and JSON-WSP. I would like to know about anyone's view between these two and what would you use if you're in my shoes. For now, I see that JSON-RPC has been around for a while and has implementations to multiple languages. JSON-WSP is at its early stages but it aims to supersede JSON-RPC (an RFC is in the works). I see that JSON-WSP will be a good solution in the long run but I might be wrong.
A: The main difference between the two protocols is that JSON-WSP can describe it's own service methods with the jsonwsp/description object. This is nice if you want your client to be able to "know" your webservices and maybe offer a dynamic client-side user-interface that can change visualisation automatically when you change the service methods. So server-side updates can potentially become very easy to distribute.
JSON-WSP has support for attachments in the specification
JSON-RPC has support for batch-method invocation - invoke several method in one request. Also you can do response-less requests (Notifications)
JSON-RPC is the oldest of the two protocols and therefore it has more implementations and a large community.
So I guess it all boils down to what your needs are.
If you are building a browser-based application JSON-WSP offers an efficient Ajax-based mechanism using the official javascript client. The JavaScript json-wsp client parses the service description and generates a proxy object with methods mapping 1-to-1 to the json-wsp methods:
http://ladonize.org/index.php/Python_Example#JavaScript_JSON-WSP_client
A: Why not use REST?
If you already know the format of your JSON types, document those as the representations of your individual resources and then offer access to them via HTTP. That way, you'll get the benefit of the underlying transport infrastructure (caching possibilities, great tooling, etc).
Use hyperlinks between each resource to allow the clients to navigate between them. The users of your API then won't be tied to a contract-based RPC mechanism which will be hard for you to evolve and requires yet another toolkit for your clients to use. Using REST will require only an HTTP library (they are a dime a dozen) and a JSON parser (which they already need). In addition, you could always later add other encoding options (say, XML) with minimal impact to your existing clients.
Using JSON does not mean having to choose between JSON-RPC or JSON-WSP. Go for the lowest common denominators for your API with long-established, uber-simple standards (like HTTP and JSON) and use them to their best advantage. Once you start layering more specs and standards in there, you'll find that the complexity of your API grows proportionally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: iOS Developer Programs Specifics plus Unity3d export I have a few general questions about the iOS developer programs.
Please, accept these from a point a view of a small company with about 4 developers:
*
*We've purchased an iPad, and developed a iOS application using Xcode and have been testing it using the simulator. The only legal path to test that application on the iPad itself is paying about 99$ to Apple ??
*After paying the developer license, is there anyway of putting arbitrary applications on the iPad without using Xcode (without having the source or project of that same application) ??
*If we buy the "iOS developer program - Company" versus the "individual" one, this means each one of us can deploy applications to different iPads (or it must be the same iPad for all of us) ??
*Finally, Unity3d exports to iOS. What does it export: an application or the Xcode project (relates to my number 2 question! How will I be able to put that export into the iPad) ??
Please forgive me if these have already been answered. I could not find them. If so, please point me to them.
Thank you in advance!
A: *
*Yes, there is no alternative.
*You cannot deploy some arbitrary app files, you must have an XCode project. I am not sure but I think you can write a make file and call all utilties at the command line.
*I don't know about the company program, but you even with the individual program you can deploy to different devices. iTunes allows you to register 5 different devices on one account but your developer certificate enables you to test on up to 100 different devices (the iTunes limit of 5 stays valid thus you have register new iTunes accounts then).
*Unity3D exports a complete XCode project ready to build for your device. You can modify some code (in certain situations you have to). I wrote an article in my blog about Integrating 3rd Party Static Libraries in Unity3D Generated XCode Projects. There you can get an idea of the process.
If you are registered as developer (I mean for free) you may have access to the iOS portal where you can find some more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem managing two activities in Android What I am trying to do is very simple. I created two classes A and B. I created a click handler in A which calls a function in B which in turn calls a function in A. In the called function in A I am create a button. My programs is being forced close when I try to push the button.
Class Loggs
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class Loggs extends Activity {
Model model;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void clickHandler(View v)
{
model = new Model();
model.startGame();
//click();
}
public void startGame()
{
Log.d("Log","Reached start game");
click();
}
public void click()
{
Log.d("Log","Reached click");
Button btn =(Button)findViewById(R.id.startButton);
btn.setEnabled(false);
}
}
Class Model
import android.app.Activity; import android.os.Bundle; import android.util.Log;
public class Model extends Activity{
Loggs log;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startGame() {
log= new Loggs();
Log.d("Logg","Reached start game Model");
log.startGame();
}
}
A: is R.id.startButton in R.layout.main? Than.. you cannot instantiate an activity with new, imo, because the default constructor for activity are private (i think). Take a look at intent
A: Look at the code. Doing "log = new Loggs();" does not call the "onCreate" method on Loggs. Which means that "setContentView" is never called.
At the Loggs#click method, the button that you get via "findViewById" will be null. As a result btn.setEnabled would cause a NullPointerException causing the program to crash.
WarrenFaith and blackbelt gives good advice. Read up on activities, when, how and why they should be used.
A: Its not really clear what you are trying to do here? Activities don't communicate with each other in this way. If you want one activity to start another you need to do so using Intents:
For example if you want to the Model activity from Loggs you would issue the following commands:
Intent i = new Intent(this, Model.class);
this.startActivity(i);
Although I'm not sure if this is what you are trying to do. As has been already said you should avoid circular dependencies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why this JQuery Ajax won't be cached Here's my script. I want the result to be cached but it keeps sending requested requests if my mouse enters it again.
$('.poplist li').mouseenter(function(){
t=$(this).parent().attr("rel");
i=$(this).attr("rel");
$.ajax({
url:"/j/place",
data:{"t":t,"tid":i},
cache:true,
success:function(data){
data= jQuery.parseJSON(data);
s=$('.left[rel='+t+']');
s.find('.intro').html(data["intro"]);
s.find('.shop-avat img').attr("src","http://img.douban.com/u/plao/"+data['img']);
}
})
})
A: jQuery.ajax's cache option does nothing when set to true, and caching is entirely left up to the browser. If it is set to false, however, a cache-busting timestamp is appended to the request. That's all.
Update:
To see that this is so, take a look at the the source of jQuery.ajax, version 1.6.4, line 676, here: https://github.com/jquery/jquery/blob/1.6.4/src/ajax.js#L676
A: A simple solution is,
You may save the result (data) in a variable and you may use an if function before your ajax request. On mouse enter, if variable have no data stored, trigger ajax request, else, return false.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the proper location for libraries in an ASP.NET MVC project? If I create a custom routing class, what's the typical convention for where it's located in an ASP.NET MVC project?
(Note that these are not domain-specific libraries as they are implementations of ASP.NET MVC's interfaces to hook the lifecycle.)
A: For me, best place for those kind of classes is kind of separate Infrastructure-named project. Those Infrastructure-projects contain general helper libraries. Web knows about Infrastructure, but not vice-versa. Even Microsoft has that kind of naming convention. Namespace for custom route class may be *.Web.Infrastructure.Routing
A: I preder to keep them in a separate project with folder for every kind.
For example for an MVC projects I usually do:
MyCompany.MyApp.Web.MVC
and then the helpers
MyCompany.MyApp.Web.MVC.Helpers
AttributeHelpers
RoutingHelpers
HtmlHelpers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Missing XML Elements in an XML file I am trying to read XML files from different machines, some of these files may have data elements that others don't have. Currently, I am using a Try-Catch block to handle these situations but I was wondering if there was a better way of doing this, any thoughts?
XmlDataDocument xmlDatadoc = new XmlDataDocument();
xmlDatadoc.DataSet.ReadXml("MachineData.xml");
DataSet ds = new DataSet("AppData");
ds = xmlDatadoc.DataSet;
DataView dv = new DataView(ds.Tables[config.GlobalVars.Paths]);
foreach (DataRowView drv in dv)
{
try
{
cApp.TransferProtcol = drv["TransferProtocol"].ToString();
}
catch { }
try
{
cApp.RemoteServerPath = drv["RemoteServer"].ToString();
}
catch { }
}
Ok, I figured out a solution based upon John Saunders post:
if(ds.Tables[0].Columns.Contains("TransferProtocol")
{
try
{
if (drv["TransferProtocol"].ToString().Length > 0)
{
cApp.TransferProtcol = drv["TransferProtocol"].ToString();
}
}
catch(Exception e)
{
Messagebox.Show(e.Message);
}
}
I agree about the empty Catch blocks but I stubbed them out for testing purposes. I have since edited my post as to what my Try-Catch block looks now.
A: That's a horrible way to "handle" the problem. If the XML may legitimately be missing elements, then check to see if the elements are present before trying to access them.
Your empty catch blocks ignore all exceptions that occur inside of them, not just exceptions that mean the element is missing.
The columns are present or not as soon as the table is loaded. You can use ds.Tables[config.GlobalVars.Paths].Columns.Contains("columnName") to determine whether or not the column exists.
If a column exists, then for any given row, the column may or may not be null. Use drv.Row.IsNull("columnName") to determine whether that column in that row is null.
A: Ok, I just noticed that XmlDataDocument is going to be deprecated soon, so I decided to scrape it and use Linq to XML, and here is my new sopultion
public List<cApplication> GetAppSettings()
{
if (!File.Exists(Config.System.XMLFilePath))
{
WriteXMLFile();
}
try
{
XDocument data = XDocument.Load(Config.System.XMLFilePath);
return (from c in data.Descendants("Application")
orderby c.Attribute("Name")
select new cApplication()
{
LocalVersion = (c!=null)?c.Element("Version").Value:string.Empty,
RemoteVersion = (c!=null)?c.Element("RemoteVersion").Value:string.Empty,
DisableApp = (c!=null)?((YesNo)Enum.Parse(typeof(YesNo), c.Element("DisableApplication").Value, true)):YesNo.No,
SuspressMessages = (c != null) ? ((YesNo)Enum.Parse(typeof(YesNo), c.Element("SuspressMessage").Value, true)):YesNo.No
}).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
List<cApplication> l = new List<cApplication>().ToList();
return l.ToList();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use my actionsciprt 3.0 flash animation as a facebook application? I tried to make a facebook app, but I failed. I have no idea how to use my flash content. I tried to make a new app with Fbook Developers, I uploaded the animation as an HTML file on my server, but it's not working. All i see is a blank page. Then I searched some codes, but none of them worked. This is my final code (which is still not working):
<fb:swf
swfbgcolor="000000"
imgstyle="border-width:3px; border-color:white;"
swfsrc='http://fb.joma-sport.hu/valencia.swf'
imgsrc='http://fb.joma-sport.hu/valencia.jpg'
width='520' height='800' />
I want sg like this:
http://www.facebook.com/JomaSport.es?sk=app_186670448052790
(My page looks like this:
http://www.facebook.com/JomaSport.hu?sk=app_269610193049698)
Any help would be appreciated!
A: Ok i got the answer. Several weeks ago a I googled " how to embed flash into html", and after a few tries I found a code, which is working. Honestly I don't remember which webpage was that, but this code is not made by me!!
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"WIDTH=520 HEIGHT=700><PARAM NAME=movie VALUE="yourfile.swf"> <PARAM NAME=quality VALUE=best> <PARAM NAME=wmode VALUE=transparent> <PARAM NAME=bgcolor VALUE=#FFFFFF> <EMBED src="yourfile.swf<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="520" HEIGHT="700" id="yourfile.swf" ALIGN="">
<PARAM NAME=movie VALUE="yourfile.swf">
<PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#000000>
<EMBED src="yourfile.swf" quality=high bgcolor=#000000 WIDTH="520" HEIGHT="700" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: swapping array rows and printing, c this is something that's been bugging me for the past two hours. I'm trying to swap two rows in a two dimensional array. This is not a problem, but I want to do it with a swap function that gets pointers. Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
void swapRows(int **a, char **b)
{
int *temp = *a;
*a = *b; // WARNING #1
*b = temp; // WARNING #1
}
void print(int a[][2],int rows,int cols)
{
int i,j;
for (i=0; i<rows; i++)
{
for (j=0; j<rows; j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
int main(void)
{
int matrix[2][2] = {{1,2},{3,4}};
print(matrix,2,2);
swapRows(&matrix[0],&matrix[1]); //WARNING #2
print(matrix,2,2);
return EXIT_SUCCESS;
}
So, here are my questions:
1)The swap functions only swaps between the first elements in each array, which makes sense. How do I get it to swap the other elements? Do I HAVE to iterate the entire row?
2)When declaring print it only worked if i set a[][]2. Before that I tried writing int **arr but I had a segmentation fault. Why is that? Also, why must I specify the number of cols in the array argument? I have rows and cols for that, why does the compiler forces me to do so?
3)finally, using this version of print() I get a warning from the compiler passing argument 2 of ‘swapRows’ from incompatible pointer type (warning #2 in the code) and I get another warning (#1) : assignment from incompatible pointer type in swapRows(). Why is that?
Thanks in advance!
A: The source of your confusion:
The type of
int m1[2][2]; // a *single* block of memory of size 2*2*sizeof(int)
//
// this is a *real* 2d-array
is not the same as that of
int **m2; // a pointer of size sizeof(int*) almost certainly the
// equal to sizeof(void*)
//
// This could be made to point at at least two logically
// distinct blocks of memory and *act* like a 2d-array
Yes, m2 (pointer to a pointer) can be dereferenced using [][], but m1 (a actual two dimensional array) can not be dereferenced with **.
This means that your call to swap rows is a horrible error. Look why...
*
*matrix[0] is the first sub array (and int[2] containing {1,2}), taking the address of it is a null operation that gets the address of matrix[0][0], which is a spot in memory containing the integer representation of 1 (that is this is a pointer-to-int).
*A similar argument applies to &matrix[1] it points a memory containing 2.
The you call swapRows which thinks that these arguments are pointers-to-pointers-to-int (which they are not, so your compiler throws a warning). It will run though because a pointer-to-int is the same size as a pointer-to-pointer-to-int (that isn't strictly guaranteed, but you'll usually get away with it). What it does when it runs is swap the point-to-int sized contents of a with the pointer-to-int sized contents of b. If it happens to be the case that sizeof(int) == sizeof(int*) (which is not uncommon), this will amount to swapping matix[0][0] with matrix[1][0].
That is not what you wanted.
What can you do about it?
*
*Declare matrix as a pointer to pointer and allocate the memory as in a ragged array, then use your existing swap
*Declare matrix as an array of pointers and allocate memory for the rows, then use your existing swap
*Keep the existing declaration of matrix and re-write the swap to swap every value.
*Keep the existing declaration of matrix, but also provide an accessor array of pointers, use your existing swap on the accessor, and always use the accessor (the only possible advantage of this over the first two options is that everything resides on the stack).
*Use the row-as-a-structure hack.
Row-as-a-structure
Consider this
typedef struct {
int r[2];
} row_t;
row_t m3[2];
m3 is an array of structures each of which is an array of ints. Access is a little awkword: m3[i].r[j], but you can do
row_t temp = m3[n];
m3[n] = m3[m];
m3[m] = temp;
to swap rows.
A: Arrays and pointers are different things, although C makes them behave similarly in many cases. You also accidentally used a char instead of an int for the second parameter. Your swapRows function should be declared like this:
void swapRows(int (*a)[2], int (*b)[2])
You will need to swap (*a)[0] with (*b)[0] and (*a)[1] with (*b)[1].
C is converting the array into a pointer (with a warning), but that is confusing in this case.
It is just a limitation of C that arrays must have a size that is known at compile time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL - Cannot add foreign key to table I have a database using MySQL 2005. I have two tables, Enrolment and AlertMsg.
The primary keys for enrolment are two columns, UnitCode and StudentID. Both these two columns are foreign keys to another table.
The primary keys for AlertMsg are three columns, UnitCode, StudentID and AlertNo.
When I try to make a foreign key with UnitCode in the AlertMsg table, like so:
ALTER TABLE AlertMsg
ADD FOREIGN KEY (UnitCode)
REFERENCES Enrolment(UnitCode)
I get the following error:
SQL Execution Error.
Executed SQL statement: ALTER TABLE AlertMsg
ADD FOREIGN KEY (UnitCode)
REFERENCES Enrolment (UnitCode)
Error Source: .Net SqlClient Data Provider
Error Message: There are no primary or candidate keys in the referenced table 'Enrolment' that match the referencing column list in the foreign key 'FK_AlertMsg_UnitCo_571DF1D5'.
Could not create constraint. See previous errors.
After some searching it seems that this is because UnitCode isn't a primary key of Enrolment. But Enrolment's table definition seems to show that it is. I'm a bit of a newbie at SQL, so I assume that if the far left column of the table definition has a key in it, it means its a primary key of the table.
Can anyone help? Thanks in advance.
A:
The primary keys for enrolment are two columns, UnitCode and
StudentID. Both these two columns are foreign keys to another table.
The primary keys for AlertMsg are three columns, UnitCode, StudentID
and AlertNo.
You say "the primary keys for ...". Well actually it is probably not multiple keys but one key that is create using multiple columns. Those columns together is what needs to be unique in your table and therefore you can not just reference one of the columns in a foreign key.
If you want this statement to work
ALTER TABLE AlertMsg
ADD FOREIGN KEY (UnitCode)
REFERENCES Enrolment(UnitCode)
The values in UnitCode in table Enrolment needs to be unique and you need to add a unique constraint on that column. I guess that is not the case so you can't add the necessary unique constraint.
You should probably use this instead:
ALTER TABLE AlertMsg
ADD FOREIGN KEY (UnitCode, StudentID)
REFERENCES Enrolment(UnitCode, StudentID)
A: Standard primary keys don't have to be the leftmost indexed column in a table, it's just a common habit that developers and DBA's who define the table put the primary key column(s) first.
In standard SQL, a foreign key must reference:
*
*Column(s) defined as a PRIMARY KEY or UNIQUE KEY in the referenced table.
*The columns in the foreign key don't have to have the same names, but they must be the same in number, order, and data type.
I suspect you're really using Microsoft SQL Server 2005, not MySQL. There's no such product release known as "MySQL 2005".
A: You can try:
*
*Add foreign key constraint to 2 columns (UnitCode,StudentID) of Enrolment table.
Or
*Add unique constraint to column (UnitCode) of Enrolment table if you only need the reference on UnitCode column.
Hth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use PrimeFaces Captcha? I went through the user guide and the showcase but couldn't find a way to get the Captcha evaluation result in the backing bean. I can see the result on the top message bar on the UI but how to get the result in the backing bean?
A: I don't think that it has any result for your beans. If you type valid text in the captcha box the process validation phase does not throw error and your input will be handled as valid. Otherwise the captcha component signal the error and you will see the error message with the h:message or the h:messages tag. (Maybe you should attach some code.)
"If an entered value is invalid, an error message is added to
FacesContext, and the component is marked invalid. If a component is
marked invalid, JSF advances to the render response phase, which will
display the current view with the validation error messages. If there
are no validation errors, JSF advances to the update model values
phase."
(From http://www.ibm.com/developerworks/library/j-jsf2/)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Joomla Seminar Component customisation I am using the Joomla Seminar component , http://extensions.joomla.org/extensions/calendars-a-events/events/events-registration/8426
I would like to retrieve the query to return the organiser's name, thus search the query across the component files.
I get stuck at this function :$config = &JComponentHelper::getParams('com_seminar');
How do I retrieve the SQL query from here? Any pointers appreciated. Thanks a lot!
A: If you want to get organiser's name by seminar number / code:
$number = "123"; // here the number to search
$db = &JFactory::getDBO();
$q = "SELECT name FROM #__users u INNER JOIN #__seminar s ON (u.id=s.publisher) WHERE s.semnum='".$number."'";
$db->setQuery($q);
$organisername = $db->loadResult();
You can change the query as your needs, for example searching by seminar id:
$q = "SELECT name FROM #__users u INNER JOIN #__seminar s ON (u.id=s.publisher) WHERE s.id='".$id."'";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Do I need to call MessageDigest.reset() before using it? The question is simple: when should I call the reset() function on the java class MessageDigest?
The question mainly comes from the OWASP reference, where in a code sample, they do:
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(salt);
byte[] input = digest.digest(password.getBytes("UTF-8"));
then, in a loop, they do:
for (int i = 0; i < iterationNb; i++) {
digest.reset();
input = digest.digest(input);
}
Now, to me, it looks as if the reset is only required once the digest instance has already been 'polluted' with calls to update. The one in the first sample, therefore, does not seem necessary. If it is necessary, is it an indication that the instance returned by MessageDigest.getInstance is not thread safe?
*
*OWASP hashing recommendation
*Random article on hashing, does not contain initial reset
A: I think you are right, the initial reset() is not necessary. The documentation states:
A MessageDigest object starts out initialized.
Also the example on the class documentation does not include the initial reset.
This has nothing to do with thread-safety, the necessity of .reset() would just indicate that getInstance() does not do the initialization itself.
You should not use the same MessageDigest object from multiple threads without synchronization anyway: A hash is only meaningful if you know in which order the parts were hashed, otherwise it is just a fancy not-totally-deterministic PRNG.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: css opacity - internet explorer i'm working with opacity today and from some reason it wont work on internet explorer
here is my CSS :
.box_1{opacity:0.4;filter:alpha(opacity=40)};
.box_1:hover{opacity:1.0;filter:alpha(opacity=100);}
and here is my HTML:
<div class="box_1">
<img src="abc.png"/>
</div>
the HOVER div does not work.
what is the problem here?
A: You're missing a curly bracket at the end of your first line, it should be:
.box_1{opacity:0.4;filter:alpha(opacity=40);}
.box_1:hover{opacity:1.0;filter:alpha(opacity=100);}
Also if you're using IE6 the :hover selector won't work on anything except <a> tags. To get around it you'll need to use something like Whatever:hover.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I append data retrieved via Ajax correctly to the DOM? I insert several(array) value with json_encode in one row from database table, now want echo they as order with jquery.
This is output from my PHP code with json_encode:
[{
"guide": null,
"residence": [{
"name_r": "jack"
}, {
"name_r": "jim"
}, {
"name_r": "sara"
}],
"residence_u": [{
"units": ["hello", "how", "what"],
"extra": ["11", "22", "33"],
"price": ["1,111,111", "2,222,222", "3,333,333"]
}, {
"units": ["fine"],
"extra": ["44"],
"price": ["4,444,444"]
}, {
"units": ["thanks", "good"],
"extra": ["55", "66"],
"price": ["5,555,555", "6,666,666"]
}]
}]
And is my js code in ajax call ($.ajax({...):
success: function (data) {
$.each(data[0].residence, function (index, value) {
$('ol#residence_name').append('<li><a href="" class="tool_tip" title="ok">' + value.name_r + '</a><div class="tooltip"></div></li>');
var info = data[0].residence_u[index];
$.each(info.units, function (index, value) {
$('ol#residence_name li .tooltip').append(value + ' & ' + info.extra[index] + ' & ' + info.price[index] + '<br>');
})
});
Now by above js code, i have in output this:
jack hello & 11 & 1,111,111 how & 22 &
2,222,222 what & 33 & 3,333,333, fine & 44 & 4,444,444
thanks & 55 & 5,555,555 good & 66 & 6,666,666
jim fine & 44 & 4,444,444 thanks & 55 & 5,555,555 good & 66 & 6,666,666
sara thanks & 55 & 5,555,555 good & 66 & 6,666,666
I want as:
jack hello & 11 & 1,111,111 how & 22 &
2,222,222 what & 33 & 3,333,333,
jim fine & 44 & 4,444,444
sara thanks & 55 & 5,555,555 good & 66 & 6,666,666
What do i do?
A: Keep a reference to the tooltip element and append the info to it:
var $li = $('<li><a href="" class="tool_tip" title="ok">' + value.name_r + '</a></li>');
var $tooltip = $('<div class="tooltip"></div>').appendTo($li);
var info = data[0].residence_u[index];
$.each(info.units, function (index, value) {
$tooltip.append(value + ' & ' + info.extra[index] + ' & ' + info.price[index] + '<br>');
});
$li.appendTo('#residence_name');
Why does your code produce this result?
Because $('ol#residence_name li .tooltip') will select every .tooltip element in every li inside #residence_name, not just the currently created one.
A: That's quite a complicated data structure you're starting with - my first instinct would be to reorganise it into a less brain-melting format! But assuming the structure is fixed, a nice clear iteration structure can help to de-confuse matters. I've provided some code below which doesn't do anything, but which does provide an easier-to-understand framework in which to work. At every stage the variables you need are extracted ready for use, and it's up to you what to do with the data. Untested, but should work :)
// Declare the variables we're going to use
var i, j; // Iterating variables
var name, unitsArray, extraArray, priceArray; // Outer loop
var unit, extra, price; // Inner loop
// Loop through the people
for( i in data[0].residence ) {
// Assign the outer-loop variables
name = data[0].residence[i].name_r;
unitsArray = data[0].residence_u[i].units;
extraArray = data[0].residence_u[i].extra;
priceArray = data[0].residence_u[i].price;
// Do something here with the name
// For each person, loop through the things they said
for( j in unitsArray ) {
// Assign the inner-loop variables
unit = unitsArray[j];
extra = extraArray[j];
price = priceArray[j];
// Do something here with the 3 inner-loop variables
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Analytics is not recording navigation using anchors despite inclusion of setAllowAnchor in the script I am struggling to get google analytics to track navigation using anchor tags. I've read that all I need to do is include:
_gaq.push(['_setAllowAnchor', true]);
However this is still not working. I have a 1 page website which uses javascript (jquery) and anchor tags for navigation. When I examine my analytics report all I see is that a user (only me for my website so far) loaded index.html and reloaded it several times, rather than navigated to a specific anchor. My analytics script is below, and is included in the head section. As I say, the script works it just doesn't track anchor navigation. Are there any work arounds or errors in my script?
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'XXXXXXXXXXX']);
_gaq.push(['_setAllowAnchor', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
A: Whatever you read about _setAllowAnchor is mistaken.
_setAllowAnchordocs is not a feature that enables anchor-aware navigation (or, onhashchange) tracking. Instead, its for detecting campaign tags in the URL's anchor, so that
http://google.com/#foo&utm_campaign=bar
gets tracked in Google Analytics with "Campaign" set to bar.
Or, as the documentation puts it:
This method sets the # sign as the query string delimiter in campaign tracking. This option is set to false by default.
However, by default, that URL value will still only be tracked in Google Analytics as "/", since the default method that Google Analytics tracks pageviews is location.pathname+location.search.
Alternatives
To allow for tracking of your internal anchors, you just need to just add a _trackPageview call, with a custom pageview value, into where ever you're detecting or changing the URL's anchor, so that it runs any time you're changing the 'page' or the 'anchor'
Basically, that just means adding this line:
_gaq.push(["_trackPageview", new_url]);
where new_url is the URL you'd like to be tracked.
Really, you could just defined new_url as:
var new_url = location.pathname+location.search+location.hash
A: In the new analytics.js it should be
ga('create', 'UA-XXXX-Y', {'allowAnchor': true});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JavaScript - jQuery interval I am using JavaScript with jQuery. I have the following script to alert hi every 30 seconds.
$(document).ready( function() {
alert("hi");
setInterval(function() {
alert("hi");
}, 30000);
});
I want to alert hi when the page loads (when document / page gets completely loaded) and on every 30 seconds interval afterwards (like hi(0s) - hi(30s) - hi(60s).. etc). But my solution works on two instances. One on DOM ready and the other in a loop. Is there any way to do the same in a single instance?
You can see my fiddle here.
A: Well, there probably is a way of doing it in just one call..
setInterval(
(function x() {
alert('hi');
return x;
})(), 30000);
Another solution would be to use arguments.callee, but as it is now deprecated, it is generally not recommended to use it.
setInterval(
(function() {
alert('hi');
return arguments.callee;
})(), 30000);
A: You could use setTimeout instead and have the callback reschedule itself.
$(function() {
sayHi();
function sayHi() {
setTimeout(sayHi,30000);
alert('hi');
}
});
A: Wrap your code in a function. Then, pass the function as a first argument to setInterval, and call the function:
$(document).ready( function() {
//Definition of the function (non-global, because of the previous line)
function hi(){
alert("hi");
}
//set an interval
setInterval(hi, 30000);
//Call the function
hi();
});
A: No, that's not possible with setInterval. You could use setTimeout for example:
function foo() {
alert('hi');
setTimeout(foo, 30000);
}
$(function() {
foo();
});
A: $(function() {
function heythere() {
alert('hi');
setTimeout(heythere,30000);
}
heythere();
});
If you want it to only run once after 30 seconds, you are looking to use setTimeout not setInterval.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: User scores Object and App scores Object With the new Scores and Achievements roll-outs I have the following questions
*
*Is there a difference between the user's scores object and the
app's scores object for the user?
*Does setting one affect the other?
*In setting a scores object is it overwritten or aggregated?
There was a statement made in the docs about "games limited to 1000 points per game" for scores...does game refer to
*
*The App in total?
*the game per person?
*the per person per game play e.g. (per turn/ per try/ per round)?
I ask this because I am developing a game where a user would have 2 sets of scoring and I want them to be counted both separately and as an aggregate.
A: I've been playing around with scores and achievements and this is what I found out:
*
*scores and achievements are separate.
*Changing the score doesn't affect the achievements.
*Adding achievements don't affect the score.
*Scores don't aggregate, so if you assign a score to a user, the user will have the new score assigned.
*Consider the achievements more like bonus points a user gets when doing a task. If you want to add the bonus points to a user's score, you'll have to assign a new score to the user.
*I noticed that the updates in score or acheivements appear mainly when the page reloads.
7.When creating achievements, don't use an https link for the image else it won't be added.
8) The total points for achievements should not be greater than 1000pts but scores can go higher (how high I do not know).
I strongly suggest creating the achievements first in a test app and adding them to your app when you're sure about what you want.
Hope I was able to help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Building a query string based on variable values. Where is the mistake? I am trying to create a query string based on GET values passed to common vars:
if isset, gTipo = $_GET['tipo'] and others like this.
So, here is the code that is not working:
$sqlLista = 'SELECT * FROM produtos';
if($gTipo <> 0 || $gLinha <> 0)
{
if($gtipo <> 0 && $gLinha == 0 )
{
$sqlLista .= ' WHERE id_tipo = '.$gTipo.'';
}
if($gtipo <> 0 && $gLinha <> 0)
{
$sqlLista .= ' WHERE id_tipo = '.$gTipo.' AND id_linha = '.$gLinha.'';
}
if($gTipo == 0 && $gLinha <> 0)
{
$sqlLista .= ' WHERE id_linha = '.$gLinha.'';
}
}
If i set my url as ?tipo=2&linha=4 , my script capture this GET vars and create the common var gTipo and gLinha. If any of this GET are not set, the gTipo or gLinha receive the '0' (zero) value.
When I run the script of query building, nothing is concatened to $sqlLista, except what is done outside the if ( $sqlLista = 'SELECT * FROM produtos'; ).
I am sure this must be a stupid thing that I cannot see. Please, help me =)
A: I think your problem is variable case:
if($gtipo <> 0...
should be
if($gTipo <> 0...
in 2 places.
A: dunno what's your problem but the code seems a bit bloated to me
I'd make it this way
$w = array();
$where = '';
if (!empty($_GET['tipo'])) $w[] = 'id_tipo = '.intval($_GET['tipo']);
if (!empty($_GET['linha'])) $w[] = 'id_linha = '.intval($_GET['linha']);
if ($w) $where = " WHERE ".implode(' AND ',$w);
$sqlLista = SELECT * FROM produtos'.$where;
hope you know what you're doing and you really need AND, not OR in the query.
if you have your validations already, the code would be even shorter
$w = array();
$where = '';
if ($gtipo) $w[] = "id_tipo = $gtipo";
if (gLlinha) $w[] = "id_linha = gLinha";
if ($w) $where = " WHERE ".implode(' AND ',$w);
$sqlLista = 'SELECT * FROM produtos'.$where;
A: Your variable names are inconsistent - $gTipo vs $gtipo.
This line will prevent your inner logic from executing. remove it.
if($gTipo <> 0 || $gLinha <> 0)
As a matter of style, you should use "else if" to prevent multiple "WHERE" lines from being appended if you make a logic error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check if iPad is in silent mode
Possible Duplicate:
Detect Silent mode in iOS5?
i have used the code below to check if silent mode is on, it works as expected on the iPhone but on the iPad it returns speaker regardless.
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if (CFStringGetLength(state) == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Silent mode"
message:@"Please turn sound on"
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
Any ideas how to modify it to work universally?
Thanks
Dan.
A: In your XIB you can add a slider to check what the volume level is at, so basically you can tell if it is silent, and know the level of the volume. For more understanding of this class, here's the link http://blog.stormyprods.com/2008/09/proper-usage-of-mpvolumeview-class.html but try this first:
The following code will create something like a volume bar.
- (void)viewDidLoad {
// create a frame for MPVolumeView image
CGRect frame = volumeViewHolder.bounds; // CGRectMake(0, 5, 180, 0);
volumeView = [[[MPVolumeView alloc] initWithFrame:frame] autorelease];
[volumeView sizeToFit];
[volumeViewHolder addSubview:volumeView];
for (UIView *view in [volumeView subviews]){
if ([[[view class] description] isEqualToString:@"MPVolumeSlider"]) {
volumeViewSlider = view;
}
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(volumeChanged:)
name:@"AVSystemController_SystemVolumeDidChangeNotification"
object:nil];
}
- (void) volumeChanged:(NSNotification *)notify
{
[volumeViewSlider setValue:[[[notify userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue]];
}
I heard that for some reason apple doesn't allow you to sell an app if you use a certain class (the one in my example) but I'm not too sure about this, I would double-check and make sure that you are 'allowed' to use it. But the code should work.
A: This SO answer answers it nicely:
Detect Silent mode in iOS5?
And regarding Gabe's answer, if his answer does indeed use a private API, Apple will reject your app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: wkhtmltopdf vs fpdf and questions regarding use and performance (HTML to PDF) I have not been able to find answers to my questions on the several posts about the same topic, that is why I will be asking more specific questions here.
My questions are about wkhtmltopdf and fpdf. I need one of those to create 1 page invoices (really basic design) and 1 page reports (basic design as well) so very small PDF documents.
I have read that most people recommend wkhtmltopdf because of it's performance but for small 1 page documents does it really make a difference vs fpdf? Is it really less memory consuming? Faster?
I know that is a silly question but I also need to know if wkhtmltopdf can be executed multiple times at once. I mean, if there are 1000 users on my site trying to save their invoice in PDF at the same time? Is there a limit, how does it work? I know that fpdf is a php class so I don't have to "worry" about this (I only need the proper php.ini configuration I guess).
What would you suggest? For small PDF documents but high performance to be able to handle a lot of requests at the same time.
Are there any other options?
Thank you for your help!
A: The short answer is yes - you can create mutiple instances of wkhtmltopdf simultaneously each converting its own html page to pdf. However, wkhtmltopdf runs as an operating system process which means that if 1000 users are viewing their invoices at the same time, 1000 wkhtmltopdf processes will be spawned in the server which is probably not what you want.
On the other hand, FPDF runs as part of the web server process inside the PHP runtime and will not have this limitation. If you are creating a small or even big a invoice, I will suggest using FPDF since it is fairly easy to create an invoice using FPDF. Not only you will have a lot of control over PDF page layout, you will also save time during maintenance/upgrade later.
One of the problem I have encountered with wkhtmltopdf is page breaking. Wkhtmltopdf will not break your pages as you might expect. For example, a line of text may be split between two pages - upper part of a line of text appearing at the end of one page and lower part appearing at the start of the next page. In order to avoid this behavior, you have to set css attributes page-break-after or page-break-before judiciously in your html pages which can be difficult sometime because you are not sure where the page will break.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Reverse numeral input I'm trying to get my code to print out the reverse of whatever integer is input. No errors, just not printing out correctly. What am I doing wrong?
#include<iostream>
#include<conio.h>
using namespace std;
int num, n;
int reverse(int);
int main()
{
cout << "Enter a number less than 1000 to be reversed:" << endl;
cin >> num;
reverse(num);
cout << "reversed number is:";
getch();
return 0;
}
int reverse(int num)
{
long sum=0;int rem;
while(n>0)
{
rem=n%10;
sum=sum*10+rem;
n=n/10;
cout << sum << endl;
}
return sum;
cout << sum << endl;
}
A: n is uninitialized in your program, yet you're using it in the while loop.
Try this:
int reverse(int num)
{
int sum=0;
while(num>0)
{
sum=sum*10+ num %10;
num=num/10;
}
return sum;
}
And since this function returns an integer which is reverse of the number which you passed to the function, you have to save the returned value, at the call-site as:
int revnum = reverse(num); //in your code, you're not doing this.
Now see the complete online demo : http://ideone.com/hLnS1
By the way, avoid global variables:
int num, n; //avoid declaring these at global level.
Define them at local scope, as I did in the demo (see it).
A: Reversing a number is easier if you treat it as a string.
e.g.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string sNum;
std::cout << "Enter a number:" << std::flush;
std::cin >> sNum;
std::reverse(sNum.begin(), sNum.end());
std::cout << "\nThe reverse is \"" << sNum << "\"";
std::cout << "\n\nPress return to finish" << std::endl;
std::cin.get();
return 0;
}
Produces
Enter a number:123456789
The reverse is "987654321"
Press return to finish
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AS2 call function inside movieclip I have a movieClip with a few animations and a layer for actionscript code.
What I need to do is to call a function that is defined in MovieClip from "Scene 1".
I've tried many combination without success:
_root.mc1.teste();
mc1.teste();
this.mc1.teste();
parent.mc1.teste();
At this moment, movie clip is located on "Stage 1" and it has instance name "mc1". I also have tried to create the same movie clip dynamicly with "attachMovie" but the problem remains.
I don't know what I'm doing wrong.
EDIT
As you can see on the image below. I have some functions defined in Layer3 on a frame1 and I want to call them from Scene1).
Any help is appreciated.
A: Are both your clips on stage?
Debugging Tip: Try to trace each clip so you know that you are targeting them correctly.
// Inside each clip, trace it's own path
trace(this);
This way, you can discover the actual path that needs to be used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I incorporate iAd into my Flash application? I was working on a simple game app using Xcode, but when I saw that image manipulation is much easier using the Flash SDK, I reprogrammed the game using Flash.
Unfortunately, I don't know how to incorporate iAds into my Flash iOS app. I tried searching on Google, but all I got were references to the ongoing battle between Apple and Adobe.
I appreciate any tips - thanks in advance!
A: To implement Apple's iAd, I found a nice way using the native extension in Air3.
There are a few tutorials/articles on Native extensions floating around.
Adobe has a page with its Native extensions for download.
http://www.adobe.com/devnet/air/native-extensions-for-air.html
A: I have written a sample for iAds Native Extensions(Introduced newly with AIR 3) that will let you insert iAds in your flash game. You can try http://code.google.com/p/iad-air-ios/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android thread not working In this code snippet, the application sleeps for the interval, but instead of appending TEXT to textStatus(TextView variable), it displays an error that Something went wrong and application is closing.
Thread time_manager = new Thread(){
public void run(){
int interval = 2000;
try{
sleep(interval);
textStatus.append("\nTEXT\n");
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
}
}
};
What part am I doing wrongly?
A: all the changes to the UI Part should be done on the UIThread, you should use something like post, or runOnUithread functions to update UI.
A: To update the UI you can also use Handler like this, it will update your UI incrementing the value of counter everytime by 1 within every second.
int response = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.myid);
thread t = new thread();
t.start();
}
public class thread extends Thread {
public void run() {
while (response < 100) {
handler.sendEmptyMessage(0);
response++;
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
tv.setText("helloworld " + response);
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need help in trying to convert number into character code I am using irb/ruby1.9.1/windows7.
I need to convert the letter "M" into character code.
I wrote the code below:
>M
I expected the result to be 77.
But the result was "M".
How can I make the letter into character code?
A: Try method ord
'M'.ord
in order to get the character code.
A: Why not use ord
"M".ord #=> 77
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Operator new initializes memory to zero There is such code:
#include <iostream>
int main(){
unsigned int* wsk2 = new unsigned int(5);
std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
delete wsk2;
wsk2 = new unsigned int;
std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
return 0;
}
Result:
wsk2: 0x928e008 5
wsk2: 0x928e008 0
I have read that new doesn't initialize memory with zeroes. But here it seems that it does. How does it work?
A: With some compilers, the debug version of new will initialise the data, but there is certainly nothing that you can rely on.
It is also possible that the memory just had 0 from a previous use. Don't assume that nothing happened to the memory between delete and new. There could be something done in the background that you never noticed. Also, the same pointer value might not be the same physical memory. Memory pages get moved and paged out and in. A pointer might be mapped to an entirely different location than earlier.
Bottom line: if you didn't specifically initialise a memory location then you can assume nothing about its contents. The memory manager might not even allocate a specific physical memory location until you use the memory.
Modern memory management is amazingly complex, but as a C++ programmer you don't really care (mostly‡). Play by the rules and you won't get into trouble.
‡ You might care if you are optimising to reduce page faults.
A: That's not operator new, that's the new operator. There's actually a big difference! The difference is that operator new is a function that returns raw memory; when you use the new operator, it invokes a constructor for you. It's the constructor that's setting the value of that int, not operator new.
A: There are two versions:
wsk = new unsigned int; // default initialized (ie nothing happens)
wsk = new unsigned int(); // zero initialized (ie set to 0)
Also works for arrays:
wsa = new unsigned int[5]; // default initialized (ie nothing happens)
wsa = new unsigned int[5](); // zero initialized (ie all elements set to 0)
In answer to comment below.
Ehm... are you sure that new unsigned int[5]() zeroes the integers?
Apparently yes:
[C++11: 5.3.4/15]: A new-expression that creates an object of type T initializes that object as follows: If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value. Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
#include <new>
#include <iostream>
int main()
{
unsigned int wsa[5] = {1,2,3,4,5};
// Use placement new (to use a know piece of memory).
// In the way described above.
//
unsigned int* wsp = new (wsa) unsigned int[5]();
std::cout << wsa[0] << "\n"; // If these are zero then it worked as described.
std::cout << wsa[1] << "\n"; // If they contain the numbers 1 - 5 then it failed.
std::cout << wsa[2] << "\n";
std::cout << wsa[3] << "\n";
std::cout << wsa[4] << "\n";
}
Results:
> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
> g++ t.cpp
> ./a.out
0
0
0
0
0
>
A: operator new is not guaranteed to initialize memory to anything, and the new-expression that allocates an unsigned int without a new-initializer leaves the object with an indeterminate value.
Reading the value of an uninitialized object results in undefined behavior. Undefined behavior includes evaluating to the value zero with no ill effects but could result in anything happening so you should avoid causing it.
In C++11, the language used is that the allocated objects are default-initialized which for non-class types means that no initialization is performed. This is different from the meaning of default-initialized in C++03.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "97"
} |
Q: How do you automatically update a string variable when a user types in a UITextView? I have a string variable and UITextView, when a user type something in the UITextView, the string must be updated automatically, so that it's value changes as UITextView's does. What I mean is this code should automatically change the string.
myString.String = textView.text;
Thank you.
A: Assign a delegate to your UITextView and implement the textViewDidChange: method:
- (void)textViewDidChange:(UITextView *)textView {
self.myString = textView.text;
}
(assuming that myString is a property of your delegate)
A: If the variable myString is an NSString* variable, you just need to call the following assignment once:
myString = textView.text;
Then myString points to textView.text.
A: myString.String = textView.text;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: explicit specialization of template class member function I have this :
template<class T, class U>
class A
{
template<size_t N>
void BindValues();
}
template<class T, class U>
template<size_t N>
inline void A<T, U>::BindValues()
{
conn->setValue<N-1>( std::get<N-1>(m_Tuple) );
BindValues<N-1>(conn);
}
template<class T, class U>
template<>
inline void A<T, U>::BindValues<1>()
{
conn->setValue<0>( std::get<0>(m_Tuple) );
}
My Compile error is:
invalid explicit specialization before '>' token
enclosing class templates are not explicitly specialized
template-id BindValues<1> for void A<T, U>::BindValues() does not match any template declaration
A: Unfortunately a template method inside a template class cannot be specialized just based on template argument of method.
You need to specialize the template class also. In other words, the member method specialization should be a complete specialization with respect to class template (i.e. <T,U>) params as well as the member template params (i.e. <size_t>).
For example, you may have to specialize something like this (demo):
template<> // <------ you have to specialize class also
template<>
inline void A<int, double>::BindValues<1>() // <-------- see A<T,U>
{
...
}
A: What you are trying to do is partial template specialization for a function, which is not allowed.
You can define the template function on N for a template specialization of A (e.g. A<int, int>::BindValues<N>()) but the other way around is not allowed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Jquery - load cookie data Consider a list of thumbnails from which the user clicks one to change the background image. The following scripts lets the user choose a background image and apply it.
$(function() {
$('.themes li a img').click(function() {
var image = 'imgs/someimage.jpg';
//Set cookie
function setCookie(){
$.cookie("html_img", image, {expires:7});
var a = $.cookie('html_img');//get cookie value
return a;
}
});
});
Another script called loadCookie.js loads the cookie which contains the chosen background when the user visits another page:
$(function() {
var startImage='';
startImage = setCookie();
$(document).ready(function(){
$('html').css("background", startImage);
});
});
IE8 says 'object doesn't support this action, line 3'; Jquery cookie plugin is installed. I know there is some little mistake I can't find. Any help making the script work is greatly appreciated.
A: Not 100% on what you're trying to do, but I think this is what you're after (assuming you're using jquery.cookie.js):
$(function() {
if($.cookie("html_img")) {
$('html').css("background", $.cookie("html_img"));
}
$('.themes li a img').click(function() {
var image = 'imgs/someimage.jpg';
// var image = $(this).attr('src');
$('html').css("background", image);
$.cookie("html_img", image, {expires:7});
return false;
});
});
A: Since this is your third question posted about this same code (previous ones here and here), you seem really confused both about this code and about the proper way to use stack overflow.
Here's how cookies work in general. On one page, you set a cookie. On a follow-on page you read that cookie and use it's value.
In this code example, you are setting a cookie in the first block of code to a background image. So far, so good.
In the second block of code, you are calling setCookie again. If you want to retrieve the background image from the cookie, then you need to get the cookie value, not set it. Your code should probably be something like this:
$(document).ready(function() {
// initialize background from cookie
var startImage = $.cookie("html_img"); // get cookie value
if (startImage) {
$(document.body).css("background-image", startImage);
}
// install click handler to change background
$('.themes li a img').click(function() {
var newBackground = 'imgs/someimage.jpg';
$(document.body).css("background-image", newBackground);
$.cookie("html_img", newBackground, {expires:7}); // save in cookie
});
});
You may also need to know that if you do not specify a path option for the cookie like path: '/', the cookie will only be readable on the current path and not elsewhere on your site. Documentation for that jQuery add-on cookie library is here.
As for using stackoverflow, you should ask a clear question about a particular piece of code and when respondents are confused or provide answers that aren't what you meant to ask, you should clarify your question appropriately until you get an appropriate answer. Remember, when people provide answers in the wrong direction, it is most likely because they don't understand what you are asking, not because they don't know how to answer. You should not post a minor variation of the same question all over again in a new question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS3 cross browser linear gradient What will be Opera and IE alternatives of following code?
background-image: -webkit-gradient(linear, right top, left bottom, from(#0C93C0), to(#FFF));
background-image: -moz-linear-gradient(right, #0C93C0, #FFF);
Note, I've tested following rules. All browsers supports them. But they are vertical gradients. How can I modify them to horizontal ones?
background-image: -webkit-linear-gradient(top, #0C93C0, #FFF);
background-image: -moz-linear-gradient(top, #0C93C0, #FFF);
background-image: -ms-linear-gradient(top, #0C93C0, #FFF);
background-image: -o-linear-gradient(top, #0C93C0, #FFF);
background-image: linear-gradient(top, #0C93C0, #FFF);
A: background-image: -ms-linear-gradient(right, #0c93C0, #FFF);
background-image: -o-linear-gradient(right, #0c93C0, #FFF);
All experimental CSS properties are getting a prefix:
*
*-webkit- for Webkit browsers (chrome, Safari)
*-moz- for FireFox
*-o- for Opera
*-ms- for Internet Explorer
*no prefix for an implementation which is in full accordance with the specification.
Use top right instead of right, if you want a different angle. Use left or right if you want a horizontal gradient.
See also:
*
*MDN: linear-gradient
Internet Explorer
For <IE10, you will have to use:
/*IE7-*/ filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#0c93c0', endColorStr='#FFFFFF', GradientType=0);
/*IE8+*/ -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#0c93c0', endColorStr='#FFFFFF', GradientType=0)";
filter works for IE6, IE7 (and IE8), while IE8 recommends the -ms-filter (the value has to be quoted) instead of filter.
A more detailled documentation for Microsoft.Gradient can be found at: http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx
-ms-filter syntax
Since you're a fan of IE, I will explain the -ms-filter syntax:
-ms-filter: progid:DXImageTransform.Microsoft.Gradient(
startColorStr='#0c93c0', /*Start color*/
endColorStr='#FFFFFF', /*End color*/
GradientType=0 /*0=Vertical, 1=Horizontal gradient*/
);
Instead of using a RGB HEX color, you can also use a ARGB color format. A means alpha, FF means opaque, while 00 means transparent. The GradientType part is optional, the whole expression is case-insensitive.
A: Rob W's answer is comprehensive, at the same time verbose. Therefore I'd like to go for a summary supporting current browsers end of 2014, while ensuring some backwards-compatibility at the same time, leaving out just IE6/7's invalid capability of rendering a linear gradient and early Webkit (Chrome1-9, Saf4-5 special way (-webkit-gradient( linear, left top, left bottom, color-stop( 0, #0C93C0 ), color-stop( 100%, #FFF ) );)
Standards syntax has changed from beginning gradient position to to direction, e.g. background-image: linear-gradient( to bottom, #0C93C0, #FFF );
Widely-supported, easy-to-read CSS:
background-color: #8BCCE1; /* fallback color (eg. the gradient center color), if gradients not supported; you could also work with an gradient image, but mind the extra HTTP-Request for older browsers */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient( startColorStr=#0C93C0, EndColorStr=#FFFFFF )"; /* IE8-9, ColorZilla Ultimate CSS Gradient Generator uses SVG bg image for IE9 */
background-image: -webkit-linear-gradient( top, #0C93C0, #FFF ); /* Chrome10-25, Saf5.1-Saf6, iOS -6.1, Android -4.3 */
background-image: -moz-linear-gradient( top, #0C93C0, #FFF ); /* Fx3.6-15 */
background-image: -o-linear-gradient( top, #0C93C0, #FFF ); /* Op11.10-12.02 */
background-image: linear-gradient( to bottom, #0C93C0, #FFF ); /* W3C, Fx16+, Chrome26+, IE10+, Op12.10+, Saf6.1+ */
An interesting side fact is, that most blog posts and browser gradient tools on the web, like f.e. famous ColorZilla's "Ultimate CSS Gradient Generator" include the MS vendor-prefixed -ms-linear-gradient value. It's supported from Internet Explorer 10 Consumer Preview on. But when you're including standards value linear-gradient, Internet Explorer 10 Release Preview renders it appropriately.
So by including -ms-linear-gradient and standards way, with -ms you're actually addressing just IE10 Consumer Preview, which comes down to nobody in your audience.
A: I got the solution for almost everything!
/* Safari 4+, Chrome 1-9 */ background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#000000), to(#FFFFFF));
/* Safari 5.1+, Mobile Safari, Chrome 10+ */ background-image: -webkit-linear-gradient(top, #000000, #FFFFFF);
/* Firefox 3.6+ */ background-image: -moz-linear-gradient(top, #000000, #FFFFFF);
/* IE 7-*/ filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#000000', endColorStr='#FFFFFF', GradientType=0);
/* IE 8+*/ -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#000000', endColorStr='#FFFFFF', GradientType=0)";
/* IE 10+ */ background-image: -ms-linear-gradient(top, #000000, #FFFFFF);
/* Opera 11.10+ */ background-image: -o-linear-gradient(top, #000000, #FFFFFF);
/* fallback image background-image: url(images/fallback-gradient.png);*/
/* fallback/image non-cover color */ background-color: #000000;
A: Here an example, which works with Opera, Internet Explorer and many other web browsers. If a browser does not support gradients, it will show a normal background color.
background: #f2f5f6;
background: -moz-linear-gradient(top, #f2f5f6 0%, #e3eaed 37%, #c8d7dc 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f2f5f6), color-stop(37%,#e3eaed), color-stop(100%,#c8d7dc));
background: -webkit-linear-gradient(top, #f2f5f6 0%,#e3eaed 37%,#c8d7dc 100%);
background: -o-linear-gradient(top, #f2f5f6 0%,#e3eaed 37%,#c8d7dc 100%);
background: -ms-linear-gradient(top, #f2f5f6 0%,#e3eaed 37%,#c8d7dc 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2f5f6', endColorstr='#c8d7dc',GradientType=0 );
background: linear-gradient(top, #f2f5f6 0%,#e3eaed 37%,#c8d7dc 100%);
I've stolen this from this website. Microsoft has built their own generator here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: make windows form Title at The middle of the tittle bar In My windows form application I want to make the title of the form in the middle of it's bar ( Title bar ) for example :
if you are on windows xp and open your my computer you will find it in the left of the title bar I want for example to make my title in the middle of the same bar
How ?
A: That's not possible using regular WinForms form properties. On the other hand, you can create a form without any border and custom draw your own borders. That will be very much like what other skinning libraries too so you can look into various skinning libs from vendors if you don't want to bother with writing your own custom routines.
A: There are basically three options:
*
*Create a custom control that has the title centered and the appropriate minimize/maximize/close buttons. Use a from with no title bar and drop your custom control on top.
*Use GDI+ to draw the title, and update its position using form resize events. Total hack, not even sure this would work.
*Calculate the number of spaces required to center the title based on the width of the form and then insert them before the title text. Lame solution, but it would work and be easy to implement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C string split problem I am writing small IRC Bot, and i need to split incoming messages for easier handling. I wrote a function get_word, which should split string. According to gdb and valgrind, problem is that function sometimes returns invalid pointer, and program fails when trying to free that pointer.
Here is the code:
char **get_word(char *str) {
char **res;
char *token, *copy;
int size = 1;
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] == ' ') {
while(str[i] == ' ') {
i++;
}
size++;
}
}
res = malloc((size + 1) * sizeof(char *));
copy = strdup(str);
token = strtok(copy, " ");
for(int i = 0; token != NULL; i++) {
res[i] = strdup(token);
token = strtok(NULL, " ");
}
free(copy);
res[size] = NULL;
return res;
}
A: One problem I see is with your nested loops:
Consider this input: ' \0'
The function execution reaches the for loop, i == 0. Then the while loop is also entered. At the end of while loop i == 1. Now the incrementation statement from the for loop is executed and i == 2. So next you will be reading past the end of the string.
EDIT
I understand that size is the number of words found in the input. So I'd go for something like:
for (int i = 0; str[i] != '\0'; ++i) {
if (str[i] != ' ' && (str[i + 1] == ' ' || str[i + 1] == '\0')) {
// Counting endings of words
size++;
}
}
A: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **split (const char *str)
{
char **arr = NULL;
size_t cnt=0;
size_t pos, len;
arr = malloc (sizeof *arr);
for (pos = 0; str[pos]; pos += len) {
char *dup;
len = strspn(str+pos, " \t\r\n" );
if (len) continue;
len = strcspn(str+pos, " \t\r\n" );
if (!len) break;
arr = realloc (arr, (2+cnt) * sizeof *arr);
dup = malloc (1+len);
memcpy (dup, str+pos, len);
dup [len] = 0;
arr [cnt++] = dup;
}
arr[cnt] = NULL;
return arr;
}
int main(int argc, char **argv)
{
char **zzz;
for( zzz = split( argv[1] ); *zzz; zzz++) {
printf( "->%s\n", *zzz );
}
return 0;
}
The reallocation is a bit clumsy (like in the OP) and improving it is left as an exercise to the reader 8-}
A: As julkiewicz points out, your nested loops where you count the words could miss the terminating null on str. Additionally, if str ends with spaces, your current code would count an extra word.
You could replace this section:
int size = 1;
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] == ' ') {
while(str[i] == ' ') {
i++;
}
size++;
}
}
..with something like this:
while (*str == ' ') str++; // skip leading spaces on str
/* count words */
int size = 0;
char *s = str;
do {
if (*s && *s != ' ') {
size++; // non-space group found
while (*s && *s != ' ') s++; // skip to next space
}
while (*s == ' ') s++; // skip spaces after words
} while (*s);
..which counts the starts of groups of non-space characters, rather than groups of spaces, and watches for the terminating null in the inner loops.
You might also consider changing:
for(int i = 0; token != NULL; i++) {
..to:
for(int i = 0; token && i < size; i++) {
..just as a slightly paranoid guard in case strtok finds more words than you counted (though it shouldn't).
A: I think gdb may be complaining about the fact that you never check the return value of malloc (or strdup) to see if it's non-NULL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mac OSX / cocoa - getting location path string with raw data for a NSPasteBoard item I have an app which allows me to drag items from my web browser to the app dock icon.
When I drag an image from the web and get is raw data with [pBoardItem dataForType:NSPasteboardTypePNG];
I get the raw image data which I need but I also need to know the location of the image form where it was taken (ie. http://www.somedomain.com/somedir/someimage.png ) OR if its local (/Users/somedude/photos/myphoto.png).
How do I get the path location information?
Thanks in advance.
[EDIT** removed an erroneous comment I made regarding stringForType here]
A: Nothing's on the pasteboard that wasn't put there by its owner (the app that copied to it).
Look for NSFilenamesPboardType and/or NSURLPboardType on the pasteboard.
If they aren't there, only an image was copied, without a path or URL. This is completely possible and valid, as in the case of a section of an image copied from Preview or an image editor, and it's also completely possible for an application to simply not put the path or URL on the pasteboard, so don't expect that an image will necessarily come with a path or URL.
when I use the stringForType: function I only get public.png (the name pasteboard gave it temporarily).
Er? Are you saying that when you asked for a string for some type, the string you got back was @"public.png"?
If so, that has nothing to do with an image on the pasteboard; @"public.png" would be the contents of the pasteboard. Perhaps you had just copied “public.png” to the clipboard yourself?
If you meant that you retrieved a string for the type @"public.png", (1) that isn't a temporary name, it's the UTI for PNG, (2) you should use the named constants, such as kUTTypePNG, in preference to hard-coded literals, and (3) the value for that type should never be a string. I wouldn't expect to get anything useful from a stringForType: message with that type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: IPad Web App. Javascript, load all content in or switch page? We are working on a protoype web application, targeted at the IPAD. We have made great use of HTML5 and the app is working well.
Part of the requirement is to allow the app to switch between "Pages" in a fluid motion just like a native app.
So one of our suggestions is to change the way the web-app works. At present the app works much like a normal website, this presents problems when switching to pages with large images or animations (As they are loaded when the page switches).
Is it recommended to change our app so what the home page simply drags the new content (via AJAX) and manipulates the page accordingly, thus creating a so called single page app. Reducing the number and size of the http requests?
If this is the case and we wish to load the content via AJAX, how can we be sure that once we have dragged the content in, each of the images on the page have loaded. This will allow us to use a simple loading icon while the transition is taking place.
A:
Is it recommended to change our app so what the home page simply drags the new content (via AJAX) and manipulates the page accordingly, thus creating a so called single page app. Reducing the number and size of the http requests?
In a single-page app (SPA), the number of requests may not be reduced, but their size may be, b/c you will have to load your scripts and view only once, then just update relevant parts of the page. (Of course, a multi-page design can also have significant speed improvements with carefully-constructed cache-control headers). One benefit of the SPA paradigm is that you can load multiple pages during initial app load, and show them when necessary. Thus, you can trade off some delay in the initial load for a snappier user experience on subsequent page changes - saving yourself a trip to the server, even if it is an "AJAX trip". This is a trade-off that I usually like to make in SPAs.
If this is the case and we wish to load the content via AJAX, how can we be sure that once we have dragged the content in, each of the images on the page have loaded.
If the images are small enough, an alternative is to use base-64 encoded images, this'll guarantee that all content is ready to be displayed at the same time.
You could attach the content to the dom in a container, but hide it. Show the container after all of the images' 'load' events have fired. If you use jQuery, a plugin that helps with this is https://github.com/alexanderdickson/waitForImages. If you are using pure JS, you'd probably have to roll your own solution, which would involve:
*
*iterate over all the images in the container,
*storing a count of the number of images (numImages) and initializing a counter (numLoaded) that tallies the number of loaded images, and
*binding to each image's 'load' event, such that when it fires, the numLoaded counter is incremented, while
*checking whether numLoaded == numImages. If true, all images have loaded and the container can be displayed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: pause page before redirecting back I'd like to make a certain WordPress page pause for a few seconds before redirecting back to the page the visitor was on. The scenario is a redirect page after successful submission of a form. It will say 'form submitted successfully' or the like for a few seconds, and then redirect back to the page the visitor was on. The redirect is just a simple browser back functionality --
<script type="text/javascript">history.go(-1);</script>
-- in the head, which is easy to add to just that specific page with a custom field. But what can I add to make the page pause for a few seconds before going back? Bear in mind that this is a WordPress site with lots of posts so I can't use some kind of body onload redirect back to a specific post with window.location = "the-post-or-page-visitor-was-on";. I need to use the browser's back history to just take the visitor back -1 to whatever page or post they were on, but just pause for a few seconds before doing so.
Thanks a lot.
A: Try window.setTimeout():
<script type="text/javascript">
window.setTimeout
(
function() { history.go(-1); },
1000 // 1 second
);
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calendar showing wrong date and time final Calendar c = Calendar.getInstance();
Toast.makeText(alarm.this, " "+c.DAY_OF_MONTH+ " " +c.MONTH+ " " +c.YEAR ,
Toast.LENGTH_LONG).show();
this code is showing 05-02-01 as the date, instead of todays date (25-08-2011)
Can anybody tell me what is happening?
regards
sandeep
A: Use the get method to get the actual field values:
c.get(Calendar.DAY_OF_MONTH) ...
The value DAY_OF_MONTH is actually a constant referencing the fields of the calendar object.
A: and, according to what Howard says in comment, you must add 1 to get the exact value for the month since it's coded between 0 and 11 :
Calendar c = Calendar.getInstance();
Toast.makeText(alarm.this, String.valueOf(c.get(Calendar.MONTH)+1)).show();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Memory leak using QVector QVector<cLibraryRecord> Library;
...
Library.push_back(cLibraryRecord(ReaderFullName, BookGenre, BookTitle, AuthorsFullName, IssueDate, ReturnDate));
...
Library.remove(i);
QVector::remove() does not clear the memory. How can I clean the memory?
Thanks in advance.
A: QVector.remove() always calls the destructor for the contained object, but the reserved size (returned by QVector::capacity()) doesn't shrink automatically when you remove elements.
You can use QVector::squeeze() to release the unused reserved memory.
But you can also have a memory leak in your class cLibraryRecord.
See Qt documentation for more details: Qt containers growth strategies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IE7 CSS Mega Menu Issue The following code for a navigation menu works brilliantly with IE8 and Firefox, Chrome etc. However, I am getting a error with IE7.
My megamenu dropdown can't display over an image. Notice in IE7 how the image (google search image) appears higher in the z-index when I hover over the yellow area. Why is this?
For reference, here is the code which I am currently using in case if anybody want to try this on their end:
<!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" dir="ltr" lang="en-US">
<![endif]-->
<!--[if IE 7]>
<html id="ie7" dir="ltr" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html id="ie8" dir="ltr" lang="en-US">
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html dir="ltr" lang="en-US">
<!--<![endif]-->
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>CSS | IE7 Issue</title>
<style type="text/css">
.row {position:relative; margin-left:-10px;}
.gu12 .row {width: 960px;}
li {padding:0;margin:0}
a {padding:0;margin:0}
.col {padding-left:10px; float:left; position:relative;}
.gu12{width: 950px;}
#nav3 ul {float:left;}
#nav3 ul li {list-style-type:none;float:left}
#nav3 ul li a {display:block;line-height:40px;}
#nav3 {padding-left:1px;height:40px}
#nav3 a span {height:40px;padding:0;margin:0;margin-top:0px!important;position: absolute; width 100%;height:100%}
a#programme-options {height:40px;width:177px;position: relative;}
a#programme-options span {background-position:-159px 0px;position: absolute;width: 100%;height: 100%;}
a#programme-options span:hover {background-position:-159px -160px!important}
a#programme-options.active span, a#programme-options:active {height:40px;width:177px;margin-top:0px!important;background-position:-159px -200px}
#nav {padding-top:15px;padding-bottom:0px;}
#nav {margin-top:45px;padding-top:0px;padding-bottom:0px;}
#nav ul {float:left;width:950px;}
#nav ul li {list-style-type:none;float:left}
#nav ul li a {display:block;line-height:40px;}
#top .avia_mega ul ul li, #top .avia_mega >li >ul li{
color:#777;
background-image: url(menu_arrow.png);
background-position: -20px -11px;
*background-position: -50px -51px; /*ie7 pseudo fix of bg images*/
background-repeat: no-repeat;
}
#top .avia_mega{height:40px; line-height:40px; padding:0; left:1px; bottom:0px; position:absolute; z-index:100}
.avia_mega, .avia_mega ul{margin:0; padding:0; list-style-type:none; list-style-position:outside; position:relative; line-height:40px; z-index:5}
#top .avia_mega li{float:left; position:relative; z-index:20; margin-left:0}
#top .avia_mega ul a:hover{text-decoration:underline}
#top .avia_mega div ul{line-height:21px}
.avia_mega1, .avia_mega2, .avia_mega3, .avia_mega4, .avia_mega5{position:absolute; display:none; top:0px; left:0; padding:8px}
#top .avia_mega div ul li{width:162px; padding:15px}
#top .avia_mega > li > ul, #top .avia_mega > li > ul ul {background:#4d0702}
#top .avia_mega > li > ul li {background:#990E03}
#top .avia_mega div ul{float:left}
#top .avia_mega div ul ul{padding:0 0 10px 0}
#top .avia_mega div ul ul ul{padding:2px 0 0}
#top .avia_mega div ul li li{width:139px; float:left; clear:both; padding:3px 0 3px 23px; margin:0}
#top .avia_mega div ul li li li{width:116px}
#top .avia_mega div ul li li li li{width:93px}
#top .avia_mega ul a{text-align:left; display:inline; line-height:21px; padding:0; height:auto; float:none; font-size:1em}
#top .avia_mega div ul ul .avia_mega_text_block{background:none; padding:3px 0 0 0; margin:0; font-size:1em; line-height:1.7em}
#top .avia_mega div ul .avia_mega_hr{width:100%; height:20px; clear:both; padding:0}
#top .avia_mega >li >ul, #top .avia_mega >li >ul ul{position:absolute; display:none; width:203px; top:40px; left:0px; padding:8px}
#top .avia_mega >li >ul ul li:first-child{left:-10px; padding-left:0; position:relative; width:234px}
#top .avia_mega >li >ul ul li:first-child a{position:relative; left:44px}
#top .avia_mega >li >ul a{width:170px; display:block; padding:2px 20px 2px 0;color:#fff;font-weight:normal!important}
#top .avia_mega >li >ul li{padding:3px 0 3px 14px}
#top .avia_mega >li >ul ul{border-top:medium none; left:224px; top:-8px}
#top .avia_mega >li:hover >ul ul, #top .avia_mega >li>ul li:hover ul ul, #top .avia_mega >li>ul ul li:hover ul ul, #top .avia_mega >li>ul ul ul li:hover ul ul, #top .avia_mega >li>ul ul ul ul li:hover ul ul{display:none}
#top .avia_mega >li:hover >ul, #top .avia_mega >li >ul li:hover ul, #top .avia_mega >li >ul ul li:hover ul, #top .avia_mega >li >ul ul ul li:hover ul, #top .avia_mega >li >ul ul ul ul li:hover ul, #top .avia_mega >li >ul ul ul ul ul li:hover ul{display:block}
</style>
</head>
<body id="top">
<div class="row">
<div class="col gu12 navarea">
<div id="nav3">
<ul id="menu-main-menu" class="avia_mega sf-menu" style="background:red">
<li><a href="/" id="home" class="home "><span></span>Home</a></li>
<li><a href="#" id="programme-options" class=""><span style="background:yellow"></span>Tester</a>
<ul>
<li><a href="#">Test Link</a></li>
<li><a href="#">Test Link</a></li>
<li><a href="#">Test Link</a></li>
<li><a href="#">Test Link</a></li>
<li><a href="#">Test Link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col gu12">
<img src="http://indiawebsearch.com/files/image/thumb_googlelogo.jpg" class="main-img" style="float:left" />
</div>
</div>
</body>
</html>
A: Issue resolved :)
I changed my HTML to:
<div class="row2">
<div class="col2 gu12">
<img src="http://indiawebsearch.com/files/image/thumb_googlelogo.jpg" />
</div>
</div>
It would appear row and col classes don't like IE7.
Thanks for taking a look.....anyone?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Objective-C: EXC_BAD_ACCESS when adding annotation to map I have the following Objective-C code:
NSString *urlStr=[[NSString alloc] initWithFormat:@"http://www.prestocab.com/driver/ajax/getFriendsOnMap.php"];
NSURL *url=[NSURL URLWithString:urlStr];
__block ASIFormDataRequest *request=[[ASIFormDataRequest alloc ]initWithURL:url];
[request setDelegate:self];
[request setPostValue:[NSString stringWithFormat:@"%f",swCoord.latitude ] forKey:@"sw_lat"];
[request setPostValue:[NSString stringWithFormat:@"%f",swCoord.longitude ] forKey:@"sw_lng"];
[request setPostValue:[NSString stringWithFormat:@"%f",neCoord.latitude ] forKey:@"ne_lat"];
[request setPostValue:[NSString stringWithFormat:@"%f",neCoord.longitude ] forKey:@"ne_lng"];
[request setCompletionBlock:^{
NSLog(@"%@",[request responseString]);
SBJsonParser *parser=[[SBJsonParser alloc]init];
//NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSDictionary *arr=[parser objectWithString:[request responseString] error:nil];
MapViewAnnotation *annotation=[[MapViewAnnotation alloc]init];
for(int i=0;i<arr.count;i++){
NSDictionary *obj=[arr objectForKey:[NSString stringWithFormat:@"%d",i]];
CLLocationCoordinate2D coord;
coord.latitude=[[obj objectForKey:@"lat"] doubleValue];
coord.longitude=[[obj objectForKey:@"lng"] doubleValue];
[annotation initWithTitle:[obj objectForKey:@"uname"] andCoordinate:coord];
//[self.mapView performSelectorOnMainThread:@selector(addAnnotation) withObject:annotation waitUntilDone:YES];
[self.mapView addAnnotation:annotation];
}
[annotation release];
//[self.mapView addAnnotations:annotations];
//[annotations release];
}];
[request setFailedBlock:^{
}];
[request startAsynchronous];
As you can see, I'm getting some data from my website using ASIHttpRequest, parsing the result and hoping to put annotations on the MKMapView.
Trouble is, when I call [self.mapView addAnnotation:...] I keep getting one of these EXC_BAD_ACCESS errors that I simply cannot get to the bottom of.
Anyone have any suggestions?
Many thanks in advance,
A: By the time the completion block runs self may not be valid. In such a case you need to copy the block to the heap.
You can wrap your block:
[ <your block> copy];
Then there is the issue of releasing the block, many times an auto release works well:
[[ <your block> copy] autorelease];
Other times you may need to explicitly release it.
You might want to typedef your block to make this clearer.
A: you get BAD_ACCESS because either the mapView or the annotation is already destroyed but you have a pointer to that instances. I guess that you dont retain the mapView. You can check these kind of errors by turning on the NSZombies and by enabling stop on exception.
Or put this code before the line of code where the error happens:
NSLog(@"mapView-desc: %@",[self.mapView description]);
NSLog(@"annotation-desc: %@",[annotation description]);
The BAD_ACCESS should now happen in one of these two lines and then you know on which obejct you have forgotten to retain ;) If there is all fine then the problem is inside mapView or the data in your annotations. The easiest way is to enable NSZombies and wait for messages in your console.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: URL file-access is disabled in the server URL file-access is disabled in the server - is the error I'm getting with Short URLs. I'm no PHP coder, so if you could post the code I should be using I would appreciate it! How do I rewrite the path?
In functions:
//////////////////////////////////////// Custom templates: page templates
add_filter('single_template', create_function('$t', 'foreach( (array) get_the_category() as $cat ) { if ( file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php") ) return TEMPLATEPATH . "/single-{$cat->term_id}.php"; } return $t;' ));
The call:
<?php $turl = getTinyUrl(get_permalink($post->ID));
echo 'Short URL <a href="'.$turl.'">'.$turl.'</a>' ?>
A: If PHP has cURL enabled you can add this function:
function getTinyUrl2($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, "http://tinyurl.com/api-create.php?url=".$url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
and then change your code to use the new function:
$turl = getTinyUrl2(get_permalink($post->ID));
echo 'Tiny Url for this post: <a href="'.$turl.'">'.$turl.'</a>'
Hope that helps
A: Tinyurl.com does not allow you to get file by php's file_get_contents function.
Use curl instead to use tinyurl api.
<?php
$url = "http://example.com";
$ch = curl_init("http://tinyurl.com/api-create.php?url=".$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFERT, true);
$tinyurl = curl_exec($ch);
curl_close($ch);
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use DotNetOpenAuth to log into Google, and get user profile I just want to login with google and want access logged in user's general profile like photo, email address and name, to display on my site. Is it possible with DotNetOpenAuth?
A: That's trivially easy. Use OpenID to "just login", instead of OAuth. Take a look at the OpenIdRelyingPartyWebForms or OpenIdRelyingPartyMvc samples for how to log a user in. Since you're only interested in logging the user in with Google, rather than displaying an input box you can just have a "Login with Google" button that calls OpenIdRelyingParty.CreateRequest("https://www.google.com/accounts/o8/id") to initiate a Google login.
As @Lirik pointed out in a comment, you can use AX to retrieve user profile info. However I don't think that will get you the user photo. If Google even makes that available (big if) you may have to use OAuth for that. And I would recommend in that case that you use the "OpenID+OAuth" extension for that, which I believe leads you to the "Google Contacts" sample you have already seen. To change that to retrieve a user photo however, you'd need to review Google's own GData API documentation to see how to retrieve a user photo (if you can).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Subreport parameters and grouping with Reporting Services First, I'll lay out the structure:
The main report is a table variable from sql server giving form type, form
number, previous date (hidden), current date (hidden, though the parent grouping is using this), the difference in times, person's id (hidden), and person's full name. The main report is only for unexpected results and isn't all of the data for a given day.
The subrepoort is totals counts of the various form types based on either the entire project (on a given day) excluding the person's id if there isn't a specific person selected or filtered by day and person's id if someone is. The subreport should be the Totals row for a given day (the intended parent group) as the main report is anomalies, the totals are for all forms done.
I've run into a few problems:
1) The date grouping thing is seperating based on date and time. Is there a way to drop the time component of a field for the sake of the grouping? I'm looking at http://thavash.wordpress.com/category/reporting-services/page/3/ right now and the FormatDateTime thing may be useful if it is more than just a visual change (ie I won't have a bunch of 9/25/11 groups).
2) The subreport takes in two parameters of person and date to generate the list. I'm wondering if there is a hybrid way of passing parameters to the subreport as the date parameter is based off the parent groups (so not sure that it can be programmatically set). The person value may be able to be achieved by taking the key of the drop down list on the form. The only problem is I'm not sure how I can tell it programmatically to take the personid, but pull the date component only of the parent group.
A: 1)
Use something like =Format(Fields!MyDateField.Value,"dd/MM/yyyy") to format the date to string. Change the formatting expression to your needs.
To properly sort the group use =Format(Fields!MyDateField.Value,"yyyyMMdd")
2)
You can pass any expression as a parameter to the subreport meaning that they can be group values, main report parameters etc.
For example: if your date parameter is on group named "table1_Group1", and you want to use it to a subreport, you can use an expression referencing to the group like =First(Fields!MyDateField.Value,"table1_Group1")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Camera working without camera permission? In one of our applications we use the camera intent to take pictures. This works on real devices - without the camera permission.
Is this correct or should I add it to this apps Manifest?
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Image capture");
contentValues.put(MediaStore.Images.Media.TITLE, "new image");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 1);
TIA
A: See this:
http://mobile.tutsplus.com/tutorials/android/android-sdk-quick-tip-launching-the-camera/
There are two things noted there. First:
A Note on Permissions:
Although your application is leveraging the Camera, it is not required to have the android.permission.CAMERA permission since it is not directly accessing the camera. Instead, it’s just launching the Camera application via Intent.
I don't see this clarified anywhere at developer.android.com, though, so this could be wrong and something else is happening.
It seems you only need the permission to access the camera primitives directly, and not via the Intent.
Note, that the same URL above also points out that you should declare the feature to prevent users without cameras from seeing your app in the market.
A: To add up to the answer above, here are the 2 ways to access the camera :
*
*https://developer.android.com/guide/topics/media/camera
*https://developer.android.com/training/camera/photobasics
In the first case, you use the camera api and use the camera directly in you app. Thus, you need to request the camera permission (android.permission.CAMERA).
In the second case, you open the camera activity of the OS. In this case, Android does not require to request the permission.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Install PHP CodeSniffer with Netbeans 7.0.1 on Windows 7 64 bits I'm trying to install PHP_CodeSniffer with Netbeans in my computer with Windows 7 64 bits.
So far...
1) I've downloaded from https://github.com/beberlei/netbeans-php-enhancements/downloads the file de-whitewashing-php-cs-1.1.1.nbm,
2)installed the plugin,
but when I go to Tools->Options it request Code Sniffer Script with a browse button, I don't know what that file is, and if a select phpcs.bat then in the next Standard drop down list nothing shows up. The menu item Show Code Standard Violation is disabled.
How can I install this?
Thanks! Guillermo.
A: The CodeSniffer script field is looking for the batch file that runs PHP CodeSniffer. The implication is that you should already have installed PHPCS before you get to that point.
If you were not already aware, the module written by Mr. Eberlei integrates PHPCS into Netbeans through PHPCS's API, not by provding the code sniffer functionality within the module itself.
If not installed already, get PEAR working on your XAMPP installation. After that's ready, then you can follow the instructions on the PHP_CodeSniffer page to install PHPCS itself.
Once that is installed, then you should have a ...path-to-PHP-installation-in-xampp.../PEAR/PHP/CodeSniffer directory, and under that, a Standards directory with the default set of standards. That is what populates the Standard combo box. I vaguely remember having to restart Netbeans after setting the CodeSniffer script field in order for the module to populate the combo box properly. Once it is populated, then you choose from that list in the combo box which standard you want PHPCS to apply to your code.
A: I had the problem and I could fix it by adding the path containing the phpcs.bat to the windows system PATH variable. For a strange reason, the plugin also needs the environnement variable to be set ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Use a section of a UIImage to create a new UIImage I'm fairly new to Ios programming and was hoping someone can help me here or point me in the right direction.
How I would I create a new image from part of an existing one?
For example, if I have an UIImage in a UIImageView, that is 100 pixels(or points) square, and I want to create a new UIImage from a section of the original.
This new UIImage might be 10 pixels square and start at the origin of the original UIImage ( it could be anywhere really ). I might then take this new image and display it in another view or add it to an array etc.
Or another way to explain might be if I had an image of one face of a Rubix cube... and I then wanted to create new images for each of the different coloured squares...
Any help or ideas will be much appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem Django on IIS 7.5 - PyISAPIe Error was: 'module' object has no attribute 'argv' I have some problem when I run the Django App on IIS 7.5..
Just follow the steps introduced by [this][1].
I successful run the project on IIS 7.5.
But, it show some problems.. like this..
Request Method: GET
Request URL: http://localhost/
Traceback:
File "D:\Program Files\Python\Python25\lib\site-packages\django\core\handlers\base.py" in get_response
101. request.path_info)
File "D:\Program Files\Python\Python25\lib\site-packages\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "D:\Program Files\Python\Python25\lib\site-packages\django\core\urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "D:\Program Files\Python\Python25\lib\site-packages\django\core\urlresolvers.py" in _get_callback
170. raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e)))
Exception Type: ViewDoesNotExist at /
Exception Value: Tried home in module core.views. Error was: 'module' object has no attribute 'argv'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: word count problem I wanna count words from text files which contain data as follows:
ROK :
ROK/(NN)
New :
New/(SV)
releases, :
releases/(NN) + ,/(SY)
week :
week/(EP)
last :
last/(JO)
compared :
compare/(VV) + -ed/(EM)
year :
year/(DT)
releases :
releases/(NN)
The expressions like /(NN), /(SV), and /(EP) are considered category.
I wanna extract the words just before each of category and count how many words are in the whole text.
I wanna write a result in a new text file like this:
(NN)
releases 2
ROK 1
(SY)
New 1
, 1
(EP)
week 1
(JO)
last 1
......
Please help me out!
here is my garage code ;_; it doesn't work.
import os, sys
import re
wordset = {}
for line in open('E:\\mach.txt', 'r'):
if '/(' in line:
word = re.findall(r'(\w)/\(', line)
print word
if word not in wordset: wordset[word]=1
else: wordset[word]+=1
f = open('result.txt', 'w')
for word in wordset:
print>> f, word, wordset[word]
f.close()
A: from __future__ import print_function
import re
REGEXP = re.compile(r'(\w+)/(\(.*?\))')
def main():
words = {}
with open('E:\\mach.txt', 'r') as fp:
for line in fp:
for item, category in REGEXP.findall(line):
words.setdefault(category, {}).setdefault(item, 0)
words[category][item] += 1
with open('result.txt', 'w') as fp:
for category, words in sorted(words.items()):
print(category, file=fp)
for word, count in words.items():
print(word, count, sep=' ', file=fp)
print(file=fp)
return 0
if __name__ == '__main__':
raise SystemExit(main())
You're welcome (=
If you will want also count that weird "-ed" or ",", tune regexp to match any character except whitespace:
REGEXP = re.compile(r'([^\s]+)/(\(.*?\))')
A: You're trying to use a list (yes word is a list) as an index. Here is what you should do:
import re
wordset = {}
for line in open('testdata.txt', 'r'):
if '/(' in line:
words = re.findall(r'(\w)/\(', line)
print words
for word in words:
if word not in wordset:
wordset[word]=1
else:
wordset[word]+=1
f = open('result.txt', 'w')
for word in wordset:
print>> f, word, wordset[word]
f.close()
You're lucky I want to learn python, otherwise I wouldn't have tried your code. Next time post the error you're getting! I bet it was
TypeError: unhashable type: 'list'
It's important to help us help you if you want good answers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Data Mining/Statistical Analysis options for a Heroku Rails app? I have a rails app that is hosted on Heroku for which I want to incorporate some live data analysis. Ideally, I'd love to figure out a way to run a generalized boosted regression model, which I know is available in both R (http://cran.r-project.org/web/packages/gbm/index.html) and Stata (http://www.stata-journal.com/article.html?article=st0087). I want to save the resulting gbm tree and then, within my app, use it to predict new results based on user input.
If that's not possible, I'd be open to using other data mining algorithms. Most important to me is the ability to integrate it into my Heroku app so that it can run without my local machine.
Options I've looked into:
1) Heroku Support suggested vendoring the R library into a ruby gem. I'm relatively new to ruby and rails, is this something that would be feasible for me to do. I've looked around for instructions on vendoring libraries in gems, but haven't been able to find much.
2) Another thread here (http://stackoverflow.com/questions/6495232/statistic-engine-that-work-with-heroku) mentioned CloudNumbers, but it doesn't seem possible to call the service from a Rails app.
3) In one of their case studies, Heroku mentions FlightCaster, which uses Clojure, Hadoop, and EC2 for their machine learning (http://www.infoq.com/articles/flightcaster-clojure-rails). I saw that Heroku supports Clojure, but is there a way to integrate it (or more specifically Incanter) into my Rails app?
Please let me know if you have any ideas.
A: I'll answer this from an R perspective.
Generally, you're going to face two problems:
1) Interfacing with R, regardless of where it's running
2) Doing this from Heroku, where there are a special set of challenges.
There are a few general approaches to the first of these -- you can use a binding to R (rsruby, rinruby, etc.), you can shell out to R (e.g., from ruby R -e "RCODEHERE"), you can access R as a webservice (see the Rook package, and specifically something like https://github.com/jeffreyhorner/rRack/blob/master/Rook/inst/exampleApps/RJSONIO.R), or you can manually access R using something like rserve.
Of these, shelling out to R is the easiest thing to do if you're just doing a single operation and aren't hugely concerned about performance. You'll need to parse the output that comes back, but that's the fastest way in my experience for a single operation.
For more significant usage, I'd suggest using either one of the bindings, or setting up R as a webservice on another Heroku app and calling to it via HTTP.
The next challenge is getting R running on Heroku -- it's not available as part of the standard environment, and it's a read-only file system with no root access, so you can't just do sudo apt-get install.
It is possible to vendor R into a gem -- someone has started doing this at https://github.com/deet-uc/rsruby-heroku, but I was personally unable to get it working. It's also possible to build R directly on Heroku by installing all of the dependencies, etc. -- this is the approach that I've taken at https://github.com/noahhl/rookonheroku (step 1 is all you need if you aren't using Rook).
Note that Heroku might not allow you to spin up a second process in the same thread as your Rails app, which is what most of the bindings do. This can make it rather difficult to get those bindings working, which is why I tend to favor either shelling out to R, or exposing it as a webservice and accessing it via HTTP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Populate radio buttons with values from database two Qs in one day...
I'm trying to get the right radio button checked when I pull data from a mysql database to display in an edit form. Have tried all kinds of code but get the same result each time: the last value is always the one checked. Mystified.
My code is somewhat complicated by being inside a long html string, hence the construction for reading the php variables. I have this code at the top of the page:
$row = mysql_fetch_assoc($result, MYSQL_ASSOC);
if ($row)
{
print("<p>$se_id is in the database. You can edit this record.</p>");
//get variables to set radio buttons in $form
$type = $row['se_source'];
$checked[$type] = "checked";
etc... and this code inside the html string:
<li>
<label for="se_source">Contributed by:</label>
echo ' . $type . '
<input id="se_source" type="radio" id = "radio" name="se_source" value="CNFP" checked = ' . $checked["CNFP"] . '>CNFP</input>
<input id="se_source" type="radio" id = "radio" name="se_source" value="User" checked = ' . $checked["User"] . '>User</input>
The echo statement is for my own sanity -- I know it's not really an echo here. But even when it says "echo CNFP" it is always the "User" button that is checked. So I know it is getting the correct value for that variable, but for some reason it defaults to the last value in the list. I've tried it with "===" as well. No joy. Any enlightenment appreciated, thanks so much for taking a look.
A: AFAIK, the value of the checked attribute isn't important, only the presence of it is sufficient to mark the checkbox as checked.
(HTML5 standard confirms this)
Try something like this:
<input id="se_source" type="radio" id = "radio" name="se_source" value="CNFP"'.(($checked["CNFP"]) ? 'checked="checked"': '').'>CNFP</input>
A: The reason that you're always getting checked on the last one is because you're setting each radio button to checked consecutively.
When you pass a set of radio buttons with the same name to a browser, the default behavior is that the last button set as checked will be the one that shows up as checked. So, if you pass five radio buttons and they are all set as checked, the radio set cannot have more than one checked option.
When a browser encounters a second radio set option that is also marked as "checked," it simply removes "checked" from the first one.
Your php code is accomplishing this in this line:
$checked[$type] = "checked";
The problem with this is that you're creating an array that will show up with:
se_source => checked
So that means checked is the row value for every member in your array.
I think you should rethink your table structure and process. Instead of creating a column for the sake of making something checked, the following is what I use.
Basically, your problem is that you need:
*
*The value in the database to match
*The value of the radio button itself
Which will allow you to:
Compare the database value (DBV) with the radio button value (RBV) and set it as checked if the comparison comes back as true.
The variables below are:
$ar_rvbs = the array of radioset values (strings or booleans, usually) you are going to loop through and check against the stored DBV.
$value = the value of each item in the radioset value array
$attrval = the stored value for radio button. it doesn't necessarily have to be in a database. you could use the post method to pass it from one page to the next.
$checked = if the DBV matches the RBV when the loop goes through, this will be set to the string "checked" otherwise it is just an empty string.
function makeRadioSet($ar_rvbs,$attrval=[DBV] /*A*/
{
foreach ($ar_rvbs as $value)
{
$checked = ''; /*B*/
if ($attrval==$value) /*C*/
$checked = "checked"; /*D*/
echo '<input type="radio" name = "fieldname" value = "'.$value.'" '.$checked.'>';
}
}
/A/ Pass the list of RBVs as an array and the DBV as a variable
/B/ Set checked to an empty string because that will be the default for all the radio buttons in the set except the one that matches the DBV
/C/ Compare the DBV to the current RBV being processed by the loop from the RBV array
/D/ If the comparison from step C returns true, make the checked string available for insertion into the input element
The echo takes care of generating each radio set option and making sure the one that matches the DBV has "checked" in the input element tag
A: You need to have the "checked" attribute ONLY on the selected radio button. So you need to modify your php code to echo in the correct format.
A: i think the bellow code will work well as you want. you must add a field to check whether it is checked.
while($result = mysql_fetch_array($queryRes)){
if(chack the radio button chacked field){
echo "<input type="radio" checked="checked" value="value" name="same" />";
}
echo "<input type="radio" value="value" name="same" />";
}
A: Check this out! This could be what you are looking for :)
Generate checkbox based on entries on a MySQL table
$sql = "SELECT name FROM students";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
echo "<input type='checkbox' name='students[]' value='".$row['name']."'>"
.$row['name'];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unable to apply a function on every img within a div i'm trying to blur every image within a DIV, but for no reason, it just doesn't work
<div id="textarea" >random HTML with imgs</div>
<script type="text/javascript">
var arraysOfImgs = $('#textarea').find('img').map(function(){
return this.id;
}).get();
for (var i = 0; i < arraysOfImgs.length; i++){
Pixastic.process(arraysOfImgs[i], "blurfast", {
amount : '1.5'
});
}
</script>';
even this didn't work out
<script type="text/javascript">
$(document).ready(function() {
var arraysOfImgs = $('#textarea').find(\'img\').map(function(){
return this.id;
}).get();
$.each(arraysOfImgs, function() {
Pixastic.process(this, "blurfast", {
amount : '1.5'
});
});
});
</script>
no error is being shown, nothing happens when i load the page...
EDIT : no more php echo..
A: The problem I think is that you're passing the images' ID values. Pixastic (if it's this one) needs the image element.
Your code might look like this:
$('#textarea img').each(function() {
Pixastic.process(this, "blurfast", {
amount : '1.5'
});
});
Note also that Pixastic provides a jQuery plugin, so you can just do this:
$('#textarea img').pixastic('blurfast', {amount: 1.5});
A: try this :
var img = new Image();
img.onload = function() {
Pixastic.process(img, "blur");
}
document.body.appendChild(img);
img.src = "myimage.jpg";
and embeded blur.js ( http://www.pixastic.com/lib/git/pixastic/actions/blur.js )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: activity indicator only animates once i have created a custom "load more" cell at the bottom of my table view. And am trying to animate a activity indicator while the table is being populated with 5 more rows. Because the data loads too quickly, i have put a 2 sec timer to delay the process and want to show the indicator animation.
I seem to be able to get the indicator animated once then it wont animate any more, however the rest of the code still executes and works fine.
here is my code for when user selects the cell...
[moreCellIndicator startAnimating];
//setup activity indicator timer
NSTimer *activityTimer = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(loadMoreTimer:)
userInfo: nil repeats:NO];
here is the code that triggers after the timer...
- (void) loadMoreTimer:(NSTimer *)theTimer {
//stop animating activity indicator
[moreCellIndicator stopAnimating];
//refresh table
... data gets reloaded
}
for some reason the first time the code is run the indicator will animate, but any more presses and it wont animate.
any help would be appreciated.
chris
edit: moreCellIndicator is declared like so...
UIActivityIndicatorView *moreCellIndicator;
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *moreCellIndicator;
A: Try to release the activity indicator after you stop it, and initialize it before you start it:
moreCellIndicator = [UIActivityIndicatorView alloc] init];
and instead of using NSTimer use:
[self performSelector:@selector(loadMoreTimer:) withObject:self afterTimeDelay:2];
And change your method to (id):sender
- (void)loadMoreTimer:(id)sender
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A keyword to reference the current object as a generic type I have a simple generic delegate:
delegate void CommandFinishedCallback<TCommand>(TCommand command)
where TCommand : CommandBase;
I use it in the following abstract class:
public abstract class CommandBase
{
public CommandBase()
{ }
public void ExecuteAsync<TCommand>(CommandFinishedCallback<TCommand> callback)
where TCommand : CommandBase
{
// Async stuff happens here
callback.Invoke(this as TCommand);
}
}
While this does work, I have no way of forcing the TCommand passed into Execute to be the type of the current object (the more derived CommandBase).
I've seen this solved by doing:
public abstract class CommandBase<TCommand>
where TCommand : CommandBase<TCommand>
{
// class goes here
}
But I'm wondering why there isn't a C# keyword for accomplishing that? What I'd love to see is something like the following:
public void ExecuteAsync<TCommand>(CommandFinishedCallback<TCommand> callback)
where TCommand : This
{
// Async stuff happens here
callback.Invoke(this);
}
Note the capital T on "This". I'm by no means a language designer, but I'm curious if I'm out to lunch or not. Would this be something the CLR could handle?
Maybe there's already a pattern for solving the problem?
A: No, there is no thistype constraint. There are some musings on this topic by Eric Lippert here: Curiouser and curiouser.
Note, in particular, the CRTP (your "solution" to the problem) isn't actually a solution.
A: No, there is nothing like that in C#. You're going to have to go with your self-referencing generic class definition if you want to do this at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Everyauth, first login works, second fails Using everyauth, the first time a user login, a profile is added to my mongodb via mongoose and the session works well. The second time a user tries to login, the server crashes with the following error:
/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/modules/everymodule.js:352
throw err;
^ TypeError: Cannot read property 'id' of undefined at
Object._addToSession
(/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/modules/oauth2.js:195:46)
at Object.exec
(/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/step.js:48:21)
at
/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/stepSequence.js:19:38
at [object Object].fulfill
(/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/promise.js:42:25)
at
/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/stepSequence.js:22:23
at [object Object].callback
(/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/promise.js:13:12)
at
/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/stepSequence.js:21:23
at [object Object].fulfill
(/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/promise.js:42:25)
at
/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/stepSequence.js:22:23
at [object Object].fulfill
(/mnt/ws/users/guiomie/70543/node_modules/everyauth/lib/promise.js:42:25)
The following is my code:
.findOrCreateUser( function (session, accessToken, accessTokExtra, fbUserMetadata) {
//Verifies if user in database already
try{
var id = fbUserMetadata.id;
var promise = this.Promise();
User.findOne({ fbid: id}, function(err, result) {
var user;
if(!result) {
user = new User();
user.fbid = id;
user.firstName = fbUserMetadata.first_name;
user.lastName = fbUserMetadata.last_name;
user.save();
} else {
user = result.doc;
}
promise.fulfill(user);
});
return promise;
}
catch(err){
console.log(err);
}
})
I use mongoose and express.
A: Untested, but from looking at your code, it looks like you need to change this line:
user = result.doc;
to this:
user = result;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CMake ExternalProject_Add() - Building with customized CMakeLists.txt I am building lua as an external project and I want to use my own CMakeLists.txt instead of the bundled Makefile. This is what I have in my main CMakeLists.txt:
include(ExternalProject)
set(lua_RELEASE 5.1.4)
ExternalProject_Add(
lua-${lua_RELEASE}
URL http://www.lua.org/ftp/lua-${lua_RELEASE}.tar.gz
DOWNLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}/download/lua-${lua_RELEASE}
SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lua/lua-${lua_RELEASE}
BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/build/lua-${lua_RELEASE}
UPDATE_COMMAND ""
PATCH_COMMAND ""
INSTALL_COMMAND ""
)
For the BUILD step to work there must be a CMakeLists.txt in the SOURCE_DIR. I have this CMakeLists.txt in the SOURCE_DIR at the moment:
cmake_minimum_required(VERSION 2.8)
project(lua)
set(lua_library
lapi.c lcode.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c
lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c
ltable.c ltm.c lundump.c lvm.c lzio.c
lauxlib.c lbaselib.c ldblib.c liolib.c lmathlib.c loslib.c
ltablib.c lstrlib.c loadlib.c linit.c
)
foreach(s ${lua_library})
set(lua_LIBRARY ${lua_LIBRARY} src/${s})
endforeach()
add_definitions(-DLUA_ANSI=1)
add_library(lua STATIC ${lua_LIBRARY})
This works but I am not happy about having the lua source files clutter my version controlled CMakeLists.txt.
Is there any way to specify a custom CMakeLists.txt for the build step that is not in SOURCE_DIR?
A: I figured it out myself. I am now using this as the PATCH_COMMAND:
PATCH_COMMAND ${CMAKE_COMMAND} -E copy
"${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lua/CMakeLists.txt" <SOURCE_DIR>/CMakeLists.txt
This allows me to have my custom CMakeLists.txt in thirdparty/lua and the upstream package is downloaded to thirdparty/lua/lua-${lua_RELEASE}. Perfect!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Set BizTalk to work with remote SQL Server I'm trying to configure BizTalk to use remote SQL Server. I open BizTalk Server Configuration utility, check Basic configuration. Then I need to provide Database server name in Database section, but I don't know what to enter. I have a sql server name, username and password, database name but I failed with my attempts to configure BizTalk to work with the sql server. Help me please.
A: Check here http://msdn.microsoft.com/en-us/library/aa578342(v=bts.10).aspx to see the default database names for all the BizTalk databases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rails3.1 autoloading failure I am trying to add a module to my Rails 3.1 app, I've been able to do this before, but it is not working now with the latest module I've added. Any thoughts greatly appreciated
in application.rb
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{Rails.root}/app/workers
#{Rails.root}/lib/validators
#{Rails.root}/lib/content_items
#{Rails.root}/lib/booher_modules
)
in lib/booher_modules/mongoid_counter_cache.rb
module Mongoid
module CounterCache
extend ActiveSupport::Concern
module ClassMethods
def counter_cache(options)
... some stuff ...
Now vote.rb:
class Vote
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::CounterCache
Anytime I try to boot up the application, I get the uninitialized constant error:
Users/Tim/Sites/polco/app/models/vote.rb:4:in `': uninitialized constant Mongoid::CounterCache (NameError)
from /Users/Tim/Sites/polco/app/models/vote.rb:1:in `'
from /Users/Tim/.rvm/gems/ruby-1.9.2-p290@cba/bundler/gems/mongoid-ccae125ccfd8/lib/rails/mongoid.rb:66:in `load_model'
... so on
I tried to put require 'lib/mongoid_counter_cache.rb' in vote.rb, but I get:
rails c
/Users/Tim/.rvm/gems/ruby-1.9.2-p290@cba/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:306:in `rescue in depend_on': No such file to load -- lib/mongoid_counter_cache (LoadError)
A: You're having this issue because Rails is trying to include "Mongoid::CounterCache".
To do this, it is looking for the file "mongoid/counter_cache.rb" somewhere in the autoload path.
So...
...
lib/booher_modules/mongoid/counter_cache.rb
...
Thus to fix...
mkdir -p lib/booher_modules/mongoid
mv lib/booher_modules/mongoid_counter_cache.rb lib/booher_modules/mongoid/counter_cache.rb
The reason your specific "require 'lib/mongoid_counter_cache.rb'" doesn't work is because that doesn't look in the autoload path it looks in the main include path ($:) which doesn't include lib/booher_modules (only autoload is configured with that)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Eclipse : how can we know the implementation classes for an interface in Eclipse I am using Eclipse IDE
I have a interface in my workspace called as Service .
Please tell me , how can i know the implementation classes for this interface ??
A: Use "Open Type Hierarchy" or press F4 when your cursor is on the interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inline admin ignores max_num and extra if an instance exists I've extended the standard Django User model with a UserProfile, and created a OneToOne relationship from the UserProfile to the User, like so:
class UserProfile(models.Model):
user = models.OneToOneField(adminmodels.User)
about = models.TextField('About the author', blank=True)
picture = models.ImageField('Picture (70px x 70px)', blank=True, upload_to='uploads/profile_pics', default='noone.png')
user_site = models.URLField(blank=True, verify_exists=False)
class Meta:
verbose_name = "Profiel"
verbose_name_plural = "Profielen"
To get the corresponding admin form included in the User admin, I created an inline admin form, and added it to the user admin, like so:
# Inline admin for the user profile
class UserProfileInline(admin.StackedInline):
model = UserProfile
fk_name = 'user'
max_num = 1
extra = 0
# Include the extra form
class MyUserAdmin(admin.ModelAdmin):
inlines = [UserProfileInline, ]
# Re-register the user form
admin.site.unregister(admin.models.User)
admin.site.register(admin.models.User, MyUserAdmin)
Than, lastly, to save an instance of UserProfile, I have a function connected to postsave. It looks like this:
def on_user_was_saved(sender,instance,created,using,*args,**kwargs):
if type(instance) == adminmodels.User:
if created:
profile = UserProfile.objects.get_or_create(user = instance)
profile.save()
else:
profile = UserProfile.objects.get_or_create(user = instance)
profile[0].save()
Now, two things go wrong:
*
*When saving the user with anything in the user profile field, the user is saved, and so is the instance of UserProfile, but the instance has been saved as if all fields were empty. When entering something new in these fields you can save that though, nothing goes wrong than.
*A second instance of the UserProfile form becomes available; max_num is ignored.
After benjaoming's input I've changed my post_save callback to:
try:
profile = UserProfile.objects.get(user = instance)
profile.save()
except:
profile = UserProfile.objects.get_or_create(user = instance)
profile[0].save()
However this doesn't solve either of the problems I already had.
A: The main issue here is that you're not actually processing the profile form. Look at the code you've written: at no point do you have anything to take the values that you've entered for the user profile and save them to the database.
Also, admin.StackedInline is not built for the purpose you're trying to use it for. That manages one-to-many relationships, not one-to-one relationships.
If you must have the functionality in the admin follow exactly the setup that you are outlining, probably your best shot is to add a custom view to AdminSite with the forms for adding and editing users. Alternatively, have people edit two forms to create a user.
Anyway, you can read more about adding views to an AdminSite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL random value in UPDATE In MYSQL db, I need to UPDATE table "people" with a random number between 8 and 120, but if the value is between 103 and 109, I want it to become 110.
How would I do such a query?
UPDATE people SET column1 = '________random expression_________'
A: I haven't tested, but perhaps it should work.
UPDATE people
SET column1 = (
SELECT if(r.rand BETWEEN 103 AND 109, 110, r.rand)
FROM ( SELECT floor(8+rand()*113) rand ) r
)
A: I wrote a Perl script to run a SQL query 20k times, and the output suggests that the SELECTed value is correct (clearly, you just want to lift and tweak the SQL from the script to update your table, but I include the script so you can prove it does work):
#!/usr/bin/perl -w
use strict;
use DBI;
use Data::Dumper;
my $dbh = DBI->connect( "dbi:mysql:test", "root", "" ) or die $!;
my $q = <<EOQ;
select if(r.bar between 103 and 109, 110, r.bar )
from ( select floor( rand() * 113 ) + 8 as bar ) r
EOQ
;
my $sth = $dbh->prepare( $q );
my $vals = {};
for ( 0 .. 20000 ) {
$sth->execute();
my $row = $sth->fetchrow_arrayref();
my $int = $row->[0];
$vals->{$int}++;
}
print join( "\n", sort keys %$vals ), "\n";
A: Guess you could always just do
UPDATE people SET column1 = floor(8+rand()*113)
UPDATE people
SET column1 = 110
WHERE column1 BETWEEN 103 AND 109
Or another way which appears to work but am sure will be bettered.
UPDATE people
SET column1 =
(
SELECT rand FROM
(
SELECT 8 as rand UNION ALL
SELECT 9 as rand UNION ALL
SELECT 10 as rand UNION ALL
SELECT 11 as rand UNION ALL
SELECT 12 as rand UNION ALL
SELECT 13 as rand UNION ALL
SELECT 14 as rand UNION ALL
SELECT 15 as rand UNION ALL
SELECT 16 as rand UNION ALL
SELECT 17 as rand UNION ALL
SELECT 18 as rand UNION ALL
SELECT 19 as rand UNION ALL
SELECT 20 as rand UNION ALL
SELECT 21 as rand UNION ALL
SELECT 22 as rand UNION ALL
SELECT 23 as rand UNION ALL
SELECT 24 as rand UNION ALL
SELECT 25 as rand UNION ALL
SELECT 26 as rand UNION ALL
SELECT 27 as rand UNION ALL
SELECT 28 as rand UNION ALL
SELECT 29 as rand UNION ALL
SELECT 30 as rand UNION ALL
SELECT 31 as rand UNION ALL
SELECT 32 as rand UNION ALL
SELECT 33 as rand UNION ALL
SELECT 34 as rand UNION ALL
SELECT 35 as rand UNION ALL
SELECT 36 as rand UNION ALL
SELECT 37 as rand UNION ALL
SELECT 38 as rand UNION ALL
SELECT 39 as rand UNION ALL
SELECT 40 as rand UNION ALL
SELECT 41 as rand UNION ALL
SELECT 42 as rand UNION ALL
SELECT 43 as rand UNION ALL
SELECT 44 as rand UNION ALL
SELECT 45 as rand UNION ALL
SELECT 46 as rand UNION ALL
SELECT 47 as rand UNION ALL
SELECT 48 as rand UNION ALL
SELECT 49 as rand UNION ALL
SELECT 50 as rand UNION ALL
SELECT 51 as rand UNION ALL
SELECT 52 as rand UNION ALL
SELECT 53 as rand UNION ALL
SELECT 54 as rand UNION ALL
SELECT 55 as rand UNION ALL
SELECT 56 as rand UNION ALL
SELECT 57 as rand UNION ALL
SELECT 58 as rand UNION ALL
SELECT 59 as rand UNION ALL
SELECT 60 as rand UNION ALL
SELECT 61 as rand UNION ALL
SELECT 62 as rand UNION ALL
SELECT 63 as rand UNION ALL
SELECT 64 as rand UNION ALL
SELECT 65 as rand UNION ALL
SELECT 66 as rand UNION ALL
SELECT 67 as rand UNION ALL
SELECT 68 as rand UNION ALL
SELECT 69 as rand UNION ALL
SELECT 70 as rand UNION ALL
SELECT 71 as rand UNION ALL
SELECT 72 as rand UNION ALL
SELECT 73 as rand UNION ALL
SELECT 74 as rand UNION ALL
SELECT 75 as rand UNION ALL
SELECT 76 as rand UNION ALL
SELECT 77 as rand UNION ALL
SELECT 78 as rand UNION ALL
SELECT 79 as rand UNION ALL
SELECT 80 as rand UNION ALL
SELECT 81 as rand UNION ALL
SELECT 82 as rand UNION ALL
SELECT 83 as rand UNION ALL
SELECT 84 as rand UNION ALL
SELECT 85 as rand UNION ALL
SELECT 86 as rand UNION ALL
SELECT 87 as rand UNION ALL
SELECT 88 as rand UNION ALL
SELECT 89 as rand UNION ALL
SELECT 90 as rand UNION ALL
SELECT 91 as rand UNION ALL
SELECT 92 as rand UNION ALL
SELECT 93 as rand UNION ALL
SELECT 94 as rand UNION ALL
SELECT 95 as rand UNION ALL
SELECT 96 as rand UNION ALL
SELECT 97 as rand UNION ALL
SELECT 98 as rand UNION ALL
SELECT 99 as rand UNION ALL
SELECT 100 as rand UNION ALL
SELECT 101 as rand UNION ALL
SELECT 102 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 110 as rand UNION ALL
SELECT 111 as rand UNION ALL
SELECT 112 as rand UNION ALL
SELECT 113 as rand UNION ALL
SELECT 114 as rand UNION ALL
SELECT 115 as rand UNION ALL
SELECT 116 as rand UNION ALL
SELECT 117 as rand UNION ALL
SELECT 118 as rand UNION ALL
SELECT 119 as rand UNION ALL
SELECT 120 as rand
) T
ORDER BY rand()
LIMIT 1
)
A: update people
set `column1` = if ((@a := floor(8+rand()*113)) BETWEEN 103 AND 109 , 110, @a)
;
A: Generate the random number in your code, and pass it to the database. Databases are designed for working with data and are not the ideal place to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.