text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Real-time Update I really hope this is not a naive question but does Facebook real time updates work on user's status updates? if so can someone point me in the right direction because I can't seem to confirm this anywhere.
A: You can't subscribe to these user connections yet: home, tagged, posts, photos, albums, videos, groups, notes, events, inbox, outbox, updates, accounts
http://developers.facebook.com/docs/reference/api/realtime/
A: It's called long-polling. Look up node.js and long-polling ajax concepts.
Essentially the client makes an initial ajax request and waits for a response with no timeout set. Server-side JS will trigger an event when the user updates his/her status and send the response to any JS clients awaiting said response. The information gets updated, and immediately the client sends another request and waits for the next event.
A: You can subscribe to the 'feed' connection of your app users, which then also triggers on status updates.
URL = 'https://graph.facebook.com/%s/subscriptions' % appid
data = {'object': 'user',
'fields': 'feed',
'callback_url': callback,
'verify_token': verify_token,
'access_token': access_token,
}
res = requests.post(URL, params=data)
print res.content
print res.ok
The access_token must be an application access token, not a user access token. The above request will subscribe you to updates of all of your users! The message sent by the Facebook server will only include the user ID of the user, though, and no details about what happened. You have to figure that out yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting SVN Error during operations: "bad record MAC" I am trying to checkout a folder on my companies svn server.
I am getting this error using Tortus SVN (version
Command: Update
Error: REPORT of '/svn/REPOSITORY/!svn/vcc/default': Could not read response body: SSL
Error: error: decryption failed or bad record mac (https://svnroot:8443)
Finished!:
Tortoise SVN Version info:
TortoiseSVN 1.6.12, Build 20536 - 64 Bit , 2010/11/24 20:59:01
Subversion 1.6.15,
apr 1.3.8
apr-utils 1.3.9
neon 0.29.5
OpenSSL 0.9.8p 16 Nov 2010
zlib 1.2.3
I thought that the problem origionally might be with my SVN client so I tried doing a checkout using Subversive (Eclipse SVN plugin). I got a similar error message:
Checkout operation for 'https:<you know all that stuff...>' failed.
svn: bad record MAC
svn: REPORT request failed on '/svn/REPOSITORY/!svn/vcc/default'
I am not sure what my next step should be. Often before I get the error it will complete some operations so by doing continuous updates I can checkout the entire project but this is a major pain in the ass.
Suggestions?
Update:
I just upgraded my TortoiseSVN to:
TortoiseSVN 1.6.16, Build 21511 - 64 Bit , 2011/06/01 19:00:35
Subversion 1.6.17,
apr 1.3.12
apr-utils 1.3.12
neon 0.29.6
OpenSSL 1.0.0d 8 Feb 2011
zlib 1.2.5
This upgraded my version of OpenSSL. Still getting the same error.
A: This seems to be a bug in openssl 0.9.8. Since 0.9.8d is numerous vulnerabilities, you should really consider updating to openssl 1.0.0e.
A: Setting the IDEA_JDK_64 environment variable to a Java 1.7 JDK solved it for me. Maybe because that JDK has an updated cacerts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# WinForms: Drawing with one or more additional threads. How? In case I have a big drawing with all kinds of geometric forms (lines, rectangles, circles, e.t.c.) it takes a lot of time for the thread to draw everything. But in real life, one building is built by more than one workers. So if the drawing is the building and the threads are the builders, it will get drawn a lot faster. But I want to know how.
Can you tell me how? Is it even possible (though I have already asked and the answer was "Yes")? Is it worth it to be used? What are the risks?
If there are questions that I have missed, please tell me about them and answer them.
Thanks!
A: Assuming you are using GDI+ and the System.Drawing.Graphics object to render your graphics (rectangles, circles, etc.) to a background drawing surface (e.g. System.Drawing.Bitmap Object): Instance members of the System.Drawing.Graphics object that you would need to use are not thread safe. See MSDN documentation here
Given this, I would not use more than one "builder" thread to render your graphics.
Instead, my recommendation would be to do all of your drawing to a System.Drawing.Bitmap object in a single background thread rather than multiple background threads if possible. You can use a status bar or other indicator to let the user know that your program is working in the background.
A: WinForms objects have strong thread affinity, making it impossible to manipulate a form or control from a thread different than the one who created it.
That said, it's worth investigating if this assertion is true for Graphics as well.
From the System.Drawing.Graphics class docs:
Any public static (Shared in Visual Basic) members of this type are
thread safe. Any instance members are not guaranteed to be thread
safe.
Doesn't smell good: All drawing methods are instance members. You can't spread operations on the Graphics object accross several threads.
A: As a simple example you can use threads to do multiple tasks using the ThreadStart delegate method, it would look something along these lines:
Thread t = new Thread(new ThreadStart(MethodToExecuteOnSecondThread));
t.Start();
while (!t.IsAlive)
{
//do something to show we're working perhaps?
UpdateMyGuiWithALoadingBar();
}
You're second thread then goes off and executes the ThreadStart() delegate method while you main thread stays responsive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: MySQL get a summary of data based on part of a string I have a table of user information, from which I want to get a report listing the most common domains. I know that I need to use count and group by, but I'm not sure how to group by only part of a string, from the '@' symbol on. Any advice?
id email name etc..
---------------------------------------------
1 username@domain.com User Userson blah
A: Try this method, using LOCATE() and SUBSTRING()
SELECT
SUBSTRING(email FROM LOCATE('@', email)) AS domain
COUNT(*) AS numusers
FROM tbl
GROUP BY domain
ORDER BY numusers DESC
The above will list domains as @example.com. To strip off the @ use instead:
SUBSTRING(email FROM LOCATE('@', email)+1) AS domain
A: SUBSTRING_INDEX might be useful here:
select
substring_index(email,'@',-1) as domain
,count(*) as userCount
from your_table
group by domain
order by usercount desc;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook place check in I have a facebook page/place for my business. I want to display on my website in real time people that checked in. It is possible?
A: You Can, All you need to do is setup a token with your facebook account that will allow you to access the information.
Token Info:
http://developers.facebook.com/docs/authentication/
Checkins: https://graph.facebook.com/me/checkins?access_token=...
Then you hit that url with your token and it returns a list of people that have checked in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Oracle - Audit Trail Does oracle have Audit Trail as an inbuilt functionality?
Do i need to create separate table for Audit Log purpose to capture INSERT, UPDATE and DELETE changes?
A: Yes, Oracle does support auditing. You won't need to create the audit tables yourself, but you will need to configure the audit settings (i.e. which tables/users/queries to audit).
http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/security.htm#i16445
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can C++ code be called from a Java applet? I'm curious if I can do this. Can C++ code compiled and loaded on the local host be called from a Java applet running in a browser?
A: Yes, it can be done if your applet is signed and the user agrees to grant the Applet full privileges.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Error WSE012 (Action Missing) when consuming WSE webservice For a small project I need to use (consume) an external (secure) webservice.
This webservice uses SOAP1.2 protocol with WSE extention (username + password)
I use VB (VS2008) and added the Service Reference, customized the app.config to use wsHttpBinding rather than basicHttpBinding
One of the public Functions of the webservice is called
searchByName(String, String)As System.Xml.XmlElement
In code I first initialize the security;
wsTST.ClientCredentials.UserName.UserName = "mycompanyname"
wsTST.ClientCredentials.UserName.Password = "abc%2011!"
and then call the Function (the code fails here):
Debug.WriteLine(wsTST.searchByName("John", "Johnson"))
A first chance exception of type 'System.ServiceModel.FaultException' occurred in mscorlib.dll.
Error message:
WSE012: The input was not a valid SOAP message because the following information is missing: action.
Can anyone tell me if consuming a WSE webservice is possible from VB.NET2008?
And can anyone point me in the right direction?
I have searched for hours, but could not find any relevant information.
Regards, Frank
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the relation between malloc diagnostics and malloc related environment variables? Here there's a list of environment variables about the malloc package:
*
*MallocStackLogging
*MallocStackLoggingNoCompact
*MallocPreScribble
*MallocScribble
*MallocGuardEdges
*MallocDoNotProtectPrelude
*MallocDoNotProtectPostlude
*MallocCheckHeapStart
*MallocCheckHeapEach
*MallocCheckHeapSleep
*MallocCheckHeapAbort
*MallocBadFreeAbort
Also, when I open the Diagnostics section of my project from XCode 4, I see that under Memory Management, there are
*
*Enable Scribble
*Enable Guard Edges
*Enable Guard Malloc
So, I'm a little bit confused. Should these environment variables be used in combination with the diagnostics settings, or are these diagnostics settings a shortcut for enabling the environment variables listed above?
A: To my knowledge they're shortcuts to the most common options; to use the others you need to set with environment variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# Unmanaged application crash when using Enterprise Library I have a C# library DLL which is loaded from an unmanaged process. So far everything is good. Now I wanted to incorporate the Enterprise Library 5.0 with its logging capabilities. I added these references:
*
*Microsoft.Practices.EnterpriseLibrary.Common.dll
*Microsoft.Practices.Unity.dll
*Microsoft.Practices.Unity.Interception.dll
*Microsoft.Practices.ServiceLocation.dll
*Microsoft.Practices.EnterpriseLibrary.Logging.dll
...and all the using statements required.
Here is an excerpt from the class:
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity.Configuration;
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode,Pack=2)]
unsafe public static class DLLDispatch
{
private static IConfigurationSourceBuilder LoggingBuilder = new ConfigurationSourceBuilder();
...
}
The problem is that when this field is defined the unmanaged processes crashes. If it is commented out, this crash does not happen. And here is the windows application log for this crash:
**Sig[0].Name=Application Name
Sig[0].Value=terminal64.exe
Sig[1].Name=Application Version
Sig[1].Value=5.0.0.507
Sig[2].Name=Application Timestamp
Sig[2].Value=003f5e00
Sig[3].Name=Fault Module Name
Sig[3].Value=clr.dll
Sig[4].Name=Fault Module Version
Sig[4].Value=4.0.30319.237
Sig[5].Name=Fault Module Timestamp
Sig[5].Value=4dd2333e
Sig[6].Name=Exception Code
Sig[6].Value=c00000fd
Sig[7].Name=Exception Offset
Sig[7].Value=000000000007382a**
I searched the web for the exception code c00000fd and found it to be a stackoverflow :-) exception.
I played around a bit and this crash occures everytime there is an instance involved from the enterprise library. If nothing is used of that library then there is no crash. What is going on here? Is it becasue the class is in unsafe context or what else can it be?
Thanks in advance.
A: I found the solution to this problem. One has to put a app-config file in the unmanaged application folder with this content:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Unmanaged application startup folder" />
</assemblyBinding>
</runtime>
</configuration>
With this information the CLR can bind assemblies and searches in the correct folder. It was not clear to me that a config file is also useful for unmanaged applications.
Thanks, Juergen
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: DetailsView data to Textbox After long time looking for a solution I found one here - I thought....
The code I tried to implement was:
If DetailsView1.Rows.Count > 0 Then
Dim row As DetailsViewRow
For Each row In DetailsView1.Rows
TextBox3.Text &= row.Cells(0).Text & " = " & row.Cells(1).Text & " "
Next
Else
TextBox3.Text = "No data found"
End If
As result I only got the line label. The row.Cells(1) did not return any data.
My DetailView show correct data from my database (total 7 lines). I need to merge these data together with some other user input fields and create an output file.
My questions are:
1) How do I get the detailview data into a textbox
2) My final task is to create an output.txt file
I have to use VB since I'm unfamilar with C#.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: what point do c libraries get linked Let's say I redefine malloc e.g. in a memory debugging program electric fence. electric fence says that one must link the library with the gcc -g -Wall -Wstrict-prototypes -lefence test.c. So my understanding is that if gcc does not find the symbols in any of the libraries then it looks into the C libraries. Is this understanding correct?
A: Yes, and to understand what gcc is actually doing, and how does it starts the linker ld which does the real work of linking, you can pass the -v flag to gcc.
A: I think you are correct: the linker tries to resolve symbols using the libraries explicitly passed as parameters first, then it's looking up symbols in the C standard libraries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using JQuery to add selected items from one combobox to another I'm trying to find the best way to add selected items from one combobox to another. The trick is I only want to add items to the destination list that don't already exist. Currently the process I use is rather ugly and does not work as I would expect.
$('#addSelectedButton').click(function() {
var previousOption;
$('#sourceList option:selected').appendTo('#destinationList');
$('select[name=destinationList] option').each(function () {
if (this.text == previousOption) $(this).remove();
previousOption = this.text;
});
});
The problem I'm having is that the appendTo method acts as more of a move rather than an add. Then there's the problem of removing the duplicates, which works in this this example, but I can't help but think there's a better way.
Any assistance would be greatly appreciated.
Thanks,
A: using clone() and grep() you can achieve this easily. First clone the options that are selected from the source and then using grep you can filter out the items that are already in the destination list.
$('#addSelectedButton').click(function() {
// select this once into a variable to minimize re-selecting
var $destinationList = $('#destinationList');
// clone all selected items
var $items = $.grep($('#sourceList option:selected').clone(), function(v){
// if the item does not exist return true which includes it in the new array
return $destinationList.find("option[value='" + $(v).val() + "']").length == 0;
});
// append the collection to the destination list
$destinationList.append($items);
});
Working Example: http://jsfiddle.net/hunter/4GK9A/
clone()
Create a deep copy of the set of matched elements.
grep()
Finds the elements of an array which satisfy a filter function. The original array is not affected.
A: I think what you want is to use "clone" in conjunction with append:
http://api.jquery.com/clone/
A: You could use clone() like this:
$('#addSelectedButton').click(function() {
var previousOption;
var clone = $('#sourceList option:selected').clone();
clone.appendTo('#destinationList');
$('select[name=destinationList] option').each(function () {
if (this.text == previousOption) $(this).remove();
previousOption = this.text;
});
});
A: You can just search the destination list for the containing value. http://jsfiddle.net/EHqem/
$('#addSelectedButton').click(function() {
$('#sourceList option:selected').each(function(i, el) {
if ($('#destinationList option[value='+$(el).val()+']').length === 0) {
$('#destinationList').append($(el).clone());
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I chain my method calls? I have an object:
var mubsisapi = {
step1 : function(){alert("a")},
step2 : function(){alert("b")}
}
$.extend(false, mubsisapi)
mubsisapi.step1().step2();
It is give step1() but not give step2(). step2() does not give an alert. How can I do this?
A: You need to return this from the function if you want to chain it.
A: Yes, your object should look like this:
var mubsisapi = {
step1 : function(){alert("a"); return this; },
step2 : function(){alert("b"); return this; }
}
returning itself to allow chaining.
A: var mubsisapi = {
step1 : function(){alert("a"); return mubsisapi;},
step2 : function(){alert("b"); return mubsisapi;}
}
A: Not JSON, but javascript object. It's not fluent, but it can be:
var mubsisapi = {
step1 : function(){alert("a"); return this;},
step2 : function(){alert("b"); return this;}
}
$.extend(false, mubsisapi)
mubsisapi.step1().step2();
A: You cannot chain your function calls. You either have to call them separately:
mubsisapi.step1();
mubsisapi.step2();
or you can change your step1 function so you can chain them:
var mubsisapi = {
step1 : function(){alert("a"); return mubsisapi;},
step2 : function(){alert("b")}
}
$.extend(false, mubsisapi)
mubsisapi.step1().step2();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Why do I get "could not be added to your itunes library because it is not a valid app" error when trying to install Ad-Hoc build? I've recently upgraded my Mac to Lion, and also Xcode 4.
In Build Settings, I've set "Code Signing" for "Release" to be "iPhone Distribution" which matches our Ad-Hoc provisioning file (which we've used in the past, on Snow Leopard/Xcode 3).
I have deleted the old Entitlements file (as it's apparently no longer used by Xcode 4).
In the Scheme section, I've set Archive to use the Release build.
I'm building with Product > Archive.
I'm saving the file by going into the Organiser and clicking Share, then making sure the same Ad-Hoc provisioning is selected.
I'm sending the resulting IPA file to my boss, who has previously installed this app. When he tries to install it, he gets the message "[appname] could not be added to your itunes library because it is not a valid app".
I've been trying every combination of settings I can think, but we just cannot get this to work. I can find this error only twice in Google - once from someone with a jailbroken phone and another posted in comments of an article, someone having the same issue, but there are no responses.
Any help would be really appreciated.
Edit: Same thing happens trying to drag the IPA into iTunes on the Mac that created it! :(
Edit2: Just taken another (almost identical) project and tried a build without "Modernizing" the project, or selected any of the new options in Xcode (icons, launch images, orientation etc.), and this build works. I'm going to work through each of the things I did with the original app with this one, testing at each step. Hopefully should be able to isolate which step is breaking the compiled app!
(also posted to Apple Dev Forums)
A: Recently I suffered a problem with an Ad-Hoc installation using TestFlight service, the message in the log didn't help too much:
Jul 25 12:52:39 MyiPad installd[477] <Error>: 0x10059c000 init_pack_state: Archive we've been requested to install is 0 bytes. That can't be a valid ipa.
After many tests, I found this question and the problem was the same, the Build field was empty (this answer save my day :-) )
So, if anyone else has this problem on TestFlight, I hope my answer allows to find this page easier ;-)
A: I also faced the same issue. After doing some research found below answers as:
*
*App Version and Build version should not blank.
*Don't put special characters in my app bundle name.
*And also there was no issues with my provisioning profiles.
After debugging found that there was name mismatch in my scheme name and info.plist file name. In my project, I have 3 schemes like a,b,c and only one a-info.plist file. I was creating IPA for different scheme like 'b'.
In your scenario, if you have created multiple schemes then check your Info.plist name. That should have to be same as your scheme name (for which you are creating an IPA).
Example. The scheme name is 'myScheme' then your Info.plist file name as 'myScheme-Info.plist'.
Hope this will help you.
A: I believe I've tracked this down... It seemed to be happening really intermittently, so it's taken some time (I'd reproduce it, roll back the change, confirm it worked, then re-apply the change, for it to then work again!).
However, after much cleaning/restart/etc., I believe it's related to the "Build" version in the target settings (there are now two version fields, "Version" and "Build"). It seems that if "Build" is blank, then this error occurs.
Unfortunately, changing this value doesn't seem to rebuild properly, so sometimes if you change it, then Archive, you still get the previous value. Manually cleaning before Archiving seems to work around this.
The value gets written into the plist file as CFBundleVersion.
A: I got the same message ("not a valid app"). In my case, I was FTPing the built app to a web server then I would be able to OTA provision it. I was not swapping to binary mode before I was putting the file, so the .ipa file got corrupted on the way. Took me most of the evening to figure that stupid mistake out...
A: ok.. do one thing.. Open info.plist.. Go to bundle identifier and change bundle identifier name. It needs to be unique.. something like "com.yourcompany.projectname" and create and try to install the ipa.. It should work
A: I came across this question while researching a similar problem so I'll answer here even though the cases are not identical, because others will search for the same error message.
I had an ad-hoc app that everyone in the development team could install fine, except one person, who got the error from iTunes:
X is not a valid app
He had been able to install earlier versions of this app. Rebuilding the app, changing the version number and changing the build number had no effect, he still could not install but others could.
I fixed it by creating a brand new Xcode project, either copying the files or copying and pasting the content of the files from the old project to the new one, and rebuilding the app and signing it in exactly the same way as the old project. It worked.
A: I had a similar issue while trying to create an .ipa for adHoc distribution for one of the Old project (built a year ago by ex-developer). After a lot of research in google and following the above solutions it didn't worked out for me somereason.
Later after following this link - here. By replacing the .plist file with the existing working projects (obviously - the relevant icons/bundle display name/identifier) and renaming with the current .plist name. It worked for me.
I literally spent about 3-4 hours to fix this issue. Hope it helps some one.
environment was native - iOS app.
A: add......
"Application requires iPhone environment" in your info.plist or if added give it value "YES".
Check "Build" and "Version" in general are not empty....
hope this will work
A: Importing the project contents in to a new Project solved the issue for me.
A: For me, we were trying to do an enterprise build of a very old app, from iOS 5.
After confirming profiles and everything else was fine, debug builds work correctly, I noticed the general consensus was around issues with the info.plist file.
I compared the info.plist with another app and sure enough,
Application requires iPhone environment = NO
Basically this key needs to always be set to YES for iOS apps regardless whether its for iPhone, iTouch or iPad...
It may not be limited to that key for everyone but make sure the info.plist looks similar to working apps.
Bundle version
Bundle versions string, short
should always be present!
A: right.. but I guess it is clashing with earlier bundle identifier( this happens because you have upgraded the Xcode). Did you try and change the existing bundle identifier name and install ? I had identical problem and wasted 3-4 days.. I changed existing bundle identifier name and it worked.. Also you may want to check Bundle name and Bundle version are present in info.plist
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: C++ Outputting text on a window Simple question, is drawing text using functions like TextOut or DrawText better then creating a static control, performance wise?
And which has better performance TextOut or DrawText?
A: Second question first: DrawText calls TextOut, so if you don't need the formatting capabilities of DrawText, you can go straight to TextOut.
If raw performance is all you care about, then drawing directly will be faster. However, raw performance should not be your sole concern. It is also more work and does not support accessibility (which means you have to write additional code to support IAccessible).
A: DrawText looks more powerful and flexible, possibly it makes more work. Regarding HDC drawing vs. static control: they are used for different purposes. For example, it is better to use static control in a dialog. But if you want to draw some text in a graph - dynamic text is much better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Double border CSS3 - FF !Chrome I'm wondering, why this double border on table TDs won't show in Chrome but only in FF? Any ideas what could be the work around? Thanks!
http://jsfiddle.net/yQQLk/1/
A: Not sure why you're using box-shadow to produce a double border, when the border property itself already supports a double border on its own. Just use the following CSS instead of what you've got:
td {
border-bottom: 3px double red;
}
Note you'll need to increase the size of the border to 3px so that both of the lines show up (with 1px, it sometimes doesn't show up at all when you specify double).
The other advantage is that this will work in all browsers, including older ones which don't support box-shadow.
A: Increase your border thickness to to see a more obvious demonstration of the rendering differences between the two browsers. It seems that in FF, the box-shadow is overlaid on top of the border, in Chrome it hides underneath.
You could use another approach - perhaps use a border-bottom combined with a text-decoration: underline.
A: Try this, it works in both the browsers:
td {
-moz-box-shadow: 0 1px 0 #000;
-webkit-box-shadow: 0 1px 0 #000;
border-bottom: 1px solid red;
box-shadow: 0 2px 0 #000;
}
I guess, this is the problem: box-shadow: 0 1px 0 #000;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to keep the Text of a Read only TextBox after PostBack()? I have an ASP.NET TextBox and I want it to be ReadOnly. (The user modify it using another control)
But when there is a PostBack(), The text get reset to an empty string.
I understand that if you set the ReadOnly property to True of a TextBox it's content does not get saved through PostBack().
Is there a way to keep the content after PostBack() and make the TextBox not editable by the user?
I tried to set the Enabled property to False,But still the content doesn't save after PostBack().
A: Another solution I found and easier one:
Add this to the Page Load method:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("readonly", "readonly");
}
A: Have your other control store the value in a hidden field, and on postback, pull the value from the hidden field and push it into the textbox on the server side.
A: txtStartDate.Attributes.Add("readonly", "readonly"); on pageload in the best of the best solutions ,instead or Javascripts,hidden variables,cache,cookies,sessions & Caches.
A: Get the value using Request.Form[txtDate.UniqueID]. You will get it !!
A: I've had this same issue but using Knockout binding 'enable' and ASP.Net Server Control Text.
This way:
<asp:TextBox ID="txtCity" runat="server" required="required" class="form-control" placeholder="City" data-bind="value: city, enable: !hasZipCode()"></asp:TextBox>
However, when the form was submitted this field value was always empty. This occurred, I presume, because if the control is disabled, it is not persist on the ViewState chain.
I solved replacing bindig 'enable' by 'attr{ readonly: hasZipCode}'
<asp:TextBox ID="txtCity" runat="server" required="required" class="form-control" placeholder="City" data-bind="attr{ value: city, readonly: hasZipCode }">/asp:TextBox>
A: Here is a way to do it with javascript in the onfocus event of the Textbox itself.
Doing it like this with javascript has the advantage that you don't need to do it in code behind, which can be difficult if you need to do it in gridviews or similar.
This javascript code is only tested on Internet Explorer and certain parts of it will only work on IE, like for example the createTextRange part which is there just to make the caret end up at the beginning of the text in the Textbox, but that part can be skipped if not needed.
If the core of this technique works on other browsers then it should be possible to make the code cross browser. The core of the idea here is the blur after setting readonly and then a timeout to set the focus again.
If you only set readonly then it does not become readonly until next time you give the Textbox focus.
And of course, the code can be put into a function instead which is called with "this" as argument.
<asp:TextBox
ID="txtSomething"
runat="server"
Text='<%# Bind("someData") %>'
onfocus="
var rng = this.createTextRange();
rng.collapse();
rng.select();
if (this.allowFocusevent=='0') {return;};
this.allowFocusevent='0';
this.readOnly=true;
this.blur();
var that=this;
setTimeout(function(){that.focus()},0);
"
/>
A: Set the ContentEditable property of textbox to false ContentEditable="false"..
It wont allow you to edit the contents of the textbox
ie;will make the textbox readonly and
also will make the value stay in the textbox after postback..
I think its the easiest way to do it..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: Apps is using high CPU usage than others normal webview EDIT : Problem solved , "memory leak" was causes by one of the javascript below that keep on running in the HTML background that the rendering is using high CPU usage:
(so if anyone can help me fix this javascript leak are welcome too.)
var cog = new Image();
function init() {
cog.src = 'data';
setInterval(draw,10);
}
var rotation = 0;
function draw(){
var ctx = document.getElementById('text').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
ctx.save();
ctx.clearRect(0,0,27,27);
ctx.translate(13.5,13.5);
rotation +=1;
ctx.rotate(rotation*Math.PI/64);
ctx.translate(-13.5,-13.5);
ctx.drawImage(cog,0,0);
ctx.restore();
}
init();
Webview is using high CPU usage than others. Normal webview apps and the CPU usage won't drop to 0%. When I see at the Task Manager the application will highlighted in red and got killed by Android.
The CPU usage will be around 15+% to 27+%
Is it memory leak or its normal ?
Image :
A: If it was a memory leak you may see that your memory usage is grow. This situation can be explained that JS actions use many resources on this app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XSL-FO- Specifying conditional visibility I have an HTML table that varies according to its content. 1-3 columns hide. 1 column name changes. All depending on content.
I am creating a PDF version of this HTML table. The PDF version uses apache-FOP with fop v1.0. The PDF output contains 2 of the aforementioned tables on one page. I do not want to create an .xsl for every combination of possibilities. That's a lot of duplication and maintenance.
I can solve the column name change simply by passing the column name in with the XML content. But, conditional visibility of the columns seems to be a far more challenging task.
How can I setup conditional visibility? Is it possible?
I'm having difficulty just getting <fo:table-column visibility="collapse" /> to work. The data still displays with visility set to hidden or collapse. display="none" looked promising. But, the API doesn't show it as a valid property for a table-column.
If I can't conditionally hide a column then I'll need to produce 18 unique xsl files...
Currently, my tables are very basic. I do
<fo:block font-size="10pt">
<fo:table table-layout="fixed" width="100%" border-collapse="separate">
<fo:table-column />
<fo:table-column />
<fo:table-column />
<fo:table-column />
<fo:table-column />
<fo:table-column visibility="collapse" />
<fo:table-column />
<fo:table-column />
<fo:table-column />
<fo:table-column />
<fo:table-header>
<fo:table-cell border-width="0.2mm" border-style="solid">
<fo:block>Header 1</fo:block>
</fo:table-cell>
//...9 other headers (these should show/hide as needed)
</fo:table-header>
<fo:table-body>
<xsl:for-each select="Object/type/SomeItem/ProcedureItemCollection">
<fo:table-row>
<fo:table-cell border-width="0.2mm" border-style="solid" >
<fo:block>
<xsl:value-of select="content1"/>
</fo:block>
</fo:table-cell>
//...9 other cells...
</fo:table-row>
</xsl:for-each>
</fo:table-body>
</fo:table>
</fo:block>
XML
<Procedure>
<SiteName>Site1</SiteName>//If Site1, don't create column 2
//If Site2, don't create column 2,3,4
//If Site3, create all columns
<itemtype1>
<item><member1></member1><member2></member2></item>
<item><member1></member1><member2></member2></item>
</itemtype1>
<itemtype2>
<item><member1></member1><member2></member2></item>
<item><member1></member1><member2></member2></item>
</itemtype2>
</Procedure>
Doing it this way, I have little flexibility in creating the table. But, this is all I know how to do.
A: After a lot of tinkering it turns out that I can add/remove columns using xsl:when and a variable.
First create a variable
<xsl:variable name="SiteName" select="Procedure/SiteName" />
Then conditionally create the 3 elements of the table (column definition, header, body). Starting with the column definition...
<xsl:choose>
<xsl:when test="$SiteName = 'Site1'">
<fo:table-column />//column 2
</xsl:when>
</xsl:choose>
Then the header
<xsl:choose>
<xsl:when test="$SiteName = 'Site1'">
<fo:table-cell border-width="0.2mm" border-style="solid">
<fo:block>Column2</fo:block>
</fo:table-cell>
</xsl:when>
</xsl:choose>
Finally, the body
<xsl:choose>
<xsl:when test="$SiteName = 'Site1'">
<fo:table-cell border-width="0.2mm" border-style="solid" >
<fo:block>
<xsl:value-of select="column2value"/>
</fo:block>
</fo:table-cell>
</xsl:when>
</xsl:choose>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What's the correct currency format in Belgian Dutch? I'm formatting some currency in Java. This piece outputs 9,99 €
final NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("nl", "BE"));
nf.setCurrency(EUR);
nf.format(new BigDecimal("9.99"));
but one of our payment providers, which returns amounts preformatted, outputs € 9,99
Which is correct for nl-BE?
And more programming related, if it turns out the payment provider, and not Java, is correct, how do I fix the Java way without hacks per locale (in the real code the Dutch in Belgium locale is not hardcoded)
A: If Wikipedia is to be believed, neither is incorrect:
In Belgian Dutch, the euro sign can go before or after the amount, the
latter being more common.
A: Short answer: Nobody cares. You can use anyone.
Somewhat longer answer: If the amount appears in a sentence, 9,99 € is more usual. If it's at the bottom of an invoice, both are used. No wait, you could even use EUR instead of €.
BTW, most people even expect 9.99 € instead of 9,99€ simply because locale data was invented 25 years late.
Be aware though that this is the opinion of a fr-BE guy ;-)
This is the kind of stuff where I believe locale info tries too much to differentiate neighbouring cultures. Think of keyboards: There is a layout for fr-FR and one for fr-BE. Letters, digits and most punctuation signs are at the same position but a few characters such as <, > or @ are at different position on the keyboard. WTF!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Change in User-Agent header triggering forms authentication I've got an app built using ASP.NET MVC 3.0. It uses asp.net's built in forms authentication, without session state, and cookies on the browser to identify the user making requests.
Now, when I'm testing the app using IE9, the typical HTML request sends this user-agent in the header, and everything works fine.
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
However, we have one page in the app that has an ActiveX container that hosts Microsoft Word in the browser. The purpose of this ActiveX container is to allow you to make modifications to the word document, click on a button to POST that word document with your changes to our server so it can be saved.
There is a method in the ActiveX control--Office Viewer Component from www.ocxt.com--called HttpPost() that POSTs the contents of the viewed document to the server.
When you call HttpPost(), it sends all the same cookies properly, but uses a different User-Agent string.
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)
The UserAgent using MSIE 5.5 string appears to cause ASP.NET or MVC to not send the request to the appropriate controller, but instead sends a redirect response to the Login page even though the cookie is correct for the session. I did a test with Fiddler, and tried using MSIE 6.0, 7.0, 8.0 and those seem to work fine, so specifically, 5.5 causes part of the server stack to redirect to login page.
This page used to work fine, so I'm not sure if something has changed in recent versions of ASP.NET/MVC, or is it because I've moved up to IE9.0, but basically, I'd like to know if it is possible to tell ASP.NET to not take the User-Agent into account when determining if a session has been authenticated already or not.
Thanks.
A: IIRC there was a change in ASP.NET 4.0 where Forms Authentication uses the user agent to detect whether it supports cookies and if it is not a recognized or unsupported user agent it simply doesn't use the authentication cookie. You will need to change the User Agent of the HTTP request.
A: How to disable this default behavior for the webserver to check cookie support on the user agent in the web.config and force cookies for all browsers...
<system.web>
<authentication mode="Forms">
<forms cookieless="UseCookies" />
</authentication>
</system.web>
What's annoying about this default setting is that some valid User-Agent headers on new browsers will cause cookies to be ignored.
this User-Agent's form auth cookie is NOT ignored...
Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3
this User-Agent's form auth cookie IS ignored...
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0_1 like Mac OS X; en-us) AppleWebKit/536.26 (KHTML, like Gecko) CriOS/23.0.1271.91 Mobile/10A523 Safari/8536.25
But adding the cookieless="UseCookies" attribute will tell ASP.NET to use the cookies from anything.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Reasons for and against objects handling their own persistence I am looking at different options for persistence modelling in Windows Phone using Isolated Storage. One of the ideas I have come up with was the concept of each object handling its own (were it makes sense of course) persistence, rather than making a repository or other such entity for the purpose of saving objects.
I can't seem to find any good information on this method of persistence which leads me to believe I may have stumbled onto an anti pattern of sorts.
Has anyone approached persistence in this manner? If so what are your for's or against's in relation to this approach.
A: There are several undeniable truths in software development:
*
*A prototype becomes a product before you know it.
*An app targetted "just for platform-x" will soon be ported to platform-y.
*The data-store will change. Probably as a result of #2.
There are more ( :) ) but these are enough for to answer your question:
Go with a respository so your objects can be tested, know nothing about persistence, and you can swap out data stores (even go over the wire!) Might as well plan for that up-front.
A: Sounds like you're talking about the Active Record pattern? It works for some folks but there are criticisms against it (mostly from a testability / separation of concerns standpoint).
The biggest issue is that you end up with persistence logic spread out across all your classes. That can quickly lead to bloat, and it also embeds assumptions about your persistence technology all over your codebase. That gets messy if you need to change where or how you store your objects.
Those assumptions also make automated testing more difficult because now you have a persistence layer dependency to work around. You could inject a repository into the object to counteract some of this stuff, but then you're implementing a repository anyway. :) Better to just keep the core classes entirely peristence-ignorant if you can...
On the plus side, it's a simpler pattern for people to grasp and is a quick way to get things done on a lightweight project. If the number of classes is small it could be the quickest way to get from A to B. I still find myself building out separate repositories on small projects however, I just can't stand having persistence stuff mixed in with my business logic.
A: Cons:
*
*Violates Single Responsibility Principle (SRP)
*Hampers testability
*Tightly couples you business logic to your database
Pros:
*
*Is simple to implement
Basically, if your data model is flat and simple, and your application requirements are modest, Active Record might be a good choice; however, it starts to break down when your mapping requirements get a bit more complex. More robust ORM patterns like Data Mapper become appropriate in cases like these.
A: Pros
*
*simplicity
Cons
*
*breaks separation of concerns
*tight coupling of business logic with database
*makes testing much more difficult
This pretty much boils down to testing becoming much harder, and decreasing the time before you have to do a major refactor in your project.
At the end of the day you need to weigh your goals and concerns for the project and decide if the loss of testing/verifiability/cleaness is worth it to gain a simpler system.
If it's a simple application, you're probably fine to drop the DAL layer, and go for the simpler model. Though if you application has lots of moving parts and is of considerable complexity, I would avoid removing the DAL as you will want to be able to test and verify your code well.
A: It flies in the face of using a Data Access Layer...not that there's anything wrong with that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to import VBScript macros into Excel workbook? I have several Excel workbooks. They all share the same macro modules. What I would like to achieve is when editing one module in one workbook not to have to edit the same module in the other workbooks.
Naturally, my first step was to export on save the modules in .bas files. But the problem is that I cannot import them on load.
I had tried this:
Private Sub Workbook_Open()
Set objwb = ThisWorkbook
Set oVBC = objwb.VBProject.VBComponents
Set CM = oVBC.Import("C:\Temp\TestModule.bas")
TestFunc
End Sub
There is a TestModule.bas in the same dir with content:
Function TestFunc()
MsgBox "TestFunc called"
End Function
When the workbook is opened, a compile error appears: Sub or Function not defined. If I manually import the module everything works just fine.
Thanks for any advice.
A: Like you, I couldn't get the import to work from the workbook_open. You could put your import code in a sub a separate module, and call it from your workbook_open like this:
Private Sub Workbook_Open()
Application.OnTime Now, "ImportCode"
End Sub
That seemed to work for me (a direct call did not...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: facebook fan pages and related open graph objects If exist a facebook fan page like this:
https://www.facebook.com/HuffingtonPost
I suppose to get likes count calling graph API:
https://graph.facebook.com/https://www.facebook.com/HuffingtonPost
Infact here I get:
{
"id": "https://www.facebook.com/HuffingtonPost",
"shares": 435839
}
On the other hand if I call
https://graph.facebook.com/HuffingtonPost
I get a more verbose output:
{
"id": "18468761129",
"name": "The Huffington Post",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-ash2/188072_18468761129_6398033_s.jpg",
"link": "http://www.facebook.com/HuffingtonPost",
"likes": 435832,
"category": "Website",
"website": "http://www.facebook.com/HuffingtonPost",
"username": "HuffingtonPost",
"company_overview": "The Internet Newspaper\nNews | Blogs | Video | Community",
"description": "The Huffington Post - The Internet Newspaper. - Company Overview: The Internet Newspaper News | Blogs | Video | Community | Facebook",
[... omissis ...]
}
Can anybody tell me what's difference between these two opengraph objects?
There is also a slight difference between number of shares and likes. Why?
Update:
During last days graph api returned also object type, so I realized that:
*
*First API call returns an link_stat type object.
*Second API call returns a page type object.
In first case shares count should represent sum of:
*
*number of likes of this URL
*number of shares of this URL (this includes copy/pasting a link back to Facebook)
*number of likes and comments on stories on Facebook about this URL
*number of inbox messages containing this URL as an attachment.
In second case like count represents only itself
May somebody confirm me shares count correctness?
A: First one is something that tells you how many likes selected url have.
Using second one you will get information about Page Object through page identifier
A: For the breakdown between likes, shares and comments (which are added up and used as the "likes" number on the likes button, you're better off using FQL.
If you use OG, something like http://graph.facebook.com/http://example.com will show you:
{
"id": "http://example.com",
"shares": 3
}
... as you've noted above. If you use FQL, you can get the breakdown of each.
<?php
// require the php sdk
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true,
));
$external_result = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT share_count, like_count, comment_count, total_count, click_count FROM link_stat WHERE url="http://example.com";'
));
echo '<li>'.number_format($external_result[0]['like_count']).' likes, '.number_format($external_result[0]['share_count']).' shares';
echo '<pre>';
print_r($external_result);
echo '</pre>';
?>
This will display something on-screen like:
* 1 likes, 2 shares
Array
(
[0] => Array
(
[share_count] => 2
[like_count] => 1
[comment_count] => 0
[total_count] => 3
[click_count] => 0
)
)
Also, SA now has a Facebook-specific site that may be helpful to you. :) facebook.stackoverflow.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to handle 150 Mb of raw videos and music files in Android I've been developing this content-based app for Android which includes over 120 MB of video .mp4-files saved on the raw folder and in addition it includes over 20 MB of sound files also saved in the raw folder.
The problem is I cannot install the app on my Android phone due to limited internal memory to handle all those files. Also, I read somewhere that the app size limit on the Android market is 50MB so I won't be able to even upload the damn thing.
I've saved the videos on the raw folder as I was able to play them fine (using VideoView).
My question is how do i cope with such size, do I have to go through making the user download the content after installing the app or is there any other way of dealing with such sizes (~140 MB).
A: You cannot distribute an APK through the market that is more than 50MB. Its not a good idea to take up 120MB of the internal storage for a single app as many phones don't have a lot of internal storage space.
You should consider stripping out all of the large files, hosting them on a server and then having the application download the files on the first launch. I would also recommend you save the files to the SD card so you don't use up too much of the precious internal storage.
Edit: I will admit that any time an app tries to download a lot of data on the initial launch I get really frustrated. Make sure you do it in a way that doesn't require the activity to be open the entire time the file is downloading. Do the downloading through a service so the user can at least use their phone while your app is downloading the media files.
A: Well, if you're sure you need all this content inside your application, the only solution I see is to download the content from a server when the application is opened for the first time. But as a user I think I won't be very happy to have a 150 Mb application on my phone. Do you really need all this data?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does Cassandra uses Heap memory to store blooms filter ,and how much space does it consumes for 100GB of data? I come to know that cassandra uses blooms filter for performance ,and it stores these filter data into physical-memory.
1)Where does cassandra stores this filters?(in heap memory ?)
2)How much memory do these filters consumes?
A: When running, the Bloom filters must be held in memory, since their whole purpose is to avoid disk IO.
However, each filter is saved to disk with the other files that make up each SSTable - see http://wiki.apache.org/cassandra/ArchitectureSSTable
The filters are typically a very small fraction of the data size, though the actual ratio seems to vary quite a bit. On the test node I have handy here, the biggest filter I can find is 3.3MB, which is for 1GB of data. For another 1.3GB data file, however, the filter is just 93KB...
If you are running Cassandra, you can check the size of your filters yourself by looking in the data directory for files named *-Filter.db
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Font Size equal to the height of the current container If I have a div that is x high, how can I make the text inside of it the max it can be assuming that it can only take up one line.
While I would prefer a CSS answer, any jquery/javascript answers are accepted just because I need this to work either way :)
A: Set the font-size and line-height to the same height of the container:
div {
height:50px;
font-size:50px;
line-height:50px;
border:1px solid red;
}
Demo: http://jsfiddle.net/AlienWebguy/V7f4w/
A: Based on Aleks G's comment, this example shows how you would incrementally increase the font size until you'd reached your max:
HTML
<div>
<span>This is some text</span>
</div>
CSS
div {
width: 300px;
}
span {
display: inline-block;
}
jQuery
var $span = $('span');
var $div = $('div');
while($span.width() < $div.width()){
$span.css({fontSize: "+=1"});
}
$span.css({fontSize: "-=1"});
If you wanted to eliminate any stuttering as the font size was being changed, you could hide the text until the while loop was complete.
A: No way I know of to do that with pure CSS that will be cross browser compatibile. Use javascript and/or jquery to do this. I'll write it out in jquery since its a bit easier:
$("mydiv").css("font-size", $("mydiv").css("height"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cache Manifest messes up my app when online Gurus of SO
I am trying to play with CACHE MANIFEST/HTML5. My app is JS heavy and built on jquery/jquerymobile.
This is an excerpt of what my Manifest looks like
CACHE MANIFEST
FALLBACK:
/
NETWORK:
*
CACHE:
/css/style.css
/js/jquery.js
But somehow, the app doesn't load the files the first time itself and the entire app breaks down.
*
*Is my format wrong?
*Should I never load JS into the Cache?
*How should I treat this differently to always check the network first if anything isn't available and only load stuff available from the Cache?
Thank you.
A: I tried a simple page with your cache manifest and it worked fine for me, so I'm not really sure what the problem is. But,
*
*Yes, there is something wrong with the format. The entries in the FALLBACK section need to have two parts: a pattern, and a URL. This says "if any page matching the pattern is not available offline, display the URL instead (which will be cached)." The main example of this (as shown here) is "/ /offline.html", which means "for all pages, if we are offline and they are not cached, display /offline.html instead." However, I don't think this is the source of your problem since I tested it with your exact manifest and it still worked.
*There is nothing special about JS files. It should be fine to load them into the cache.
*I don't understand the third question. There are possibly two goals here: a) how do you check to see if there is a newer version of the file available online first, before going back to the cache, and b) how do you check the network to see if there is a file that is not cached, and if we are offline, fall back to an error page. The answer to (a) is that once you have turned on the cache manifest, things work very differently. It will never check for new versions of the files unless there is a new version of the manifest also. So you must always update the manifest whenever you change any files. The answer to (b) is the FALLBACK section.
See Dive Into HTML5's excellent chapter on this, particularly the section "The fine art of debugging, a.k.a. “Kill me! Kill me now!”" which explains how the manifest updates.
Also I don't think we've gotten to the meat of your question, because it's unclear what you mean by "the app doesn't load the files the first time itself". Which files don't load? Do they load properly after a refresh? Etc.
A: The only way I got this to work to refresh a cache was to rename the manifest file with a commit number or timestamp, and change the cache declaration to
<html manifest='mymanifest382330.manifest'>
I made this part of my build.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: replace last character in a line with sed I am trying to replace the last character in a line with the same character plus a quotation mark '
This is the sed code
sed "s/\([A-Za-z]\)$/\1'/g" file1.txt > file2.txt
but does not work. Where is the error?
A: try:
sed "s/\([a-zA-Z]\)\s*$/\1\'/" file
This will replace the last character in the line followed by none or many spaces.
HTH Chris
A: It seems pointless to replace a character with itself, so try this: for lines ending with a letter, add a quote to the end:
sed "/[a-zA-Z]$/s/$/'/"
A: This does what you ask for:
sed "s/\(.\)$/\1'/" file1.txt > file2.txt
A: Your line only matches a line with a single character. Note that the s operation only takes effect if the line matches, not if only a subset of the line matches the regex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: multiple scatter plots in single Pdf in R I have a function which takes a tab delimited file as an input and creates scatter plot for the values(one scatter plot per file) in the tab delimited file.I need a function which can print scatter plots in one pdf file(ie one scatter plot per page).Here is my function which prints one scatterplot per file.
scatter.plot=function(file)
{
raw.Data=read.delim(file="D:/output/illumina.txt",row.names = 1, dec = ".")
raw.expression <- raw.Data[,seq(1,dim(raw.Data)[2],2)]
dim(raw.expression)
raw.calls <- raw.Data[,seq(2,dim(raw.Data)[2],2)]
dim(raw.calls)
IDs <- colnames(raw.expression)
for (i in 1:(dim(raw.expression)[2]-1))
{
for( j in i:(dim(raw.expression)[2]) )
{
if (i != j)
{
pdf(file=paste(directory,"/",IDs[i],"_gegen_",IDs[j],".pdf",sep=""))
correlation <- round(cor(raw.expression[,i],raw.expression[,j]),2)
maximum <- max(log2(raw.expression[,i]))
minimum <- min(log2(raw.expression[,i])) plot(log2(raw.expression[,i]),log2(raw.expression[,j]),xlab=IDs[i],ylab=IDs[j],pch='.',text(maximum-2,minimum+0.5,labels=paste("R = ",correlation,sep=""),pos=4,offset=0))
dev.off()
}
}
}
}
The above function takes the illumina text file as a input and prints each scatter plots in single pdf.I want all them in one pdf..
As the illumina text file is large..I ve given a minimal information code for input data is below
input.file=list(ProbeID=c(870131,5310368,1070445,6770328,610373,450431,1050114,770300,3290546),X1692272066AAVGSignal=c(46.1234,48.73746,50.15939,51.36239,53.75028,55.18534,49.32711,49.49868,50.40989),X1692272066ADetectionPval=c(0.5924308,0.4665211,0.3595342,0.213246,0.1390102,0.5443959,0.5291121,0.4461426,0.6914119),X1692272066BAVGSignal=c(49.38838,50.76025,50.41117,50.52384,58.56867,55.49637,48.71999,57.0689,45.99026),X1692272066BDetectionPval=c(0.5851529,0.4556041,0.4905386,0.4818049,0.05604076,0.1441048,0.6375546,0.08515284,0.8377001),X1692272066CAVGSignal=c(52.47962,51.48042,51.93637,50.08885,56.68196,54.18305,52.03677,57.8032,52.71201),X1692272066CDetectionPval=c(0.4708879,0.5553129,0.5145561,0.661572,0.1783115,0.338428,0.5080058,0.1106259,0.4490539))'
Please do help me
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: A map with two keys
Possible Duplicate:
How to implement a Map with multiple keys?
Multiple Keys to Single Value Map Java
I have to get the value of an enum based on two incoming string attributes. I have been doing this as map for single values. Now I am faced with making a concatenation. Is there a way to have a map have two keys such that I could
Map.get("attr1","attr2");
and this would return the correct enum. Or will I simply have to concatenate all possible values and use this as the key?
I'm searching for the squeaky clean solution (aren't we all :P)
A: Well, you could use Map<String, Map<String, YourEnum>>.
We use this a lot and thus made our own Map implementation that provides two keys and internally uses the map-of-maps approach.
A: You could have a map of maps, i.e.
Map.get("attr1").get("attr2");
or you could define a object with an equals method, i.e.
Map.get(new MyObject("attr1", "attr2"));
A: In this case I would make a wrapper class with those two attributes, implement equals() and maybe implement Comparable and compareTo delegating onto the two elements of the composite key. And use this class as key to the map.
It would be like rolling your own Pair class. Take a look at this question's answers, that elaborate on the matter: What is the equivalent of the C++ Pair in Java?
A: Why not create an class that contains the two keys and use that as the map key?
For example:
public class BiKey implements comparable<BiKey>
{
private String key1;
private String key2;
// getters and setters
// equals and hash code.
// implement comparable.
}
Map <BiKey, Blammy> blammyMap; // Blammy is the value type.
A: Similar to Thomas's approach, we (At my work) have 'Dimensional' map classes that are simple wrappers around several Maps.
public class MultiKeyMap {
private HashMap<keyOne, Object> keyOneToObjectMap;
private HashMap<keyTwo, Object> keyTwoToObjectMap;
...etc
}
It is very easy to keep all the maps in sync with each other and allows for a decently quick search without tons of potentially complex code. (However, this comes at the cost of increased Memory use)
A: org.apache.commons.collections.map.MultiKeyMap is what you want
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiKeyMap.html
example
private MultiKeyMap cache = MultiKeyMap.decorate(new LRUMap(50));
public String getAirlineName(String code, String locale) {
String name = (String) cache.get(code, locale);
if (name == null) {
name = getAirlineNameFromDB(code, locale);
cache.put(code, locale, name);
}
return name;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to resize iphone keyboard? I am developing a program in which I have to change the size of the keyboard according to the size of a UITextView, either increase or decrease. How can I do this?
A: it's impossible in standard SDK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# LINQ How to get a data source from a db? I am trying use LINQ in a C# program to get information from a database. I have found a lot of examples showing basic to advanced queries, but I can't find anything to get a basic database connection. See basic LINQ example below:
var adultNames = from person in people
where person.Age >= 18
select person.Name;
I just can't figure out how to get to a specific database table and return information out of it. I want to be able to connect to a db table and return some information out of it. Thanks!
A: Theres a very simple way to connect to a database although I suggest you read the app config afterwards and other parts of your project to see how it works.
In the menu strip go to Data -> Add New Data Source. From here pick database then entity data model. Follow the rest of the steps to create a datasource for your project.
In your program you can create an object of the datasource by using:
WhatYouCalledTheDataSource datasourceObject = new WhatYouCalledTheDataSource();
You can then make queries on this object by changing your first line of the query to:
var adultNames = from person in datasourceObject.people
to get the data you want, once you have the query you can place the results into a list like:
List<string> queryResults = new List<string>();
queryResults.AddRange(adultNames);
bearing in mind that I basing on the thought that name would be a string.
You can also create lists based on tables like
var adultNames = from person ...
...
select person;
List<people> queryResults = new List<people>();
queryResults.AddRange(adultNames);
A: It sounds like you have been looking at examples of LINQ, which allows you to query from a data set. What you need in addition is called an Object Relational Mapper (ORM). Look at LINQ to SQL or The Entity Framework (newer) to get starts with this. This layer will introspect a database and create a lot of infrastructure to pull data out for you based on the data model.
A: If you're using Linq to Sql, then this may help: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
entity framework: http://www.codeguru.com/csharp/csharp/net30/article.php/c15489
A: There are a number of ways to retrieve data from a database. ADO.NET is the general technology. Your specific options are:
System.Data/SqlClient/ODP
You can use the standard query system in ADO.NET to get data from any database that uses ODBC, or use native data providers such as SqlClient or ODP. The SqlClient namespace may be used to get data from SQL Server. The Oracle Data Provider (ODP) is used with Oracle.
You have to write the queries/stored procedures yourself using "raw" ADO.NET.
Here is an excellent listing of ADO.NET example code: http://msdn.microsoft.com/en-us/library/dw70f090.aspx
Here is a link to Oracle's ODP:
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
LINQ to SQL
LINQ to SQL is a LINQ provider specifically for the SQL Server database. It is still supported, but is superseded by Entity Framework.
More detail here: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
Entity Framework
Entity Framework works natively with SQL Server and can work with Oracle using third-party or open-source data providers.
Entity Framework 4/4.1 will allow you to use an Entity Data Model (EDM) as an abstraction of your database. The EDM will surface a set of objects with which you can interact, and a Context object is used to retrieve/commit data to the database. The CRUD queries are dynamically generated from your LINQ syntax, so you don't have to write T-SQL or PL-SQL queries yourself in most cases.
Here is a basic example of Entity Framework:
http://www.codeproject.com/KB/database/sample_entity_framework.aspx
A: if you have a database table people then you can use LINQ-to-SQL to return information from it, first you need to reference the following two assemblies.
using System.Data.Linq;
using System.Data.Linq.Mapping;
define the following entity like this:
[table]
class people
{
[column]
public int Age { get; set; };
[column]
public string Name { get; set; };
}
then you can write tour query against database
Datacontext db = new DataContext("database Connection String");
var adultNames = from person in db.GetTable<people>()
where person.Age >= 18
select person.Name;
A: If you have a look at this NerdDinner pdf file that creates a MVC solution, it shows step by step how to create a dataset using Linq to SQL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: IOS: store an array with NSUserDefault I want to store an array with NSUserDefault, then, I put in applicationDidEnterBackground
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
and in application didFinishLaunchingWithOption
myArray= [[NSMutableArray alloc]
initWithArray:[[NSUserDefaults standardUserDefaults]
objectForKey:@"myArray"]];
it's ok for multitasking device, but for not-multitasking device, how can I solve?
A: Do not forget to sync the buffer before going into background:
[[NSUserDefaults standardUserDefaults] synchronize];
A: The previous answers are all correct, but note that neither applicationDidEnterBackground nor applicationWillTerminate are guaranteed to be called in all situations. You are usually better off storing important data whenever it has changed.
A: Store the object in NSUserDefaults in -applicationWillTerminate:, if it hasn't already been saved by the invocation of -applicationDidEnterBackground: (i.e. check if multitasking is supported, if it is, then don't save it because it's already been saved.)
- (void) applicationWillTerminate:(UIApplication *) app {
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)] &&
![[UIDevice currentDevice] isMultitaskingSupported]) {
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
}
}
A: Save NSUserDefaults at
- (void)applicationWillTerminate:(UIApplication *)application
A: set
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
in
applicationWillTerminate
A: and don't forget to use the encodeWithCoder and initWithCoder inside the object that you are trying to save and that is contained in the array
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Learning Exception Handling Patterns One thing that has always mystified me in programming is the use of appropriate exception handling. Code Complete points out that often times 90% of code is focused on handling exceptions. While I know the basics of implementing a basic exception, I have not found good general resources for such an important topic.
I am looking for good resources (not necessarily tied to a specific language) for learning how to implement good Exception Handling techniques. Most of the Exception Handling topics on stackoverflow seem to focus on a specific situation in a specific language. What would be your recommendations?
A: I have been a designer and coder of safety-critical systems for many years, and key to that type of system is robustness, one aspect of which is exception handling.
Some basic best practices:
1) At any level, catch only those exceptions you can deal with then and there. To "deal with" almost always means to retry or give up what you were trying to do, and that usually means that you should catch the exception one level up from where the exception-throwing call is issued.
2) Catch exactly those exceptions listed by the API documentation, no more, no less. Even if there are five exceptions listed for a call, don't catch their common base class (if they have one). However, you don't always need to catch all exceptions from the same call in the same place.
3) Don't pass nitty-gritty exceptions up to a level where they carry no meaningful information. Instead, catch the exception at the low level, log it if appropriate and return a status code or throw a more generic exception to the caller above.
4) Only use (and do use) catch-all handlers when you are in a critical section. Catch the exception, relinquish the resource (semaphore or whatever), rethrow the exception.
5) Logging an exception is not handling it. If all you do in a particular handler is log the exception, you should probably get rid of that handler.
6) Be very careful with exception handlers in loops, especially loops without a delay or a way out if the exception is thrown. You can easily get stuck in a busy loop that way.
A: I know of two good resources for proper exception handling strategies, they however pertain more to the .NET framework..
The first is the framework design guidelines by Krzysztof Cwalina (The lead designer of the .NET framework)
http://blogs.msdn.com/b/kcwalina/archive/2005/03/16/396787.aspx
The second is about what happens under the hood when exceptions are thrown, it will provide some good insight to help with your decision on how to handle exception. The book is called C# via CLR by Jeffrey Richter
http://shop.oreilly.com/product/9780735627048.do
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Implementing some cryptography algorithms on sql server Can we write a user defined function to encrypt a string of text based on a key in sql server 2000? For e.g. I want to try writing a triple DES algorithm to encrypt text. How to write statements for this? I checked around the internet; I can't understand the language of cryptography to begin with...
A: Consider upgrading to SQL Server 2005 or higher, which includes numerous encryption functions. They make it easy:
*
*Create a certificate to manage your key (CREATE CERTIFICATE)
*Create an encryption key from a password (CREATE SYMMETRIC KEY)
*Write encrypted data to table (ENCRYPTBYKEY())
*Read decrypted data from table (DECRYPTBYKEY())
dotnetslackers.com has an easy-to-read howto on the basics.
If you absolutely must stick with SQL Server 2000, you should strongly consider a third-party package for encryption, as writing 3DES from scratch is no small task. Application Security used to put out a product called 'DbEncrypt', but I don't know if it's still available.
A: I just found this article --> http://www.sqlservercentral.com/articles/Security/freeencryption/1980/. Seems you can do this via extended stored procedures. There are some 3rd party dlls which allow you to do this. There is a link to download the dlls (zipped) from the site. You have to add this to your sql server's binn folder, and call some scripts to add it to the extended stored procedures list. I not sure if this will work for sql server which runs of 64-bit machines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery Ui Autocomplete - How to remove the html from the selected value I am using the jquery ui autocomplete plugin in my page.
$( "#birds" ).autocomplete({
//source: sampleData(),
source: function(request, response) {
response(data(request.term));
},
enter code here
minLength: 3,
select: function( event, ui ) {
//alert(ui.item.label);
log( ui.item ?
"Selected: " + ui.item + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
The response call back gets a string array as its return value.
the string is of this sample format ..Akola,India-Akola(AKD)
The suggestion list comes up fine with the actual rendered from the string.
But when I select the value the value gets defaulted to the actual html string.
How do I make the selected value to have only the string and not the html ?
Item.label and Item.value remain the same..label shows up fine in suggestion..
but I need to make the item.value contain only the string.
Thanks
Yogesh
A: try using this.value.text() or else refer to this question. you may have to play around a little to parse the HTML but these options should work
A: In order to make this work you should also pass item.value
On select it looks for item.value first and then for item.label
That way you can leave your select: like that
select: function( event, ui ) {
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Queue of defined type implementation in C I am trying to find an implementation of a queue to use it to hold processes that are of type GDB. I have been looking all over the place and whatever I use I get an incompatible type when i try to enqueue the process of type GDB in the queue. Anyone knows an implementation of a queue that I can use or Hash_table ?
A: Any general-purpose queue worth using (including one you could roll on your own) should allow you to store void *, no questions asked.
So you should only store the address of whatever "process of type GDB" means.
A: I use this one, serves me fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Super column vs serialization vs 2 lookups in Cassandra We have:
users, each of which has events, each of which has several properties (time, type etc.). Our basic use case is to fetch all events of a given user in a given time-span.
We've been considering the following alternatives in Cassandra for the Events column-family. All alternatives share: key=user_id (UUID), column_name = event_time
*
*column_value = serialized object of event properties. Will need to read/write all the properties every time (not a problem), but might also be difficult to debug (can't use Cassandra command-line client easily)
*column is actually a super column, sub-columns are separate properties. Means reading all events(?) every time (possible, though sub-optimal). Any other cons?
*column_value is a row-key to another CF, where the event properties are stored. Means maintaining two tables -> complicates calls + reads/writes are slower(?).
Anything we're missing? Any standard best-practice here?
A: Alternative 1 : Why go to Cassandra if you are to store serialized object ? MongoDB or a similar product would perform better on this task if I get it wright (never actually tried a document base NoSQL, so correct me if I'm wrong on this one). Anyway, I tried this alternative once in MySQL 6 years ago and it is still painful to maintain today.
Alternative 2 : Sorry, I didn't had to play with super colunm yet. Would use this only if I had to show frequently many information on many users (i.e. much more than just their username and a few qualifiers) and their respective events in one query. Also could make query based on a given time-span a bit tricky if there are conditions on the user itself too, since a user's row is likely to have event's columns that fit in the span an other columns that doesn't.
Alternative 3 : Would defenitly be my choice in most cases. You are not likely to write events and create a user in the same transaction, so no worry for consistency. Use the username itself as a standard event column (don't forget to index it) so your calls will be pretty fast. More on this type of data model at http://www.datastax.com/docs/0.8/ddl/index.
Yes it's a two call read, but it do is two different families of data anyway.
As for a best-practices, the field is kinda new, not sure there are any widely approved yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: testing http.get() with qunit in node.js I'm trying to write a simple qunit test for a node.js library, code.js. The first test case is the simplest one i'm trying and doesn't use any exported function in my code.js library, but it doesn't work.
The QUnit module is as follows:
module = QUnit.module
var = http.require('http');
test("client test", function(){
expect(1);
var options = {
host: 'www.google.es',
port: 80,
path: '/'
}
http.get(options, function(res){
ok(true, "http.get callback success");
});
});
I think that one of the problems is that the test execution finish before the get callback gets executed, but i'm not really sure. Maybe the rest of the problems are that i'm a beginner with qunit, so i'll really apreciate any comments.
Solution: I will use an asyncTest:
asyncTest("client test", function(){
expect(1);
var options = {
host: 'www.google.es',
port: 80,
path: '/'
}
http.get(options, function(res){
ok(true, "http.get callback success");
start();
});
});
A: To be honest, this API appears to be an afterthought, but I think you're looking for asyncTest rather than test
https://github.com/kof/node-qunit/blob/master/test/api.js#L107-115
Not a fan of this module.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Encoding html entities in url string I'm trying to prepare a url that has special characters in it, to be used as GET variables in a php file. I think I need html entities and urlencode, which I then need to decode in the other php file. But I'm running into some problems with correctly encoding them.
This is what I have:
<?php $title = "This is a ‘simple’ test"; ?>
<?php $titleent = htmlentities($title); ?>
<?php $titleentencoded = urlencode($titleent); ?>
<?php $date = '21-12-2011'; ?>
<p>Title: <?php echo $title; ?></p>
<p>Title html entities: <?php echo $titleent; ?></p>
<p>Title encoded: <?php echo $titleencoded; ?></p>
<p><a href="index.php?title=<?php echo $titleencoded; ?>&date=<?php echo $date; ?>">Go!</a></p>
The $titleencoded variable turns out to be empty. I'm overlooking something obvious but I can't see it. What am I doing wrong?
EDIT: New code after suggestions
Okay, so here's what I came up with:
<?php $title = "This is a ‘simple’ test"; ?>
<?php $titleentencoded = urlencode($title); ?>
<?php $htmlent = htmlentities($titleentencoded); ?>
<?php $date = '21-12-2011'; ?>
<p>Title: <?php echo $title; ?></p>
<p>Title encoded: <?php echo $titleentencoded; ?></p>
<p>Title html entities: <?php echo $htmlent; ?></p>
<p><a href="index.php?title=<?php echo $htmlent; ?>&date=<?php echo $date; ?>">Go!</a></p>
Is this the right way?
A: Your variable is empty because you have a typo. You initialize $titleentencoded but later use $titleencoded:
<?php $titleentencoded = urlencode($titleent); ?>
// Should be
<?php $titleencoded = urlencode($titleent); ?>
See @Quentin's answer for a logic error.
A: You are doing it backwards.
You are putting data in a URL, then a URL in an HTML document.
You need to urlencode the data, put it in the URL then htmlencode the URL and put it in the document.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Translate VBA syntax to Matlab for Activex control of Word document I am a newbie to using activex controls in matlab. Am trying to control a word document. I need help translating between VBA syntax and Matlab, I think. How would one code the following in matlab?
Sub macro()
With CaptionLabels("Table")
.NumberStyle = wdCaptionNumberStyleArabic
.IncludeChapterNumber = True
.ChapterStyleLevel = 1
.Separator = wdSeparatorHyphen
End With
Selection.InsertCaption Label:="Table", TitleAutoText:="", Title:="", _
Position:=wdCaptionPositionAbove, ExcludeLabel:=0
End Sub
Thanks, I looked at the help and the source but I am still feeling dense. I want to be able to control caption numbering and caption text in an automated report. Am using Tables and figures. I just can't quite get my head around how to code the addition of the captions.
The following code gets me part way there. But I don't have control over numbering style, etc,. I have tried to figure out the activex structure but I can't make sense of it. In particular, In particular the first bit the VB subroutine above.
% Start an ActiveX session with Word
hdlActiveX = actxserver('Word.Application');
hdlActiveX.Visible = true;
hdlWordDoc = invoke(hdlActiveX.Documents, 'Add');
hdlActiveX.Selection.InsertCaption('Table',captiontext);
A: After some fiddling, I think I got it to work:
%# open Word
Word = actxserver('Word.Application');
Word.Visible = true;
%# create new document
doc = Word.Documents.Add;
%# set caption style for tables
t = Word.CaptionLabels.Item(2); %# 1:Figure, 2:Table, 3:Equation
t.NumberStyle = 0; %# wdCaptionNumberStyleArabic
t.IncludeChapterNumber = false;
t.ChapterStyleLevel = 1;
t.Separator = 0; %# wdSeparatorHyphen
%# insert table caption for current selection
Word.Selection.InsertCaption('Table', '', '', 0, false) %# wdCaptionPositionAbove
%# save document, then close
doc.SaveAs2( fullfile(pwd,'file.docx') )
doc.Close(false)
%# quit and cleanup
Word.Quit
Word.delete
Refer to the MSDN documentation to learn how to use this API. For example, the order of arguments of the InsertCaption function used above.
Note that I had to set IncludeChapterNumber to false, otherwise Word was printing "Error! No text of specified style in document" inside the caption text...
Finally, to find out the integer values of the wd* enums, I am using the ILDASM tool to disassemble the Office Interop assemblies (as this solution suggested). Simply dump the whole thing to text file, and search for the strings you are looking for.
A: Have a look at the help for actxserver and the source code for xlsread.m in the base MATLAB toolbox. If you're still stuck, then update your question with your progress.
EDIT:
You'll need to check the VBA help, but the first part ought to be possible via something like:
o = hdlWordDoc.CaptionLabels('Table');
o.NumberStyle = <some number corresponding to wdCaptionNumberStyleArabic>;
o.IncludeChapterNumber = true;
o.ChapterStyleLevel = 1;
o.Separator = <some number corresponding to wdSeparatorHyphen>;
In my experience, you have to get the values from the enumerations, such as wdCaptionNumberStyleArabic and wdSeparatorHyphen from a VBA script then hard-code them. You can try the following, but I don't think it works:
o.NumberStyle = 'wdCaptionNumberStyleArabic';
o.Separator = 'wdSeparatorHyphen';
A: Instead of hard-coding the text values into the code, you can use the enum constants. This will help when a different language of Word is installed.
A list of the Enums can be found here: https://learn.microsoft.com/en-us/office/vba/api/word(enumerations)
So instead of:
Word.Selection.InsertCaption('Table', '', '', 0, false) %# wdCaptionPositionAbove
you can use this:
NET.addAssembly('Microsoft.Office.Interop.Word')
Word.Selection.InsertCaption(...
Microsoft.Office.Interop.Word.WdCaptionLabelID.wdCaptionTable.GetHashCode,...
' My custom table caption text', '', ...
Microsoft.Office.Interop.Word.WdCaptionPosition.wdCaptionPositionAbove.GetHashCode, false)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for 'software web directory' package for own installation Like this done in
*
*http://directory.fsf.org/
*http://www.ohloh.net/
so anyone in our company (include bosses) can look:
*
*what projects exist (good to have web search capability)
*who is primary mainteners, responsible employees
*provide CHANGES, latest version
*point to BTS (Trac/Mantis), VCS (SVN/Git/HG), Wiki, Mail list, NNTP, Night build, CI build, etc...
*may be provide some summary info based on activity on BTS/VCS (how many opened bugs, how often and who commit)
I don't need extra features as Wiki. and package must work with several existing sofware management/development tools, and does not restricted with Java/C#...
I look on WEB without happen as don't know gold "keywords". Search on StackExchange also don't show any result.
Some requested features available in enterprise application architecture for project hosting (like KForge, FusionForge, GForge) but thay too complex and dictate toolset for teams...
A: Seems that all existing software directory project built in house and their sources are not released for public.
Look for most complete list of software directories enabled site that I found. Only OpenSymphony provide sources of some components.
So complete lightweight solution does not exist currently.
I going to write own...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selenium RC and Firefox4 support Who knows in which release of selenium server firefox4 (firefox5) works correctly. On http://seleniumhq.org/about/platforms.html mentioned that both versions are supported, but I didn't find in release notes anything like Fixes of Firefox4 support
A: The new server (selenium-server-standalone-2.14.0.jar) runs with current versions of Firefox (8.x)
A: Selenium RC 0.9.2 should run FF4
A: you can download newer versions also they have only one jar file. or even edit older versions to support for newer versions of browsers ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to disable up/down pan in UIWebView? I want to have my web view pannable left and right but not up and down.
Is that possible?
Thanks.
A: ok, well wrap your one line of html like this:
<html>
<head>
<meta name = "viewport" content = "height = device-height, user-scalable = no, width = WIDTH">
</head>
<body>
...YOUR HTML
</body>
</html>
Replace width with the width of your content, and see how it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Defining Control-Shift-* Emacs keyboard shortcuts I'm trying to define the following two keyboard shortcuts to move between windows in Emacs:
*
*C-shift-n: Move to the next window
*C-shift-b: Move to the previous window
I thought the following will do it but it doesn't.
(defun select-next-window ()
"Switch to the next window"
(interactive)
(select-window (next-window)))
(defun select-previous-window ()
"Switch to the previous window"
(interactive)
(select-window (previous-window)))
(global-set-key (kbd "C-<S-n>") 'select-next-window)
(global-set-key (kbd "C-<S-p>") 'select-previous-window)
The problem seems to be with the last two lines that define the actual keyboard shortcuts to the functions that switch the windows (if I use simpler keyboard shortcuts instead of Control-Shift-* it works).
So, how do I use kbd to define Control-Shift-n and Control-Shift-p?
A: Assuming you never use caps lock, here's a super simple solution:
(global-set-key (kbd "C-N") 'select-next-window)
or
(global-set-key (kbd "C-<S-N>") 'select-next-window)
The problem is that when you hit shift you're sending capital N.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Eclipse equals generation: null check missing? I let Eclipse generate the equals method for my class and it starts with:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
[...]
It seems to me, a check like if (obj == null) return false; is missing. Otherwise, if a null reference is passed to equals there will be a null pointer exception in obj.getClass(). Am I wrong or is Eclipse wrong?
A: Perhaps you are having an old eclipse version. My eclipse generates this:
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
A: You are right, if Eclipse does it that way. But it doesn't. On my machine, Eclipse Indigo / Ubuntu, given this Class:
public class Foo {
private String bar;
}
Eclipse would generate the following equals() method:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Foo other = (Foo) obj;
if (bar == null) {
if (other.bar != null) return false;
} else if (!bar.equals(other.bar)) return false;
return true;
}
For comparison, here's the equals() method I would write for the same class (using Guava):
@Override
public boolean equals(final Object obj) {
return obj instanceof Foo ? Objects.equal(bar, ((Foo) obj).bar) : false;
// ^--- implicit null check here
}
I use this Eclipse code template to achieve this:
${:import(com.google.common.base.Objects)}
@Override
public boolean equals(final Object obj){
return obj instanceof ${enclosing_type} ? Objects.equal(${field1:field}, ((${enclosing_type}) obj).${field1}) : false;
}
@Override
public int hashCode(){
return Objects.hashCode(${field1});
}
@Override
public String toString(){
return MoreObjects.toStringHelper(this).add("${field1}", ${field1}).toString();
}
Unfortunately, I have to keep one of these around for each cardinality of fields, so I have templates named eq1 (the above), eq2, eq3, eq4 etc. It's a small nuissance, but it's still a lot better than the monster methods generated by Eclipse.
Guava docs
A: Yes, passing null as obj would give a NullPointerException with that code.
A: You indeed need a null check. My version of Eclipse generates equals methods with a null check.
A: if (obj) is null, the obj.getClass() will throw an NPE
A:
It seems to me, a check like if (obj == false) return false; is missing.
Why do you want to compare object with a Boolean value? ;-)
I suppose you though about obj == null check, and that is exactly what Eclipse generates in my case:
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestGetClass other = (TestGetClass) obj;
if (id != other.id)
return false;
return true;
}
I am using 3.7 version. Anyway, you are right... actually Eclipse... too ;-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the difference between creating the Container using Blob storage Service REST API and StorageClient class library in azure storage service? What is the difference between creating the Container using REST APIs and StorageClient class library ?
A: Developer experience is the only difference. The StorageClient uses REST under the covers. REST is the only API for storage and the client just takes care of the nitty gritty stuff (canonicalization, signing, setting up HTTP request, etc.).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What permission am missing? I'm taking sms backup using this
public void smsbackup() throws IOException
{
InputStream in = new FileInputStream("/data/data/com.android.providers.telephony/databases/mmssms.db");
File dir = new File("/mnt/sdcard/bcfile");
dir.mkdirs();
OutputStream output = new FileOutputStream("/data/data/com.android.app/files/");
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0)
{
output.write(buffer, 0, length);
}
output.flush();
output.close();
in.close();
}
It throws an exception like permission denied I don't know what permission will i give. Anyone tell me? Thanks in Advance.
A: You will need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
because of
File dir = new File("/mnt/sdcard/bcfile");
I wonder if you can ever access: /data/data/com.android.providers.telephony/databases/mmssms.db
A: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
you have to add this permission since you are trying to write files to SDcard. hope this helps
A: <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
You also need the permission of reading inbox messages.
Hope it will help you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When using MVC in GWT, is it better to have the model use raw strings or SafeHtml? I'm writing code in GWT that follows MVC pattern.
By the time my view renders, my strings should be escaped into SafeHtml.
I'm trying to decide whether to have my model operate in terms of unsafe strings and do the conversion in the view, or to use SafeHtml in the model and identify errors in when bulding the model.
Is there a best practice?
My reasoning for doing the SafeHtml conversion late is that it is a rendering issue, and that there may not be a need to pay the cost of escaping for strings that are not eventually displayed. On the other hand, data that cannot be converted to SafeHtml is an issue that should be caught early and preclude the model from being "valid".
A: I would use raw string objects since the model should be view agnostic, should not have any dependencies to any presentation framework, let's suppose tomorrow you would write a thin eclipse client and communicate with your model using web services, you do not need to retrieve SafeHtml scaped strings just strings, desktop clients communicating with web services or even command line clients should not need to know anything about SafeHtml strings.
Just my two cents!
Pablo
A: Pablo is right, but there is another point. SafeHtml is used to secure your application, because the client shouldn't trust the server and vice-verse. Now if you would use SafeHtml directly in the model you would trust the server with the assumption that the server provides the correct escaped and sanitized HTML code. To avoid this use raw strings and convert them to SafeHtml in the view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Alloc - add as accessoryView - release: does it leak? Does this leak memory? This code is executed in cellForRowAtIndexPath: outside the cell creation block (so each time the table cell is updated).
MyView *myView = [[MyView alloc] init];
// ... configuration code
cell.accessoryView = myView;
[myView release];
Or in other words, will the UITableViewCell release the object in its accessoryView when a new object gets assigned to it?
Thanks.
A: Yes, the cell will release the accessory view and you do not have a leak in the example.
A: The property accessoryView of a UITableViewCell is a retain type, in common with many view properties in the kit. Check the Apple documentation for UITableViewCell to convince yourself of this. Therefore there will be no leak in your example - the retain count has been correctly managed. You've also correctly released after setting the accessory view, on account of your alloc call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript grab part of class I have a string
<li class="views-row views-row-4 views-row-even views-row-last" style="overflow-x: hidden; overflow-y: hidden; float: left; width: 221px; height: 227px; ">
<div class="views-field-field-image-fid">
<span class="field-content"><img class="imagefield imagefield-field_image" width="221" height="215" alt="" src="http://test.com/sites/default/files/1_03_2.png?1316715258"></span>
</div>
<div class="views-field-field-pager-item-text-value">
<span class="field-content">hydraSense®h</span>
</div>
<div class="views-field-field-slide-text-value">
<div class="field-content">hgfhfghgfhgfhhhgf</div>
</div>
</li>
And I want to get the views-row-4 from <li class=" how could I get this? My method of splitting by class didn't seem to work.
A: The first step is to get the li element itself. The easiest way is to attach and id to the guy then you can use the following to get the DOM element.
var element = document.getElementById('theNewId');
var classAttr = element.getAttribute('class');
var second = classList.split(" ")[1];
This assumes the "views-row-4" class is always the second one in the class list. If it's not then we'd need some other criteria by which to search for the value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS not working for IE I have a shopping cart display button on the top of my site and its supposed to show a red price for the total in your cart
the CSS works in FF and in chrome, but not in IE.
CSS:
.cart-info {
background-image: url("/skin/frontend/default/photo/images/header/head-cart-bg.gif");
background-position: left center;
background-repeat: no-repeat;
color: #264796;
height: 38px;
padding: 19px 0 0 50px;
width: 150px;
font-weight: bold;
}
.cart_price {
color: #c70000;
font-weight: bold;
float: left;
font: 14px Arial,Helvetica,sans-serif;
left: 114px;
position: absolute;
top: 57px;
width: auto;
}
.cart_price a {
float: left;
margin: 2px 0 0 8px;
}
A: Sounds like IE is applying a different font color for .cart_price a. Assuming this is your markup:
<div class="cart_price">
<a href="">$123.45</a>
</div>
Adding the red color to the .cart_price a rule will fix it:
.cart_price a {
color: #c70000;
float: left;
margin: 2px 0 0 8px;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Vb.net conditional linq query In this query against a datatable i'm trying to do some conditional filtering.
The check against Timeband(index N) should only be done when the Index exists. (the base code only had three item fields, i've converted them to a simple list)
Dim res As DataTable =
(
From dr As DataRow In dtTimedRow.AsEnumerable()
Select dr
Where
(TimeBands.Count > 0 AndAlso
dr.Field(Of Short)(fldStarttime) >= TimeBands(0).StartTime
And dr.Field(Of Short)(fldStarttime) <= TimeBands(0).EndTime
) Or
(TimeBands.Count > 1 AndAlso
dr.Field(Of Short)(fldStarttime) >= TimeBands(1).StartTime
And dr.Field(Of Short)(fldStarttime) <= TimeBands(1).EndTime
) Or
(TimeBands.Count > 2 AndAlso
dr.Field(Of Short)(fldStarttime) >= TimeBands(2).StartTime
And dr.Field(Of Short)(fldStarttime) <= TimeBands(2).EndTime)
).CopyToDataTable()
The above code triggers an Exception if the count = 1. It executes the code next to imeBands.Count > 1 which it should not. What would be the correct solution for this code.
In the mean time i've added a simple filter function.
A: The problem is that you use And when you should be using AndAlso:
TimeBands.Count > 2
AndAlso dr.Field(Of Short)(fldStarttime) >= TimeBands(2).StartTime (= cond1)
And dr.Field(Of Short)(fldStarttime) <= TimeBands(2).EndTime (= cond2)
Since And and AndAlso have the same operator precedence, this is evaluated left-to-right as follows:
(TimeBands.Count > 2 AndAlso cond1) And cond2
And does not short-circuit, i.e., the right-hand side of the expression (cond2) is always evaulated, yielding an exception when TimeBands.Count <= 2. Change all your Ands to AndAlsos, and you should be fine:
TimeBands.Count > 2 AndAlso cond1 AndAlso cond2
An alternative would be to put parenthesis like this:
TimeBands.Count > 2 AndAlso (cond1 And cond2)
but that's just wasting performance. Since cond1 and cond2 don't have side effects, there's no reason to avoid short-circuiting. For the same reasons, I recommend to also change your Ors to the short-circuiting variant OrElse.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a diff tool that allows copy-paste Is there a diff tool that allows you to paste two segments of text and get a diff? I can't use an online tool because I'm dealing with proprietary data, and I haven't found a tool that provides that feature.
A: For those who use Atom, there’s the split-diff package.
A: KDiff3 can do that too. On startup just Cancel the open dialog and than copy&paste snippets into the two panes. It immediately (re)computes their diff.
A: Notepad++ makes it really easy to do that: paste first text, open new tab, paste second text then Plugin > Compare > Compare.
Make sure you have the compare plugin installed.
Source: https://stackoverflow.com/a/15817384/965176
A: Try WinMerge. It'll do that.
Steps:
*
*Download and install winmerge
*Open WinMerge & Create new <CTRL+N>
*Paste into left & right, then refresh <F5>
A: In case anyone comes here looking for a tool for Macs that can do this, it seems that there are two tools that can do just this.
*
*Beyond Compare, the Mac version is currently in beta.
*Kaleidoscope app
*
*Copy first text
*File -> New from Clipboard
*Copy second text
*Edit -> Paste to comparison
Unfortunately, it doesn't seem to be possible to change the texts once they've been pasted.
There is also a similar (closed) question (the question itself was for a Mac tool, but at least one answer has an alternative diff tool for Windows):
Diff tool for Mac without saving text to files
A: I think this might be what you're looking for - Line Diff - it's a online tool that takes as input two snippets of code/text, diff them and then render a nice github like html page (permanent or temporary stored) that you can then share with coworkers.
A: I used BBEdit (Mac OS X):
*
*paste your snippets into 2 separate new documents (without saving)
*go to search → find differences
*using the clock icon, pick your new documents
The app has a subscription model, but this doesn't seem to be a premium feature.
A: You can try online tools
it's good
https://www.diffchecker.com/
Or you can try KDIFF3 its also a good tool
http://kdiff3.sourceforge.net/
A: also you can try online diff tool , maybe it's useful to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: How to inject a JavaScript function and its call from text area? How can I submit a function definition and its call from
<input type="text">
tag?
EDIT:
My friend have written a php script where he takes the value of tag and without calling strip_tags function prints on another page. Now I want to show an example with JavaScript (I believe it should be possible) that I can inject a JavaScript code into his website. That is my task.
A: If you want to invoke script from your textbox, try to use eval in javascript.
<script type="text/javascript">
function Invoke()
{
var ctrl = document.getElementById('content')
eval(ctrl.value);
}
</script>
<input type="text" id="content" />
<input type="button" onclick="Invoke()" value="Invoke" />
Code: http://jsfiddle.net/AuPRM/
A: Assign the return value of yourFunction.toString() to the value property of the field.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: MEF ComposeExportedValue method I have the following situation :
I have in UserControl A , in this user control I manage selecting a list of contacts for sending email. I added to its ViewModelA an Action so after filling the contacts I can call this action and this will move the operation with the contacts list to the control which call the UserControlA
[Import(AllowDefault = true, AllowRecomposition = true)]
public Action<IEnumerable<Contact>> ActionContactMethod
In UserControl B which contains UserControlA I declared a method void Send(Action<IEnumerable<Contact>> contacts) which is the same signature of the action in UserControl A.
I use MEF composition container to compose it :
CompositionContainer.ComposeExportedValue(new Action<IEnumerable<Contact>>(Send));
This way , when the user choose his contacts then the Action in ViewModelA which wired with the method Send in ViewModelB will happen and the Send method will be called .
The first time I see the recomposition occured and the method send is wired correctly, the second time I'm trying to use the ComposeExportedValue I get an exception, because there is already an Export definition to the Action<IEnumerable<Contact>>.
How I can remove this part from the container so I can compose it again, or if there is another workaround. I used the Compose and the ComposePart method but the recompositions dosn't happen this way.
Thanks in advance...
A: Using ComposeExportedValue<T> doesn't give you enough control over the ComposablePart instances used during composition. You can control recomposition using CompositionBatch instances. Here is an example class:
[Export]
public class Broker
{
[Import(AllowRecomposition = true)]
public Action<string> Writer { get; set; }
}
I've specified a property which is actual a delegate, now look at the following:
class Program
{
static void Main(string[] args)
{
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
var part1 = batch.AddExportedValue<Action<string>>(ConsoleWrite);
container.Compose(batch);
var broker = container.GetExportedValue<Broker>();
broker.Writer("Hello");
var batch2 = new CompositionBatch(null, new[] { part1 });
batch2.AddExportedValue<Action<string>>(ConsoleWrite2);
container.Compose(batch2);
broker.Writer("Goodbye");
Console.ReadKey();
}
static void ConsoleWrite(string message)
{
Console.WriteLine(message + " from ConsoleWrite");
}
static void ConsoleWrite2(string message)
{
Console.WriteLine(message + " from ConsoleWrite2");
}
}
What I've done here, is I've created two separate batches, one which allows me to compose my original delegate, wired up to ConsoleWrite, and one which allows me to remove my original delegate, and then compose my second delegate, ConsoleWrite2. During the first composition, my delegate is wired up in my Broker instance. Now, because I have specified that [Import] to be recomposable, when I compose my second batch, it removes my original part (which is my delegate), and composes my new part (which is my new delegate).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I calculate the difference of two angle measures? How can I calculate the difference of two angle measures (given in degrees) in Java so the result is in the range [0°, 180°]?
For example:
350° to 15° = 25°
250° to 190° = 60°
A: Just take the absolute value of their difference, then, if larger than 180, substract 360° and take the absolute value of the result.
A: /**
* Shortest distance (angular) between two angles.
* It will be in range [0, 180].
*/
public static int distance(int alpha, int beta) {
int phi = Math.abs(beta - alpha) % 360; // This is either the distance or 360 - distance
int distance = phi > 180 ? 360 - phi : phi;
return distance;
}
A: Just do
(15 - 350) % 360
If the direction doesn't matter (you want the one that yields the smallest value), then do the reverse subtraction (mod 360) and calculate the smallest value of the two (e.g. with Math.min).
A: How about the following:
dist = (a - b + 360) % 360;
if (dist > 180) dist = 360 - dist;
A: In addition to Nickes answer, if u want "Signed difference"
int d = Math.abs(a - b) % 360;
int r = d > 180 ? 360 - d : d;
//calculate sign
int sign = (a - b >= 0 && a - b <= 180) || (a - b <=-180 && a- b>= -360) ? 1 : -1;
r *= sign;
EDITED:
Where 'a' and 'b' are two angles to find the difference of.
'd' is difference. 'r' is result / final difference.
A: diff = MAX(angle1, angle2) - MIN(angle1, angle2);
if (diff > 180) diff = 360 - diff;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Is it possible to distinguish between click and selection? I have a div with a hidden child. Clicking in the div will toggle the visibility of the child. This works well.
Now the user wants to select some text in the child. Dragging the selection works but as soon as the mouse button is released, the div closes (because of the inClick handler).
If possible, I'd still like to be able to close the div from anywhere in the child because the child can be quite large (hundreds of lines, so it would be tedious to scroll to the div to toggle the child).
Needs to work with IE6+ and all sane browsers. I can't use jQuery directly :-( but I can copy code from jQuery so if jQuery had a solution, I clone it.
Suggestions?
A: You can do a check on window.getSelection() to see if it contains anything before closing your inner div.
For IE6 you'll want to substitute this with document.selection.
Note that this is proprietry to IE so you'll want to distinguish which method to use via object detection.
Working Demo
A: You could have a toggle control on the side of the DIV:
toggle.onclick = function () {
if ( this.className === 'closed' ) {
this.className = '';
content.style.display = '';
} else {
this.className = 'closed';
content.style.display = 'none';
}
};
Live demo: http://jsfiddle.net/HcVfW/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem Render backbone collection using Mustache template I am quite new to backbone js and Mustache. I am trying to load the backbone collection (Object array) on page load from rails json object to save the extra call . I am having troubles rendering the backbone collection using mustache template.
My model & collection are
var Item = Backbone.Model.extend({
});
App.Collections.Items= Backbone.Collection.extend({
model: Item,
url: '/items'
});
and view
App.Views.Index = Backbone.View.extend({
el : '#itemList',
initialize: function() {
this.render();
},
render: function() {
$(this.el).html(Mustache.to_html(JST.item_template(),this.collection ));
//var test = {name:"test",price:100};
//$(this.el).html(Mustache.to_html(JST.item_template(),test ));
}
});
In the above view render, i can able to render the single model (commented test obeject), but not the collections. I am totally struck here, i have tried with both underscore templating & mustache but no luck.
And this is the Template
<li>
<div>
<div style="float: left; width: 70px">
<a href="#">
<img class="thumbnail" src="http://placehold.it/60x60" alt="">
</a>
</div>
<div style="float: right; width: 292px">
<h4> {{name}} <span class="price">Rs {{price}}</span></h4>
</div>
</div>
</li>
and my object array kind of looks like this
A: Finally it turns out that mustache doesn't handle array of objects sent to the template, so i had to wrap it with other object like this
render: function() {
var item_wrapper = {
items : this.collection
}
$(this.el).html(Mustache.to_html(JST.item_template(),item_wrapper ));
}
and in template just looped the items array to render the html
{{#items}}
<li>
<div>
<div style="float: left; width: 70px">
<a href="#">
<img class="thumbnail" src="http://placehold.it/60x60" alt="">
</a>
</div>
<div style="float: right; width: 292px">
<h4> {{name}} <span class="price">Rs {{price}}</span></h4>
</div>
</div>
</li>
{{/items}}
Hope it helps to someone.
A: Mustache can handle arrays using {{#.}}{{.}}{{/.}}
A: This happens because mustache expects a key/value pair -being the value an array- for Non-Empty Lists. From the mustache man page, section "Non-Empty Lists":
Template:
{{#repo}}
<b>{{name}}</b>
{{/repo}}
Hash:
{
"repo": [
{ "name": "resque" },
{ "name": "hub" },
{ "name": "rip" },
]
}
Output:
<b>resque</b>
<b>hub</b>
<b>rip</b>
If you pass only an array, mustache does not have a way to know where to expand it inside the template.
A: Using Hogan.js implementation.
Given template:
<ul>
{{#produce}}
<li>{{.}}</li>
{{/produce}}
</ul>
And context:
var context = { produce: [ 'Apple', 'Banana', 'Orange' ] );
We get:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Exporting an Excel file to .html -- issues Can anybody help me with this?
I am taking a table in Excel and exporting it as a web page. I noticed that the webpage rendered things differently -- such as spacing (it's putting in LOTS of white space where there should be none). Also, it's displaying columns that were hidden in my excel file.
Can anybody let me know how to export this so that the space rendering is not so different?
Also, does anybody know how to export this in a way where I can keep some Excel functions (i.e. sort, filtering, etc.)?
A: For hidden columns, Excel's html format simply doesn't respect them. I set my column width to 1 pixel to "hide" them. If you have a lot of them together, it looks terrible in Excel and creates even more white space in the html, but I couldn't come up with a better way.
A: I think you could use Appizy to do it. It's a render service from .ods to .html :
*
*First transform your Excel file into an OpenDocument with Open or LibreOffice
*Convert it using the html render tool of Appizy. The hidden cells will have the css attribute "display:none"
If you don't want your formulas to be working, the free version should be fine for you. I hope it can help.
BR, Nicolas
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Refresh ActiveResource Cache I have an active resource model in one of my applications, and I need to be able occasionally do a find(:all), and force it to repull the data from the remote service. How can I do this? I saw the connection(refresh=true) piece, but I don't want it to refresh EVERY SINGLE TIME. More like I just want to be able to flush the cache when I want to, or to force a particular transaction to repull from the remote.
A: You might check out cached_resource. I am not sure how you are caching currently. Cached resource caches the responses to requests made with active resource. At the moment it seems to cache every request that goes through active resource, but allows you to refresh a specific request by doing:
MyActiveResource.all(:reload => true).
A: As far as I know, ActiveResource doesn't do any caching and will pull from the remote service every time you do find(:all).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: payment regarding in-app purchase i was implementing the in-app purchase.All i am doing in a apple sandbox i have done transaction completely and also apple is returning the response = 0 when i verify the receipt, but my question is where do i look for successful payment received. Which email id i will get mails like "you have received the amount from user1". ? or should i look to itune connect?
here is my code for receiving response:
- (BOOL)verifyReceipt:(SKPaymentTransaction *)transaction {
NSString *jsonObjectString = [self encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length];
NSString *completeString = [NSString stringWithFormat:@"http://test.clientarea.in/WS/two.php?receipt=%@", jsonObjectString];
NSLog(@"completestring%@",jsonObjectString);
NSURL *urlForValidation = [NSURL URLWithString:completeString];
NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation];
[validationRequest setHTTPMethod:@"GET"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil];
[validationRequest release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSInteger response = [responseString integerValue];
NSLog(@"response string...%d",response);
[responseString release];
return (response == 0);
}
- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *output = (uint8_t *)data.mutableBytes;
for (NSInteger i = 0; i > 18) & 0x3F];
output[index + 1] = table[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) > 6) & 0x3F] : '=';
output[index + 3] = (i + 2) > 0) & 0x3F] : '=';
}
return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];}
A: You need to look in iTunes Connect. Apple generates reports by region (which they will send out to the registered account admin) some time after the month closes.
These reports are a bit opaque and will not give you specific device uniqueIdentifiers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Possible to attach event handler to listview('refresh') in jQuery Mobile? I have a listview that I'd like to bind a callback to after I call listview('refresh').
In the optimal case I'd love to do something like this:
listviews = $('[data-role="listview"]').live 'refresh', -> Console.log "Listview refresh"
I haven't found anything in the docs that say you can do anything like this, so I was thinking it could be possible to perhaps listen for DOM change events though the only thing I found is an event called DOMNodeInserted but support doesn't seem to be there on every browser.
A: You refresh the listview yourself, so why not put an additional call in your code like that:
$whatever.listview('refresh').trigger('IrefreshAlistview');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with append json_encode I want append service by jQuery.each(), but it in my js code not worked?
This is my output from PHP code:
{
"data": [{
"service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"],
"address": "chara bia paeen"
}, {
"service": ["koko", "sili", "solo", "lilo"],
"address": "haminja kilo nab"
}, {
"service": ["tv", "wan", "hamam", "kolas"],
"address": "ok"
}]
}
This is is my jQuery code:
$.ajax({
type: "POST",
dataType: "json",
url: 'get_residence',
data: dataString_h,
cache: false,
success: function (respond) {
$.each(respond.data, function (index, value) {
$('ol li').append('<a href="">' + value.service + '</a>');
});
},
"error": function (x, y, z) {
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
What do i do?
A: You will need another $.each loop because service is an Array:
$.each(respond.data, function (index, value) {
$.each(value.service, function () {
$('ol li').append('<a href="">' + this + '</a>');
});
});
to just format the array:
$.each(respond.data, function () {
$('ol li').append('<a href="">' + this.service.join(', ') + '</a>');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to document (javadoc) a message handler method? I have a class which implements Handler.Callback
So, in my code i have something like this :
@Override
public boolean handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what)
{
case ThreadMessages.MSG_1:
{
break;
}
case ThreadMessages.MSG_2:
{
break;
}
case ThreadMessages.MSG_3:
{
break;
}
case ThreadMessages.MSG_4:
{
break;
}
case ThreadMessages.MSG_5:
{
break;
}
}
return false;
}
How should i comment this method to reflect the messages that my class can handle ?
The purpose here , is to let a developer know what message he can send to the class without having to read the source code , just using the java doc.
Thanks
A: My Advice:
In class ThreadMessages Rename MSG_1 and the other static fields to some meaningful names.
Above your handleMessage
Add the following comments:
/**
* Can handle {@link ThreadMessages#MSG_1}, {@link ThreadMessages#MSG_2}, {@link ThreadMessages#MSG_3}, {@link ThreadMessages#MSG_4}, and {@link ThreadMessages#MSG_5}
*/
And in class ThreadMessages
Explain each static feild by adding above it
/**
* this is used for
*/
A: Oracle has a great document about how to comment your code so you can generate Java Docs later on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get image height and width PHP Hello I need to get the height and width on the fly of an uploaded image.
This is the PHP function I am using, but it does not return anything for the width and height..
Could you please help me?
list($width, $height, $type, $attr) = getimagesize($_FILES["Artwork"]);
$min_width = "1000";
$min_height = "1000";
if ((($_FILES["Artwork"]["type"] == "image/gif") || ($_FILES["Artwork"]["type"] == "image/jpeg") || ($_FILES["Artwork"]["type"] == "image/jpg")
|| ($_FILES["Artwork"]["type"] == "image/pjpeg")) && ($_FILES["Artwork"]["size"] < 20000000) && ($width > $min_width) && ($height > $min_height) && ($width == $height))
{
if ($_FILES["Artwork"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["Artwork"]["error"] . "<br />";
}else{
move_uploaded_file($_FILES["Artwork"]["tmp_name"],
$path_image . $imageName);
header("Location: http://pitchmystuff.co.uk/m/digidist/tracks/".$idAlbum."");
}
}else{
//echo "invalid file";
echo '<script>
alert("There was an error uploading your coverart file. Please check the requirements and try again.'.$width.$height.'");
document.location ="http://pitchmystuff.co.uk/m/digidist/albums/";
</script>';
}
A: <?php
$imagedetails = getimagesize($_FILES['Artwork']['tmp_name']);
$width = $imagedetails[0];
$height = $imagedetails[1];
?>
A: Should be
list($width, $height, $type, $attr) = getimagesize($_FILES["Artwork"]['tmp_name']);
See http://www.php.net/manual/en/features.file-upload.post-method.php
A: <?php
/*$size = getimagesize("http://heartbeatperformance.com.p9.hostingprod.com/customerphotos/photoes/51HDE3cnl2L.jpg");
list($width, $height) = $size;
echo "width: $width<br />height: $height";*/
$testing = "http://heartbeatperformance.com.p9.hostingprod.com/customerphotos/img/logo.png";
//echo $testing;
list($width, $height, $type, $attr) = getimagesize($testing);
echo "Image width " . $width;
echo "Image height " . $height;
?>
A:
$DOCS_NAME = $_FILES['DOCS']['name'];
$DOCS_SIZE = getimagesize($_FILES['DOCS']['tmp_name']);
$DOCS = file_get_contents ($_FILES['DOCS']['tmp_name']);
$FILE_SIZE = $_FILES["DOCS"]["size"];
$FILE_TYPE = $_FILES["DOCS"]["type"];
echo 'Width = '.$DOCS_SIZE[0]. "<br />";
echo 'Height = '.$DOCS_SIZE[1]. "<br />";;
echo '2 = '.$DOCS_SIZE[2]. "<br />";;
echo '3 = '.$DOCS_SIZE[3]. "<br />";;
echo 'bits = '.$DOCS_SIZE['bits']. "<br />";;
echo 'channels = '.$DOCS_SIZE['channels']. "<br />";;
echo 'mime = '.$DOCS_SIZE['mime']. "<br />";
echo 'type = '.$_FILES["DOCS"]["type"]. "<br />";
echo 'size = '.$_FILES["DOCS"]["size"]. "<br />";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Problem passing decimal value to database (Access) I want to pass decimal value to database table. When I send value 1,5 to database then save value as 15.
Code:
txtKm.Text="1,5";
zelezniceDataSet.VozniRediRow row;
row.Km = decimal.Parse(txtKm.Text);
zelezniceDataSet.VozniRedi.AddVozniRediRow(row);
vozniRediTableAdapter.Update(zelezniceDataSet.VozniRedi);
When debug decimal parsing the value is correct (1.5)
A: You probably want to look at an overloaded form of decimal.Parse that accepts a culture-specific format option. My guess is decimal.Parse sees your comma as a thousands-separator and just removes it.
A: seems to me that decimal.Parse is ignoring the comma ... if you pass "1.5" is the correct value saved? If so then you need to use the overload that takes the culture to use when parsing Decimal.Parse(String, NumberStyles) and pass it the correct number style for the language you are using.
EDIT ... more info ..
decimal.Parse(test, CultureInfo.GetCultureInfo("EN-us").NumberFormat );
will output 15 for test = "1,5" because in English the "," char is the thousands separator
decimal.Parse(test, CultureInfo.GetCultureInfo("NL-nl").NumberFormat );
will output 1.5 for test = "1,5" because in Dutch the "," char is the decimal separator
Hope this helps :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why do php variables need to be identified by $?
Possible Duplicate:
Why does PHP have a $ sign in front of variables?
In languages like bash and Perl, strings need not be quoted and that is why variable access needs to be identified by using $. Why does PHP need the similar mechanism?
A: It's a historical decision, probably because it allows to include variables in a string literal:
$variable = "handle to data storage";
echo "a $variable";
A: Because PHP is influenced by Perl. Back then, when it was conceived, PHP was just a set of Perl scripts.
A: PHP Constants are a seperate type, but behave much like variables (except they can't be changed, of course... that's what they're constants for) and look a lot like 'em too. For readability, it's nicer to have an identifier. (<- random guess, not)
Besides:
$lol = abcdef;
$lol === 'abcdef'; // true
Undefined constants will throw a notice and will be interpreted as a string.
ohyes, and inside strings, variables can also be used, so an identifier is absolutely necessary (thanks to phihag)
A: I think simply because without it mixing variable inside string will not be possible
$name = "bond";
echo "My name is $name" ;
Now without $ name will act as string .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Where to find what commands/properties are available for AppleScript in Microsoft Outlook 2011 Does anyone know where I can find a list of available applescript commands/properties for Microsoft Outlook 2011?
I am trying to copy subject of the opened message into the clipboard and save the message as PDF to my desktop with subject as the file name.
Thanks.
A: All applications that are apple-scriptable have a "dictionary" of terms as part of the application itself. To access a dictionary open AppleScript Editor, under the File menu choose "open dictionary", and then choose the application.
A second way would be to drag/drop the application onto the AppleScript Editor icon in the dock or applications folder.
A third way... under the Window menu in AppleScript Editor choose "Library". That window is a quick-access tool to access the dictionaries of various applications. You can click the "+" button to add applications not in that list. Double-click an application in the list to access its dictionary.
A 4th way... if AppleScript Editor and the application you are interested in are both in the dock, you can command-drag the application's dock icon onto the AppleScript Editor's dock icon.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: uploadify Characters (čžćšđ) issue I am using http://www.uploadify.com/ but when I upload images with character (čžćšđ) like "čžćšđ.jpg" čćžšđ is corrupted and uploaded image looks like čćžšđ.jpg.
How can I prevent this? What to do that čžšđ will work after upload?
A: The problem is on uploadifys encoding and there is only one thing you can do about it:
Change the characters in your file.
I highly doubt that it will be fixed soon, even if you tell them about the problem. Either use someone else or change the name of your files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chrome & PopUp window names I am opening pop up windows from a website (flash content) the following way:
RING = window.open(path,'RING_Projekt','width=800,height=600,scrollbars=no,top=' + t + ',left=' + l +'');
The HTML file opened in the popup is valid HTML with a <title>, yet Chrome (all other browsers do work fine) will display "Untitled" in the title bar.
Does anyone know why this is happening and if there is an error / workaround that could fix this? Or is this some kind of a pop up blocker malfunction / bug?
Thanks!
EDIT: Playing around, I noticed the following (unfortunately it ADDS to my confusion...): the page with the flash content opens another popup (displaying news) on load by doing:
var NEWS = window.open('popup/news.htm','RING_news','width=400,height=400,scrollbars=no,top=20, left=20');
When I now open a popup with the function mentioned in the above post, then go and close the news-Popup opened on load and then switch back to the "on-click"-Popup the popup magically acquired a name. When you close this and open it again, the name is gone again.
To be honest: I don't get it. I should be able to have more than one pop-up, right? Also, I cannot see any naming problems or anything else that could explain this behavior.
Am I missing something big here? Or is this a plain bug?
A: Ok, I am a 99.99% sure this is a Chrome bug, so I'll answer this myself.
Chrome seems to read the specified title correctly from the HTML (as it will be displayed in the task bar), but seems to have problems when having to display the name in the bar on the popup (see screenshot below). When you start to fiddle with the popup (move / resize), the title will sometimes appear and disappear again. Yet, the names in the task bar will always be right (that plus the fact that it works in every other browser lets me think it is a bug).
I am running Chrome 14.0.835.186 m on Windows Vista.
A: http://code.google.com/p/chromium/issues/detail?id=113201
its a open bug
A: This is a bug with Chrome. However, there is a workaround for this.
If you put the following script in the page that opens in the popup window, it seems to work fine.
<script language"text/javascript">this.window.resizeBy(1,1);this.window.resizeBy(-1,-1);</script>
A: The second argument to window.open isn't the <title> of the new window, used by <a target="...">, for example.. The title is determined by the content of the page.
See MDN docs for more info.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to fix jslint The '&&' subexpression should be wrapped in parens error I put everything in parentheses but code below still throws error in jslint:
Problem at line 5 character 104: The '&&' subexpression should be wrapped in parens.
if ((typeof (c1) === 'string') && (typeof (c2) === 'string') && (c1 !== n...
How to fix ?
"use strict";
function t() {
var c1, c2;
if (((typeof (c1)) === 'string') && ((typeof (c2)) === 'string') && (c1 !== null) && (c2 !== null) && ((c1.trim()) === '') || ((c2.trim()) !== '')) {
return;
}
}
A: It's complaining about the form if(a && b && c || d) because (I suppose) it's not immediately obvious whether && or || will take precedence. Fix it to look like if(a && b && (c || d)) and it will stop complaining.
A: I think it wants this:
if (((typeof (c1) === 'string') && (typeof (c2) === 'string') && (c1 !== null) && (c2 !== null)) && ((c1.trim()) === '') || ((c2.trim()) !== '')) {
wrap the 4 anded expressions on the left of the && at 100.
A: I'm fairly certain you want the following:
function t() {
var c1, c2;
if (typeof c1 === 'string' && typeof c2 === 'string' && c1 !== null && c2 !== null && (c1.trim() === '' || c2.trim() !== '')) {
return;
}
}
Not everyone knows the precedence for boolean logic, so they want you to wrap the c1.trim() || c2.trim() statements in parenthesis so it's clear how they get operated.
As a side note, I think it's ridiculous that jslint wants spaces between my operators and my operands. I think it's much more clear when there is NOT a space.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Joining Tables in ASP.NET Ambiguous Error.. It highlights this line:
bojDA.Fill(objDS, "ShopCart");
and right above that is my select statement which looks like:
any advice on this issue now would be helpful, thank you
Thank you
I think the new error has something to do with:
SELECT productid,productname,productsku,quantity,productprice,productprice * quantity AS TotalPrice,ShoppingCartRecID,UOM,PackingSlip,LogoDesignNumber,CustomText,NameText,ExtraCharge,custitem,t1.CatalogType,CatalogID,RelatedChargeID,UPSFlag FROM ShoppingCart t1 INNER JOIN ItemCatalogProfile t2 on t1.CatalogType = t2.Integration
when i try entering this into SQL Server, it just pulls back empty columns
A: Just join the tables in the select query that's used to bind the GridView (or other databound control), like this:
SELECT Table1.Column1,
Table2.Column2
FROM Table1
INNER JOIN Table2
ON Table1.SomeColumn = Table2.SomeColumn
A: There are two ways to work with data from a persistant store. One is to grab raw data and attempt to shape it on the UI layer. The other is to shape the data when you retrieve it. Okay, technically, you can shape the data at any layer.
Your issue is largely due to having one data definition throughout your application. You have the same data definition in the database, the business logic and the UI. For some of the layers, separating out the data into two "sources" (or similar), where the data has different names, depending on context.
The direction I would take to solve the problem is create a "view model" that has the bits named correctly for the purpose of this particular page. You need not change the data structure throughout all layers to do this. Just shape the data for the UI before you bind it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Updating the summary table based on triggers and stored procedures I have a typical LAMP based site + Zend Framework where I have a base table and a summary table. Summary table is used to display data in reports.
Base table -
ID | Status
1 | 1
2 | 1
3 | 2
4 | 2
5 | 1
6 | 1
Summary table -
Status | Count
1 | 4
2 | 2
The base table will be changed(insert,update,delete) at an average of 20 times per day.
Currently, I am using triggers to call a stored procedure which will update the summary table based on the base table.
This is the stored procedure.
CREATE PROCEDURE UpdateSummary()
BEGIN
UPDATE summary a
INNER JOIN
(SELECT status, count(*) c from base group by status) b
ON a.status = b.status
SET a.count = b.c;
END
And I have 3 triggers (one for each - Insert, Delete and Update). I have shown the insert sample alone below. Other are similar to this.
CREATE TRIGGER S_T_TRIGGER_I
AFTER INSERT ON base
FOR EACH ROW
CALL UpdateSummary();
I want the summary table to be updated to the latest values always.
Using triggers and stored procedure like this is the best way or is there a elegant way to do this?
A: Well you are re-querying the DB over and over for data that you already know.
Why not just update the summary with only the changes.
DELIMITER $$
CREATE TRIGGER ai_base_each AFTER INSERT ON base FOR EACH ROW
BEGIN
INSERT INTO summary (status, count) VALUES (NEW.status,1)
ON DUPLICATE KEY UPDATE
SET count = count + 1;
END $$
CREATE TRIGGER ad_base_each AFTER DELETE ON base FOR EACH ROW
BEGIN
UPDATE summary s
SET s.count = s.count - 1
WHERE s.status = OLD.status;
END $$
CREATE TRIGGER au_base_each AFTER UPDATE ON base FOR EACH ROW
BEGIN
UPDATE summary s
SET s.count = s.count - 1
WHERE s.status = OLD.status;
INSERT INTO summary (status, count) VALUES (NEW.status,1)
ON DUPLICATE KEY UPDATE
SET count = count + 1;
END $$
DELIMITER ;
This will be much much faster and more to the point much more elegant.
A: Why don't you use a view like :
CREATE VIEW Summary AS
SELECT status, count(*)
FROM Base
GROUP BY status;
Each time you need, just do :
SELECT *
FROM Summary
And you'll get your result in real time (each call re-computed).
Views can be used the same way like table is used in Zend Framework. Just that you need to specify a primary key explicitly as explained here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MongoDB: mongoimport seems to ignore blank field value in first position of tsv file mongodb version v1.8.0 on Mac 10.6.8.
I'm trying to run a mongoimport on a TSV (tab separated value) file.
For some reason, it's ignoring blank fields even though I'm not using the --ignoreBlanks switch. At least, I think that's what's happening.
You can download my test file here: http://pastebin.com/9XzbDfgP
Here's my mongoimport command:
mongoimport --drop --headerline --type tsv -d movies -c performances --file ~/Desktop/100performance.tsv
So what happens is it ends up importing the wrong fields into the wrong field names (headers). And it leaves off some of the fields. It's having trouble with blank fields. I populated some of those blank fields and it seemed to do better. That's not a real fix though, obviously.
Ideas?
A: This is working for me now using mongodb/mongoimport v2.0.1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django : NoReverseMatch for HttpResponseRedirect I am trying to Redirect to the post's page soon as it's saved , well it's saved but the redirection won't work , it's working very fine on the development server .. not in the production one .
I tried :
return HttpResponseRedirect(reverse('emr.main.views.viewprofile', args=(profile.id,)))
Well it's working fine but, in production host i have to change emr.main.view.viewprofile to myproject.main.views.viewprofile ! because viewprofile itself it's not working
then i got template syntax error :
TemplateSyntaxError Exception Value: Caught NoReverseMatch while
rendering: Reverse for 'main.views.add_record' with arguments
'(47L,)' and keyword arguments '{}' not found.
main.view.add_comment which is a url tag
Add record
how to solve this issue ?
url.py
(r'^add/record/(?P<patient_id>\d+)/?$', add_record),
(r'^add/current/(?P<patient_id>\d+)/?$', add_current),
Edit :
The main issues are :
*
*Naming the APP/views needs to rename all the files to fix this for development instead of emr.main.views.add_records to myproject.main.views.. since function itself is not working
*URL tags such as {% url main.views.add_record profile.id %} still returning errors ..
A: You are passing a tuple to reverse() whereas the function expects a list.
Try args=[profile.id] instead.
However, it's difficult to answer this properly without seeing the function definition (or at least signature) for the viewprofile() function.
A: I think your best bet is to use named url's, as this sounds like a Python path issue with your views.
See https://docs.djangoproject.com/en/1.3/topics/http/urls/#url
It would also be helpful if you would post your urls.py config.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Service.onDestroy() is called directly after creation, anyway the Service does its work I built a Service and it didn't work as expected, so I debugged it. During debugging, I saw that the service's onDestroy() method is called directly after returning from onCreate(). When I comment out the cleanup that happens in onDestroy(), the service does its work, but this should not be my solution. So my question is, why is onDestroy() called so early and why is the service running anyway? Or how can I prevent onDestroy() from being called at the wrong time?
For your information: I've subclassed IntentService.
Thanks for any help.
Binabik
A: If you are subclassing IntentService you should be using onHandleIntent(Intent intent) for the lifecycle of your service. Your service might be moving to onDestroy quickly becuase you do not have code inside of onHandleIntent. Although without your code I cannot say for sure.
Also it might aways move to onDestroy quickly because IntentService is auto threaded for you and might just launch the worker thread which calls onHandleIntent and move to onDestroy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: web.config backslash appears twice Visual Studio 2010 I have an asp.net web application that I made in Visual Studio 2008. Everything worked just fine until I switched to VS 2010. When that happened, I started seeing some weird behavior with my database connection string. The string (edited, but format is the same) is as follows:
<add name="DBname" connectionString="Data Source=SomeText\SomeMoreText;Initial Catalog=DB;Integrated Security=True" providerName="System.Data.SqlClient"/>
The problem is with the SomeText\SomeMoreText part.
When I run this in the debugger, the '\' is changed into '\\'. This breaks everything.
My question, which probably has an extremely simple answer is this:
How can I get VS2010 to treat the connection string like a normal string without trying to insert the extra slash?
A: The extra slash is not there as far as interpretation of the string is concerned. It is merely an escape character '\' before the slash '\'.
Want proof? Add the following to your code (with proper naming of course):
Debug.WriteLine(connectionStringValueHere);
Here is a small app:
string test = "This\\is\\a\\test";
Console.WriteLine(test);
Debug.WriteLine(test);
Console.Read();
Note that the string, in both console and debug (output window) is This\is\a\test. If you do the following in the immediate window when the code is at a breakpoint:
? test
You see the following output
? test
"This\\is\\a\\test"
But you have the escapes present, which is normal for strings in .NET.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Text Reader I want to make a program that read the inputed text and parse every word and store it in a data structure, so i can later have some statistics about that (frequency of words, most common word etc).
I need guidance about two things:
a. best approach for my "parse function", which will divide the text in terms
b. best approach for data structure choice, in what concerns complexity, access times and best suitable for the case.
A:
a) best approach for my "parse function"
Use a Scanner it has nice functions for next (word) etc.
b) best approach for datastruture choice
A map from word to a statistics object: Map<String, WordStatistics>.
A: Depending on the other stats you need, it sounds like you want to use a Map<String, Integer>. Then for each key (the word you read in) you can store how many times you read it in. The rest sounds like homework...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: get text from textbox and textarea and save in cookie value using jquery or javascript I have one textbox and one textarea. I want to save the text whatever I entered in that textbox but that textbox is in Iframe.
How I do it using jquery or javascript?
Please help me.
A: Use jQuery.cookie plugin to work with cookies.
$("#myframe").contents().find('#textboxid').blur(function() {
$.cookie('textboxvalue', $(this).val()); // for storing
});
Where myframe id of the frame and textboxid id of the textbox inside of iframe.
A: window.localStorage is another option working on IE8+, modern browsers without the 4K ceiling:
localStorage['textareaKey'] = $('#textarea').val();
$('#textarea').val(localStorage['textareakey']);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone ALAssetsLibrary get all images and edit please help me with my question:
Can I give URLs and metadata for all the images/videos in iPhone library with ALAssetsLibrary?
Can I edit/delete these images/videos?
A: the above code has missed some braces so it is resolved below
ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
assets = [[NSMutableArray alloc] init];
[al enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
NSLog(@"%@",asset);
NSLog(@".. do something with the asset");
}
}
];
}
failureBlock:^(NSError *error)
{
// User did not allow access to library
// .. handle error
}
] ;
A: Take a look at the documentation for ALAssetsLibrary here. To access all photos and videos you need to enumerate all groups (albums) in the photo library and then enumerate all photos and images in each group. You cannot delete assets using the API. iOS 5 adds extra functionality - it's still under NDA though and cannot be discussed here - have a look at the beta documentation and Apple Developer forums for iOS5.
Your code will need to do something like this:
ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
[al enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
.. do something with the asset
}
}
];
}
failureBlock:^(NSError *error)
{
// User did not allow access to library
.. handle error
}
];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: change of icons and launch screen in xcode 4 hopeing for some help on this one
Hi set my icons up in xcode for using the neat drag and drop feature. A week later i made amendments to my icons. Drag and dropped the new amended items in deleting the older versions. The new versions show up on in the summary drag and drop section and in my project files yet when I build and run it is still showing the older versions even though i have deleted them.
Hope someone can help me out in this one. Not sure if it makes a difference, but im building the app to the simulator.
Thanks in advance for any tips on this one.
Cheers,
Laff
A: Open your iPhone simulator and select 'Reset Content and Settings' and try running your application on simulator.
A: Clean (also delete the build folder on disk) and rebuild the project. Also Delete the app from simulator. This way you make sure nothing stale got stuck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Starting a process as a subprocess in Python I am writing a program that uses multiple worker processes (a pre-forking model) with the following code.
from multiprocessing import Process
for i in range(0,3):
Process(target=worker, args=(i,)).start()
I use Windows. I notice that they are run as separate processes when I wanted them to start as subprocesses instead. How do I make them subprocesses of the main process?
I am hesitant to use the subprocess module as it seems suited to run external processes (as far as I have used it).
An update: It seems Windows does not launch new processes as sub-processes. Python doesnt support getppid() (get parent's PID) in Windows.
A: You seem to be confusing terminology here. A subprocess is a separate process. The processes that are created will be children of the main process of your program, and in that sense are subprocesses. If you want threads, then use multithreading instead of multiprocessing, but note that Python won't use multiple cores/CPUs for multiple threads.
I am hesitant to use the subprocess module as it seems suited to run external processes
I'm sorry, I don't understand this remark.
A: What do you wall subprocess ? To me they are subprocess of your main process. Here my example and returned output.
import time, os
from multiprocessing import Process
def worker():
print "I'm process %s, my father is %s" % (os.getpid(), os.getppid())
print "I'm the main process %s" % os.getpid()
for i in range(0,3):
Process(target=worker).start()
The output is :
I'm the main process 5897
I'm process 5898, my father is 5897
I'm process 5899, my father is 5897
I'm process 5900, my father is 5897
You have 3 subprocesses attached to a main process...
A: Short answer: http://docs.python.org/library/threading.html
Longer: I don't understand the question, aitchnyu. In the typical Unix model, the only processes a process can start are subprocesses. I have a strong feeling that there's a vocabulary conflict between the two of us I don't know how to unravel. You seem to have something like an "internal process" in mind; what's an example of that, in any language or operating system?
I can attest that Python's subprocess module is widely used.
You write "... multiple working threads ..." Have you read the documentation to which I refer in the first line at the top of this response?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: reuse of variables I'm working on project that need do call the same method several times, but with different arguments.
Can I use the same variable or do I have to declare another variable?
For example:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(domains["ServiceLogin"]);
req.Method = "GET";
req.Referer = "Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0";
req.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
CookieCollection cookies = response.Cookies;
response.Close();
etc..
Do I use the req variable or declare req2 for example
req = (HttpWebRequest)WebRequest.Create(domains["ServiceLogin"]);
req.Method = "POST";
req.CookieContainer = myCookieContainer;
What's the best way/practice to do this?
A: You can reuse the variable - you might consider not doing this though and name them each so you know what the responsibility of each request is, i.e. reqLogin and reqData. In the long run this makes for more readable code in my opinion.
A: I'd go for declaring a new variable. That way, if someone happens to quickly eyeball the code then they're not going to be confused or have to spend long working out that they're two different requests.
A: I think I would extract one or different methods, would have to see more code
e.g.
var getDataRequest = CreateGetDataRequest();
var postRequest = CreatePostRequest();
or maybe this could be one method with a few parameters
A: Variables are cheap, except when they are confusing. One of a variable's most important characteristics is its scope, which gets obfuscated when it is reused. Don't focus on reusing something because it has the same type; that is much like reusing a napkin (eew!). Focus on the problem they solve (a spill on my shirt vs. my friend's).
A: I'll be categorical: never reuse variables like this. It prevents proper isolation of concerns and makes the code harder to read and harder to change. Think about if you want to refactor the code later (you should already do this) and encapsulate each piece in its own method. Reusing the same variable just gets in the way...
A: Local variables are cheap; there's no compelling benefit to re-using them unnecessarily. Therefore: write your code so that each variable has a clear purpose and that purpose is described by its name. Once each variable's name describes its purpose, it will become more clear whether you need one variable or multiple variables.
A: IMHO there is no best practice in this case. The code should be readable and convenient for you and future coders.
A: If they don't overlap you might as well use the same variable. It makes no real difference, so choose what is most readable.
You are creating a new object with each call to CreateWebRequest, that is what matters.
A: It really depends on the answer to the question "Is it important that I still have a reference to req later?" In other words, do you ever need to call anything off of req again? If the answer is no, don't declare a new variable. If the answer is yes, then store all of the requests in a List<HttpWebRequest> or some other data structure that can manage the requests for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: SVG height incorrectly calculated in Webkit browsers I have a issue specific to Webkit browsers (Safari & Chrome, on Mac & PC).
I'm using Raphael JS to render SVG data and using a responsive layout to scale the SVGs with the browser window. The SVGs are set to 100% width/height using JQuery. The containing elements have their widths set in percentages to maintain the ratios of the layout as the page resizes.
Trouble is Webkit doesn't calculate the height correctly, it adds extra pixels (sometimes hundreds) around the SVG image; which breaks the layout.
If you open the following link in a Webkit browser you'll see the green extra pixel areas. If you use the developer inpspector in safari you'll see the reported size for the SVG is bigger than the SVG displayed.
http://e-st.glam.ac.uk/simulationgames/svgheightbug/index.html
If you open the link in Firefox or Opera you'll see the layout as it should work (the green here is caused by margins I have deliberately set).
IE8 was having a similar problem which using height:auto fixed, but this won't work in Webkit.
Has anybody else had this problem? Anybody have a solution?
I think it may be a Webkit bug (checked the nightly build already, issue persists), but before I log it I thought check to make sure nobody else has a solution first.
A: svg { max-height: 100%; }
WebKit bug documented here: https://bugs.webkit.org/show_bug.cgi?id=82489
I also added the workaround to the bug tracker.
A: I had a similar problem for Safari. Case was that the svg width and height were rendered as dom element attributes (in my case width="588.75px" height="130px"). Defining width and height in css could not overwrite this dimension setting.
To fix this for Safari I removed the width and height information from the SVG file while keeping viewBox intact (you can edit .svg files with any text editor).
Git diff snippet of my .svg file:
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 588.75 130"
- height="130"
- width="588.75"
xml:space="preserve"
version="1.1"
A: I just set the height to a very large size in the svg to maintain the aspect ratio. Using 100% comes with too many problems. This works better for me because I did not want to use js.
Full props to:
http://www.seowarp.com/blog/2011/06/svg-scaling-problems-in-ie9-and-other-browsers/
width="1200" height="235.5"
A: It's hard for me to understand exactly what you want with your example, or what is not as you intend it. However, in general, if you are using a layout with percentage widths and height containers and you want content to fill those containers, you need to take them out of the flow (using position:absolute on the content and position:relative or position:absolute on the containers).
Here's a simple example that works find in Chrome and Safari:
http://phrogz.net/SVG/size-to-fill.xhtml
The #foo div has its height and width as a percentage of the body. It has a red background that will never be seen because the SVG is position:absolute inside it and set to fill it completely, and have a green background. If you ever see red, it is an error.
#foo, svg { position:absolute }
#foo { left:20%; width:30%; top:5%; height:80%; background:red; }
svg { top:0; left:0; width:100%; height:100%; background:green; }
<div id="foo"><svg ...></svg></div>
A: This is a known issue that has been fixed by the Chromium team with version 15.0.874.121. I verified this fix myself just today.
http://code.google.com/p/chromium/issues/detail?id=98951#c27
A: i know how to fix it, you have just to put this at the begining of your svg file: "preserveAspectRatio="xMinYMin none" it must be into svg tag like this:
Problem will be fix
A: As previously pointed out WebKit's scaling of SVG improved recently. It is still quite broken in the current Safari (version 5.1, WebKit 534), in my opinion. I did a few experiments and recorded my findings on my website:
http://www.vlado-do.de/svg_test/
In short: embedding svg with <object> works under most conditions in WebKit 535. For older WebKit I embed it in an <img> tag. That's fine if you don't want links inside your svg (but it does not work in older Gecko and strangely also is problematic in current Chromium).
A: I found that adding "position: absolute;" to the image element (if it's within a parent that's also absolutely positioned), which had my .svg being called, made the "height: 100%;" declaration become relative to its container instead of the page/browser/device.
Tested this on both Chrome and Safari (mobile webkit) for iOS 7.1, and it fixed my problem (the .svg file was going way outside of its container).
Hopefully this a somewhat reliable fix for others here who were having trouble. Worth a shot?
A: I was having a problem with Javascript returning incorrect "height" values for SVGs, and I found the solution was simply to run my script (the bit that needed to access the height) on window.load rather than document.ready.
document.ready fires when the DOM is ready, but images have not necessarily been rendered at this point. At the point where window.load fires, images will have been loaded (and thus the browser will be able to access their dimensions correctly).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: c++ win32 prevent context menu from closing I would like to prevent the context menu from being closed in my win32 c++ application. I want to prevent closing the submenu when user clicks on a submenu item. Which message do i have to implement/override?
A: Haven't done win32 dev in a while, however just random thoughts that come to my mind - maybe will be helpful:
1) maybe you could try to show the context menu again right after the item was clicked
2) or do it the complex way - find, then subclass the context menu window, then intercept WM_CLOSE/WM_DESTROY messages
Overall this seems to be a weird thing to want to implement. Maybe the menu is not the right UI element if you want to keep it on the screen after the selection was made. Maybe you need a modeless dialog instead?
A: Please see the following article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: SWT: addFilter or addKeyListener on Composite i want to have some composite-wide keyboard-shortcuts. The composites in question are in a tab-folder. I have a little function, which traverses all children of my composite and adds a KeyboardAdapter to every one of them.
The problem I have is that, when I open on of the tabs pressed keys aren't registered. I first have set the focus on some selectable widget in the tab, then it works. When i switch to another tab and then back, the focus is still kind of there (a grey selection instead of a blue one in a table for example), but it, again, doesn't work, until i click somewhere.
How can I do this? I thought about adding a filter to my display, but i only want events in a certain composite (and everything in there).
Thank you
A: Key events are delivered to the component that has keyboard focus. Composites do not get the keyboard focus, it is usually one of their child components that gets it and then they start receiving the key events (in case they are not used by children). Having the key listener on the parent Shell may possibly work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pyramid and .ini configuration Each Pyramid application has an associated .ini file that contains its settings. For example, a default might look like:
[app:main]
use = egg:MyProject
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
...
I am wondering if it is possible to add your own configuration values in there, and read them at run-time (mostly from a view callable). For instance, I might want to have
[app:main]
blog.title = "Custom blog name"
blog.comments_enabled = true
...
Or is it better to have a separate .ini file and parse it during startup?
A: Sure you can.
In your entry point function (main(global_config, **settings) in __init__.py in most cases), your config is accessible in the settings variable.
For example, in your .ini:
[app:main]
blog.title = "Custom blog name"
blog.comments_enabled = true
In your __init__.py:
def main(global_config, **settings):
config = Configurator(settings=settings)
blog_title = settings['blog.title']
# you can also access you settings via config
comments_enabled = config.registry.settings['blog.comments_enabled']
return config.make_wsgi_app()
According to the latest Pyramid docs, you can access the settings in a view function via request.registry.settings. Also, as far as I know, it will be in event subscribers via event.request.registry.settings.
Regarding your question about using another file, I'm pretty sure it's good practice to put all your config in the regular init file, using dotted notation like you did.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: How to suppress ANT Copy Message He Guys,
i wonder how to suppress ANT [copy] and [mkdir] notifications like Copied 2 empty directories to 2 empty directories under… during the Build process.
Maybe it's impossible but does anyone has some suggestions for me?
Regards
A: You can write and install your own custom listener or logger. See the ant documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Creating an MS Word document in an Android App I am working on a client project for an android app and wanted to confirm if the designed solution appears to be utilizing the most appropriate technology and resources.
The application gathers data from the user via a series of questions, compiles the data into a single human-readable document, then sends the document out via email. My client requires the delivered doc to be in MS Word format. I am currently building my doc in the app using xml, setting the extension type as ".doc", then sending. Since the latest versions of MS Word seem to have no problem handling these types of files, this seems to be the most appropriate solution.
Is there anything obvious that I am missing? Should I be handling this another way?
A: You aren't writing DOC files correctly. If really need to save .DOC files I suggest you read this .pdf regarding thd DOC file format put out by the OpenOffice team.
As you are already writing the file in XML consider using Microsoft's Office XML format instead of writing the XML to a .DOC file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: IE Plug-Ins (QVP) in C# WebBrowser Control? I'm writing a C# application that uses a System.Windows.Forms.WebBrowser control to access a web application.
In this web application we use a program (Quick View Plus) that integrates with Internet Explorer to provide in-browser viewing for a number of document types not normally handled by Internet Explorer (WPD, DOC, XLS, PDF, etc.).
My understanding of the WebBrowser control is that it shares settings with the user's own copy of IE, however, I am seeing different behavior between the two:
*
*When I open the web application in Internet Explorer, all desired file types are successfully opened using Quick View Plus.
*When I open the web application in the WebBrowser control, only PDFs are loaded in Quick View Plus (showing, at least, that it can run inside a WebBrowser control) - however, other formats (for instance WPD, XLS, DOC) are not opened in Quick View Plus - instead the browser downloads them and automatically opens them with the default application.
Why could this behavior vary, and what steps should I take to try to get it to behave consistently?
If relevant, IE8 is in use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Asynchronous WCF service calls from a Windows Service I have written a windows service that utilises asynchronous WCF service calls.
Upon testing, it seems that the method on the service executes perfectly but the callback to my windows service itself isn't being handled.
Upon reading the logging, I came across the following entry where my asynchronous service call should have returned:
The description for Event ID 0 from source gupdate cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
Could this be related to the account the service is running under or could there be another reason why this is happening? This one is under NetworkService.
A: gupdate is the program used by Google to update their locally installed applications. So this entry has nothing to do with your problems.
Please try to run the service temporarily under your own administrator login credentials to see if this fixes the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to "assert" in Puppet? Is there a way to assert that a variable (or more specifically, a fact) in puppet has a particular value, and to abort the installation if it doesn't?
For background, here is the situation:
In most cases I can refer to hostnames, but sometimes I need to use an IP address. For example, our log collector host needs to open a port in the firewall for several specific machines (and not a whole subnet). I need to use IP addresses to open a hole in the firewall. Since the IP addresses of machines don't change, I was planning on encoding the IP address as part of the configuration, but I'd like to check on the individual hosts that the actual IP address matches the one in its configuration and fail if it doesn't. Is that possible?
A: I believe something like this would work:
if $ipaddress != $expectedipaddress {
fail("IP mismatch")
}
The fail() function causes a parse failure. Wrapping it in a conditional should get the assert behavior you want.
I haven't tested this specific usage, but if parsing fails a new catalog isn't compiled and the client doesn't get anything.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is the issue with 10 digit mobile no data in mysql? I made a table for storing contact record of user of my website. It also contains a 10 digit mobile no.
Table structure is like this:
CREATE TABLE contact_user
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
contact INT(10)
)
Now the problem is that if I insert a 10 mobile no.(e.g.9595891256) using phpmyadmin into contact field it will insert some random value and shows a warning saying "data out of column range"
But if I insert a simple 10 digit no (e.g.4561327894) then it works well and no warning is shown.
SO please tell me what is the issue in inserting a mobile no in this column?
I am using mysql 5.1 on ubuntu 11.04 and also using phpmyadmin.
A: INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. Whether you put INT(2) or INT(10), MySQL still only stores an (unsigned, in this case) INT which has a maximum value of 4294967295.
You can use a BIGINT instead of INT to store it as a numeric. I wouldn't recommend this, however, because it won't allow for international numbers. If you are certain your application will only use US numbers, using BIGINT will save you 3 bytes per row over VARCHAR(10) -- if that sort of thing concerns you.
Since it is a phone number (and therefore you won't be doing numeric calculations against it), try using a VARCHAR(20). This allows you the ability to store international phone numbers properly, should that need arise.
A: The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned), according to the MySQL documentation. If your value exceeds this limit, you integer will overflow, hence the not-that-random value.
Also, INT is not the best solution to store phone numbers. You might lose leading zeros if they are one or more. Also, international phone numbers start with a + sign. Consider using a VARCHAR. This will end up using more space in the database, but will provide more consistency.
A: It is because of the max size of type INT you need to use a different type to hold a number that large. Try using BIGINT.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I open a file with unknown associations in iOS? I think it's rather impossible, but will ask anyway. My application uses file association to open some types of files. What I need is to make file associations within my app. For example I have some files in my app's Documents folder and when user wants to open that it would be a great idea to ask him in which application he would like it to open (like Mail app does).
It can possibly be done with URL schemes, but if I don't know what applications user has, it can't be used. So, is there any way to use the device's file associations within an application?
A: You should take a look at Document Interaction Programming Topics for iOS. It explains how you can use the UIDocumentInteractionController class to present the user a list of apps which support a given file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting the most played track out of the iPod library (MPMediaQuery) I need to get out the 25 most Played Songs out from my iPod Library with my iPhone app. i am using a MPMediaQuery.
One solutions would be to loop through all tracks and them comparing by MPMediaItemPropertyAlbumTrackCount. But i think thats a bit unefficient. Is there a way to directly get the Most Played items playlist?
A: I think you are looking for MPMediaItemPropertyPlayCount not MPMediaItemPropertyAlbumTrackCount. MPMediaItemPropertyAlbumTrackCount is the track number of the song as it appears in its album.
MPMediaItemPropertyPlayCount unfortunately cannot be used for making queries with MPMediaQuery since it is a user-defined property.
Your best option is to store all the play counts in a database like Core Data when your app is opened for the first time and update it by registering for notifications when the user's library changes.
A: you can use NSSortDescriptor to sort the most played songs
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:MPMediaItemPropertyPlayCount ascending:NO];
NSArray *sortedSongsArray = [[everything items] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JSF. How to set a value of JavaScript function to a field of Bean? Good morning! How to set a value of JavaScript function to a field of Enterprice Java Bean?
I have the js function:
<script type="text/javascript">
function getTimezone() {
var d = new Date()
var gmtMinutes = -d.getTimezoneOffset();
return gmtMinutes;
}
</script>
I'm trying to use:
<a4j:jsFunction name="timezone" assignTo="MyBean.gmtMinutes">
<a4j:actionparam name="timezone" value="getUserId()"/>
</a4j:jsFunction>
But I did not get. I think that I incorrectly used the tag a4j:jsFunction. Give me advice please how to use the tag correctly!
A: You can register a jsFunction which sends parameter's value to server:
<a4j:jsFunction name="updateTimeZone">
<a4j:param name="timezone" assignTo="#{MyBean.gmtMinutes}"/>
</a4j:jsFunction>
And then invoke that jsFunction from JavaScript:
<script type="text/javascript">
function sendTimezoneToServer() {
var d = new Date()
var gmtMinutes = -d.getTimezoneOffset();
updateTimeZone(gmtMinutes);
}
</script>
There is also an example of the same on RichFaces Showcase:
http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=jsFunction&skin=blueSky
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: tomcat security constraints How do you negate a security constraint in tomcat?
Basically, I have one security constraint defined which setup up basic authentication for the entire context.
How can I exclude one file, for example, /public-available.html from this? So I have authentication setup for everything, except this one resource.
A: Read this: http://java.dzone.com/articles/understanding-web-security
In case you face any problem, let me know.
It will be much easier to manage your security constraint if you put files with different access in different folder/hierarchy. ex: /public/public-available.html, /restricted/xyz.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7570976",
"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.