text stringlengths 8 267k | meta dict |
|---|---|
Q: Can I execute the number stored in a register as an instruction in MIPS? If I take an instruction and break it down into the binary representation of its op code, rs, rt etc... could I then put this binary number into a register and get MIPS to treat it as an instruction?
For example:
The instruction: add $t0, $s0, $t0
Breaks down to:
000000 10010 01000 01000 00000 100000
Which corresponds to the integer: 18696
Could I store this integer in a register, and then get MIPS to treat it as an instruction?
I ask this with the idea of self-modifying code in mind.
A: The correct answer is - no. As pointed out in a comment by a user who read the question more carefully than I did the first time, the value must be first written to memory, then you load an address value of the memory where that value is stored, and then you jump to it.
You may want to explore more how JIT compilers work, as they use a lot of code modification (to be clear, they do not modify the code generator, but they do a lot of live patching of the generated code during the execution).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: OpenGL camera with 3 vectors Okay, so I was following this tutorial to help me with making a camera in OpenGL: http://nehe.gamedev.net/data/articles/article.asp?article=08
So I followed it, and after some struggling, finally had a solution where I now had 3 vectors that represented the 3 axes of my camera.
The problem though? I can't figure out how to use that information to actually get the right rotations/translations! I tried using gluLookAt, using the camera's position for the first parameters, then the Z axis of the camera for the target, and the Y axis for the up parameters. The result is that the camera never stops looking at a single point, regardless if I move up/down/left/right, and rotations behave even more weirdly...
Am I taking the complete wrong approach? I've considered using quaternions to somehow calculate the transformations I need, but can't figure out how to get the parameters I need for it/ how to get started... essentially I just want a simple FPS-like camera to begin with, where I can move around, and look up/down and to the sides (previously I had it mostly working, except when looking up and then turning around, the rotation screwed up...)
General or specific help would be much appreciated! Because I've been working on this for hours and hours, and the situation just isn't improving...
To sum it up... I need help making a camera that can yaw/pitch/roll... without being stuck to staring at a single point.
EDIT:
Okay, so, apparently rotating in the correct order can really help out! Silly me. Regardless, I'd still be interested to know how if I could use the three axes of my camera to form a quaternion for my transformations.
A:
I tried using gluLookAt, using the camera's position for the first parameters, then the Z axis of the camera for the target, and the Y axis for the up parameters.
The second set of parameters isn't the look-at direction, but the look-at position. You need to take the camera position and offset it by the Z-axis to get a look-at position in the direction you want to look in.
Regardless, I'd still be interested to know how if I could use the three axes of my camera to form a quaternion for my transformations.
Yes. You turn them into a matrix, then convert the matrix into a quaternion. There are many online resources that explain the process of converting a rotation matrix into a quaternion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: redirect http to https in grails I have a follow up question about redirecting grails apps from http to https. another user showed me that, the config file, i can do something like this:
grails.plugins.springsecurity.secureChannel.definition = [
'/**': 'REQUIRES_SECURE_CHANNEL',]
right now, this will cause the user to see a page that says:
Unable to connect
Firefox can't establish a connection to the server at localhost:8443.
Is this what it should be doing? if so, how do i have my grails app redirect to https?
thanks!
jason
A: Grails doesn't run over HTTPS by default. You'll need to execute run-app with -https option.
A: HTTPS is usually over port 443 not 8443 - this could be your problem or typo in your question?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android and receiving sms I need to write some application on android. I want to application listen to incoming sms. When phone receives sms from specified phone number, application will recognize that the sms is from this phone number and do some work, process data from sms. Is there possible to do something like this in android? If there is some way to do that could you tell me how can I do it? Thanks for any help and tips.
A: There are lots of examples available for the same on web, here is one of them.
Receive SMS
Sample with Source
Another One with Source
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get another element with jQuery I build multi level menu and my HTML structure looks like this:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>
<ul> #this is set up as display: none;
<li>subitem 1</li>
<li>subitem 2</li>
<li>subitem 3</li>
</ul>
</li>
<li>item 3</li>
<li>item 4</li>
</ul>
And I am solving a question, how to display all subitems after moving the cursor on the item1.
I can do something like this:
$('ul li ul').mouseover(function() {
$(this).find('li').show();
});
But this doesn't works me... could anyone help me, please, how to display sub-ul block of items for mouseover event?
Thank you
EDIT: Thanks for your replies guys, I already found my stupid fault thanks to your helps.
A: Attach it to the parent LI, otherwise there is not an element that is displayed for the mouseover to fire on.
Note as well that if all you have in the LI containing the UL is the UL with the non-displayed LI's, it will potentially be hard to mouseover that as well.
$('ul li ul').parent().mouseover(function() {
$(this).find('li').show();
});
http://jsfiddle.net/kSq4T/1/
A: You could always add a class to your item elements and do something like this:
<ul>
<li class="item">item 1</li>
<li class="item">item 2</li>
<li>
<ul> #this is set up as display: none;
<li>subitem 1</li>
<li>subitem 2</li>
<li>subitem 3</li>
</ul>
</li>
<li>item 3</li>
<li>item 4</li>
</ul>
$('#item').mouseover(function()
$(this).children.show();
A: write your function in $(document).ready
$(document).ready(function(){
$('ul > li > ul').mouseover(function() {
$(this).find('li').show();
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: User prompt won't go away I recently created a Java program, and in an effort to give the desktop application its own icon, create a .bat file that ran the .jar and then converted the .bat to an .exe using a free converter.
The problem I am having is that whenever I run the exe, windows prompts the user asking if you want to run a program from an unknown publisher.
How can I make that go away? How do I sign my program?
A:
..give the desktop application its own icon..
Deploy it using Java Web Start. JWS works on any platform for which the J2SE is available (as opposed to just Windows), and offers desktop shortcuts and menu items with icons (amongst many other neat features).
If you need to digitally sign your app. for webstart, see the File Service demo., which comes complete with source & build file.
While this might not be an answer to the stated question, it achieves the combined goal of creating a desktop icon for an app., while not showing a CLI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using fscanf to set a variable in a different class I'm trying to read a number from a file and set it to a public variable in a different class. The function that is reading the file has a pointer-object instance of that class. I'm facing a weird issue:
The following works:
int dummy;
fscanf(file,"%d",&dummy); // assume the file stores the number 10
globals->var = dummy;
cout << "variable is " << globals->var << endl; // this outputs 10 to console. great!
But I'm going to have a lot of fscanf's to do, and I don't want to create all of these redundant dummy variables. I tried the following:
fscanf(file,"%d",&globals->var);
cout << "variable is " << globals->var << endl; // this outputs 2.9e-321 (aka junk)
Is there a reason that doesn't work? Do I need to do it like globals->&var, or some variation like that? I tried to wrap it in parentheses like so: &(globals->var), but that didn't work either. Is there a reason this is not working (without me having to paste many many many lines of code)
Thanks!
A: As you said in the comment, the type of var is double. Yes, that is the problem. You should use %f for it.
Apart from that, I would give you a piece of advice:
Prefer using C++ stream for I/O work. They're type-safe. If you use them, you would not face this problem which you faced it with fprintf.
Here is how you should use it:
std::ifstream file("filename.txt");
file >> globals->var; //don't worry about whether var is int, or double!
Cool, isn't it?
A: The Problem is most probably that globals->var is a float or double convert it to an int or some other integer-type and it should work
The reason why it's outputting "junk" is that float/double numbers are encoded in a special way. If you just overwrite that memory with an perfectly valid integer like:
double value = 0.0;
*((int*)&value) = 42;
// value is now something like 2.07508e-322
you nonetheless get a "strange" number. This is what happens internally in scanf with %d as parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Difference between std::string's operator[] and const operator[] Can anyone please explain the difference between:
const char& operator[] const
and
char& operator[]
in C++?
Is it true that the second one is duplicating the string? and why?
A: No, the second returns a non-constant reference to a single character in a string, so you can actually use it to alter the string itself (the string object is not duplicated at all, but its contents are possibly modified).
std::string s = "Hell";
s[0] = 'B';
// s is "Bell" now
Given this sample, char& operator[] can of course be used to access a single character without modifying it, such as in std::cout<< s[0];.
However, the const overload is needed because you cannot call non-const member functions on const objects. Take this:
const std::string s = "Hell";
// ok, s is const, we cannot change it - but we still expect it to be accessible
std::cout << s[0];
// this, however, won't work, cannot modify a const char&
// s[0] = 'B';
Generally, the compiler will pick the const overload only when being called on a const object, otherwise it will always prefer to use the non-const method.
A: The issue is with const-correctness. Allowing read-only access in a const string and allowing writable access in a mutable string require two methods.
The const char& operator[] const accessor is necessary if you want to access a character from a const std::string. The char& operator[] accessor is necessary to modify a character in a std::string.
A: They both return references to the internal member of the string.
The first method is defined as a const method (the last const) and as such promises not to change any members. To make sure you can;t change the internal member via the returned reference this is also const.
const char& operator[](int i) const
// ^^^^^ this means the method will not change the state
// of the string.
//^^^^^^^^^^^ This means the object returned refers to an internal member of
// the object. To make sure you can't change the state of the string
// it is a constant reference.
This allows you to read members from the string:
std::string const st("Plop is here");
char x = st[2]; // Valid to read gets 'o'
st[1] = 'o'; // Will fail to compile.
For the second version it say we return a reference to an internal member. Neither promise that the object will not be altered. So you can alter the string via the reference.
char& operator[](int i)
// ^^^^^ Returns a reference to an internal member.
std::string mu("Hi there Pan");
char y = mu[1]; // Valid to read gets 'i'
mu[9] ='M'; // Valid to modify the object.
std::cout << mu << "\n"; // Prints Hi there Man
Is it true that the second one is duplicating the string? and why?
No. Because it does not.
A: The second one does not need to duplicate (copy) the string. It just returns a reference to a character which is modifiable. The first one returns a non-modifiable reference, because it has to: the function itself is const, meaning it can't mutate the state of the string.
Now, if you have copy-on-write strings (an optimization employed sometimes), then getting a non-const reference to a piece of the string may imply copying (because the reference implies writing). This may or may not be happening on your particular platform (which you didn't specify).
A: Some Basics :
With operator[] you can both edit value in a container/memory and read value.
With const char& operator[] const you are only allowed to read value.
Eg.
std::string ss("text");
char a = ss[1];
with char& operator[] you can edit the value. Eg
ss[1] = 'A';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Security risks from user-submitted HTML I am using a contentEditable div that allows users to edit the body HTML and then post it directly to site using an AJAX request. Naturally, I have to do some security checks on it. The most obvious was ensuring that no script tags were submitted by searching for <script in the submitted HTML. This is done after first running htmlentities, transferring the data to another server, and then running html_entity_decode. In addition, every tag that is opened must be closed and every tag that is closed must be opened within the user submitted HTML.
Disregarding unrelated security risks (such as SQL injection) and non-security risks (such as a user posting an inappropriate image), what are other security risks, if any, specifically linked to allowing a user to add HTML directly to a page?
To be more specific,
*
*Are there ways to put scripts in the page without explicitly using a script tag, OR
*Are there ways to compromise the security of a site or its users by editing the HTML without using scripts?
A: Yes. There are an alarming number of ways that malicious code can be injected into your site.
Other answers have already mentioned all of the most obvious ones, but there are a lot of much more subtle ways to get in, and if you're going to accept user-submitted HTML code, you need to be aware of them all, because hackers don't just try the obvious stuff and then give up.
You need to check all event handling attributes - not just onclick, but everything: onfocus, onload, even onerror and onscroll can be hacked.
But more importantly than that, you need to watch out for hacks that are designed to get past your validation. For example, using broken HTML to confuse your parser into thinking it's safe:
<!--<img src="--><img src=fakeimageurl onerror=MaliciousCode();//">
or
<style><img src="</style><img src=fakeimageurl onerror=DoSomethingNasty();//">
or
<b <script>ReallySneakyJavascript();</script>0
All of these could easily slip past a validator.
And don't forget that a real hack is likely to be more obfuscated than this. They'll make an effort to make it hard for you to spot, or to understand what it's doing it you do spot it.
I'll finish by recommending this site: http://html5sec.org/ which has details of a large number of attack vectors, most of which I certainly wouldn't have thought of. (the examples above all feature in the list)
A: Yes and yes.
There are A LOT of ways for users to inject scripts without script tags.
They can do it in JS handlers
<div onmouseover="myBadScript()" />
They can do it in hrefs
<a href="javascript:myBadScript()">Click me fool!!</a>
They can do it from an external source
<iframe src="http://www.myevilsite.com/mybadscripts.html" />
They can do it in ALL SORTS of ways.
I am afraid that the idea of allowing users to do this is just not a good one. Look at using Wiki markup/down instead. It'll be much safer.
A: Did you think about security risk from <object> and <embed> objects?
I'd use strip_tags() for stripping html tags
A: Javascript can be called any number of ways by using the event attributes on elements, like:
<body onload="..">
A similar question posted here recommends using HTMLPurifier instead of trying to handle this on your own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: WM_COPYDATA with and without quotes yields different results Using WM_COPYDATA to pass command line params to another app instance with Delphi XE as follows:
function DAppInstance.SendParamsToPrevInstance(AWindowHandle: THandle): Boolean;
var
copyData: TCopyDataStruct;
cmdParams : string;
i : integer;
begin
cmdParams := '';
for i := 1 to ParamCount do
cmdParams := cmdParams + ParamStr(i); //#1
//cmdParams := cmdParams + '"' + ParamStr(i) + '" '; //#2
//cmdParams := cmdParams + format('"%s" ', [ParamStr(i)]); //#3
//cmdParams := cmdParams + format('%s;', [ParamStr(i)]); //#4
copyData.lpData := pchar(cmdParams);
copyData.cbData := 1 + (bytelength(cmdParams));
copyData.dwData := WaterMark; //ID for APP
result := SendMessage(AWindowHandle,
WM_COPYDATA,
Application.Handle,
LPARAM(@copyData)) = 1;
end;
yields different results if the strings are quoted / appended to.
if #1 is used - the string comes in clean but is not usable if not quoted as filenames can have spaces and this:
C:\Users\MX4399\Research\delphi\instance\doc with spaces.doc
will be see as 3 paramaters in the end, while using #2 to quote the strings, or appending anything (#3, #4) causes
"C:\Users\MX4399\Research\delphi\instance\doc with spaces.doc"'#$FF00'궳獧
A: I believe that @TOndrej has spotted the main cause of the problem. However, I think you have a second more subtle bug.
Your app which receives the WM_COPYDATA message is, I think, treating lpData as a null-terminated string. If the data is malformed then you will have a buffer overrun. I believe that is exactly what is happening in your examples but it just turns out to be benign. The marshalling of WM_COPYDATA copies just the size of buffer specified in cbData. You must make sure you don't read beyond it. A malicious app could send you a WM_COPYDATA message with data to make you do just that. Instead I recommend you use cbData when reading.
So to send the string you write:
copyData.lpData := PChar(cmdParams);
copyData.cbData := ByteLength(cmdParams))
copyData.dwData := WaterMark;
And then when you receive it you allocate a buffer and copy to that buffer based on the value of cbData.
SetString(cmdParams, PChar(copyData.lpData), copyData.cbData div SizeOf(Char));
A: I think you meant copyData.cbdata := 1 * SizeOf(Char) + ... instead of just 1 + ....
A: On a separate but related note, rather then using ParamStr() (which itself has a number of known bugs) to parse the original command-line and rebuild a new string from it, you could just use GetCommandLine() to get the original command-line instead and send it as-is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What languages would one need to know to do something like this? I want to be able to make like.. grids, or spreadsheets, etc.. here are a couple examples..
http://killgrid.com/grid/325
http://demo.warsheet.com/
I want to create a site somewhat similar to those, I would allow users to sign up and create spreadsheets with custom IDs that the owner of the spreadsheet adds through an admin panel..
I write php, but I know that wont be enough to create the website, what would be used to create the design of the spreadsheet and such?
All answers are appreciated.. if you guys could just point me in the right direction, that would be great!
A: HTML, and CSS. Those two "languages" combined will allow you to create web pages. By applying HTML "tables", you can create the kinds of "grids" or "spreadsheets" that you showed. Using your PHP skills as well, you will be able to create dynamic tables which change based on your data.
Tutorial:
http://dev.opera.com/articles/view/1-introduction-to-the-web-standards-cur/#toc
I suggest that you do the HTML one (first link) first.
Hope that helps,
-Sunjay03
A: HTML, images, CSS, and bit of javascript is great combination for this purpose
A: There's nothing special about the pages you link to. To describe the structure of tabular data in HTML, use tables. You'll need forms to capture the data (and something to process and store the data on the server (a programming language and a database). Then apply CSS for the colour scheming. You don't even need client side JS for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Persistent Code Memoization in Compilers and Run-Times Environments I believe the concept of a code-cache (for example ccache) should be extended into a more fine-grained memoization of both intermediate code (IC) and target code (TC) in compilers such as GCC or LLVM+Clang.
This can then be used for a whole range of ground-breaking cleverness benefiting both programmer productivity and compile-, run-time performance and run-time memory usage.
More specifically, this repository (or database) should automatically cache IC and TC of functions. These can then be looked up and reused in different sets of builds (compiled only once link many) in across sets of programs and libraries and not just across object boundaries during linking (LTO).
This would especially benefit C++ STL container-algorithm-instantiations. For example how many times hasn't algorithms such std::sort applied on std::vector<T> been instantiated and optimized and compiled in different programs using the same type T typically int, float and double?
In an implementation, IC-modules should be indexed by keys constructed from hash-chain (SHA-1 should suffice) of compiler configuration and IC-code-tree (including the sub-tree-code-hashes of the functions it calls) and stored in for example an std::unordered_map providing very cheap lookups. To even further promote reuse of code the IC-repository could be put online as network-service.
Of course the memoizations should only be cached when needed for optimal good performance. This should have a very small overhead. As most hash-keys lookups should be misses the keys should be placed in memory but not necessarily the code-snippets.
This project has already proved the usefulness of this idea applied to the Python language. I believe Haskell (GHC) may be the ideal language for experimenting with these ideas because of its default function purity and flexible control on function side-effects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: WxPython Updating Frame to show buttons I am new to wx widgets. I am trying to make a GUI in which I have to show certain buttons based on certain conditions. The problem is that when I create this new button after Frame.show() The button is not visible until I take the mouse over the place the button is supposed to be. I tried Frame.Refresh() But that isn't working.
self.button = wx.Button(panel, 1, 'Delete', (230, 120))
self.Bind(wx.EVT_BUTTON, self.delSong, self.button)
self.button2 = wx.Button(panel, 3, 'Refresh', (130, 120))
self.Bind(wx.EVT_BUTTON, self.shelving, self.button2)
self.button.Disable()
self.button2.Enable()
self.button3 = wx.Button(panel, 1, 'Exit', (230, 120))
self.Bind(wx.EVT_BUTTON, self.close, self.button3)
self.button3.Hide()
self.Show()
try:
fooo
except KeyError:
self.button.Destroy()
self.button3.Show()
What I want to do here is to remove the button and show button3. But In case of the exception the button3 is not displayed in the frame. Is there something else that refreshes the frame ?
A: You probably just need to call the Frame's Layout() method. That's what I do when I insert or remove a widget. I also recommend learning sizers as they are very handy for automatic sizing and positioning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rectangle inside another rectangle Is it possible to create drawable from xml like on the picture? The first rectangle contains a second rectangle.
If yes, please explain to me how.
A: If you want simple rectangles you could use a LayerList with two shapes as content:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#a1a1a1" />
</shape>
</item>
<item android:top="5dp" android:right="5dp" android:bottom="5dp"
android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="#f1f1f1" />
</shape>
</item>
</layer-list>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Executing javascript loaded via DOM insertion I'm working on something that will add a widget to a customer's site, and I want to load my js asynchronously so as not to block the customer's page loading. I've been reading a lot of threads about this, and have been trying to implement the pattern suggested here as my project is very similar:
http://friendlybit.com/js/lazy-loading-asyncronous-javascript
The problem I have is the code in my dynamically-loaded javascript file just doesn't get executed. Sorry if this seems to be a duplicate question, but I've spent hours searching and trying slightly different techniques, and I've read numerous posts including these stackoverflow questions:
*
*Load javascript async, then check DOM loaded before executing callback
*Load jQuery in a js, then execute a script that depends on it
*Loading scripts dynamically
but I'm still struggling to make this work, so I was hoping if I ask the question directly someone here might be able to help me out!
I've currently got the following as a really basic test; obviously there's a lot more going on in my real script, but I just need to understand what's happening here (or, in fact, what's not happening).
So in my code file "test.js" I simply have:
run_test = function () {
alert('hello from test');
};
then on the page I have:
(function () {
load_test = function () {
var t = document.getElementsByTagName('script')[0];
var s = document.createElement('script');
s.type = 'text/javscript';
s.async = true;
s.src = 'test.js';
s.onload = s.readystatechange = function () {
if (run_test) run_test();
s.onload = null;
s.onreadystatechange = null;
};
t.parentNode.insertBefore(s, t);
};
load_test();
})();
I've already tried several variations on this - I've tried removing "s.async = true" just to see if it makes a difference, but it doesn't. I originally had the following instead of "load_test();", as suggested in the first post I mentioned:
window.attachEvent ? window.attachEvent('onload', load_test) : window.addEventListener('load', load_test, false);
but the result is always the same, I never see the message "hello from test". In fact I can even put alerts in the load_test function - if I put an alert just before the line "s.onload = s.readystatechange .." I see that message, but an alert within that onload function never appears. So it would appear that the dynamically added script's onload never fires.
BTW as an aside - may or may not be relevant, but I generally test in Firefox, and if I look at the html in firebug, I see the test.js script has been loaded, but if I expand that node I just see the message "Reload the page to get source for ...". Doesn't matter how many times I reload the page, I can't see the code. I have tried testing in other browsers with the same results.
Can't help feeling I'm missing something fundamental here; any help would be very much appreciated!
Pete
Thanks all for the input.
@zzzzBov, thanks for the example, although I'm not sure I completely understand still - I thought that "onload" would fire once after the script finishes loading, in the same way as attaching code to the onload event of the page. My understanding of "onreadystatechange" was that it was just to catch the same thing in IE.
In response to your comments, the new script is inserted in the head of the page (with the insertBefore statement) right before the original script block (assuming the original script block is in the head, which it is).
With regard to the test.js path, I omitted the path just to simplify the example. My path to the script is definitely correct; I can see via firebug that the script is actually added (to the head).
My problem was that after the script loaded, it simply failed to run, but I think I was actually hitting some caching problems as I've since got this working using the pattern described in the first link I posted above (here it is again for good measure: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/).
So my code is something like this:
(function () {
var addscript = function () {
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = "myscript.js";
h.appendChild(s);
};
window.attachEvent ? window.attachEvent('onload', addscript) :
window.addEventListener('load', addscript, false);
})();
If you check the comments on that post, I think it's explained somewhere why it's a good idea to still include "s.async = true" even though in this case the script is attached to the window onload event.
My "real" main script does actually require jQuery, so I think my eventual solution will be to use something like this to load jQuery, then once I know that's loaded, let jQuery do the work of loading any other scripts I need.
Thanks again for the help.
Pete
A: You've got a few issues with your script. Here's one that should work.
function loadScript(src, callback)
{
var s, r;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
document.body.appendChild(s);
}
The issue with your load_test function is that it'll call run_test() before the new script has executed. Your script will remove the onload and onreadystatechange event callbacks at the first onreadystatechange event which is typically loading.
Also, async should be unnecessary, as the newly added script will be inserted at the end of the document.body wherever that may be. If you'd like to load the script after the rest of the page, then wait for the rest of the page to load (body.onload or document.onreadystatechange) before calling loadScript.
The biggest issue with your script sounds like test.js doesn't exist at the path it's being called. Make sure that adding <script type="text/javascript" src="test.js"></script> inline actually works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Can i start .Net Console Application under custom user? I have a console application that i would like to run as 'MySpecificUser'. Can i specify this user in app.config?
A: No, you can't. By the time the config file is read by the CLR it is too late to specify the user the process runs under. On the other hand you could write a launcher console application in whose config file you specify a username and password which are used to run the actual application using for example this Process.Start overload.
A: You can use the runas utility in order to execute any program as a specific user.
This is not something you could specify in a config, however, not directly.
A: I don't think this is possible by editing the app.config.
You should rather use Process.Start in order to run the process under another user. You will need to provide a password for the user account otherwise it will not work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Yii require_once fail, can't run demo project Interestingly I have another version of yii running and that runs with out error but that one does not have gii. I installed the latest and when I build a demo project, it give me this error. I think it is related to permission. I tried different solution but could not make it work.
I am using XAMMP on Mac OS Lion
Fatal error: require_once() [function.require]: Failed opening
required '/Users/tstuser/Sites/yii2/demo2/../framework/yii.php'
(include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear')
in /Users/tstuser/Sites/yii2/demo2/index.php on line 13
Trying changing the directory permission but to no avail.
A: I had the same problem on my Debian Linux server. I fixed this by installing php-pear.
Please see this guide for installing pear on xampp and Mac OS.
Hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to start notification on custom date&time? I know how to start a notification X milliseconds after some click event. A code like this
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
triggerNotification();
}
};
timer.schedule(timerTask, 3000);
Where the code for notification looks like this
CharSequence title = "Hello";
CharSequence message = "Hello, Android!";
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "A New Message!", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, AndroidAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(AndroidAlarmService.this, title, message, pendingIntent);
notification.defaults = Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_ID, notification);
How can I set notification to appear on specific date at specific time, let say October 1, 7 PM?
A: I think that the best way will be to create a service that sets the notification and then activate the service using an AlarmManager.
Here is my code for doing that.
That's the code for the AlarmManager:
private void startAlarm() {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(int year, int month, int date, int hour, int minute, int second);
long when = calendar.getTimeInMillis(); // notification time
Intent intent = new Intent(this, ReminderService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC, when, pendingIntent);
}
Here is the Service:
public class ReminderService extends IntentService {
private static final int NOTIF_ID = 1;
public ReminderService(){
super("ReminderService");
}
@Override
protected void onHandleIntent(Intent intent) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long when = System.currentTimeMillis(); // notification time
Notification notification = new Notification(R.drawable.icon, "reminder", when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, YourActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent , 0);
notification.setLatestEventInfo(getApplicationContext(), "It's about time", "You should open the app now", contentIntent);
nm.notify(NOTIF_ID, notification);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Debugging C++ code involving use of: vector, string, STL I am C++ beginner. When I try to debug C++ code using following constructs like string, vector of certain native types, STL etc, debugging gets tedious. I use MS Visual Studio 2010/ Visual C++ 2010 Express.
e.g.
-- While using string as below:
string str;
getline(cin, str);
for(i=0; i<str.size();i++)
Watch window does not show values for str[i]. It says overloaded operator not found. I have to manually collapse the whole string variable str and see the char elem at that particular index, which gets cumbersome.
-- While using vector as below, same issue. If I set variable v1[k] in watch window same error.
vector<int> v1(100);
for(int k=0;k<100;k++)
{
v1.push_back(k);
}
-- Tried using simple STL iterators like it.begin() , it.end() and algorithms like sort(), reverse() , I could not debug inside those functions by stepping, or could not set break point into those.(I know they being inside STL or some such standard library they would be assured to be bug-free, but one can still use them incorrectly by passing something invalid/incorrect)
Coming from C language usage of many years, to C++, I find this lack of 'debug ability' , or some restrictions in that , painful, while I am trying to understand large chunks of C++ code written by someone else, at work.
My questions -
What are effective ways to debug working code to understand its functionality while using idioms like step in, breakpoints, watch point, watch windows. Is any particular debugger better/worse than other.(Like say gdb being better) or are there any specific tricks/tips to aid debugging.
In general how to analyze a C++ code to understand its working?
A: A very small amount of types have "debug visualizers" specified for them to assist in debugging. They are in general a fantastic help and I find it almost impossible to get anything done without them now (why do I care about the implementation of a vector.. I just want to know what's in it!)
If, however, you do want to disable them, google around for the "autoexp.dat" file that controls that. You can just remove a few lines in that, and everything will go back to flat types. I will warn you that things like maps and sets become essentially un-debuggable without the visualisers.
Alternatively, switch into C++/CLI. VS2010 doesn't support debug visualisers in C++/CLI, which is usually a tremendous frustration, but I guess may be what you're looking for.
A: As you have found out, trying to use overloaded operators in the watch window simply won't work. You need to break open the objects and pull out the member variables.
In MSVC, std::vector has a member variable _Myfirst that points to the first element of its buffer. To get the item at index i you can add
(v._Myfirst)[i]
To the watch window. You can also use
(v._Myfirst),10
To show the first 10 elements of the array.
There should be a similar member variable for std::string.
A: In Tools > Options.. > Debugging > General uncheck the following items:
*
*Show raw structure of objects in variables windows
*Use Native Compatibility Mode
Then you shall see the formatted output.
A: I like Peter Alexander answer but for some reason didn't work for me. I'm using gnu GCC compiler and Looks like the implementation data type is different.
Inspired me to find the one below, which worked in my case:
To get the item at index (i) you can add
*(v._M_impl._M_start+i)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Clojure list member cast error I try to write function thats return true if element exist in list and false if not.
My code:
(defn is_member [elem ilist]
((elem []) false)
(if (= elem (first (list ilist)))
(true)
(is_member elem (rest (list ilist)))
)
)
I try to run it:
(is_member 1 '(1,2,3,4))
But get error:
#<CompilerException java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IFn
What's wrong? How can i fix it?
Thank you.
A: Looks like you're coming from a language with more extensive pattern-matching than Clojure has; ((elem []) false) is basically nonsense in Clojure. Instead, just test whether ilist is empty.
There are a number of other errors, so here's a snippet that actually works while being as close to what you intended as possible:
(defn is_member [elem ilist]
(cond (empty? ilist) false
(= elem (first ilist)) true
:else (is_member elem (rest ilist))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How gcc linker works in including files This is really a newbie question. I'm learning C, and I don't understand how to link together
different files.
I have a header like
/* file2.h */
int increment(int x);
and a C file
/* file2.c */
#include "file2.h"
int increment(int x)
{
return x+1;
}
Now I want to include the header in file1.c in order to use the function increment.
From what I have understood I have to do something like:
/* file1.c*/
#include "file2.h"
int main()
{
int y = increment(1);
return 0;
}
But when I try to compile the whole thing, using
gcc -o program file1.c
I get an error message like
/tmp/ccDdiWyO.o: In function `main':
file1.c:(.text+0xe): undefined reference to `increment'
collect2: ld returned 1 exit status
However if I include also file2.c
/* file1.c*/
#include "file2.h"
#include "file2.c" /* <--- here it is! */
int main()
{
int y = increment(1);
return 0;
}
Everything works as expected.
But if I have understood only the header file (with only declarations in it) has to be included. So how can I inform gcc that the definition of function increment declared in file2.h is in file2.c?
A: The easiest way is to compile them both directly:
$ gcc -o program file1.c file2.c
But for more complicated systems you might want to do it in steps. Here's a simple command line recipe:
$ gcc -c file1.c
$ gcc -c file2.c
$ gcc -o program file1.o file2.o
Even better for something complicated like this would be to use make, though.
Aside from your specific problem, why are you using GCC? You could use clang and get better error messages, faster compiling, and feel like you're living in the future!
A: gcc -o program file2.c file1.c
this will compile file1.c and file2.c and link them together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: array_key_exist on first layer of multidimensional array Can somebody tell my why the following code doesn't work?
$ReturnData=array(
'cardauth'=>array('success'=>'')
);
$Query="SELECT cardauth FROM y WHERE x = '".$x."'";
$Data=mysql_query($Query);
while($Row = mysql_fetch_array($Data)){
foreach($Row as $k => $v){
if(array_key_exists($k,$ReturnData)){
$ReturnData[$k]['success']=$v;
}
}
}
die(print_r($ReturnData));
I'm trying to set the values of the second dimension of the array $ReturnData with the column that is being crossed by the mysql fetch. 'cardauth' will be a BIT. I use the same method to populate single dimension arrays inside of the same loop. I've removed all the unnecessary code.
array_key_exists is not working. $ReturnData['cardauth']['success'] is not being set to the value of the column.
A: Use else to solve your problem! This else could be:
} else {
printf("array_key_exists did return true because [%s] does not contain %s",
implode(array_keys($ReturnData), ', '),
$k);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting circular references in SQL I have the following table:
CREATE TABLE X (
A SOMETYPE NOT NULL,
B SOMETYPE NOT NULL,
C SOMETYPE NULL,
PRIMARY KEY (A,B),
FOREIGN KEY (A,C) REFERENCES X (A,B)
);
The entities stored in X are hierarchically organized: If a row (A1,B1,C1) exists and C1 IS NOT NULL then it is considered to be a "child" of (A1,C1,C2) whatever C2 is. Since an item cannot descend from itself, I would like to make it illegal that circular hierarchical sequences exist:
-- legal
INSERT INTO X (A1,B1,NULL);
INSERT INTO X (A1,B2,B1);
INSERT INTO X (A1,B3,B2);
INSERT INTO X (A1,B4,B2);
-- currently legal, but I want to make it illegal
UPDATE X SET C = B1 WHERE B = B1; /* B1-B1 */
UPDATE X SET C = B2 WHERE B = B1; /* B1-B2-B1 */
UPDATE X SET C = B3 WHERE B = B1; /* B1-B2-B3-B1 */
UPDATE X SET C = B4 WHERE B = B1; /* B1-B2-B4-B1 */
UPDATE X SET C = B2 WHERE B = B2; /* B2-B2 */
UPDATE X SET C = B3 WHERE B = B2; /* B2-B3-B2 */
UPDATE X SET C = B4 WHERE B = B2; /* B2-B4-B2 */
UPDATE X SET C = B3 WHERE B = B3; /* B3-B3 */
UPDATE X SET C = B4 WHERE B = B4; /* B4-B4 */
How do I do this?
Alternatively, I could add a field representing the "level" in the hierarchy to the table:
CREATE TABLE X (
A SOMETYPE NOT NULL,
B SOMETYPE NOT NULL,
C SOMETYPE NULL,
LEVEL INT NOT NULL,
PRIMARY KEY (A,B),
FOREIGN KEY (A,C) REFERENCES X (A,B)
);
Then I would like to require that LEVEL be 0 when C IS NULL, and parent's LEVEL + 1 otherwise.
I am using SQL Server 2008 R2.
A: To check for circular references i have used a trigger and recursive CTE:
CREATE TRIGGER trgIU_X_CheckCircularReferences
ON dbo.X
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Results TABLE ([Exists] BIT);
WITH CteHierarchy
AS
(
SELECT x.A, x.B, X.C, 1 AS [Type]
FROM inserted i
JOIN X x ON i.A = x.A AND i.C = x.B
UNION ALL
SELECT x.A, x.B, X.C, 2 AS [Type]
FROM CteHierarchy i
JOIN X x ON i.A = x.A AND i.C = x.B
WHERE NOT EXISTS
(
SELECT *
FROM inserted a
WHERE a.A = x.A AND a.B = x.B
)
)
INSERT @Results ([Exists])
SELECT TOP(1) 1
FROM CteHierarchy h
JOIN X x ON h.A = x.A AND h.C = x.B
OPTION(MAXRECURSION 1000);
IF EXISTS(SELECT * FROM @Results)
BEGIN
ROLLBACK;
RAISERROR('Circular references detected', 16, 1);
END
END
GO
Now, we can run some tests:
--Test 1 - OK
PRINT '*****Test 1 - OK*****';
SELECT * FROM X;
BEGIN TRANSACTION;
UPDATE X
SET C = 'B1'
WHERE B = 'B4';
SELECT * FROM X;
--This transaction can be commited without problems
--but I will cancel all modification so we can run the second test
ROLLBACK TRANSACTION;
PRINT '*****End of test 1*****';
GO
--Test 2 - NOT OK
PRINT '*****Test 2 - NOT OK*****';
SELECT * FROM X;
BEGIN TRANSACTION;
UPDATE X
SET C = 'B1'
WHERE B = 'B1';
--Useless in this case (test 2 & test 3)
--Read section [If a ROLLBACK TRANSACTION is issued in a trigger] from http://msdn.microsoft.com/en-us/library/ms181299.aspx
SELECT * FROM X;
--Useless
ROLLBACK TRANSACTION;
--Useless
PRINT '*****End of test 2*****';
GO
PRINT '*****Test 3 - NOT OK*****';
SELECT * FROM X;
BEGIN TRANSACTION;
UPDATE X
SET C = 'B4'
WHERE B = 'B1';
GO
Results:
*****Test 1 - OK*****
(4 row(s) affected)
(0 row(s) affected)
(1 row(s) affected)
(4 row(s) affected)
*****End of test 1*****
*****Test 2 - NOT OK*****
(4 row(s) affected)
(1 row(s) affected)
Msg 50000, Level 16, State 1, Procedure trgIU_X_CheckCircularReferences, Line 34
Circular references detected
Msg 3609, Level 16, State 1, Line 8
The transaction ended in the trigger. The batch has been aborted.
*****Test 3 - NOT OK*****
(4 row(s) affected)
(1 row(s) affected)
Msg 50000, Level 16, State 1, Procedure trgIU_X_CheckCircularReferences, Line 34
Circular references detected
Msg 3609, Level 16, State 1, Line 7
The transaction ended in the trigger. The batch has been aborted.
For the second test, you can see how this trigger has canceled (ROLLBACK TRANSACTION) the transaction and, after UPDATE, nothing has been executed (in current batch).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: javamail works from desktop but not android emulator i have a javamail based gmail program, i tried using a standalone java app on the desktop and had no trouble, but when i run on android emulator i am getting:
D/SntpClient( 74): request time failed: java.net.SocketException: Address fami
ly not supported by protocol
CODE:
Properties props = System.getProperties();
props.setProperty("mail.imaps.host", "imap.gmail.com");
props.setProperty("mail.imaps.auth", "true");
props.setProperty("mail.imaps.debug", "true");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", 993, "xxxx@gmail.com", "xxxxx");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use a static constant (declared in parent class ) via a child class ( inherited class ) I have something like this :
class ParentClass
{
public static const ON_SOME_EVT:String = "onSomeEvent" ;
....
}
class ChildClass extends ParentClass
{
....
}
main()
{
trace( ChildClass.ON_SOME_EVT ) ; //<< compiler error on doing this
//1119: Access of possibly undefined property ABC through a reference with static type Class.
}
Then how should i achieve this. I want to access the constant via child class but not the parent class.
Thanks.
A: static vars can't be inherited
A: I think you can just do trace(ON_SOME_EVT); in the ChildClass, because the constant is inherited too if I'm not mistaken.
But the constant is a static member of ParentClass so outside of the inheritance tree you cannot avoid using ParentClass.ON_SOME_EVT. Why don't you want to use that?
A: The best way to do this is just to re-declare your static const in the child class and reference the ParentClass.ON_SOME_EVT.
class ParentClass
{
public static const ON_SOME_EVT:String = "onSomeEvent" ;
....
}
class ChildClass extends ParentClass
{
public static const ON_SOME_EVT:STring = ParentClass.ON_SOME_EVT;
....
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jqGrid tableToGrid loses scrollbar on sort I'm using the tableToGrid method of jqGrid to convert an ASP.Net GridView into a jqGrid. The grid is converted and everything looks good. But once I click a column to sort by, the data gets sorted and then I lose the vertical scrollbar, or really, just the ability to scroll. It seems like it wants to implement paging when I don't have any paging. For example, the data being returned and bound to the grid contains about 75 rows that I just list; with no paging. After I click a column to sort, it shows about 20 rows, there is no vertical scroll bar and I can't see the other rows (the ones past 20). Do I have to setup paging?
Thank you for any assistance.
tableToGrid("#ContentPlaceHolder1_grid",
{ height: 600,
forceFit: true,
viewrecords: true,
hidegrid: true,
gridview: true,
autowidth: true,
colNames: ['Id', 'Number', 'Facility', 'Department', 'Category', 'Job Title', 'Date Last Modified'],
colModel: [
{ name: 'Id', index: 'Id', width: 30, hidden: true },
{ name: 'Number', index: 'Number', width: 75, title: false },
{ name: 'Facility', index: 'Facility', width: 120 },
{ name: 'Department', index: 'Department', width: 120 },
{ name: 'Category', index: 'Category', width: 120 },
{ name: 'Job_Title', index: 'Job_Title', width: 170, sortable: false },
{ name: 'Date_Last_Modified', index: 'Date_Last_Modified', width: 100, sortable: true, align: 'right' }
]
});
My GridView is wrapped inside an UpdatePanel.
<asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="content" class="ui-widget half-height-widget">
<div class="ui-widget-header ui-corner-top">
<h2 id="PageTitle">
<img alt="JSA" src="Images/jsa.png"/>Open JSA Document
<span id="toolbar">
<asp:Button ID="open" Text="Open" CssClass="button" runat="server" />
</span>
</h2>
</div>
<div class="ui-widget-content ui-corner-bottom">
<div id="content-div" style="overflow: auto;">
<div id="files" style="height: 601px;">
<asp:GridView runat="server" ID="grid" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate><img class="jqGrid-icon" onclick='alert(<%# Eval("Id") %>);' alt='' src="images/magnifier-medium.png" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Number" HeaderText="Number" />
<asp:BoundField DataField="Facility" HeaderText="Facility" />
<asp:BoundField DataField="Department" HeaderText="Department" />
<asp:BoundField DataField="Category" HeaderText="Category" />
<asp:BoundField DataField="Job_Title" HeaderText="Job Title" />
<asp:BoundField DataField="Date_Last_Modified"
HeaderText="Date Last Modified" />
</Columns>
</asp:GridView>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
A: You should just include rowNum: 1000 in the list of jqGrid options in the second parameters of tableToGrid. If you don't have visible pager the local data paging still exist. So you should increase the page size from the default value rowNum: 20 to any large enough value (like 1000 or 10000 for example). Probably the usahe of height: 'auto' is one more option which you need.
See the modified demo here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Example for SimpleExpandableListAdapter I am trying to implement ExpandableListView in android. But I did not find any good tutorial.
I have to draw a check box and a textview on my parent view. On child view the first item contains a checkbox an image view and the last three are text views. Can any one please help me how to extend SimpleExpandableListAdapter?
A: The first place to look for an example on customizing the adapter of an ExpandableListView is the samples application provided with the SDK that you can find at:
{sdk_root}/samples/platform-xx/ApiDemos/src/com/example/android/apis/view/ExpandableListView1.java
For the question's case(the same layout for all groups followed by two types of layouts for the children rows)below you can find an example of a custom adapter. Notice that I extended BaseExpandableListAdapter, I've done this because extending SimpleExpandableListAdapter makes sense only for small changes(as its name suggest is designed to tackle basic usage scenarios).
private static class CustomExpandableAdapter extends
BaseExpandableListAdapter {
// identifiers for our two types of rows, if the child rows are the same
// this aren't required.
private static final int FIRST_CHILD = 0;
private static final int OTHER_CHILD = 1;
private LayoutInflater mInflater;
private List<HashMap<String, Object>> mGroupData;
private List<ArrayList<HashMap<String, Object>>> mChildData;
public CustomExpandableAdapter(Context context,
List<HashMap<String, Object>> makeGroupData,
List<ArrayList<HashMap<String, Object>>> makeChildData) {
mInflater = LayoutInflater.from(context);
mGroupData = makeGroupData;
mChildData = makeChildData;
}
@Override
public int getChildType(int groupPosition, int childPosition) {
if (childPosition == 0) {
return FIRST_CHILD; // this is the first child row so return
// FIRST_CHILD as the type of row
}
return OTHER_CHILD;
}
@Override
public int getChildTypeCount() {
return 2; // two types of children rows
}
@Override
public HashMap<String, Object> getChild(int groupPosition,
int childPosition) {
return mChildData.get(groupPosition).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// if we don't have a recycled row available inflate one BASED on
// the type of row this child should have.
int type = getChildType(groupPosition, childPosition);
ChildViewHolder holder;
if (convertView == null) {
holder = new ChildViewHolder();
switch (type) {
case FIRST_CHILD:
convertView = mInflater.inflate(
R.layout.view_expandlistchild, parent, false); // contains only an ImageView and a CheckBox
holder.image = (ImageView) convertView
.findViewById(R.id.imageViewChild);
holder.check = (CheckBox) convertView
.findViewById(R.id.checkBoxChild);
break;
case OTHER_CHILD:
convertView = mInflater.inflate(
android.R.layout.simple_list_item_1, parent, false); // contains only a TextView
holder.text = (TextView) convertView
.findViewById(android.R.id.text1);
break;
}
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
final HashMap<String, Object> item = getChild(groupPosition,
childPosition);
// we set the data on the row based on the type of the row(so we
// access only the views we do have in the layout)
switch (type) {
case FIRST_CHILD:
holder.image.setImageResource((Integer) item.get(CHILD_IMAGE));
// pass in the checked listener this as a tag so we can identify
// the proper data position and update it
holder.check.setTag(new PositionsWrapper(groupPosition,
childPosition));
holder.check
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
// set the new status of the checked item
// otherwise the status will be erased as the
// user scrolls down and up
PositionsWrapper pw = (PositionsWrapper) buttonView
.getTag();
mChildData.get(pw.groupPosition)
.get(pw.childPosition)
.put(CHILD_STATUS, isChecked);
}
});
holder.check.setChecked((Boolean) item.get(CHILD_STATUS));
break;
case OTHER_CHILD:
holder.text.setText((CharSequence) item.get(CHILD_TEXT));
break;
}
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return mChildData.get(groupPosition).size();
}
@Override
public HashMap<String, Object> getGroup(int groupPosition) {
return mGroupData.get(groupPosition);
}
@Override
public int getGroupCount() {
return mGroupData.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// normal row building like in any custom adapter
GroupViewHolder holder;
if (convertView == null) {
holder = new GroupViewHolder();
convertView = mInflater.inflate(R.layout.view_expandlistgroup,
parent, false); // contains a TextView and a CheckBox
holder.text = (TextView) convertView
.findViewById(R.id.textGroup);
holder.check = (CheckBox) convertView
.findViewById(R.id.checkBoxGroup);
convertView.setTag(holder);
} else {
holder = (GroupViewHolder) convertView.getTag();
}
final HashMap<String, Object> item = getGroup(groupPosition);
holder.text.setText((CharSequence) item.get(GROUP_TEXT));
holder.check.setTag(Integer.valueOf(groupPosition));
holder.check
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// again, save the new status in the data list so we
// keep the status as the user scrolls
Integer groupPosition = (Integer) buttonView
.getTag();
mGroupData.get(groupPosition).put(GROUP_STATUS,
isChecked);
}
});
holder.check.setChecked((Boolean) item.get(GROUP_STATUS));
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
/**
* Simple class that wraps two integers representing the group and child
* row position.
*
* @author Luksprog
*
*/
private static class PositionsWrapper {
int groupPosition;
int childPosition;
PositionsWrapper(int groupPosition, int childPosition) {
this.groupPosition = groupPosition;
this.childPosition = childPosition;
}
}
// basic ViewHolder classes
private static class GroupViewHolder {
TextView text;
CheckBox check;
}
private static class ChildViewHolder {
ImageView image;
CheckBox check;
TextView text;
}
}
The full sample can be found here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get a return value from a recursive Groovy closure? i seem to have written a recursive closure :) difficult enough but i am not struggling on how to get feedback from this closure. My written closure deletes a file recursively from the a starting point on the filesystem. I want to now how many files have been deleted!
How can is get feedback on how many files i have deleted? I tried with delegate etc but no luck so far..
def deleteClosure
deleteClosure = {
it.eachDir( deleteClosure )
it.eachFileMatch( ~".*123.jpg" ) {
it.delete()
}
}
deleteClosure(new File("/tmp/delete.me"))
A: There is no need to write your own recursive closure code, Groovy adds an eachFileRecurse method to File objects. To get a count of files deleted you can always just increment a counter:
import groovy.io.*
def filesDeletedCount = 0
new File('/tmp/delete.me').eachFileRecurse(FileType.FILES) {
if (it.name ==~ /.*123.jpg$/) {
it.delete()
filesDeletedCount++
}
}
println "Files deleted: ${filesDeletedCount}"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VS2010 don't publish particular folders/files I saw this question but it's related to VS2008 so I thought maybe things have changed:
Don't publish particular folder in ASP.NET
Anyway the question is, when I publish my ASP.net website it creates the publish folder and publishes files such as web.configand the images/ directory. The web.config on the live server has different configuration, and the images don't need to be uploaded again.
Can I make it not publish specific files/folders as it would make my upload process a lot faster and safer.
A: Yes. Simply change Build Action property of your file to None
A: The solution must contain a project file (.csproj). You get this if you work with Web Application projects instead of Web Site projects. You can also convert you Web Site project to the Web Application project. Personally I never work with Web Site projects, they have management issues (like the one we are discussing about) and offer little support for additional projects, like Console App project or Class Library projects.
A: In my case, since I use a web site project, I simply cut & paste the massive images folder to a parent folder outside of the project before publishing. Then, I cut & paste the folder back into the project folder after publishing completes. It only takes a few seconds to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: map a servlet in runtime I need to map a servlet in runtime. Is there anyway of doing it? I saw a method called addServlet in servletContext Interface. But I couldn't find a way to access it.
A: You can dynamically add servlets at runtime in Servlet 3.0. As you found, you do need access to the ServletContext in order to do this. The ServletContext is available from most web components, such as servlets or listeners. I'm not sure your use case for doing this, but here are a couple examples where you may access the ServletContext in order to add web components at runtime -
public class MyServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
config.getServletContext().addServlet(...);
}
. . .
}
public class MyListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
sce.getServletContext().addServlet(...);
}
public void contextInitialized(ServletContextEvent sce) {}
}
A: I think the only way to do this would be to use a filter, and then based on the request URL, load the servlet and call directly into it, as opposed to using the chain.doFilter(req, resp); If you have an authentication filter; make sure to add this new filter lower on the web.xml so you don't accidentally forget to authenticate!
There is a library which could help you with this here: http://code.google.com/p/urlrewritefilter/
This filter works basically as I have described.
To be honest though; I think you should re-assess why you're doing this in the first place. You likely don't need to do this and if you think about it you can probably find a way around whatever problem you're having using the good 'ole static servlet-mappings in your web.xml. That decision is yours to make though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Deploying MongoDB, CouchDb on OpenVZ? I want to write hobbistic app and deploy it on Linux 64 bit on OpenVZ. I googled and it seems that MongoDB doesn't work well under OpenVZ environment so the way to go is CouchDB? Or for small databases on just one server without any extraordinary featues I can go with MongoDB?
Best regards
Artur
A: For a brand new application, the database and OpenVZ will probably not matter much. I suggest choosing the one you are most familiar with (including SQL databases) so that you can focus on the application features.
On the other hand, if you want to learn a database, then choose the one you want to learn, and don't worry about performance yet. For example, see this question of comparing various NoSQL databases.
A: If later you want to replicate your data with couchDB, keep in your mind that couchDB doesn't support persistence replication !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extending the XHTML DTD to use special chars in ID attributes I want to validate XML templates that are a XHTML extension. Now there are special characters like { and | in ID attributes. Is it possible to extend the XHTML DTD to overwrite the restriction to the characters allowed in the ID attribute? Or are the characters defined by the XML specification?
A: You cannot use the characters '{' and '|' directly in id attributes because in the XML specification it says
Values of type ID must match the Name production. A name must not appear more than once in an XML document as a value of this type; i.e., ID values must uniquely identify the elements which bear them.
The name production is here. If you expand the syntax rule you see that the only characters allowed in a name are given by these productions:
[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
Unfortunately the left brace and the pipe are not allowed. The codepoints for those characters are #7B and #7C respectively; not in the accepted character ranges.
TL;DR: the legal characters for ID attributes are owned by the XML spec and your two characters are not legal.
ADDENDUM
Here are some examples. The following document passes validation for XHTML on the W3C validation site:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>A title</title>
</head>
<body id="anid">
</body>
</html>
but the following will not
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>A title</title>
</head>
<body id="ani{d">
</body>
</html>
We get the error:
Line 8, Column 16: character "{" is not allowed in the value of attribute "id"
Now it's rather interesting that if you really want the left curly bracket in the id name, you can try this:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>A title</title>
</head>
<body id="ani{d">
</body>
</html>
But you get the same error! You might want to try this; the validator shows the line with the ampersand hash x seven b semicolon but it thinks there is a left brace there.
The bottom line is that you simply cannot have ids with characters other than those allowed by the XML specification.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Retrieve a thumbnail of a video I'm trying to make an application for showing the best movie trailers. I'd like to show a grid view with the thumbnails of each video and then clicking them open a new Activity for playing the video.
Given a moment of the video, how can I retrieve the thumbnail? If that is complicated the first frame is enought too. Thanks
A: If you are using API 2.0 or newer this will work.
To get video id:
String[] proj = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA
};
Cursor cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, MediaStore.Video.Media.DISPLAY_NAME+"=?",new String[] {"name.mp4"}, null);
cursor.moveToFirst()
id = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
To get the thumbnail of the video:
ImageView iv = (ImageView ) convertView.findViewById(R.id.imagePreview);
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id, MediaStore.Video.Thumbnails.MICRO_KIND, options);
iv.setImageBitmap(curThumb);
EDIT:
If you are on android-8 (Froyo) or above, you can use ThumbnailUtils.createVideoThumbnail from video path:
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Maps API is not marking restaurants, schools, etc on my map. When using the Google maps API to display the map, restaurants, schools, airports, stores, etc. are not being marked as seen on maps.google.com.
How do you make the API mark these locations?
A: You'd need to use the Places library, but it won't be as easy as you'd like. There are currently some 126 different place types you'd have to consider.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Core Data and threads / Grand Central Dispatch I'm a beginner with Grand Central Dispatch (GCD) and Core Data, and I need your help to use Core Data with CGD, so that the UI is not locked while I add 40.000 records to Core Data.
I know that CD is not thread safe, so I have to use another context, and then save the data and merge contexts, as far as I was able to understand from some articles.
What I couldn't do yet, is put the pieces together.
So, in my code, I need your help on how to to that.
I have:
/*some other code*/
for (NSDictionary *memberData in arrayWithResult) {
//get the Activities for this member
NSArray *arrayWithMemberActivities = [activitiesDict objectForKey:[memberData objectForKey:@"MemberID"]];
//create the Member, with the NSSet of Activities
[Members createMemberWithDataFromServer:memberData
andActivitiesArray:arrayWithMemberActivities
andStaffArray:nil
andContactsArray:nil
inManagedObjectContext:self.managedObjectContext];
}
How can I transform this to work on the background, and then, when done saving, save the data and update the UI, without blocking the UI while saving the 40.000 objects?
A: Here's a snippet which covers GCD and UI in it's simplest terms. You can replace doWork with your code that does the CoreData work.
Concerning CD and thread safety, one of the nice parts about GCD is you can sections off areas of your application (subsystems) to synchronize and ensure they get executed on the same queue. You could execute all CoreData work on a queue named com.yourcompany.appname.dataaccess.
In the sample, there's a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:@"Working ..."];
[[self doWorkButton] setEnabled:NO];
// async queue for bg work
// main queue for updating ui on main thread
dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
dispatch_queue_t main = dispatch_get_main_queue();
// do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue,
^{
[self performLongRunningWork];
dispatch_async(main, ^{ [self workDone]; });
});
// release queues created.
dispatch_release(queue);
}
- (void)performLongRunningWork
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
}
- (void)workDone
{
[[self feedbackLabel] setText:@"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
A: Here's a good example for you to try. Feel free to come back if you have any questions:
self.mainThreadContext... // This is a reference to your main thread context
NSPersistentStoreCoordinator *mainThreadContextStoreCoordinator = [self.mainThreadContext persistentStoreCoordinator];
dispatch_queue_t request_queue = dispatch_queue_create("com.yourapp.DescriptionOfMethod", NULL);
dispatch_async(request_queue, ^{
// Create a new managed object context
// Set its persistent store coordinator
NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
[newMoc setPersistentStoreCoordinator:mainThreadContextStoreCoordinator]];
// Register for context save changes notification
NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
[notify addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:newMoc];
// Do the work
// Your method here
// Call save on context (this will send a save notification and call the method below)
BOOL success = [newMoc save:&error];
if (!success)
// Deal with error
[newMoc release];
});
dispatch_release(request_queue);
And in response to the context save notification:
- (void)mergeChanges:(NSNotification*)notification
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.mainThreadContext mergeChangesFromContextDidSaveNotification:notification waitUntilDone:YES];
});
}
And don't forget to remove the observer from the notification center once you are done with the background thread context.
[[NSNotificationCenter defaultCenter] removeObserver:self];
A: This blog post has a detailed description on Core Data concurrency and sample code:
http://www.duckrowing.com/2010/03/11/using-core-data-on-multiple-threads/
A: Adding another source of info you can check
ThreadedCoreData
the Sample Code of Apple's iOS Developer Library, which have been recently updated (2013-06-09)
Demonstrates how to use Core Data in a multi-threaded environment,
following the first recommended pattern mentioned in the Core Data
Programming Guide.
Based on the SeismicXML sample, it downloads and parses an RSS feed
from the United States Geological Survey (USGS) that provides data on
recent earthquakes around the world. What makes this sample different
is that it persistently stores earthquakes using Core Data. Each time
you launch the app, it downloads new earthquake data, parses it in an
NSOperation which checks for duplicates and stores newly founded
earthquakes as managed objects.
For those new to Core Data, it can be helpful to compare SeismicXML
sample with this sample and notice the necessary ingredients to
introduce Core Data in your application.
A: So the selected answer for this is from nearly 2 years ago now, and there's a few issues with it:
*
*It's not ARC friendly - need to remove release call on newMoc - ARC won't even compile with that
*You should be doing the weakSelf / strongSelf dance inside the block - otherwise you're probably creating a retain loop on the observer creation. See Apple's doc's here: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html
*@RyanG asked in a comment why he's blocking. My guess is because the recently edited method has waitUntilDone:YES - except that's going to block the main thread. You probably want waitUntilDone:NO but I don't know if there's UI updates firing from these change events as well so it would require testing.
--Edit--
Looking further into #3 - waitUntilDone:YES isn't a valid methodSignature for managed context objects, so how does that even work?
A: Much easier way to do it than attach the persistent store coordinator to a new context, which is not thread safe either, btw.
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrency];
[context setParentContext:<main thread context here>];
[context performBlock:^{
...
// Execute all code on current context
...
}];
NSError *error = nil;
[context save:&error];
if (!error) {
[context.parentContext save:&error];
if (error) {
NSLog(@"Could not save parent context: %@", error);
}
}
else {
NSLog(@"Could not save context: %@", error);
}
Great tutorial on how to use multi-context Core Data:
http://www.cocoanetics.com/2012/07/multi-context-coredata/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: Escaping strings with python mysql.connector I am trying to insert a bunch of strings into mysql using python and mysql.connector. My current code looks something like this:
db = mysql.connector.Connect('config blah blah')
cursor = db.cursor()
data = (somestring1, somestring2)
sql = "INSERT INTO mytable (col1, col2) VALUES ('%s', '%s')"
cursor.execute(sql, data)
How should I go about escaping my strings? I could try doing it in python but I know this isn't the right way.
Note: I realise mysql.connector is still in development.
update:
Line 4 should read:
sql = "INSERT INTO mytable (col1, col2) VALUES (%s, %s)"
A: Since mysql.connector is DB API v2.0 compliant, you do not need to escape the data yourself, it does it automatically for you.
A: The answer from infrared is the best approach.
But, if you really need to escape some arbitrary string, you can do this (before 2.1.6):
db = mysql.connector.connect(......)
new_str = db.converter.escape('string to be escaped')
Newer versions (use lowlevel C-API):
db = mysql.connector.connect(......)
new_str = db._cmysql.escape_string('string to be escaped')
Another option is to use mariadb python connector (pip install mariadb).
db = mariadb.connector(....)
new_str = db.escape_string("quote ' this")
A: Indeed, the best approach would be to let module escape values by itself. If you absolutely need to do it by hand (I, for example, want to only print SQL in my script's debug mode, and mysql.connector doesn't seem to implement mogrify()), there's also another option:
>>>> import mysql.connector
>>>> cnx = mysql.connector.connect()
>>>> cur = cnx.cursor()
>>>> cur._connection.converter.escape("tic ' toc")
"tic \\' toc"
Admittedly, it still uses "non-public API", but at least it is consistent between recent versions (so far; tested on 2.0.4, 2.1.3, 2.2.9, 8.0.16).
A: Here is what worked for me:
import mysql.connector
db = mysql.connector.connect(host="HOST", # your host, usually localhost
user="USERNAME", # your username
passwd="PASSWORD", # your password
db="DATABASE") # name of the data base
query_string = "Geor'ge"
escaped_string = db.converter.escape(query_string)
The first step is to import mysql.connector, followed by creating a connection by using the connect function. After that, you can call the db.converter.escape function.
A: You can do this with the pymysql package:
import pymysql
from pymysql.converters import escape_string
from mysql.connector import connect, Error
then you can do:
with connect(
host="localhost",
user="root",
password="",
database="mydb",
) as connection:
with connection.cursor(buffered=True) as cursor:
cursor.execute(escape_string("YOUR_SQL_STATEMENT"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Driver development: Uninstalling Windows driver I'm hacking on a virtual HID driver, and for some reason, I'm unable to disable and unable to uninstall the driver in Device Manager.
devcon.exe remove also throws an error. Removing the device in Game Controllers dialog in Control Panel tells me to go to Device Manager to remove the device.
Any idea what may be causing this to happen? What might cause Windows to think it's unable to remove the driver?
Small update.
Putting the computer to standby allowed me to remove the device.
Removing parts of HID report descriptor (such as the multitouch report, mouse report and keyboard report, neither of which I used) has also fixed the issue.
However, I'd like to understand what exactly went wrong. What has locked down the driver so it cannot be uninstalled?
A: Any process that might be using the driver could be holding it open. One way to see this is to use Sysinternals' Process Explorer and use the "Find" command under the "Handles" menu to search for the name of any DLLs related to the driver.
So, for many drivers shutting down the related processes is easy, but it can be more challenging for one related to the file system. For example, even if you close all maps or mounts on the virtual device, any Windows Explorer processes (including the login shell) could have loaded the driver. Again, PROCEXP is helpful for figuring out some of this...
A: It's a kernel-mode driver so, you can't "just" disable it. For a driver to be successfully unload, I/O manager must send the clean up request when there are no other handles waiting to be processed or closed.
And if it is a PnP driver, PnP manager must send IRP_MJ_SHUTDOWN request to the I/O manager so that I/O manager can start the unloading callback routine.
One way of disabling it by force could be, you can debug the machine's kernel. By doing that you can see which processes are sending requests to this driver and then manually unload the driver (tho it might have severe effects because all of those open handles that hold the driver open must be closed by the I/O manager)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom Iteration over a list item in Python I have a list in python with following sample contents:
['mark', 29, 'american', 'james', 45, 'british', 'arthur', 76, 'australian']
as is clear from the pattern the first item in a list is name, second is age and the third is nationality.
What will be the most efficient way of iterating over it so as to separate the elements inside one for loop.
I am new to python and do not know the best method of doing it.
for i in len(0, len(my_list):
name =
age =
nationality =
A: Try this handy pattern:
from itertools import izip
iters = [iter(my_list)] * 3 # change 3 to number of items in each group
for name, age, nationality in izip(*iters):
print name, age, nationality
A: Just loop in steps of 3:
for i in xrange(len(my_list)/3):
name, age, nationality = my_list[3*i:3*i+3]
A: The best way to implement new kinds of iteration is to write a generator. They let you encapsulate the iteration style and separate it from the rest of your code:
def by_threes(seq):
it = iter(seq)
while True:
yield next(it), next(it), next(it)
for a, b, c in by_threes(range(20)):
print a,b,c
prints:
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
15 16 17
If you had need to tuplize a sequence flexibly, you could use this:
def by_chunks(seq, n):
"""Yield lists [a,b,..] from `seq`, each list having `n` elements."""
l = []
for i, x in enumerate(seq):
l.append(x)
if (i % n) == n-1:
yield l
l = []
A: Use step indices with zip (or itertools.izip):
>>> l = ['mark', 29, 'american', 'james', 45, 'british', 'arthur', 76, 'australian']
>>> for name, age, nationality in zip(l[::3], l[1::3], l[2::3]):
... print (name, age, nationality)
...
('mark', 29, 'american')
('james', 45, 'british')
('arthur', 76, 'australian')
A: one method of doing it is:
names = mylist[0::3]
ages = mylist[1::3]
nationalities = mylist[2::3]
you can then iterate as
for name in names:
print name
etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is 'publish_actions' extended permissions available for testing? I've been trying to test out Scores and Achievements using the 'publish_actions' extended permissions but when I add it, it doesn't show up in the Request for Permission page. It's like its ignored.
I've tried a couple different ways:
$loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_actions', 'canvas' => 1, 'fbconnect' => 0, 'redirect_uri'=>config_item('facebook_url')));
$loginUrl = 'https://www.facebook.com/dialog/oauth?'
. 'client_id=' . config_item('fbappid')
. '&redirect_uri=' . urlencode(config_item('facebook_url'))
. '&state=' . $_SESSION['state']
. '&scope=publish_actions';
Both way don't work. Has anyone else had any luck testing this out?
Referencing code here:
http://developers.facebook.com/blog/post/539/?ref=nf
A: I ran into this same issue here is what you need to do.
1) Go to the apps page https://developers.facebook.com/apps/ and select your app
2) On the left nav bar under Settings got to Auth Dialog
3) At the bottom of this page click on Configure how Facebook refers users to your app
4) You should now be able to add publish_actions
permissions.
5) Read the following links (its a pain to find)
https://developers.facebook.com/docs/beta/opengraph/tutorial/ https://developers.facebook.com/docs/beta/authentication/
A: this might help as well (quoting facebook):
"While in Open Graph Beta, the 'publish_actions' permission can only
be requested from developers and test users of your app. The
'publish_actions' permission will be ignored if requested from any
other user."
it only comes up after updating the permissions inside the app configuration. lost so much time because of this lacking documantation...
A: ran into the same problem yesterday.
i think fb will change this behaviour in the near future, but currently it seems that the app must be in the category 'game' to request the 'publish_actions' permission... (i am in the sandbox mode)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Unable to drill down into a variable in Firebug Occasionally in firebug I'm unable to drill down into a variable expression when stepping through javascript code. Sometimes it's flukey behavior and I'll refresh the page and the next time through I am able to drill down. However with some variables I'm never able to. I'll give an example:
I'm using the google visualization api and I have the following code:
var row = tableChart1.getSelection();
var test5 = queryWrapper1;
var dt = test5.currentDataTable;
var dv = test5.currentDataView;
var x = dv.getViewRowIndex(row[0].row);
var y = dt.getRowProperties(row[0].row);
alert(test5.currentDataTable.getRowProperty(row[0].row,"ticker"));
The variable that I'm not able to drill down into is y. Here's the documentation for getRowProperties() (here's the link link to documentation):
Returns: Object
Returns a map of all properties for the specified row. Note that the
properties object is returned by reference, so changing values in the
retrieved object changes them in the DataTable.
Any explanation as to why firebug won't let me examine the properties of the returned object would be much appreciated. Thanks.
Update: I'm using firebug 1.7.3.
Also here's a screen shot of what I'm seeing:
A: I tried testing it a bit with some example code from Google. It's not an issue with Firebug. The object that gets returned from your call to dt.getRowProperties(row[0].row); really is empty. The documentation on getRowProperty mentions that null is returned if no such property exists. It seems that an empty object is returned for the related function getRowProperties, if there are no properties.
The properties of a row, column, or cell are used by some visualizations to change their behavior, as explained in the documentation. You have to explicitly set these properties with the relevant functions.
If you want to test it out, to prove that it isn't Firebug, change the code like so:
var row = tableChart1.getSelection();
var test5 = queryWrapper1;
var dt = test5.currentDataTable;
var dv = test5.currentDataView;
var x = dv.getViewRowIndex(row[0].row);
// Add this bit
dt.setRowProperty(row[0].row, 'foo', 'bar');
var y = dt.getRowProperties(row[0].row);
alert(test5.currentDataTable.getRowProperty(row[0].row,"ticker"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Embedding python + numpy code into C++ dll callback I am new of python embedding.
I am trying to embed python + numpy code inside a C++ callback function (inside a dll)
the problem i am facing is the following. if i have:
Py_Initialize();
// some python glue
// python invocation
Py_Finalize();
everything works fine.
but if i have:
Py_Initialize();
_import_array(); //to initialize numpy C-API
// some python glue + numpy array object creation
// python invocation via PyObject_CallObject()
Py_Finalize();
this crashes at the second time it reaches _import_array(); (meaning that it works for the first callback)
if i instead do the python and numpy initialization just once and the finalization in the destructor (thus not every time initializing/finalizing), everything crashes when leaving the callback..
The problem here i guess is numpy, but i dont know how to solve it
A: Try make sure your .dll is only initialized once, regardless of how many times the code is actually invoked.
Here is a link on "C++ Singleton in a DLL":
Singleton in a DLL?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Header file for atomic builtins of gcc I wanted to know what is the header file that is used for the atomic builtins of gcc?
I want to use these 2 functions for implementing the mutex for a thread library that I am currently creating.
bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...);
type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...);
I tried searching on net, but just could not find the header file for these builtins. So if someone could point out what is the header file for these functions, it would be of great help. Also currently for testing, I will be compiling my code using gcc. But eventually I would be creating my own make file for compilation. Since these are gcc builtins, will there be any issues in usage of these functions when I compile using my own makefile? Will I have to take special care in my makefile in order to make these functions work? Any help would be greatly appreciated.
A: There are no header requirements but you may need to explicitly specify the architecture (using the -march flag)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: android choose between two starting activities I need to choose between two starting (Main) activities based on some stored data. Logic I am trying to achieve is something look like:
if (data == something) showActivity1();
else showActivity2();
Is there a way to declare something like this in manifest? Multiple
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> tags?
Or is there a point in application where this code would be suitable?
I was thinking of creating one activity, and then just set them different content views and handle logic accordingly, but these two activities are very very different, so it would result in a lot of unconnected code in one file.
Thanx in advance.
A: If you set multiple MAIN & LAUNCHER tag, multiple activities appear in your application list. So, that's not what you want.
My recommendation is like this...
*
*make an transparent activity( works as facade )
*judge which activity to start
*start target activity and finish facade activity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Zend Framework: DB / Models: Securing Other Users Rows - Overriding Concrete Methods I am trying to research the best way to secure users data.
Example: An application has a table 'widgets', each user can have as many 'widgets' as required. The application identifies the 'widgets' by the 'userId' column, which referenced the ID of the logged in user.
Currently the best way I have been able to secure the widget data from being accessed if by overriding the fetchAll() method with my own in my models, and add in WHERE userId = X before passing the params to parent::fetchAll() like so:
class Model_Widgets extends Zend_Db_Table_Abstract {
protected $_name = 'widgets';
/**
* Abstracted function to ensure data security
* Adds in a WHERE to the SELECT to check if this user is the datas owner
*
* @see Zend_Db_Table_Abstract::fetchAll()
*/
public function fetchAll($where = null, $order = null, $count = null, $offset = null)
{
// Handle the additional security check
$userId = 'userId = ' . Model_Users::getUser()->id;
// Merge the WHERE userId statement with the rest
if($where)
{
if(is_array($where))
$where[] = $userId;
else
$where = array($where, $userId);
}
else
$where = $userId;
return parent::fetchAll($where, $order, $count, $offset);
}
This method works fine, but I cant help to think that there must be a better way, I have recently discovered $_rowClass but am still not sure I understand the concept. If overriding concrete functions is the only way to apply these security checks, is there a way to override them once rather than in each model perhaps via a helper, and then simply add a function like the following to each model that needs to check the user against the row:
public function fetchAll(...)
{
return SecurityCheckHelper::fetchAll(...);
I hope this makes sense, in reality all I am trying to do is make sure users cant access other users data by playing about with ID's in the URL etc.
Thanks guys
A:
Currently the best way I have been able to secure the widget data from being accessed if by overriding the fetchAll() method with my own in my models, and add in WHERE userId = X before passing the params to parent::fetchAll()
You really should do this for all functions of Zend_Db_Table_Abstract then as this could result in some nasty bugs later on.
these security checks, is there a way to override them once rather than in each model perhaps via a helper, and then simply add a function like the following to each model that needs to check the user against the row:
Why don't you create a new abstract base class that implements this feature for all of your models? Like My_Db_Table_Abstract extends Zend_Db_Table_Abstract.
am trying to do is make sure users cant access other users data by playing about with ID's in the URL etc
This is the controller's job!
In my projects I solve this by using ACL and custom asserts (in my models). This even allows you further modifications without changing your models.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Compiler error about class graph being not finitary due to a expansively recursive type parameter With this piece of code:
trait B[T]
trait C[T]
class A[T] extends B[A[C[T]]]
I get the following error:
error: class graph is not finitary because type parameter T is expansively recursive
class A[T] extends B[A[C[T]]]
^
Can someone explain what the error message is about, why T is infinitely recursive and why the following code works?
class A[T] extends B[A[T]]
A: From the Scala 2.9 specification (note that this is in the Change Log as a change that was introduced in 2.4, so it's not a "new restriction" in 2.9):
The implementation of subtyping has been changed to prevent infinite
recursions. Termination of subtyping is now ensured by a new
restriction of class graphs to be finitary.
Kennedy and Pierce explain why infinitary class graphs are a problem:
Even disregarding subtyping, infinite closure presents a problem for
language implementers, as they must take care not to create type
representations for supertypes in an eager fashion, else non-
termination is the result. For example, the .NET Common Language
Runtime supports generic instantiation and generic inheritance in
its intermediate language targeted by C. The class loader maintains a
hash table of types currently loaded, and when loading a new type it
will attempt to load its supertypes, add these to the table, and in
turn load the type arguments involved in the supertype.
Fortunately, as Kennedy and Pierce point out, there's a convenient way to check whether a class graph is infinitary. I'm using their definitions throughout this answer.
First I'll make your type variables distinct for clarity:
trait B[X]
trait C[Y]
class A[Z] extends B[A[C[Z]]]
Next we construct the type parameter dependency graph using Kennedy and Pierce's definition. The only declaration that's going to add edges to the graph is the last one, for A. They give the following rules for building the graph:
For each declaration C <X̄> <:: T and each subterm D<T̄> of T, if T_j = X_i add a non-expansive edge C#i → D#j; if X_i is a proper subterm of T_j add an expansive edgeC#i → D#j
So first we look at Z and C[Z], which gives us a non-expansive edge from Z to Y. Next Z and A[C[Z]] gives us an expansive edge from Z to Z, and Z and B[A[C[Z]]] gives us an expansive edge from Z to X:
I've indicated non-expansive edges with dashed arrows and expansive edges with solid ones. We have a cycle with an expansive edge, which is a problem:
Infinitary class tables are characterized precisely by those graphs
that contain a cycle with at least one expansive edge.
This doesn't happen for class A[Z] extends B[A[Z]], which has the following graph:
See the paper for a proof that a class table is infinitary iff it's expansive.
A: The answer above is really well formed, but also quite complex. As this page is very high on google search results for 'non finitary graph', I thought I'd add a 'hand waving' explanation. The class definitions in your problem give us this subtype relation element:
A[X] <: B[A[C[X]]]
The compiler sees however that the definition is recursive (uses A[_] in the definition of A[X]) and tries to expand it, so it substitutes the argument type C[Z] for the parameter type X in the definition of A and obtains:
A[C[X]] <: B[B[A[C[X]]]
And we see where it is going: definition of A can be expanded indefinitely.
Note there is no subtype relation with A[X], as the type is invariant in X.
I know nothing about compilers and the maths behind the problem, I simply tried to come to some conclusion from my observations as to 'what' happens, without an answer to 'why'. What I said is thus most likely factually incorrect or inprecise, but the take out is:
if you use a type constructor A in the definition of A
(which can be done only as a type argument to another type (B)),
you cannot give it as a type argument a complex term (C[X]).
The fact that X occurs inside the C[X] argument is irrelevant:
type Z
type A[X] <: B[A[C[Z]]]
leads us to:
A[C[Z]] <: B[B[A[C[Z]]]
This doesn't happen if you use simply A[X] in the definition of A[X], because X itself is not expanded.
To be more constructive, one can try to work around it by giving B as arguments type constructor A and the argument C[X]:
trait A[X] extends B[A, C[X]]
And apply A to C[X] in the body of B instead.
A: The answer above is really well formed, but also quite complex. As this page is very high on google search results for 'non finitary graph', I thought I'd add a 'hand waving' explanation. The class definitions in your problem give us this subtype relation element:
A[X] <: B[A[C[X]]]
The compiler sees however that the definition is recursive (uses A[_] in the definition of A[X]) and tries to expand it, so it substitutes the argument type C[Z] for the parameter type X in the definition of A and obtains:
A[C[X]] <: B[B[A[C[X]]]
And we see where it is going: definition of A can be expanded indefinitely.
Note there is no subtype relation with A[X], as the type is invariant in X.
I know nothing about compilers and the maths behind the problem, I simply tried to come to some conclusion from my observations as to 'what' happens, without an answer to 'why'. What I said is thus most likely factually incorrect or inprecise, but the take out is:
if you use a type constructor A in the definition of A
(which can be done only as a type argument to another type (B)),
you cannot give it as a type argument a complex term (C[X]).
The fact that X occurs inside the C[X] argument is irrelevant:
type Z
type A[X] <: B[A[C[Z]]]
leads us to:
A[C[Z]] <: B[B[A[C[Z]]]
This doesn't happen if you use simply A[X] in the definition of A[X], because X itself is not expanded.
Also: if the compiler throws a StackOverflowError in the typer phase, this may be one of the causes:
java.lang.StackOverflowError
at scala.reflect.internal.Types$Type$$anon$1.apply(Types.scala:794)
at scala.reflect.internal.Types$SingleType.mapOver(Types.scala:1477)
at scala.reflect.internal.Types$Type$$anon$1.apply(Types.scala:794)
at scala.reflect.internal.Types$SingleType.mapOver(Types.scala:1477)
Stack trace added in case someone encounters the problem and tries to search for it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Web2py AJAX autofilling of form i've a from an i want to fill it automatically based on information from a data base and filled fields :
in db_wizard.py
db.define_table('sender',
Field('name'), # e.g. Daniel
Field('email'),# e.g. daniel@daniel.com
Field('opening'), # e.g. Dear Daniel
...)
db.define_table('receiver',
Field('name'), # e.g. John
Field('email'), # e.g. John@john.com
Field('tel'), # e.g. 111 222 111
...)
db.define_table('letter',
Field('sender', db.sender.id), # e.g. Daniel
Field('receiver', db.receiver.id), # e.g. John
Field('opening'), # should be filled automatically when choosing/changing the value of "sender"
...)
so letter.opening should get the value of receiver.opening[letter.sender.id], that means the value of opening of the chosen sender
A: If the 'opening' text should be filled in instantly when the user selects a recipient, then you'll probably want to use Ajax. Check out this lazy options widget. You'll have to modify it to fill in a string input instead of an options list, but otherwise it should do what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fixing the Subversion user does not own lock on path error I am trying to delete a folder within my Subversion repository. My TortoiseSVN client gives me the following error message when I try to commit this change:
Commit Failed (details follow):
User {username} does not own lock on {path}
page {filename} currently locked by {another user}
If you want to break the lock, use the 'Check for modifications' dialog.
I do want to break the lock and delete the folder, but I can't see an obvious way to do it from the Check for Modifications folder. Does anyone have any suggestions?
A: An administrator can break the lock. See "Breaking and Stealing Locks" from this page.
A: From Pedro's answer, I was able to figure out how to do this from within Tortoise SVN. You can find the full instructions in this tread on the SVN Forum:
http://www.svnforum.org/threads/39826-Commit-problem-User-does-not-own-lock-on-path
The short version is:
*
*Open the Check for Modifications dialog
*Click the Check Repository button
*You should now see the name of the user that holds the lock in the Lock column (you may need to scroll right to see this column in your list.)
*Right click on the file with the lock. You should now see the Break Lock option on the context menu.
If you have a lot of files, you can select all files in your list (Ctrl-A) and apply the Break Lock for everything, as described here:
How can I release locks in Subversion recursively?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: CSS text-overflow - apply ellipsis if text extends (n)th line I'm using the following code to to prevent text from overflowing to a new line:
.info-box{
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
height: 3em;
width: 300px;
font-size: 1em;
line-height: 1em;
}
This works, as expected, but there is room for three lines in this box. How can I command browsers to apply the elipsis if the text extends beyond the third line? Or does text-overflow only work over one?
I probs won't bother if I need JS for this.
A: You can fake it with CSS like this.
Add a <span>...</span> at the beginning of the div.
<div class="info-box"><span>...</span>Lorem ipsum dolar etc.</div>
In your CSS
*
*get rid of the nowrap and text-overflow
*add some padding-right
*position the span down by the bottom right.
CSS
.info-box{
overflow:hidden;
height: 3em;
width: 300px;
font-size: 1em;
line-height: 1em;
padding-right:20px;
}
.info-box span{
position:relative;
top:31px;
left:297px;
display:inline-block;
}
Working Example: http://jsfiddle.net/jasongennaro/UeCsk/
fyi... there will be a small gap at the top left, where the ellipsis is supposed to be (because we are using position:relative;.
fyi 2... this should work with however many lines you want (you mentioned three in the question) provided that you adjust the top and left.
A: I know this is an old question, but I found this fix and it works fine for me.
https://codepen.io/martinwolf/pen/qlFdp
@import "compass/css3";
/* Martin Wolf CodePen Standard */
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,600,700);
* {
margin: 0;
padding: 0;
@include box-sizing(border-box);
}
body {
padding: 3em 2em;
font-family: 'Open Sans', Arial, sans-serif;
color: #cf6824;
background: #f7f5eb;
}
/* END Martin Wolf CodePen Standard */
$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;
h2 {
display: block; /* Fallback for non-webkit */
display: -webkit-box;
max-width: 400px;
height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
margin: 0 auto;
font-size: $font-size;
line-height: $line-height;
-webkit-line-clamp: $lines-to-show;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Cufon is not showing after the text is dynamically updated I'm currently building an e-commerce site in wordpress using the WP-ecommerce plugin.In product page, the stock is updated after you select an attribute(size, color etc). It basically shows if the product is in stock or not. The text gets cufon when the page loads, but after the stock is updated, that is you select an attribute, the test suddenly loses cufon as well as the small shopping cart in the sidebar. I have no idea what is causing the problem. you can see the site here : http://tinyurl.com/43pd8br . Thanks for helping!
A: You'll need to call cufon again after the text is updated. Unlike CSS, which applies a style to any element matching the selector now and in the future of the page, Cufon is JS, meaning it responds to events.
When you first load your page, you are applying cufon - so it goes and finds all the matched elements and does its thing, then it's done. When you update your text without a page load, cufon is not aware of this - as far as knows, it's done its job and has finished.
So what you need to do is a callback - in the script that dynamically updates your text, add your cufon actions once the update has happened.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A simple DEVISE sign-up... Why doesn't this rspec/capybara test pass? A typical DEVISE create account page should redirect to a welcome page for new users
describe ArtistsController do
render_views
....
describe "Sign UP should redirect to welcome page" do
it "should redirect to welcome page on valid sign up", :js => true do
visit destroy_artist_session_path #just to be sure we're logged out
visit new_artist_registration_path
fill_in 'Email', :with => 'newguy@newguy.com'
fill_in 'Password', :with => 'password'
fill_in 'Password confirmation', :with => 'password'
click_link_or_button 'Sign up'
#save_and_open_page <-- reveals we are still on the sign-up page
page.should have_content("Welcome")
end
end
I manually QA'd this scenario on my local machine and it works fine. But the test doesn't seem to work; it does NOT continue to the welcome page. The new user is NOT created in the DB. There is no complaint by capybara that it cannot find the button or anything.
What am I doing wrong?
A: I had the same issue, it was connected to subdomains.
The session key was "lvh.me",
but tests were using "example.com" by default.
My test was submitting login form correctly, user was authenticated no problem, then Devise was redirecting to the home page in "example.com" domain, and the app was not able to find session data (which were under "lvh.me" key), and was redirecting back to login page w/o any flash messages or errors.
So if you are using subdomains, be sure to set up Capybara hosts before logging user in. Just for a case, here is what I do:
def go_to(subdomain)
Capybara.app_host = "http://#{subdomain}.lvh.me"
Capybara.server_port = 3000
host! "#{subdomain}.lvh.me:3000"
end
A: It seems like you're being redirected back to the login page.
*
*Does the output of save_and_open_page container any flash messages?
*Have you checked the test.log for clues?
*Try set the Capybara driver to mechanize and you'll be able to watch what happens - it may help in tracking down the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I differentiate between records in a has_many relationship? I have a table of venues, venuetypes and just added a table of venuetype_icons.
Currently a venue belongs to a venuetype and a venuetype has many venues. Each venue is displayed with an icon depicting its venuetype.
The venues can be either free or premium and I would like for each venuetype to have 2 icons, one for a free venue and one for a premium venue.
I have set up venuetypes to have many venuetype_icons. The venuetype_icon records have a name field and the paperclip file fields.
I'd like to set my view up as such:
<% if venue.plan == 'premium' %>
display the premium venuetype_icon
<% else %>
display the regular free icon
<% end %>
But how can I differentiate between the free and premium icons if there stored in the same table? Would it be possible to add in a drop down when creating new icons to mark them as free or premium? and if so how would that work in the view?
I hope this makes sense, please ask for any clarification if needed.
Thanks for any help its much appreciated!
A: If you know that for each VenueType, there's only going to be one icon per plan, and the amount of plans is going to be pretty limited and hardcoded, I would reverse the relation from VenueType to VenueTypeIcons:
class VenueType
belongs_to :free_icon, :class_name => "VenueTypeIcon", :foreign_key => "venue_type_icon_free_id"
belongs_to :premium_icon, :class_name => "VenueTypeIcon", :foreign_key => "venue_type_icon_premium_id"
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AChartEngine Messed up labels My chart displays fine but as soon as I scroll to the side, I have random time appearing and it messes up the dates, see this picture:
http://img14.imageshack.us/img14/8329/statqs.jpg
I'd like to only display the date and nothing else, I don't know how the renderer comes up with time that I never entered.
Also I'd like to know how I can prevent scrolling to the left (x axis) and down (negative y), I can no longer use SetPanLimits because my x values are dates and not numbers.
Any help would be greatly appreciated!
A: I know this is very old, but for the next user, it may help to have the solution.
You can specify the date format to use
/**
* Creates a time chart intent that can be used to start the graphical view
* activity.
*
* @param context the context
* @param dataset the multiple series dataset (cannot be null)
* @param renderer the multiple series renderer (cannot be null)
* @param format the date format pattern to be used for displaying the X axis
* date labels. If null, a default appropriate format will be used.
* @return a time chart intent
* @throws IllegalArgumentException if dataset is null or renderer is null or
* if the dataset and the renderer don't include the same number of
* series
*/
public static final Intent getTimeChartIntent(Context context, XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer, String format) {
return getTimeChartIntent(context, dataset, renderer, format, "");
}
To show only day and month, use something like the following:
Intent intent = ChartFactory.getTimeChartIntent(context, dataset, mRenderer, "dd-MMM");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create Graph actions with GET curl -F 'access_token=AAAAASrf1VhwBAOU0pZAzvwBYQLjcJClsMA2e7al0qsRP5uJ0KoUmMuc7aNq56gXmSQd6c2h9vfdQUscvtC3ZAZCxP36USGFy0fNqdhq5gZDZD' \
-F 'article=http://example.com' \
'https://graph.facebook.com/me/teglilka:iztegli'
Is this the only way to set action, is there GET method ?
A: The graph API supports simulated POST requests by adding a ?method=POST parameter to the call
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: html button to call php shell_exec command I have google the heck out of this an I cannot get an answer to this. I hate php, but out php guy is too busy and I need HELP!
I want to call a perl script from an html button. But, I just want it to run in the back ground, I don't need to display anything from it... Would something like this work?
<html>
<body>
<p>
<button onclick=<?php exec('test.pl') ?>Run Perl</button>
</p>
</body>
I would prefer not to use cgi, I want to keep this as simple as possible.
Thanks
A: That will not works, you have to create an action for that:
<?php
if (isset($_POST['button']))
{
exec('test.pl');
}
?>
<html>
<body>
<form method="post">
<p>
<button name="button">Run Perl</button>
</p>
</form>
</body>
A: Looks like you are trying to call PHP with a JavaScript action. This will not work. You can try submitting a form and executing the PHP code when the form is submitted, like:
<?php if (isset($_POST['button'])) { exec('test.pl'); } ?>
<form action="" method="post">
<button type="submit" name="button">Run Perl</button>
</form>
A: Addressing the 'run in background' part of this problem, you should be able to put an & at the end to force it to the background.
So exec('test.pl &');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Vim does not open Git branch files I checkout an old git commit as a branch, with:
git checkout -b b48cdaa
Then I open vim (actually Macvim) and I expect to see the files from the old commit, but all the files are the current (master branch) rev. Why is that? How can I look at an old rev in vim?
Thanks in advance.
A: git checkout -b b48cdaa
is creating a new branch called b48cdaa in your case referencing the current HEAD.
What you probably want to do is
git checkout -b branch_name b48cdaa
.
A: You're not doing what you think you're doing. git checkout -b b48cdaa creates a new branch named "b48cdaa".
If you drop the -b, it should checkout the commit with the specified sha1 (and leave you in "detached head" state).
git checkout --help for more information.
(Note that this has nothing to do with vim.)
A: Here is the man, it seems the -b flag does not what you expect :
git checkout [-q] [-f] [-m] [[-b|-B|--orphan] <new_branch>] [<start_point>]
-b
Create a new branch named <new_branch> and start it at <start_point>; see git-branch(1)
for details.
You just created a new branch named b48cdaa holding the new files.
A: According to the Git documentation (for the checkout command) :
-b Create a new branch named and start it at ; see git-branch(1) for details.
Just tape git checkout b48cdaa
But be careful
When you do this, you change the HEAD to the commit b48cdaa. My advice is to tape this command in another branch. So :
git checkout -b test_branch
git checkout b48cdaa
And when you are ready to return to the original head :
git checkout master
(if you want to remove the test_branch :
git branch -d test_branch
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery Wrapping some string with conditional i have string need to be wrapped by tag HTML with conditional like this:
<h1>Test</h1>
Then nothing will happen
<h1>Test Lagi</h1>
Then the first word will be wrapped by span, result <h1><span>Test</span> Lagi</h1>
<h1>Test Lagi ah</h1>
Then only the first word will be wrapper by span, result:
<h1><span>Test</span> Lagi ah</h1>
How to do that in jQuery?
A: After following CoryLarson's link Here is a better solution:
http://jsfiddle.net/avmFe/
$(function(){
$('h1').each(function(){
var me = $(this);
if(/(\W+)/.test(me.html())) {
me.html(me.html().replace(/^(\w+)/, '<span>$1</span>'));
}
});
});
Hope it helps.
A: $(function(){
$('h1').each(function(){
var txt = $(this).text();
var wordArray = txt.split(' ');
var new_first = '<span>'+wordArray[0]+'</span>';
var new_txt = txt .replace("wordArray[0]",new_first);
$(this).html(new_txt);
});
});
A: http://jsfiddle.net/Rs4TA/1/
$('*:contains("Test")').html('<span>Test</span>');
If your "test" is a static text, it could be done by this way.
A: This does it: http://jsfiddle.net/RE9rp/1/
And here's the JS:
function wrapFirstWord($el, word){
$el.each(function(){
var txt = $(this).text();
var wordArray = txt.split(' ');
if(wordArray[0] === word && wordArray.length > 1){
var newHTML = '<span>' + word + '</span>';
for(var i = 1; i < wordArray.length; i++){
newHTML += ' ' + wordArray[i];
}
$(this).html(newHTML);
}
});
}
$(function(){
wrapFirstWord($('h1'),'Test');
});
You simply pass to wrapFirstWord() the set of elements you want to check for the word ($el), as well as the word you are looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: .htaccess Redirect sub-folder Hi I'm not a programmer by any stretch of the imagination and am trying to do a multi 301 redirect in my htaccess file based on the following:
So I have a ton of urls all with similar naming conventions - here is a sample of 2.
http://www.hollandsbrook.com/garrett-at-gold/
http://www.hollandsbrook.com/garrett-ace-250/
These urls need to redirect to:
http://www.hollandsbrook.com/garrett-metal-detectors/garrett-at-gold/
http://www.hollandsbrook.com/garrett-metal-detectors/garrett-ace-250/
I could just redirect them 1 line at a time, but I'd like to use regex.
Here's what I was thinking so far but not working:
RewriteRule ^garrett-([a-z])/$ /garrett-metal-detectors/$1/ [R]
Basically i need to redirect any page right off the root that starts with "garrett-" to include the folder path of "garrett-metal-detectors".
Any thoughts would be MUCH appreciated. Many thanks in advance for your help.
A: if you want temprorary redirect use:
RewriteRule ^garrett\-([a-z0-9\-]+)/?$ /garrett-metal-detectors/garrett-$1/ [R=302,L]
if you want permanent redirect use:
RewriteRule ^garrett\-([a-z0-9\-]+)/?$ /garrett-metal-detectors/garrett-$1/ [R=301,L]
A: I'm am not an expert on Regular Expressions, but looks like your reg ex may be a bit off...
try:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^((garrett)(-[a-z0-9]).*)/$ /metal-detectors/$1/ [R]
This is looking fro anything starting with "garrett" followed by any letter/number/hyphen combo.
Note: having "garett" in the destination part give you a loop of redirects, so you may have to choose a different word, or remove it all together...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: IE Rendering Problems I have been developing a website template for my school website. I have finished all necessary development but now have noticed a problem. When opening the site in IE, it does not align everything as it does when it is loaded in Chrome or Firefox. I'm guessing that there is some CSS property that is not being handled properly by IE (this problem is more obvious on wide-screen monitors).
I have uploaded the template here: http://test.victoriaparkci.com/tpl2/
CSS is here: http://test.victoriaparkci.com/tpl2/style.css
How would I fix this problem?
Thanks for the help.
A: Remove the content above from the DOCTYPE Element, a page should start with doctype
this content :
<!--VICTORIA PARK COLLEGIATE INSTITUTE SCHOOL WEBSITE
All of this website's material and content is owned by the administration of
Victoria Park C.I., 15 Wallingford Rd, North York, ON, Canada.
Prior permission must be obtained before use, modification or replication of this website's code or content.-->
A: What I notice is that the content div is failing to expand with the length of body_right. Try floating the content DIV to the left.
#content {
float:left;
margin: 20px 0 0 0;
background:#FFFFFF;
border:1px solid #ececec;
padding: 0 10px 30px 5px;
overflow:hidden;
}
From my experience, usually a DIV will not expand to its content length because it is not floated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: design - sixth normal form I have the following tables:
Blogs { BlogName }
BlogPosts { BlogName, PostTitle }
Blog posts is modeling an entity and a relationship at the same time which is invalid according to 6nf (according to the third manifesto).
In 6nf, it would be:
Blogs { BlogName }
Posts { PostTitle }
BlogPosts { BlogName, PostTitle}
If I wanted to order blog posts by a sequence nbr (just an example), that would be another table
BlogPostsSorting { BlogName, PostTitle , SortOrder }
Do I have it correct?
A: What are the keys of your tables? Based on the column names I guess that the key of BlogPosts can only be {BlogName,PostTitle}. In that case BlogPosts is already in 6NF - it has no nonprime attributes and therefore cannot be nonloss decomposed. The Blogs relvar and Posts relvar would be redundant - you don't need them.
Blog posts is modeling an entity and a relationship at the same time
which is invalid according to 6nf (according to the third manifesto)
Can you tell me where you think the Third Manifesto says that's invalid. I'm sure it doesn't but I'd like to know how you arrived at such a conclusion.
A: sqlvogel is correct in this answer.
Except for this little detail: whether Blogs is redundant or not depends on whether you want/need to enforce a constraint to the effect that all Blogs tuples must have at least one corresponding BlogPost tuple. You didn't state anything to make that clear.
The same holds for your third relvar Posts, except that in this case it is highly unlikely that it could be valid for a PostTitle to exist, without it appearing as the title of at least one BlogPost.
Whether you need the SortingOrder relvar as an extra one depends on whether or not there can be BlogPosts for which no sorting order is needed. If there cannot, then your SortingOrder relvar simply replaces BlogPosts. If there can, then you can have the two relvars; or alternatively you can still just have the SortingOrder relvar, and hack your way through the case of posts without ordering by using a dummy value (e.g., always -1).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Object reference is required? am learning C# and have written a simple bit of code, but i don't understand why i have to declare the variables userChoice and numberR within the scope of the Main method and not within the scope of the class. If i declare it within the class like this, i get build errors
using System;
namespace FirstProgram
{
class Program
{
string userChoice;
int numbeR;
static void Main()
{
Console.WriteLine("Write a number...");
userChoice = Console.ReadLine();
numbeR = Convert.ToInt32(userChoice);
Console.WriteLine("You wrote {0}", numbeR);
Console.ReadLine();
}
}
}
But only this will give me no errors:
using System;
namespace FirstProgram
{
class Program
{
static void Main()
{
string userChoice;
int numbeR;
Console.WriteLine("Write a number...");
userChoice = Console.ReadLine();
numbeR = Convert.ToInt32(userChoice);
Console.WriteLine("You wrote {0}", numbeR);
Console.ReadLine();
}
}
}
Shouldn't i be able to use those two variables within Main just by declaring them in the Class like above? I am confused... thanks for any advice.
A: You can't do it because Main() is a static function. Your variables are declared as instance variables and can only be accessed on an instance of the Program class. If you declare userChoice and numbeR as static variables, it will compile.
static string userChoice;
static int numbeR;
static void Main()
{
//your code
}
Static members mean you can use the member without instantiating the class. Imagine:
public class MyClass
{
public static int StaticInt;
public int NonStaticInt;
}
means you could do:
MyClass.StaticInt = 12; // legal
MyClass.NonStaticInt = 12; // error, can't staticly access instance member
and all classes would have access to that change, since there is only one MyClass.StaticInt in your program. To change NonStaticInt, you would have to create an instance of that class, like so:
MyClass mine = new MyClass();
mine.NonStaticInt = 12; // legal
mine.StaticInt = 12; // Error, cannot access static member on instance class.
A: You have to make your variables static since your Main method is static.
A: Since Main is static, your variables would also need to be static in order to be used like this. If you declare them as:
static string userChoice;
static int numbeR;
Then it will work.
You currently have them declared inside an instance of a Program object. However, static methods (such as Main) are part of the type, not a specific instance.
A: because Main is static
if you declare the variables (a.k.a. fields) as static too you can declare them in the class
static string userChoice;
static int numbeR;
Non static methods and variables are called instance methods and variables. Instance variables relates to a specific object while static variables are shared among all created objects within the class.
The rules are that static methods can only call static methods and access static variables, but instance methods can call both static and non static variables and methods.
A: The reason is because Main() is a static method and the two class fields (userChoice and numbeR) are instance fields.
Main() can be called statically, but the two class fields won't be defined until an instance of the Program class is created.
A: The Main() method is declared as static. However, in your first code sample you declare two variables (userChoice & number) as instance variables. The static Main() method does not belong to a specific object, but to a certain type. Your variables however do belong to a specific instance of the Program type. You cannot use instance variables in a static method.
A: The problem is that Main is static. You will have to declare the variables userChoice and numbeR as static. Then it will compile. Here is the corrected example:
using System;
namespace FirstProgram
{
class Program
{
static string userChoice;
static int numbeR;
static void Main()
{
Console.WriteLine("Write a number...");
userChoice = Console.ReadLine();
numbeR = Convert.ToInt32(userChoice);
Console.WriteLine("You wrote {0}", numbeR);
Console.ReadLine();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Telephone Words problem Please help solve this:
Telephone numbers are often given out as a word representation, so that they are easy to remember. For example if my number is 4357, the text given is HELP. There could be many other possibilities with the same digits, most of which do not make sense.
Write a space-and-time-optimal function that can, given a phone number, print the possible words that can be formed from it.
A: Based on the detailed explanation in the comment this should be a simple permutation combination problem:
Each digit will have a number of characters associated to it (example 4 could mean either of G,H or I) and then for a combination of digits the permutation can be computed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: boost::bind function with its input argument error I am trying to do multithreading by boost::bind. But, I got error:
src/model.cpp:225: instantiated from here
/boost_1_45_0v/include/boost/bind/mem_fn.hpp:333: error: pointer to member type void (Model::)(taskDataSPType&) incompatible with object type taskDataSPT1ype
make: * [model.o] Error 1
Here is my code:
void Model::runTask(taskDataSPType& myTask)
{}
taskDataSPType myTask;
fifo_pool tp(thread_num);
for (int i = 0 ; i < totalTaskNum ; +i)
{
taskQueue.wait_and_pop(myTask, i);
myTask.taskID = i ;
// run the typical iterations
tp.schedule(boost::bind(&Model::runTask, &myTask));
}
tp.wait();
In another header file, I have :
typedef struct taskDataSPT1ype taskDataSPType;
struct taskDataSPT1ype
{
int taskID;
int startNode;
int endNode;
};
A: Model::runTask is (presumably) a non-static member function. That means you cannot call it without an instance of the class. boost::bind knows this, and therefore it expects the first parameter to be a Model of some form, or a derived class thereof. So your bind takes two parameters: the Model and the function argument taskDataSPType&.
Also, your argument is a reference, but you seem to be attaching a pointer. That's not going to work either. You may need to use boost::ref, as follows:
tp.schedule(boost::bind(&Model::runTask, /*Some Model Instance*/,
boost::ref(myTask)));
A: &Model::runTask is a member function, and as such it has an extra implicit argument this. So in your particular case, you want to bind it with two arguments: an instance of Model and a taskDataSPType object. Note that if one wants to pass references with bind it has to use boost::ref or boost::cref.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run Ook!? (VS Language Integration) I downloaded the Ook! source, opened the .csproj and ran it in debug mode. The VS Experimental Instance fires up as expected, but now I can't figure out how to get to a blank code file so I can actually try writing in Ook! I don't see "Ook!" in any of the project templates.
Also, if anyone has a link to the Ook! video tutorial, I'd appreciate it. Can't seem to find it anymore.
A: Because the Ook language service is geared towards files with a .ook extension, just create a text file, change the extension to .ook and open it in the Visual Studio experimental instance.
There's also a video about this on Channel 9, is that the one you were looking for?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: scaling vector images through librsvg Is it possible to scale the svg before getting its pixel buffer through librsvg? I can see API like rsvg_pixbuf_from_file_at_zoom but it is marked as deprecated.
Is there some other way to do it? I wan to avoid using cairo for this, if possible.
A: You do not have many choices, it's either:
*
*using a deprecated function like rsvg_pixbuf_from_file_at_size() (which is not that bad, it's not very likely this function will go away any time soon)
*or using the RsvgHandle object with rsvg_handle_new_from_file() and rsvg_handle_render_cairo() on a cairo surface create at the right dimension
You can limit the usage of cairo to a minimum if you want a GdkPixbuf at the end by:
*
*creating a RsvgHandle with rsvg_handle_new_from_file()
*creating a cairo context and setting up the transformation matrix you want
*render the svg with rsvg_handle_render_cairo()
*grab the pixbuf with rsvg_handle_get_pixbuf()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Log4j mapping all loggers to a single logger Our middleware team assignes logger names to each application and that is how they know where to direct our socket appenders to.
I would like to use the standard Logger.getLogger(Clazz.class) paradigm but that does not work with the above constraint. Also we can't log library statements out to our socket appender which would come in handy a lot.
Is there a fairly painless way to map everything from all loggers to this middleware assigned logger?
I think our middleware group messed up in how the configured the enterprise logging system. It looks like there is a setApplication property on the SocketAppender that should be used instead. Regardless, this is what we have to deal with...
A: You'd like to redirect your "regular" loggers' output to the "middleware logger" directly, i.e. without setting the middleware logger's appender on all the "regular" loggers, right?
If this is the case, try writing your own appender:
class MiddlewareRedirectingAppender extends AppenderSkeleton {
private Logger middlewareLogger = Logger.getLogger("your 'middleware' logger name");
public void doAppend(LoggingEvent event) {
// implement whatever filtering, etc. you want
middlewareLogger.log(...);
}
}
Attach this appender to your "regular" loggers, or just to the root logger (depending on how your "middleware" logger behaves).
Disclaimer: this is just a loose idea, I haven't tested it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: A static resource file? Android uses a static resource file R. This file (at least in eclipse) is automatically updated when ever you add new id's of any sort. How can I create/implement the same feature in a normal java application? Is it as simple as just writing an xml parser and just updating the resource file after the xml is modified?
A: In a way, yes. You need to create a custom build script/program which runs at the start of each build (before anything else), scans your resource folder files (and if they are XML files it needs to read in the XML files and parse out the string resources or whatever from those), then write it all to a Java file in some manner (e.g. R.string_name = "string value").
Make sure the XML files aren't actually packaged in your .jar, since all that information will be stored inside your Java resources file now.
For things which aren't XML files you could just store the filename as a string in the Java resources file.
A: You didn't specified the type or the use of the resources. I don't know android, but I'll try to help; If you just need to access some resource in your application you can use properties or resource, there are some differences see this other question Properties vs Resource Bundle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: localStorage and 'file:' protocol not persistent, SQLite gives SECURITY_ERR Introduction
I work with RapidWeaver — Mac OS X CMS application — and it uses no server environment. It has an editor and a preview mode. The preview mode is a Webkit based renderer, and I can use 'Inspect Element', like you normally could do in Safari.
I want to store some settings for a toolbar, either using localStorage or SQLite. I have read some information about indexedDB, though I have found no concrete implementations on how to use it.
Problems with localStorage
localStorage works fine when I stay in the preview mode, when I switch between editor and preview mode the url — location.href — is slightly altered:
file:///private/var/folders/s7/x8y2s0sd27z6kdt2jjdw7c_c0000gn/T/TemporaryItems/RapidWeaver/98970/document-143873968-28/RWDocumentPagePreview/code/styled/index.html
file:///private/var/folders/s7/x8y2s0sd27z6kdt2jjdw7c_c0000gn/T/TemporaryItems/RapidWeaver/98970/document-143873968-29/RWDocumentPagePreview/code/styled/index.html
document-143873968-28 changes into
document-143873968-29
What I have read about localStorage, that it's basically globalStorage[location.hostname] for FireFox. As far as I know globalStorage is not supported in Safari, so I can't try that.
Problems with SQLite
When I try to open a database:
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
var db = openDatabase(shortName, version, displayName, maxSize);
I get this in my console:
SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent.
That basically wraps up my question, I will appreciate any answers or comments sincerely.
A: Using the following solution: Implementing a WebView database quota delegate with a few modifications I was able to get it to work.
The following delegate method worked for me (place in your webViewDelegate):
- (void)webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(id) origin database:(NSString *)databaseIdentifier
{
static const unsigned long long defaultQuota = 5 * 1024 * 1024;
if ([origin respondsToSelector: @selector(setQuota:)]) {
[origin performSelector:@selector(setQuota:) withObject:[NSNumber numberWithLongLong: defaultQuota]];
} else {
NSLog(@"could not increase quota for %@", defaultQuota);
}
}
By default the database is given 0 bytes, which results in the vague error message you get above. The above method is called after an attempt is made to create a database when there is not enough space. Note that this method is defined in WebUIDelegatePrivate.h ( http://opensource.apple.com/source/WebKit/WebKit-7533.16/mac/WebView/WebUIDelegatePrivate.h ) and using may preclude you from submitting your app to the mac app store.
A: localStorage is a html5 mechanism to give scripts a bit more space than cookies. Safari supports it: https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html
I don't know offhand what, if any, path restrictions it should have for file:/// based apps.
Edit: looking into the path restrictions further, I see that what you got should work with Safari, FF recently fixed a bug that would keep it from working there: https://bugzilla.mozilla.org/show%5Fbug.cgi?id=507361
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Universal mysql escaping and html tags stripping in PHP?
Possible Duplicate:
PHP: the ultimate clean/secure function
Is there a way to mysql escape all variables in my code before sending it to the database as well as stripping all HTML tags? I don't want to go to each variable to do that, so I wonder if there is a universal way to instruct my PHP pages (maybe put something in the header?) to do that before processing mysql_query calls?
Thanks!
A: Use PDO when querying your database to escape values in your query.
A: There is, but that's just wrong. The escpaing should happen at the db layer, not at the input. Please read this answer.
And to answer the question, you can use array_map on the $_REQUEST variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to select an item for dropdown menu with mechanize in python? I am REALLY confused. I'm basically trying to fill out a form on a website with mechanize for python. I got everything to work except the dropdown menu. What do I use to select it and what do I put for the value? I don't know if I'm supposed to put the name of the selection or the numerical value of it. Help would be greatly appreciated, thanks.
Code snippet:
try:
br.open("http://www.website.com/")
try:
br.select_form(nr=0)
br['number'] = "mynumber"
br['from'] = "herpderp@gmail.com"
br['subject'] = "Yellow"
br['carrier'] = "203"
br['message'] = "Hello, World!"
response = br.submit()
except:
pass
except:
print "Couldn't connect!"
quit
I'm having trouble with the carrier, which is a dropdown menu.
A: According to the mechanize documentation examples, you need to access attributes of the form object, not the browser object. Also, for the select control, you need to set the value to a list:
br.open("http://www.website.com/")
br.select_form(nr=0)
form = br.form
form['number'] = "mynumber"
form['from'] = "herpderp@gmail.com"
form['subject'] = "Yellow"
form['carrier'] = ["203"]
form['message'] = "Hello, World!"
response = br.submit()
A: Sorry for reviving a long-dead post, but this was the still best answer I could find on google and it doesn't work. After more time than I care to admit, I figured it out. infrared is right about the form object, but not about the rest, and his code doesn't work. Here's some code that works for me (though I'm sure a more elegant solution exists):
# Select the form
br.open("http://www.website.com/")
br.select_form(nr=0) # you might need to change the 0 depending on the website
# find the carrier drop down menu
control = br.form.find_control("carrier")
# loop through items to find the match
for item in control.items:
if item.name == "203":
# it matches, so select it
item.selected = True
# now fill out the rest of the form and submit
br.form['number'] = "mynumber"
br.form['from'] = "herpderp@gmail.com"
br.form['subject'] = "Yellow"
br.form['message'] = "Hello, World!"
response = br.submit()
# exit the loop
break
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Label text evaluation Jquery Why is the label's text is evaluated as not equal to "" in the below script even when in reality there is not any text in it:
$('label[class*="lb"]').each(function(index){
if($(this).text()!=""){
a_arr.push($(this).val());
alert(index+ " " + $(this).val());
}
});
$(this).text()!="" is evaluated true even when the label has no text. Why?
A: try using trim function. Might be there is additional white spaces
if($.trim($(this).text())!="") {
//your code here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How could I return 4 random rows in SQL? This is my calling code from PHP currently:
$getfromdb = "SELECT `myTable`.* FROM `myTable` WHERE `status`=1 and ORDER BY rand() LIMIT 4";
This is sufficient enough for now, as the number of rows in the table is pretty small (<1000).
However,
(a) the randomness is not enough (meaning some of the same rows are being returned pretty often), and
(b) the size of the table will increase very quickly, meaning performance will take a hit.
How could I make this such that the code could be more random and efficient?
There is an autoincrement on the primary key (id) - but there are holes as well.
A: If you know the table's approximated cardinality, I think you can set OFFSETrandomly. For example:
$cardinality = 100000;
$limit = 4;
$offset = rand(0, $cardinality - $limit);
$getfromdb = "
SELECT * FROM (
SELECT `myTable`.* FROM `myTable` WHERE `status` = 1
OFFSET $offset LIMIT 500
) ORDER BY rand() LIMIT $limit
";
Well, its sampling method has bias however.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recognising gestures from the home screen I am developing an app for iPhone.
I am looking for a way to run some code once a drag gesture is recognized on the homescreen (or on all screens if possible).
Does anyone know how to get this with the iOS SDK using Xcode and Objective-C?
A: Your app cannot receive gestures anywhere in iOS except within itself and its own views while it's active (not counting system notifications and the app icon).
A: I doubt this is possible. To do this, you will need to hook into the OS at a lower level than is usually allowed.
iOS is locked down much more than Mac OS, I'm afraid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Haskell Extensible IO Exceptions? In the documentation for Control.Exception in base 4.4.0.0 there is an example of how to make exception hierarchies. The example shows how one can catch generalizations of a specific exceptions by declaring instances of the Exception class in terms of the parent exception. This is cool, but how do I make my exceptions children of existing exceptions. For example, I want to make exceptions that are caught by type constraints on IOException. The example in Control.Exception shows this:
*Main> throw MismatchedParentheses catch (\e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException)))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses catch (\e -> putStrLn ("Caught " ++ show (e :: IOException)))
*** Exception: MismatchedParentheses
How can I get IOException constraints to catch my exceptions?
A: You can't. IOException is not designed to be extensible in such a way.
In general, you cannot extend existing data types willy-nilly. There's a good reason for that, as it would require existing functions to know what to do with the new values. There are ways around this, but they all require the data type to be designed with this in mind.
It's not clear to me why you want your custom exceptions to be treated like IO exceptions, though. If you want to catch both types, just nest applications of catch, one for each type. Or perhaps it would be better to turn things around and allow IO exceptions to be wrapped within your own exception type. The documentation already has good examples of how to do that. It all comes down to what you're trying to achieve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Fluent Interface, Need something like global methods in C# Im currently trying to build a Fluent Interface for a ServiceLocator. To ensure that each the developer can easily setup 1-to-n mappings
I'd like something like this
ServiceLocator.Instance.For<IFoo>(Use<Foo>(), Use<FooBar>());
Singleton is workin fine... the methodsignature for the For method looks like this
public void For<TInterface>(params type[] services)
{
// ...
}
So I was looking for something like a global method
C# has some global methods, all methods which are defined on System.Object. But when I create a new generic ExtensionMethod on System.Object, the method will not be visible.
public static class MyExtensions
{
public static void Use<T>(this Object instance)
{
// ..
}
}
MethodChaining would be the alternative, but this approach looks sexy :D
Has anyone an idea?
A: Well, actually when I create an extension method for Object, it is visible. As in,
public static class Extensions
{
public static void doStuff<T>(this T myObject)
{
}
}
class Program
{
static void Main(string[] args)
{
int a = 5;
a.doStuff();
string b = "aaa";
b.doStuff();
List<int> c = new List<int>() { 1, 2, 3, 10 };
c.doStuff();
Extensions.doStuff(c);
}
}
Did I misunderstand your question?
A: You need to add a using statement for the namespace containing your extension method in order for it to be visible. Adding extension methods to object is rarely a good idea.
EDIT:
Okay, now I understand what you're asking. In order to use an extension method you need an instance. You're asking for a static extension method on object (Equals and ReferenceEquals are static methods), and that's not possible. If you define an extension method on object, it will be available on all instances and I'm sure that's not what you want.
public static class ObjectExtensions
{
public static string TypeFullName(this object obj)
{
return obj.GetType().FullName;
}
}
static void Main(string[] args)
{
var obj = new object();
Console.WriteLine(obj.TypeFullName());
var s = "test";
Console.WriteLine(s.TypeFullName());
}
A: Service Locator is widely considered to be an anti-pattern. Also, a common registration interface is widely considered to be an unsolvable problem unless you are requiring use of a specific container.
Looking past these two questionable decisions, you can remove the need for the global method by defining overloads of For which accept multiple type arguments:
ServiceLocator.Instance.For<IFoo, Foo, FooBar>();
The For methods would look like this:
public void For<TInterface, TImplementation>()
public void For<TInterface, TImplementation1, TImplementation2>()
...
You have to define an overload for each type count, but it requires the minimal syntax and maximum amount of discoverability. For reference, the .NET Framework's Action and Func types support 9 type arguments.
After writing this out, though, I wonder if I misunderstood the question: why would you specify multiple implementations for the same interface? Wouldn't that lead to ambiguity when resolving IFoo?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I get blankNode ID in dotnetrdf librery in C# I create a blankNode like this code using dotNetRDF
BlankNode ddd = k.CreateBlankNode();
and then assert it in a n3 file but when I open the n3 file by notpad it show this blankNode like [].
How can I create a blankNode ID by myself to then delete this?
delete a node or triple using dotenetrdf librery?
A: If you really need an explicit ID then you must use the following form of the method:
IBlankNode bnode = g.CreateBlankNode("id");
Note that this does not guarantee that the library won't convert it to the anonymous syntax [] in the N3 output as this is simply a syntax compression. If you really want to avoid this syntax compression you can create and configure a Notation3Writer manually and set the CompressionLevel property to be low (anything < 5 should stop the use of [])
Otherwise if you want to delete an anonynmous blank node this you need to formulate some selection criteria that will allow you to locate the relevant node and then retract triples based upon that
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XPath - selecting node based on following sibling I have a query like this:
/plist/dict[1]/dict/dict/dict/key/following-sibling::dict/string[string()='Algier']
What I really want to select is the 'key' node (just before the following-sibling::dict) one.
The xml is like this :
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>en_GB</key>
<dict>
<key>Africa</key>
<dict>
<key>Algeria</key>
<dict>
<key>60390</key>
<dict>
<key>NAME</key>
<string>Algier</string>
<key>LATITUDE</key>
<string>36.7500</string>
<key>LONGITUDE</key>
<string>3.0500</string>
</dict>
<key>60391</key>
<dict>
<key>NAME</key>
<string>Some other city</string>
<key>LATITUDE</key>
<string>36.7500</string>
<key>LONGITUDE</key>
<string>3.0500</string>
</dict>
</dict>
</dict>
</dict>
</dict>
</plist>
In other words, I want to select '60390' when the city name is 'Algier' or (60391 when city name is 'some other city').
I'm doing this in a QML XmlListModel.
Updated code
QML used:
import QtQuick 1.0
Rectangle {
id: container;
width: 360
height: 360
function onLocationModelLoaded(){
console.debug(weLocationModel.count);
}
XmlListModel{
id: weLocationModel;
source: "we_locations.plist";
query: "/*/dict/dict/dict/dict/key[following-sibling::dict[1]/key[.='NAME' and following-sibling::string[1] = 'Algier']]"
XmlRole{
name: "cityId";
query: "name()";
}
onStatusChanged: {
if (status == XmlListModel.Ready){
console.debug("Location Model Ready");
container.onLocationModelLoaded();
}
}
}
}
It seems like the nested following-sibling is not working.
for example something like:
query: "/*/dict/dict/dict/dict/key[following-sibling::dict[1]/key[.='NAME']]"
Both of these always return:
Error XPST0003 in file:///Users/Ali/qtprojects/welocationtest-build-simulator/welocationtest.app/Contents/MacOS/welocationtest, at line 2, column 97: syntax error, unexpected ], expecting )
Error XPST0003 in file:///Users/Ali/qtprojects/welocationtest-build-simulator/welocationtest.app/Contents/MacOS/welocationtest, at line 2, column 91: syntax error, unexpected ], expecting end of file
file:///Users/Ali/qtprojects/welocationtest-build-simulator/welocationtest.app/Contents/Resources/qml/welocationtest/main.qml:17:9: QML XmlRole: invalid query: "name()"
Location Model Ready
0
Could it be possible QML is not following XPath standard? THe solution works in all other path editors.
A: One XPath expression that selects exactly the wanted key element is this:
/*/dict/dict/dict/dict
/key
[following-sibling::dict[1]/key
[.='NAME'
and
following-sibling::string[1] = $pCity
]
]
When $pCity is set/substituted-by "Algier", this XPath expression selects:
<key>60390</key>
When $pCity is set/substituted-by "Some other city", this XPath expression selects:
<key>60391</key>
XSLT-based verification:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:param name="pCity" select="'Some other city'"/>
<xsl:template match="/">
<xsl:copy-of select=
"/*/dict/dict/dict/dict
/key
[following-sibling::dict[1]/key
[.='NAME'
and
following-sibling::string[1] = $pCity
]
]
"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied against the provided XML document:
<plist version="1.0">
<dict>
<key>en_GB</key>
<dict>
<key>Africa</key>
<dict>
<key>Algeria</key>
<dict>
<key>60390</key>
<dict>
<key>NAME</key>
<string>Algier</string>
<key>LATITUDE</key>
<string>36.7500</string>
<key>LONGITUDE</key>
<string>3.0500</string>
</dict>
<key>60391</key>
<dict>
<key>NAME</key>
<string>Some other city</string>
<key>LATITUDE</key>
<string>36.7500</string>
<key>LONGITUDE</key>
<string>3.0500</string>
</dict>
</dict>
</dict>
</dict>
</dict>
</plist>
the wanted, correct result is produced:
<key>60391</key>
When in the above transformation we replace:
<xsl:param name="pCity" select="'Some other city'"/>
with:
<xsl:param name="pCity" select="'Algier'"/>
and apply the transformation again, then again we get the correct result:
<key>60390</key>
A: To get the number for a city you can use a RegEx, too (especially if QML XPath support is not good enough):
import QtQuick 1.0
Rectangle {
id: container
width: 360
height: 360
Component.onCompleted: {
loadWeLocationsFile();
}
property string weLocationsXML
signal weLocationsLoaded()
function loadWeLocationsFile() {
// load file
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
// get file content
weLocationsXML = doc.responseText;
// emit signal
weLocationsLoaded();
}
}
doc.open("GET", "we_locations.plist");
doc.send();
}
function getIDByName(name) {
// escape special characters for regex (maybe there is a better way to do this)
var safeName = name.replace(/[-.,?+*#^$()[\]{}\\|]/g, "\\$&");
// create regex
var regex = new RegExp("<key>(.*?)</key>\\s*<dict>\\s*<key>NAME</key>\\s*<string>" + safeName + "</string>", "m");
// execute regex
var match = regex.exec(weLocationsXML);
if (match != null && match.length > 1) {
return match[1]; // name found, group 1 contains id
} else {
return null; // no such name in XML
}
}
// Test it ...
onWeLocationsLoaded: {
console.log("Number for 'Algier':", getIDByName("Algier"));
console.log("Number for 'NotInXML':", getIDByName("NotInXML"));
console.log("Number for 'Some other city':", getIDByName("Some other city"));
}
}
Output:
Number for 'Algier': 60390
Number for 'NotInXML': null
Number for 'Some other city': 60391
If you need the number in a QML model you can create a ListModel and add the number to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Save a SecKeyRef Asymmetric Key Pair to disk as a Certificate I have created two SecKeyRef items via SecKeyGeneratePair, but now I would like to turn the public key into a x509 Digital Certificate – and/or both the public and private keys into a PKCS #12 (.p12) certificate – and save it to disk as a file. This way I can do whatever I need to with it, including sending the certificates to other services or computers.
I would prefer to not use the keychain, but even with that I am having some trouble finding good documentation on exactly how to create a certificate out of a pair of SecKeyRefs, and writing them out as a certificate file.
A: You want the Security Transforms Programming Guide. It covers most of what you need for this. Some parts (like SecItemExport) are not documented in the reference documentation, only in the public header files. But SecItemExport is the new 10.7 way to handle this stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I continually update when UISlider is past a certain value? I'm implementing a UISlider that allows users to select a position on a football field. The idea of the slider is for the field to scroll forward when the slider value is above a certain value (the section with the arrow).
My issue is that I can only respond to the slider on UIControlEventValueChanged - so the field will only scroll forward when the user is actually moving the slider. I'd like it to move forward as long as the value is above a certain amount.
Any idea how I can do this? (I'm open to any suggestion, including an implementation that does not use a UISlider, composite implementations, etc.).
Here's the implementation:
A: The easiest way to handle this is with a timer. Add an NSTimer instance variable to your class, named—for the sake of the example below—moveTimer, then set up something like this:
- (void)sliderChanged:(UISlider *)slider
{
if(slider.value > 5)
{
if(moveTimer == nil)
{
moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self action:@selector(move) repeats:YES];
}
}
else
{
if(moveTimer != nil)
{
[moveTimer invalidate];
moveTimer = nil;
}
}
}
- (void)move
{
// update the background behind your slider
}
A: I found a solution that works for me:
[self performSelector:@selector(sliderMoved) withObject:nil afterDelay:0.5];
I call the sliderMoved method after every 0.5 seconds when slider.value > 0.5.
A: Try setting the continuous property of the slider to YES.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery Datepicker beforeShowDay - range selected
I'm doing a website for an hotel, and I'm trying to do a datepicker to book the days that somebody wants to stay there.
http://jsfiddle.net/newpatriks/PmPGV/
Here you have that I have done, but I've some problems:
*
*I don't know why, but when the users select the range days, the calendar starts from the month that contains the "end day" choosen.
*The css run ok for the .temp_1, but not going well for the .temp_2 and .date_selected (I'm going crazy about this...)
Thanks a lot :)
A: JQuery Datepicker has a built in range select: datepicker/date-range.
Here is an example from the following question: jQuery datepicker- 2 inputs/textboxes and restricting range
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Simple Question About the jQuery Datepicker's Calendar Icon Sorry for the simple question.
I'm using a jQuery DatePicker. I want the little calendar icon to appear next to the text input area. I'm using the Smoothness jQuery UI theme.
Does jQuery UI include the calendar.gif icon (not the datepicker itself, but just the little icon)? If not, can you suggest where I can get a free small calendar.gif?
As I understand it, I add the calendar as follows:
buttonImage: 'images/calendar.gif'
Thank you.
A: You could use the built in icons from jQuery UI; there is a calendar icon. The code is something like:
$("#datepicker").datepicker({
showOn: 'button'
}).next('button').text('').button({
icons: {
primary: 'ui-icon-calendar'
},
text: false
});
See it in action: http://jsfiddle.net/william/rrcmq/.
It is inspired by this article: http://www.somethinghitme.com/2010/10/06/use-built-in-jquery-ui-icon-with-datepicker/.
A: I far as I know it does not. I provided my own when I used the datepicker with one but I already had an icon.
You can google it but there are some free icons here: http://findicons.com/search/calendar
A: Just go to JQueryUI site then click Demo and choose Dateicker and select icon trigger example. You will on this page(datepicker icon-trigger example), and the page will look like below picture.
Now you right click on the calendar icon marked by yellow and download it by choose "Save Image As..." and include it in your project than buttonImage: 'images/calendar.gif' will work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: MATLAB - Plotting multiple graphs I am new to MATLAB and am having difficulty plotting multiple graphs. Here are my vectors to graph:
S = [1.2421
2.3348
0.1326
2.3470
6.7389
3.7089
11.8534
-1.8708
...]
Y = [1.1718
1.8824
0.3428
2.1057
1.6477
2.3624
2.1212
-0.7971
...]
w = [0.1753
0.3277]
S is my training data and Y is my output vector. Then I add a column vector to my training data:
O = ones(length(S), 1)
X = [S 0]
w = inv(X'*X)*X'*Y
So I am trying to plot X, Y and w on the same graph. I plot w first, hold, X and this is where I get lost. Basically they are not on the same scale because the size of x is much less than X (X and Y are both vectors of size 100 and w is of size 2).
plot(w)
Then I do:
hold
plot(X)
Now the w that I plotted is so small compared to the plot of X. How would I make them the same scale? Also maybe making them a different color?
A: plotyy will create the figure you are looking for. See the examples in the link for further plot customization.
A: I'd just comment, but I don't have enough reputation... If you are not aiming to present the data, but just be able to visualize it, you can rescale your datasets and avoid the not-so-easy-to-work-with plotyy (although it is the best answer):
W = W/max(W);
X = X/max(X);
plot(W)
hold on
plot(X)
For additional formating of the plots, see mathworks polt. There you can change color, linewidth and whatnot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: content management - global variables This is how I manage content on my site:
PageLoader.class
class PageLoader {
private $page_dir;
private $page_headers = '';
private $page_html = '';
public function __construct($page_dir)
{
$this->page_dir = $page_dir;
}
public function load()
{
$file_found = false;
ob_start();
$file_found = include("./{$this->page_dir}");
$file_contents = ob_get_contents();
ob_end_clean();
if($file_found != false)
{
$this->page_html = $file_contents;
}
}
public function outputBody()
{
echo $this->page_html;
}
}
index.php
$connection = mysql_connect(....);
$is_user_logged = login(...);
$view = new PageLoader($_GET['page']);
$view->load();
?>
<html>
<head>
<? $view->outputHeaders(); ?>
</head>
<body>
<? $view->outputBody(); ?>
</body>
</html>
One problem with this:
Those two variables $connection and $is_user_logged_in are not accessible from within load() method. Most of my inner pages depend on those variables for various reasons. Since they both appear NULL in that scope, inner pages fail to function.
This could solve the problem: $view->setVariable("connection", $connection) but I have a lot more than 2 'main' variables so I'm not sure if this is the best way...
What can I do? Feel free to suggest any alternative ways for me to manage my content as my way is probably the least professional...
A: The immediate answer to your question is: Import global variables.
In php global variables have to be explicitly "imported". This is done with the global keyword:
$gvar = "asdfad";
function myfunction()
{
global $gvar;
echo $gvar;
}
This however doesn't seem as the best idea, because this means that your class is not a logical independent unit.
You probably should declare properties in the class (that hold the required data) and are set at some external initialization (like a constructor).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AJAX blocking Javascript Consider the following code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
});
</script>
The first script is for background changing logic and the second script gives list of thumbnails of the themes. The problem is that the first script doesn't work beacause of the second. If I don't use this AJAX technique everything works fine. Working code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<div id="dcontent">
<?php include('printThumbs.php'); printThemesThumbs();?>
</div>
The background changing logic looks like:
$(function() {
$('.themes li a img').click(function() {//code
});
Any help will be greatly appreciated.
A: in your first snippet of the code you defined a click function on .Theme and in the third snippet of the code .theme, is this correct?, i mean both classes seems to be different try to use the same class name return by your php function.
A: you have to add your second code in a callback function. you can't bind something if it is not already in the dom. if you want to make changes to the printThumbs output you need to add a callback...
<script>
$(document).ready(function() {//this is also a callback function when document is ready
$('.Themes').click(function(){//this can be understand as a call back too... code is fired after a click
$('#dcontent').load('printThumbs.php',function(){/*your callback code here...this code will be fired after you've loaded printThumbs*/}
});
});
</script>
if you want to do some jquery or other client side stuff on the respons of an ajax call (html,xml, json or whatever) you have to specify a callback function. to make things less complicated you have to look at the callback function just as the on document ready function with the difference that the callback is applied to the respons of your ajax call. if the code is not in a callback function you can't manipulate the respons because it is not injected in the dom/it simply does not exists in your browser when the document is ready.
A: You're calling $(document).ready() twice, as $() is an alias, and the second definition is overwriting the first. First you are setting the document ready callback to
function() {
$('.themes li a img').click(function() {//code
}
and then overwriting it with
function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with android layout files in Eclipse I am facing strange problem while developing my android apps in Eclipse. Whenever I click on any xml file under layout folder eclipse shuts down.If I open any xml file from other location then it works fine.I tried deleting / creating new projet, Eclipse restart, PC restart but no luck.
Here is the log which is generated in Eclipse folder when Eclipse shuts down
#
# An unexpected error has been detected by HotSpot Virtual Machine:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d252e14, pid=3236, tid=332
#
# Java VM: Java HotSpot(TM) Client VM (1.5.0-b64 mixed mode)
# Problematic frame:
# C [fontmanager.dll+0x12e14]
#
--------------- T H R E A D ---------------
Current thread (0x00858f68): JavaThread "main" [_thread_in_native, id=332]
siginfo: ExceptionCode=0xc0000005, reading address 0x2500212c
Registers:
EAX=0x25002000, EBX=0x076ac700, ECX=0x0012ddc4, EDX=0x00010014
ESP=0x0012dd2c, EBP=0x0012dd88, ESI=0x00b6e800, EDI=0x00000800
EIP=0x6d252e14, EFLAGS=0x00010206
Top of Stack: (sp=0x0012dd2c)
0x0012dd2c: 00000000 0012ddb4 6d24e9e4 00b6e800
0x0012dd3c: 076ac700 03ab5fa0 340a6450 00000000
0x0012dd4c: 0012dd4c 340ca05d 0012dd74 340ca440
0x0012dd5c: 00000000 67ea0028 0012dd64 34a45f10
0x0012dd6c: 0012dd88 34a46508 00000000 34a45f60
0x0012dd7c: 0000000c 146e35e0 00c45de0 0012ddc8
0x0012dd8c: 6d2617ec 076ac700 00000001 00000048
0x0012dd9c: 00000048 0012ddb4 00000001 0012ddc4
Instructions: (pc=0x6d252e14)
0x6d252e04: ff 15 30 c0 26 6d 83 c4 0c 8b 46 04 85 c0 74 09
0x6d252e14: 66 8b b8 2c 01 00 00 eb 1b 8b 46 08 85 c0 74 09
Stack: [0x00030000,0x00130000), sp=0x0012dd2c, free space=1015k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C [fontmanager.dll+0x12e14]
C [fontmanager.dll+0x217ec]
C [fontmanager.dll+0x21ecc]
j sun.font.FileFont.getFontMetrics(J)Lsun/font/StrikeMetrics;+0
j sun.font.FileFontStrike.getFontMetrics()Lsun/font/StrikeMetrics;+16
j sun.font.FontDesignMetrics.initMatrixAndMetrics()V+28
j sun.font.FontDesignMetrics.<init>(Ljava/awt/Font;Ljava/awt/font/FontRenderContext;)V+62
j sun.font.FontDesignMetrics.<init>(Ljava/awt/Font;)V+5
j sun.awt.SunToolkit.getFontMetrics(Ljava/awt/Font;)Ljava/awt/FontMetrics;+44
j sun.awt.windows.WToolkit.getFontMetrics(Ljava/awt/Font;)Ljava/awt/FontMetrics;+13
j android.graphics.Paint_Delegate.updateFontObject()V+140
j android.graphics.Paint_Delegate.setTextSize(Landroid/graphics/Paint;F)V+25
j android.graphics.Paint.setTextSize(F)V+2
j android.widget.TextView.setRawTextSize(F)V+17
j android.widget.TextView.<init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V+2609
j android.widget.EditText.<init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V+4
j android.widget.AutoCompleteTextView.<init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V+4
j android.widget.AutoCompleteTextView.<init>(Landroid/content/Context;Landroid/util/AttributeSet;)V+5
v ~StubRoutines::call_stub
V [jvm.dll+0x8168d]
V [jvm.dll+0xd4179]
V [jvm.dll+0x8155e]
V [jvm.dll+0xe44fe]
V [jvm.dll+0x9f405]
C [java.dll+0x6bee]
j sun.reflect.NativeConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object;+72
J sun.reflect.DelegatingConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object;
j java.lang.reflect.Constructor.newInstance([Ljava/lang/Object;)Ljava/lang/Object;+92
j android.view.LayoutInflater.createView(Ljava/lang/String;Ljava/lang/String;Landroid/util/AttributeSet;)Landroid/view/View;+269
j com.android.layoutlib.bridge.android.BridgeInflater.onCreateView(Ljava/lang/String;Landroid/util/AttributeSet;)Landroid/view/View;+34
j android.view.LayoutInflater.createViewFromTag(Ljava/lang/String;Landroid/util/AttributeSet;)Landroid/view/View;+65
j com.android.layoutlib.bridge.android.BridgeInflater.createViewFromTag(Ljava/lang/String;Landroid/util/AttributeSet;)Landroid/view/View;+5
j android.view.LayoutInflater.rInflate(Lorg/xmlpull/v1/XmlPullParser;Landroid/view/View;Landroid/util/AttributeSet;)V+139
j android.view.LayoutInflater.inflate(Lorg/xmlpull/v1/XmlPullParser;Landroid/view/ViewGroup;Z)Landroid/view/View;+176
j android.view.LayoutInflater.inflate(Lorg/xmlpull/v1/XmlPullParser;Landroid/view/ViewGroup;)Landroid/view/View;+12
j com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate()Lcom/android/ide/common/rendering/api/Result;+292
j com.android.layoutlib.bridge.Bridge.createSession(Lcom/android/ide/common/rendering/api/SessionParams;)Lcom/android/ide/common/rendering/api/RenderSession;+36
j com.android.ide.common.rendering.LayoutLibrary.createSession(Lcom/android/ide/common/rendering/api/SessionParams;)Lcom/android/ide/common/rendering/api/RenderSession;+12
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession()Lcom/android/ide/common/rendering/api/RenderSession;+558
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.PreviewIconFactory.render()Z+385
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.PreviewIconFactory.initColors()V+22
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.PreviewIconFactory.getBackgroundColor()Lorg/eclipse/swt/graphics/RGB;+8
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.PaletteControl.reloadPalette(Lcom/android/sdklib/IAndroidTarget;)V+305
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.reloadPalette()V+21
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart$ConfigListener.onConfigurationChange()V+277
j com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.onTargetChange()V+17
j com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor.onDescriptorsChanged(Lorg/w3c/dom/Document;)V+48
j com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor.initUiRootNode(Z)V+99
j com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor.xmlModelChanged(Lorg/w3c/dom/Document;)V+10
j com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor$XmlModelStateListener.modelChanged(Lorg/eclipse/wst/sse/core/internal/provisional/IStructuredModel;)V+12
j com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor.createTextEditor()V+140
j com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor.createAndroidPages()V+10
j com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor.addPages()V+1
j org.eclipse.ui.forms.editor.FormEditor.createPages()V+1
j org.eclipse.ui.part.MultiPageEditorPart.createPartControl(Lorg/eclipse/swt/widgets/Composite;)V+16
j org.eclipse.ui.internal.EditorReference.createPartHelper()Lorg/eclipse/ui/IEditorPart;+321
j org.eclipse.ui.internal.EditorReference.createPart()Lorg/eclipse/ui/IWorkbenchPart;+27
J org.eclipse.ui.internal.WorkbenchPartReference.getPart(Z)Lorg/eclipse/ui/IWorkbenchPart;
j org.eclipse.ui.internal.EditorReference.getEditor(Z)Lorg/eclipse/ui/IEditorPart;+2
j org.eclipse.ui.internal.WorkbenchPage.busyOpenEditorBatched(Lorg/eclipse/ui/IEditorInput;Ljava/lang/String;ZILorg/eclipse/ui/IMemento;)Lorg/eclipse/ui/IEditorPart;+233
j org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(Lorg/eclipse/ui/IEditorInput;Ljava/lang/String;ZILorg/eclipse/ui/IMemento;)Lorg/eclipse/ui/IEditorPart;+27
j org.eclipse.ui.internal.WorkbenchPage.access$11(Lorg/eclipse/ui/internal/WorkbenchPage;Lorg/eclipse/ui/IEditorInput;Ljava/lang/String;ZILorg/eclipse/ui/IMemento;)Lorg/eclipse/ui/IEditorPart;+8
j org.eclipse.ui.internal.WorkbenchPage$10.run()V+29
j org.eclipse.swt.custom.BusyIndicator.showWhile(Lorg/eclipse/swt/widgets/Display;Ljava/lang/Runnable;)V+116
j org.eclipse.ui.internal.WorkbenchPage.openEditor(Lorg/eclipse/ui/IEditorInput;Ljava/lang/String;ZILorg/eclipse/ui/IMemento;)Lorg/eclipse/ui/IEditorPart;+59
j org.eclipse.ui.internal.WorkbenchPage.openEditor(Lorg/eclipse/ui/IEditorInput;Ljava/lang/String;ZI)Lorg/eclipse/ui/IEditorPart;+7
j org.eclipse.ui.internal.WorkbenchPage.openEditor(Lorg/eclipse/ui/IEditorInput;Ljava/lang/String;Z)Lorg/eclipse/ui/IEditorPart;+5
j org.eclipse.ui.ide.IDE.openEditor(Lorg/eclipse/ui/IWorkbenchPage;Lorg/eclipse/core/resources/IFile;ZZ)Lorg/eclipse/ui/IEditorPart;+36
j org.eclipse.ui.ide.IDE.openEditor(Lorg/eclipse/ui/IWorkbenchPage;Lorg/eclipse/core/resources/IFile;Z)Lorg/eclipse/ui/IEditorPart;+4
j org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor(Lorg/eclipse/core/resources/IFile;Z)Lorg/eclipse/ui/IEditorPart;+27
j org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor(Ljava/lang/Object;Z)Lorg/eclipse/ui/IEditorPart;+12
j org.eclipse.jdt.ui.actions.OpenAction.run([Ljava/lang/Object;)V+59
j org.eclipse.jdt.ui.actions.OpenAction.run(Lorg/eclipse/jface/viewers/IStructuredSelection;)V+16
j org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(Lorg/eclipse/jface/viewers/ISelection;)V+12
j org.eclipse.jdt.ui.actions.SelectionDispatchAction.run()V+5
j org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup.handleOpen(Lorg/eclipse/jface/viewers/ISelection;Z)V+22
j org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4.open(Lorg/eclipse/jface/viewers/ISelection;Z)V+9
j org.eclipse.ui.OpenAndLinkWithEditorHelper$InternalListener.open(Lorg/eclipse/jface/viewers/OpenEvent;)V+25
j org.eclipse.jface.viewers.StructuredViewer$2.run()V+8
J org.eclipse.core.runtime.SafeRunner.run(Lorg/eclipse/core/runtime/ISafeRunnable;)V
J org.eclipse.ui.internal.JFaceUtil$1.run(Lorg/eclipse/core/runtime/ISafeRunnable;)V
v ~RuntimeStub::alignment_frame_return Runtime1 stub
j org.eclipse.jface.util.SafeRunnable.run(Lorg/eclipse/core/runtime/ISafeRunnable;)V+4
j org.eclipse.jface.viewers.StructuredViewer.fireOpen(Lorg/eclipse/jface/viewers/OpenEvent;)V+32
j org.eclipse.jface.viewers.StructuredViewer.handleOpen(Lorg/eclipse/swt/events/SelectionEvent;)V+31
j org.eclipse.jface.viewers.StructuredViewer$6.handleOpen(Lorg/eclipse/swt/events/SelectionEvent;)V+5
j org.eclipse.jface.util.OpenStrategy.fireOpenEvent(Lorg/eclipse/swt/events/SelectionEvent;)V+38
J org.eclipse.jface.util.OpenStrategy$1.handleEvent(Lorg/eclipse/swt/widgets/Event;)V
J org.eclipse.swt.widgets.EventTable.sendEvent(Lorg/eclipse/swt/widgets/Event;)V
J org.eclipse.swt.widgets.Display.runDeferredEvents()Z
J org.eclipse.swt.widgets.Display.readAndDispatch()Z
J org.eclipse.ui.internal.Workbench.runEventLoop(Lorg/eclipse/jface/window/Window$IExceptionHandler;Lorg/eclipse/swt/widgets/Display;)V
v ~OSRAdapter
j org.eclipse.ui.internal.Workbench.runUI()I+393
j org.eclipse.ui.internal.Workbench.access$4(Lorg/eclipse/ui/internal/Workbench;)I+1
j org.eclipse.ui.internal.Workbench$5.run()V+55
j org.eclipse.core.databinding.observable.Realm.runWithDefault(Lorg/eclipse/core/databinding/observable/Realm;Ljava/lang/Runnable;)V+12
j org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Lorg/eclipse/swt/widgets/Display;Lorg/eclipse/ui/application/WorkbenchAdvisor;)I+18
j org.eclipse.ui.PlatformUI.createAndRunWorkbench(Lorg/eclipse/swt/widgets/Display;Lorg/eclipse/ui/application/WorkbenchAdvisor;)I+2
j org.eclipse.ui.internal.ide.application.IDEApplication.start(Lorg/eclipse/equinox/app/IApplicationContext;)Ljava/lang/Object;+84
...<more frames>...
And it grows to two more pages. Any guess / suggestion ?
PS : I will really appreciate if anybody can edit my question as I am not sure what should be exactly asked / mentioned.
Thanks,
Ajinkya.
A: Old JRE version was causing this issue. Updated JRE and BOOM :)
Eclipse crashes when I invoke Android Layout Editor
A: One thing that worked for me is to right-click the layout file and open is as another type (say text file or another xml format options in there). I used to have these errors on Ant xml files when I worked on them and this shortcut worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "NOT EXISTS" in swi-prolog I'm stuck on a simple problem in prolog.
Let's consider the program
worker(bill).
worker(smitt).
worker(fred).
worker(dany).
worker(john).
car(bmw).
car(mazda).
car(audi).
owner(fred,mazda).
owner(dany,bmw).
owner(john,audi).
I need to add one more predicate no_car(X),that will be true if the worker X has no cars,i.e,if we input a query
?:- no_car(X).
the prolog should answer
X=smitt,
X=bill,
yes
What i have done is
hascar(X):-owner(X,_).
nocar(X):- worker(X),not hascar(X).
But this approach does not work because anonimous variables are avaliable only for queries.
So,i'm really stuck on this.
I know there are "NOT EXISTS" words in SQL which allow to express this logic in a query,but is there something similar to them in prolog?
A: The following works for me and provides the expected result:
no_car(W):-
worker(W),
\+ owner(W, _).
Now this is close to what you have. For one thing, you can of course use _ in predicates; it is not restricted to queries. I usually use \* for negation, and not gives me a syntax error here!?
EDIT:
Ah! In my, albeit dated, version of Prolog you have to use not(hascar(X)) to make it work, so not/1 needs to be used as a term, not an operator. But the manual also says not is deprecated in favor of \+.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using Selenium to click on an element which is in nested
* My page looks like the code given below in inspect element mode.
I have series of li tags inside div tags, whose ids are dynamically created while I load the page.
I need to click on Summary, intent, conversion elements.
Can anyone please help me how to do this in selenium RC.
The ids are dynamically generated so I cannot use the id option here. For example : the id yui_3_3_0_1_131676060142810944 is dynamically generated. Using xpath also, I could not click on these elements.
Please let me know if there is a way out. It would be very helpful for me.
The actual inspected source is here if it might help in looking into this.
http://paste.ubuntu.com/696262/
A: Here is the DOM tree with nested div
<div class="aui-helper-clearfix aui-tree-node-content aui-tree-data-content aui-tree-node- content aui-tree-node-selected aui-tree-expanded" id="aui_3_4_0_1_1005">
<div class="aui-tree-hitarea" id="aui_3_4_0_1_1224">
</div><div class="aui-tree-icon" id="aui_3_4_0_1_1214">
</div><div class="aui-tree-label aui-helper-unselectable" id="aui_3_4_0_1_1218">OSS</div> </div>
Here is the xpath that selects the clickable node (for Selenium)
$x("//div[contains(@class,'aui-tree-node-content') and (contains(.,'OSS'))]//div[contains(@class,'aui-tree-hitarea')]")
A: The obvious answer is:
selenium.click("link=Summary");
...
selenium.click("link=Intent");
...
selenium.click("link=Conversion");
...
A little less obvious would be:
selenium.click("xpath=//*[@id='reports-subtab-summary']/a");
...
selenium.click("xpath=//*[@id='reports-subtab-intent']/a");
...
selenium.click("xpath=//*[@id='reports-subtab-conversions']/a");
...
which has the advantage that it doesn't depend on page-text that might change (due to language translation, etc.).
A: You can use css path for example:
html body#gsr div#searchform.jhp form#tsf div.tsf-p div table tbody tr td table tbody tr td#sftab.lst-td div.lst-d table.lst-t tbody tr td table tbody tr td.gsib_a div input#lst-ib.gsfi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the right Scala and Java collection combination to use with nested JAXB? Working with JAXB, the standard way of dealing with a list of "nested" resource representations (e.g. <products><product>X</product><product>Y</product></products> is to create a wrapper object, which in Java might look like this (borrowed from Jhopify):
@XmlType(name = "")
@XmlRootElement(name = "products")
public class ProductList {
List<Product> products = new ArrayList<Product>();
@XmlElement(name = "product", required = true)
public List<Product> getProducts() { return products; }
public void setProducts(List<Product> products) { this.products = products; }
}
However I'm struggling to determine exactly which collection objects to use when translating this to Scala. There's a good introductory post to doing this on the Mostly Blather blog, which uses a Scala Iterable implicitly converted (using JavaConversions) to and from a JCollection.
This works great for marshalling a JAXB class to XML but unfortunately when unmarshalling this throws UnsupportedOperationException on each add attempt. Based on the last paragraph on this Scala documentation page it looks like this happens because Java does not distinguish between mutable and immutable collections in their type.
To deal with the unmarshalling, I've tried an alternative approach specifically using mutable objects:
@XmlType(name = "")
@XmlRootElement(name = "products")
class ProductList {
private var products: Buffer[Product] = new ArrayBuffer[Product]
@XmlElement(name = "product", required = true)
def getProducts: JList[Product] = products
def setProducts(products: JList[Product]) {
this.products = products
}
}
But unfortunately with this approach, unmarshalling gives me an exception:
java.lang.NoSuchMethodError: ProductList.getProducts()Ljava/util/Collection;
Edit: as per Travis' request, here is my unmarshalling code:
val jaxbContext = JAXBContext.newInstance(ProductList.getClass())
val unmarshaller = jaxbContext.createUnmarshaller()
val root = unmarshaller.unmarshal(new StreamSource(new StringReader(responseString)), ProductList.getClass())
val r = root.getValue().asInstanceOf[ProductList]
val representations = r.getProducts.asScala.toList // Uses scalaj
So I'm a bit stumped... I've looked at scalaj's available conversions too but nothing obvious jumps out. Any help much appreciated!
A: Could you post your unmarshalling code? I've done something similar with JAXB from Scala, and what you have looks like it should work. Here's a complete working example:
import javax.xml.bind.annotation._
class Thing {
@scala.reflect.BeanProperty var name: String = _
}
@XmlRootElement(name = "things")
class Things {
import scala.collection.JavaConversions._
import scala.collection.mutable.Buffer
private var things: Buffer[Thing] = Buffer[Thing]()
@XmlElement(name = "thing", required = true)
def getThings: java.util.List[Thing] = this.things
def setThings(things: java.util.List[Thing]) {
this.things = things
}
}
I'll write the test code in Scala as well, but it would work identically in Java.
object Things {
import java.io.StringReader
import java.io.StringWriter
import javax.xml.bind.JAXBContext
def main(args: Array[String]) {
val thing1 = new Thing
val thing2 = new Thing
thing1.setName("Thing 1")
thing2.setName("Thing 2")
val list: java.util.List[Thing] = new java.util.ArrayList[Thing]
list.add(thing1)
list.add(thing2)
val things = new Things
things.setThings(list)
val context = JAXBContext.newInstance(classOf[Things])
val writer = new StringWriter
context.createMarshaller.marshal(things, writer)
println(writer.toString)
val readThings = context.createUnmarshaller().unmarshal(
new StringReader(writer.toString)
).asInstanceOf[Things]
println("Size: " + readThings.getThings.size)
println("Name of first: " + readThings.getThings.get(0).getName)
}
}
This compiles and produces the output you'd expect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to generate 12 different Brush Colors at run time (12 is a number that may vary) I want to generate 12 different visible Brush Colors in WPF in my code behind and the number of colors which is initially 12 may vary as the application evolves i.e. I want to generate as many different visible Brush Colors depending on a given count?
I would explain it a little more:
I am creating Rectangles in a for loop and for each rectangle created at run time I have to assign a Fill Color e.g.
for (i=0; i<12; i++)
{
Rectangle rect = new Rectangle();
rect.Fill = <I want to assign a unique visible color>;
rect.Stroke = Brushes.Black;
rect.StrokeThickness = 1;
}
A: What you probably need is an RGB to HSL, and HSL to RGB converter. You can then divide the total hue (usually represented as degrees in a circle, but sometimes a percent value) by the number of colors required. Incrementing the hue value by the segment amount should produce the most differentiated colors possible.
Most examples use the WinForms Color object since it was able to provide H S and L values. There are lots of online examples:
https://web.archive.org/web/20141023005253/http://bobpowell.net/RGBHSB.aspx
how to use HSL in Asp.net
A: Brushes can be assigned colors, This SO question should help you in getting the colors, and then assign them each time you create a new brush for any number of brushes.
Just for reference:
Brush Class
Brushes class
A: Use a random number generator to create the RGB triple for the colour. Save it in a list. Then the next time round the loop check the newly generated colour against the list. If it's not in the list use it, if it is choose again.
Potentially this could run into trouble if you have a lot of colours so you're more and more likely to hit an existing colour, but for 12 (or so) colours it should be OK.
Alternatively create a list of 100's of colours and remove each one from the list when it's picked randomly. This will ensure you don't get any clashes but would require you extend the list if you needed more colours.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to disable Ctrl+V in windows? How can i disable Ctrl+V shortcut-key in windows and handle it by my own application? Actually , i want to ignore it and send another key instead of Ctrl+V.
A: You can use RegisterHotKey() to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to self destruct an object in objective-c? My object finish their job. He have the control of work flow, but now it have to call a function in the object that create it and have to be released. The problem is like this:
AnObject *object;
- (void)function
{
object = [[AnObject alloc] init];
[object doYourJob];
//The program continue to run next line, it don't stop here. So, I can't send a [object release] here
}
- (void)callThisWhenFinish
{
//do something
//can't call [object release] because it is in the stack and run a line of a released object
}
So, how can I release the memory of object, I try this:
*
*Send a [object release] in callThisWhenFinish or in function. - Fail! The program still have to run some lines of AnObject.
*Use delegate way to run callThisWhenFinish. - Fail! I cant release AnObject because it try to run the next line when the function callThisWhenfinish finish.
*Use a NSNotificationCenter to post a notification to callThisWhenFinish. Fail! When I post notification it immediate call the callThisWhenFinish and AnObject can run the next line and it is release, causing a crash.
*Use the same NSNotificationCenter with a delay on it. How safe is this way? How can I know that AnObject will not be called again?
*Use the [object autorelease]. This work, but I don't know when it is done. My AnObject use a lot of RAM and have to be free as fast as possible.
Any other idea?
A: If your object is doing background work, it is a good idea to have it retain itself during that time. That way, you don't have to worry about it being deallocated until it is done. Your function method can safely release it after starting the action, but it won't be deallocated until it is ready to be.
AnObject *object;
- (void)function {
object = [[AnObject alloc] init];
[object doYourJob];
[object release];
}
- (void)callThisWhenFinish {
//do something
}
In AnObject:
- (void)doYourJob {
[self retain];
// enter background and call backgroundMethod
}
- (void)backgroundMethod {
// This is the method which doYourJob calls in the background to do the work
// Do some work
[delegate callThisWhenFinish];
// do whatever else needs to be done
[self release];
}
A: If you can't make it an ivar, why not something like this:
- (void)callThisWhenFinishAndRelease:(id)obj
Then you have a pointer to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: BitShifting, Storing 3 u_int8_t in one integer and read out again i have a question for you guys which is driving me nuts for 2 days already. Maybe its because i am missing the basics on bit shifting but somehow i don't get it into my head. What i want is a simple program which reads in 3 char or uint8_t's, stores them into one big int and then reads it out later again.
It is the first time that i experiment with bit shifting, and somehow i am stuck.
This is the code:
int main (int argc, const char * argv[])
{
u_int8_t insert1;
u_int8_t insert2;
u_int8_t insert3;
int data;
printf("Please enter value1: ");
scanf("%d", &insert1);
printf("Please enter value2: ");
scanf("%d", &insert2);
printf("Please enter value3: ");
scanf("%d", &insert3);
data |= insert3<<16 | insert2<<8 | insert1;
printf("\nValue1: %d\n", data);
printf("Value2: %d\n", data>>8);
printf("Value3: %d\n", data>>16);
return 0;
}
When i Enter
126
103
255
i get:
Value1: 16711680
Value2: 65280
Value3: 255
Which is completely wrong. I am pretty sure that the value is stored correctly stored into data but i don't know how to read out.
Thanks very much :-)
A: You never initialized data and you're doing this:
data |=
Either initialize it to zero or change the line to this:
data = insert3<<16 | insert2<<8 | insert1;
A: You have three errors:
*
*you're passing a pointer to a uint8_t to scanf, but you're using the %d conversion which expect a pointer to an int; you need to use %hhd to tell scanf that you are using a storage the size of a char, otherwise you risk to corrupt your stack; or you can change your variables to be of int type, or better (since the question is tagged C++) use the std::istream extraction operator (operator >>) that is type-safe
*you didn't initialize data, and used the |=, thus mixing uninitialized value with your user entered values (which will produce garbage)
*when using printf, you need to mask the high-order bit if you only want to see the low order bits
So, your code need to read:
#include <iostream>
static void readvalue(const char* name, uint8_t& outValue) {
std::cout << "Please enter " << name << ": " << std::flush;
std::cin >> outValue;
std::cout << "\n";
}
int main() {
uint8_t value1, value2, value3;
readvalue("value1", value1);
readvalue("value2", value2);
readvalue("value3", value3);
data = insert3<<16 | insert2<<8 | insert1;
std::cout << "Value1: " << (data & 0xff);
std::cout << "Value2: " << ((data >> 8) & 0xff);
std::cout << "Value3: " << ((data >> 16) & 0xff);
}
A: I almost sure it should be >>> instead of >>. I also had similar problem.
Edit: This is correct for Java when you're working with negative numbers, however you won't be able to store easily negative numbers and get them later, since you will have to know when you have a negative or a positive number inside the integer and add if's accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does pypy handle recursions? I have a script I wrote in python and it works fine but I was curious to see if I could speed it up. It basically is recursive script.
If I run it within normal python 2.7, it takes about 30 seconds. When I run the same thing using pypy than I get the following error:
RuntimeError: maximum recursion depth exceeded
I'm not sure what pypy is doing differently because I'm not modifying the script.
Can anyone help me understand what is going on?
Update:
ok I figured it out. Increasing the limit helped but I think I was running the wrong file. I found a file under the bin directory called py.py and was using that. I'm not sure what the file does but its slower than normal python. I had to search and find 'pypy-c' seems to work now.
A: As you suggest in your update your problem was that you were using py.py (which is for running PyPy's interpreter on top of CPython). PyPy has a higher recursion limit than CPython normally. You can use sys.setrecursionlimit() to increase the recursion limit, sys.getrecursionlimit() does not provide the actual recursion limit.
PyPy 1.6.0:
>>>> sys.getrecursionlimit()
100
>>>> def infinite(level=0):
.... print level
.... return infinite(level+1)
....
>>> infinite()
<snip>
1010
Traceback (most recent call last):
File "<console>", line 2, in infinite
RuntimeError: maximum recursion depth exceeded
>>> sys.setrecursionlimit(sys.maxint)
>>> infinite()
<snip>
9769
zsh: segmentation fault pypy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Get Data from another activity to App Widget Hi I have an Activity 1 which needs to send data to Appwidget (widget) which has a text view.
For sending data between activites i know that we can use intent.putExtra("mydata", dataString); and recive the same with String data = bundle.getString("mydata"); But in my case i need to send data (String) to app Widget.
When i use
Bundle dataFromPrevious = getIntent().getExtras();
String newString = dataFromPrevious.getString("mydata");
inside AppWidgetProvider it throws an error in getIntent saying getIntent is undefined for the type Class.
How can i get the string inside this AppWidget? Also this text will be updated from activity 1 with new string often so is using SharedPrefrences a good choice for this situation? Is there any other way?
UPDATE 1:
As mentioned by Joseph, i have added
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
in my manifest,
Now i have also created an OnRecieve Override in AppWidget
@Override
public void onReceive(Context context, Intent intent) {
Bundle getPrevData = intent.getExtras();
String data = getPrevData.getString("mydata");
newdata = data;
super.onReceive(context, intent);
}
In my On Update i have
views.setTextViewText(R.id.dataWidget,newdata);
Here the newdata is the public static String But it dose not display anything!!! when i setTextViewText to a textview in the widget. Am i missing something here? Please help...
UPDATE 2:
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.Toast;
public class MainWidget extends AppWidgetProvider {
private RemoteViews views;
public static String newdata
@Override
public void onReceive(Context context, Intent intent) {
Bundle getPrevData = intent.getExtras();
String data = getPrevData.getString("mydata");
newdata = data;
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
views = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
appWidgetManager.updateAppWidget(appWidgetIds, views);
//views.setTextViewText(R.id.dataWidget,newdata);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
And this is my Another activityvthat sends data:
final String text = ((TextView)findViewById(R.id.textview)).getText().toString();
Intent intent = new Intent(FirstActivity.this, MainWidget.class);
intent.putExtra("mydata", text);
A: You need to use BroadcastReceivers. In a nutshell: add a BroadcastReceiver to your AppWidgetProvider which acts upon a custom Intent and then refreshes your widgets.
From your Activity then all you need to do is send a broadcast (Context.sendBroadcast) with the custom intent (and you can add data to the Intent with putExtra as per usual).
A: You can update the data in widget without using Broadcast receiver.
*
*Save data in sharedPreference.
*Create the remote views using new data and use AppWidgetManager.updateWidget to update the widget.
Here is the sample code.
RemoteViews updateViews = buildUpdate(context); // Update the view using the new data.
ComponentName thisWidget = new ComponentName(context, WidgetClassName.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, updateViews);
This is what i did in my previous application.
Saneesh CS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Database design - a many-to-many table which links the same entities? I have a table User with a column id. I want the user to have relationships with other users, so I create a table Relationships with columns user_id_1 and user_id_2.
The questions is how to constrain the table so that
1) there are no entries where user_id_1 equals user_id_2.
For example, entry (1, 1) is bad, because it indicates a relationship to oneself.
2) if there is an entry (user_id_1, user_id_2), the entry (user_id_2, user_id_1) is not allowed.
For example, having entries (1, 2) and (2, 1) is bad, because it indicates the same relationship.
I am using MySQL, although I think this is a general design issue. Thanks!
A: You can write a INSERT and UPDATE triggers on the join table that check these conditions.
A: You use a trigger:
DELIMITER $$
CREATE TRIGGER bi_relationschip_each BEFORE INSERT ON relationship FOR EACH ROW
BEGIN
IF NEW.user1_id = NEW.user2_id THEN
SELECT error_user1_cannot_be_equal_to_user2 FROM generate_error;
END IF;
END $$
DELIMITER ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP array_walk does nothing? I'd like to put each file name in $xsl_dir_path (absolute path) in select element. I've tried this:
$files = glob($xsl_dir_path . "/*.xsl");
array_walk($files, 'basename');
but it's not working at all, i can still see the full names of the files. I know i can apply basename when lopping through $files and build the option elements, but i'd like to do it before any html output.
A: array_walk is useful when your callback function accepts a reference or when you use user-defined callback functions. In this case, the basename argument is not a reference.
What you want is array_map:
$files = glob($xsl_dir_path . "/*.xsl");
$files = array_map('basename', $files);
A: That's because basename() isn't supposed to change the value of the array cells, only to return the new values. You need to pass to array_walk() a function that actually changes the value of the cell. Based on array_walk docs:
function my_basename(&$item)
{
$item = basaname($item);
}
$files = glob($xsl_dir_path . "/*.xsl");
array_walk($files, 'my_basename');
A: Try this:
function basename_for_walk (&$value, $key) {
$value = basename($value);
}
$files = glob($xsl_dir_path . "/*.xsl");
array_walk($files, 'basename_for_walk');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Namespacing animations Is it possible to namespace animations? Specifically, my problem is that on a given element $myElement I am doing animations of two types. Now I would like to use .stop() on only one of these types, not both.
How can I do that?
EDIT
Code available here: http://jsfiddle.net/y34ME/1/
My problem is that when I click the span I want it to fade away, regardless of whether I do a mouseout. Currently, the mouseout interrupts the fading away because of the .stop(), but I need the .stop() to prevent mouseover and mouseout events to queue up.
A: Is there a reason you need to use delegate? This code seems to do what you want:
$("span").hover(
function() {
$(this).animate({backgroundColor: "blue"}, 1000);
},
function() {
$(this).animate({backgroundColor: "white"}, 1000);
}
);
$("span").click(function() {
$(this).animate({backgroundColor: "green"}, 1000).fadeTo(2000, 0);
});
A: Just use undelegate. For cleaner code it can all be encapsulated in one delegate call also.
$('p').delegate('span',{
'mouseover':function(e){
$(this).stop(true, true).animate({backgroundColor: 'blue'}, 1000);
},
'mouseout':function(e){
$(this).stop(true, true).animate({backgroundColor: 'white'}, 1000);
},
'click':function(e){
$(this).animate({backgroundColor: 'green'}, 1000).fadeTo(2000, 0).undelegate( 'mouseout' );
}
});
A: I think what you really want is to not trigger the mouseout at all if you're already fading the element away. Andrew's method works well, but if you want to keep your event handlers intact (for example, if there's a way to show this element again), use a state class:
$('p').delegate('span:not(.hidden)', {
'mouseover': function () {
$(this).stop(true, true).animate({backgroundColor: 'blue'}, 1000);
},
'mouseout':function () {
$(this).stop(true, true).animate({backgroundColor: 'white'}, 1000);
},
'click': function () {
$(this).addClass('hidden').stop(true, true).animate({backgroundColor: 'green'}, 1000).fadeTo(2000, 0);
}
});
http://jsfiddle.net/y34ME/4/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: JavaMail: How to use different SOCKS5 for different threads? I wrote multithreading application which connects to some email accounts from database per thread.
I know that JavaMail have no any options to use SOCKS5 for connection so I decided to use it via System.setProperty method. But this method sets SOCKS5 for whole application and I need to use one SOCKS5 per thread. I mean:
*
*first thread: uses SOCKS 192.168.0.1:12345 for bob@localhost to
connect
*second thread: uses SOCKS 192.168.0.20:12312 for
alice@localhost to connect
*third thread: uses SOCKS 192.168.12.:8080
for andrew@localdomain to connect
and so on. Can you tell me how to do this?
A: You need to create your own socket using the Proxy you want:
SocketAddress addr = new InetSocketAddress("socks.mydomain.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("smtp.foo.com", 25);
socket.connect(dest);
Then use it for the connection:
SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
transport.connect(socket);
Edit: The tricky bit is if you need authentication with the SMTP server to send mail. If that's the case, you have to create a subclass of javax.mail.Authenticator and pass it to the Session.getInstance() method:
MyAuthenticator authenticator = new MyAuthenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter",
authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(properties, authenticator);
Where the authenticator looks like:
private class MyAuthenticator extends javax.mail.Authenticator
{
private PasswordAuthentication authentication;
public Authenticator()
{
String username = "auth-user";
String password = "auth-password";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
This is all untested, but I believe it's everything you have to do. It should at least put you on the right path.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: getting node-id in theme_uc_product_sell_price For my ubercart drupal installation, I want to achieve conditional CSS formatting for list and sell price based on their values.
List price: --$120.00-- (stroked out)
Sell price: $100.00
I see that both are processed individually in theme_uc_product_sell_price and theme_uc_product_price. My questions where do I compare there values? As per my investigation I cannot override uc_product_view (which is master of all) in theme-template as it's not wrapped with theme(...).
If I can get current node ID in my template override zen_uc_product_sell_price I can still achieve this by loading node. Is this possible, how can I get node id?
A: Solved. Required to create node-product.tpl.php in theme folder. Although, this requires to create your own template, it's pretty easy. All the required HTML code are available in following variable -
$node->content['body']["#value"];
$node->content['sell_price']["#value"];
$node->content['add_to_cart']["#value"];
$node->content['image']["#value"];
List price and sell price are available as $node->list_price and $node->sell_price to comapre.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML/CSS - Semi-Transparent background of div? With Scrollbar next to it Hello i am looking for solution to do that:
http://www.delightfulwoman.pl/depilacja-laserowa/
When you click on the link on the left, the text changes inside right box...
I just want to know how to make that CornerRounded SemiTransparent div background, with scrollbar NEXT to it, not inside it.
You would say i can look into source file, but i am not that good at CSS, and i cant see transparency or opacity there :s or anything similar.
A: This website is using an image as the background for that DIV. They are using a PNG file which supports transparency. So in the CSS for the DIV (.o_right_cont) they are using an image of a rounded and translucent box instead of any fancy CSS.
On the inside of that DIV they have another DIV (.ofe_desc). They set the overflow to auto so that way the scrollbar would appear when the content is larger than the DIV.
.o_right_cont {
background: url(gfx/cennik_bg.png) no-repeat;
width: 670px;
height: 420px;
float: left;
margin: 10px 0px 0px 30px;
text-align: left;
padding: 10px;
}
.ofe_desc {
width: 662px;
height: 400px;
text-align: left;
overflow: auto;
line-height: 15px;
padding: 8px 30px 8px 8px;
}
Let me know if you have any questions.
Kind Regards,
- Chris
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cloudera's Flume vs Facebook's Scribe Is there anyone who got a chance to work on both? I need to set up a framework to move data around. Basically, we have clickstream data coming in as text files. This data needs to be moved around form the app-servers to HDFS, and then to S3 after archival.
I need help in choosing between Flume and Scribe. Which one is better in terms of manageability, setting up and which is easier to customize?
A: View the answer posted here
I'll quote the answer:
*
*Flume allows you to configure your Flume installation from a
central point, without having to ssh into every machine, update a
configuration variable and restart a daemon or two. You can start,
stop, create, delete and reconfigure logical nodes on any machine
running Flume from any command line in your network with the Flume
jar available.
*Flume also has centralised liveness monitoring. We've heard a
couple of stories of Scribe processes silently failing, but lying
undiscovered for days until the rest of the Scribe installation
starts creaking under the increased load. Flume allows you to see the
health of all your logical nodes in one place (note that this is
different from machine liveness monitoring; often the machine stays
up while the process might fail).
*Flume supports three distinct types of reliability guarantees,
allowing you to make tradeoffs between resource usage and
reliability. In particular, Flume supports fully ACKed reliability,
with the guarantee that all events will eventually make their way
through the event flow.
*Flume's also really extensible - it's really easy to write your own
source or sink and integrate most any system with Flume. If rolling
your own is impractical, it's often very straightforward to have your
applications output events in a form that Flume can understand (Flume
can run Unix processes, for example, so if you can use shell script
to get at your data, you're golden).
This isn't an exhaustive list of benefits to using Flume - I haven't
touched on using decorators for lightweight transformation or
metadata extraction, the configuration language, the ability to run
several logical nodes in a single Flume process, automatic bucketing
and rolling of log files in HDFS... there's lots more about Flume
that we're looking forward to sharing with everyone.
The key difference to me is that Cloudera is actively supporting
Flume. While I do generally trust Facebook to maintain great open
source projects, Cloudera's business is built around providing support
for tools like this, so I have faith that Flume will longterm be
better supported. I want to minimize the time I have to think about
this particular problem. That said, so far I've had a lot of annoying
issues where Flume was either a bit convoluted in its abstraction or
buggy in its implementation, as you might expect from a pre-1.0
technology. If Asana weren't still in beta, I'd probably have chosen
Scribe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.