text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Why doesn't the bitwise Not ever work on copied/pasted strings? Simple enough to test:
echo(~~"Hello World"); //Echos Hello World
echo(~"Hello World"); //Echos �����ߨ����
echo(~"�����ߨ����"); //Echos @B@B@B@B@B W@B@B@B@B
Why does it work properly for the two Nots directly on top of each other, but not for the copied and pasted string output?
I'd guess there's probably some data being lost somewhere, but how can I output the data in such a way that if I copy and paste it into code which finds the bitwise Not of it, it will actually work?
This has been bugging me and some others I know for quite a while!
A: That happens because the char you see has invalid (non existent) code.
For example H code is 72. ~72 is -73.
As long as it is not valid char and cannot be shown - it is shown as a square with question mark. Thus it cannot be translated back, because you cannot copy char with code -73 (or to be more precise - your notepad or OS cannot do that)
A: Ascii H is 0100 1000 or character 72, ~H is 1011 0111 or character 183. This is beyond the basic Ascii table of 128.
Given that PHP does not dictate a specific encoding for strings, the character produced will depend on the code page of your script.
This might be non-printable character (hence represented by �), which are simply replaced by the symbol � when you copy/paste.
See Php Strings for more details on the implementation of strings as arrays of bytes.
A: As already mentioned, the problem is that the characters you are trying to echo are non-printable. You can examine what is going on in the various steps of this script to see what you can do if you do indeed need to store this and retrieve it later.
$a = "Hello World";
$b = ~$a;
$chars = unpack("c11chars", $b);
foreach ($chars as $char) {
echo $char . ' = ' ;
echo chr($char) . "\n";
}
$out = '';
foreach ($chars as $char) {
$out .= pack("c", $char);
}
echo ~$out;
Output:
-73 = ?
-102 = ?
-109 = ?
-109 = ?
-112 = ?
-33 = ?
-88 = ?
-112 = ?
-115 = ?
-109 = ?
-101 = ?
Hello World
The ? are what are echoed for me, since they are non-printable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to install svn post-commit hook I am running SVN on Linux. I was hoping to run auto deployment once committed. Based on my searching, it looks like svn post-commit might do the trick. But I couldn't find SVN post-commit from my SVN installation. So I wonder if it's a separate install? Is there any SVN post-commit hook that I can download and install?
A: First, you probably don't want to do this as a post-commit. The reason is that you don't want to do anything that takes too long to do in a hook because the user has to wait for the hook to complete before they can continue.
To answer your question, take a look at the repository directory on your server, you should see the following directories and files:
*
*README.txt
*conf
*db
*format
*hooks
*locks
One of the directories is called hooks. Take a look in this directory:
*
*post-commit.tmpl
*post-lock.tmpl
*post-revprop-change.tmpl
*post-unlock.tmpl
*pre-commit.tmpl
*pre-lock.tmpl
*pre-revprop-change.tmpl
*pre-unlock.tmpl
*start-commit.tmpl
These are templates for the various hooks. You'll see these are all simple BASH/Korn/Bourne shell scripts. You'll be using the svnlook command to get information about the revision or transaction (if pre-commit hook) that your user just committed.
What you would do is run the command svnlook changed to see what was changed, then based upon this information, you'll have to fetch the file, and deploy it. This means you'll have to create a working directory and do a checkout. Imagine a developer doing a checkin, and then waiting for your post-commit hook to do a checkout and deployment.
What you would be better off doing is getting something like Jenkins to do your post commit tasks. Jenkins is normally a continuous build server. Whenever someone does a commit, Jenkins does a checkout on that project and does the build. It can run all sorts of tests, and then email the developers if there are any problems.
However, it can also simply do a checkout and deployment if you really have nothing to build. Jenkins uses Java 1.6 to run, but otherwise, it's pretty easy to install and use. It's all menu driven, and you don't need to know how to create XML files or write any programs to use it.
So, take a look at Jenkins and see about doing your deployments from there. This way, your developers can continue their work while Jenkins handles the deployments. And, you can have Jenkins send out an email, an IM, Tweet, or even change a traffic light from green to red if there is an issue with the deployment.
A: It's not a separate install. In your respository directory, there is a 'hooks' dir. You can find post-commit.tmpl, just modify the file and rename it to executable file according your os type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: ActionView::Template::Error (960.css isn't precompiled) I have an iframe which renders a partial and is not part of the main application layout or asset pipeline.
I'd like to include some style sheets, however I am getting this error:
ActionView::Template::Error (960sm.css isn't precompiled):
Rails 3.1
Heroku
A: Style sheets that are not included in a manifest (directly by name or indirectly via require_tree) are not precompiled, so will not accessible in production.
You need to add the sheet to the list of items to precompile in the environment application.rb.
config.assets.precompile += ['960sm.css']
And then access it in the view:
stylesheet_link_tag('960sm')
A: Instead of managing a list of CSS files, you may prefer to simply adjust the extension by adding .scss to the filename.
Hence, 960sm.css would become 960sm.css.scss.
This should not break anything as valid CSS is valid SCSS.
A: If you have a lot of standalone assets, then instead of adding each one to the list, like this
config.assets.precompile += ['960sm.css']
you may want to just precompile everything, like this:
def precompile?(path)
%w(app lib vendor).each do |asset_root|
assets_path = Rails.root.join(asset_root, 'assets').to_path
return true if path.starts_with?(assets_path)
end
false
end
# Precompile all assets under app/assets (unless they start with _)
Rails.application.config.assets.precompile << proc do |name, path|
starts_with_underscore = name.split('/').last.starts_with?('_')
unless starts_with_underscore
path = Rails.application.assets.resolve(name).to_path unless path # Rails 4 passes path; Rails 3 doesn't
precompile?(path)
end
end
(Based on the code in the Rails Guide.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: How can I apply css3 scale to an element's first-letter pseudo-element? I have a paragraph tag with a first-letter pseudo rule. I would like to apply the scale rule to that first letter but it doesn't seem to work.
Does the first-letter pseudo element support css3 scale?
<p>This is some Text</p>
<p>This is some more Text</p>
p:first-child:first-letter { font-family: "Baskerville"; font-size: 60px; -webkit-transform: scaleX(.8); display: inline-block; }
A: working fine here, you sure you're using Webkit browser to view the results?
UPDATE:
This DOES work: http://jsfiddle.net/szXHZ/5/
You have to float the element and you have to set display to block!!
You will have to mess around with the style a little because it looks a bit ragedy (change line-height for a better look and maybe remove the clear that i've put on the second paragraph), but the transform does work when hovered. You can alter it so that you don't need to hover if you prefer that..
A: Try this instead.
<p><span class="firstletter">T</span>his is some Text</p>
.firstletter { font-family: "Baskerville"; -webkit-transform: scale(2); display: inline-block; }
Now it works. http://jsfiddle.net/sP3JZ/7/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I get Qt4 running with ruby 1.9.2 on Windows 7? Summary
I'm writing a Ruby 1.9.2 app using Qt4 for its GUI which I want to distribute on Linux, OS X and Windows. I have the app running fine on everything except my Windows 7 64-bit box.
There are working examples of Win7 + Qt4 + 1.8.7, but apparently not Win7 + Qt4 + 1.9.2. There are two gems for Ruby-Qt bindings, qtbindings and qtruby4 (sometimes referred to as qt4-qtruby), but I have not yet seen either of them running on Win7 with Ruby 1.9.2.
The Problem With qtruby4
This article from October 2008 and its updated version from June 2011 served as good starting points, but I differed from the latter by installing Ruby 1.9.2 via RubyInstaller for Windows' download page. 1.8.7 seemed to work fine, but I get some unusual errors when I try it with 1.9.2. Requiring 'rubygems' and then requiring 'Qt' results in:
no such file to load -- 'qtruby4'
The first article from above links to a more in-depth article from dr1ku which may provide some clues.
*
*It might be worth reproducing dr1ku's steps with the latest versions of these libraries.
*dr1ku and the 2008 paschenda.org article both use a special Windows Qt4-QtRuby installer, but the maintainer notes that he hasn't had the time to update it. I'm not completely clear on what the special installer does, but I suppose paschenda.org's 2011 article no longer uses it because DevKit ostensibly helps RubyGems itself build Qt4 without assistance.
Found in the Wild
Here are some people who appear to be have encountered the same problem:
*
*no qtruby library on windows
*Ruby 1.9.x + Qt4Ruby…. a pipe dream???
*qtruby4 LoadError in ruby 1.9.1 / win32 for qtruby4-2.1.0
The Problem With qtbindings
My app actually uses the qtbindings gem, so I tried installing that instead, with gem install qtbindings --platform=mswin32.[1] However, when I tried to require 'Qt' with the qtbindings gem installed, I got a Windows popup with the following message:
The procedure entry point _Z10qvsnprintfPcjPKcS_ could not be located
in the dynamic link library QtCore4.dll. Just give up, inferior flesh creature.
(I have copy and pasted the message without any embellishment whatsoever.)
Found in the Wild
Here are some people who appear to be have encountered the same problem:
*
*this one's in German
*gpg4win: help
Potential Success Stories
Someone out there seems to have had success by installing the qtbindings gem on 1.9.2 with gem install qtbindings (no --platform argument), if you look at the replies to this thread:
*
*help -- qt, ruby, ms-windows?
I tried installing with gem install qtbindings on 1.8.7, but I have not tried it with 1.9.2 yet. When I tried it with 1.8.7, I ran into the same "procedure entry point could not be located" issue as before.
Footnotes
[1] - I'm actually not completely clear on the difference between the qtbindings gem and the qtruby4 gem. For example, does the latter include the C extension and the former does not? I'm not sure. Additionally, I have seen references to qt4-qtruby, which I think is just the mswin32 version of qtruby4, at least as far as I can tell from the Korundum download page.
A: The Solution
The following steps work on Windows 7:
*
*Install Ruby 1.9.2 via the official download page.
*In a Windows shell, run gem install qtbindings.
The trivial example (require 'rubygems'; require 'Qt') should now work.
No extra steps are required because a binary gem is provided just for the Windows platform. The gem install qtbindings step will therefore take a few minutes as it downloads the large binary, but it contains all of the requisite parts to require and run Qt apps.
Compiling from source on Windows is supported, and documented in the project's README file.
The Low-Down
I e-mailed the maintainers of qtbindings and qtruby. Here's the full story:
qtruby is a package provided by the Korundum project. Korundum provides Ruby bindings to all of KDE, whereas qtruby provides bindings for only Qt.
qtbindings (github) is a modified and repackaged version of qtruby specifically optimized for cross-platform usage. I shall copy and paste the "Goals" section from its README here:
Goals
*
*To make it easy to install a Qt binding for Ruby on all platforms
using RubyGems
*To maintain an up-to-date binary gem for Windows that is bundled
with the latest version of Qt from http://qt.nokia.com
*To reduce the scope and maintenance of the bindings to only bind to
the libraries provided by the Qt SDK.
*To increase compatibility with non-linux platforms
Though the Korundum downloads page does provide mswin32 versions of its gem, as of this writing they are not actively vetted by anyone, and so should not be relied upon. The QtRuby maintainer informed me that the RubyForge page will probably not be reliable until after QtRuby 3 is released.
The Recap
Right now (10/3/2011), don't use the qtruby gem on Windows. Use qtbindings.
You might be able to use qtruby on other platforms and qtbindings on Windows, but you'll probably be asking for trouble. If you are just going for Qt and don't care about the rest of KDE, qtbindings is probably a safe bet.
The maintainers of QtRuby are planning some methodology updates in the near future (such as using git), so there may be increased shared fixes and updates between the two projects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Hibernate Search Filter not working with Tokenized field I am using Hibernate search 3.3 to search a Lucene index. I have a filter I need to use on a certain field, but also make it TOKENIZED for full text search. What I have found is that when I have the field set to UN_TOKENIZED, the filter works and full text search doesn't, and when I have it set to TOKENIZED, full text search works and the filter doesn't.
POJO
@Field(name = "owningOrganization", index = Index.UN_TOKENIZED, store = Store.YES)
@FieldBridge(impl = OrganizationNameFieldBridge.class)
public Organization getOwningOrganization()
{
Filter
@Factory
public Filter getFilter()
{
BooleanQuery query = new BooleanQuery();
Term orgTerm = new Term("owningOrganization", userOrganization);
Term activeTerm = new Term("currentStateIsActive", "1");
query.add(new TermQuery(orgTerm), Occur.SHOULD);
query.add(new TermQuery(activeTerm), Occur.SHOULD);
return new CachingWrapperFilter(new QueryWrapperFilter(query));
}
When I enter search terms of owningOrganization:"This is the exact value of an organization" I get no results, but the filter works as desired. And opposite when I switch it to TOKENIZED.
Any suggestions?
A: You should index the field twice, once for searching (analyzed) and once for filtering. Per default using a TermQuery does not apply any analyzing. It searches the index for the term as specified.
@Fields({
@Field(name = "owningOrganization_untokenized", index = Index.UN_TOKENIZED),
@Field(name = "owningOrganization", index = Index.TOKENIZED, store = Store.YES
}
)
public Organization getOwningOrganization(){
}
With this approach you have the owning organization field available tokenized and un-tokenized. You just have to use the right field name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: hiding the cursor in a full screen java application on the Mac using webstart I have a fullscreen Java application in which I need to hide the cursor on a Mac.
I've created the transparent cursor as instructed here and elsewhere, which works
fine on Windows. It does not work on the Mac. I've tried a both a system command
and a native command to get ride of it, but that only works when I run it locally
on my own computer. When I compile it and upload it to a server using webstart,
then download it and run it, it no long works.
I've attempted simply changing the cursor to one of the default cursers, and that
does not work on startup either. Both the invisible cursor and default cursor do
work once I move the cursor up to the top of the screen, but I need it to be
invisible immediately. I have setUndercorated set to true.
I've searched everywhere and found answers that work on windows, or that work when
I run locally on my Mac, but nothing that works when the application is downloaded
and run on any Mac.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Detecting a movieclip has been Flipped horizontally on the stage in as3 If two movie clips instances of the same movieclip are placed on the stage and one is flipped horizontally in Flash.. Is there a way I can detect which one has been flipped horizontally in code? ScaleX seems to remain unchanged.
The MovieClip has been flipped horizontally using the Flash UI (Edit->Flip Horizontal), not via code.
A: Try:
function isFlippedHorizontally( obj:DisplayObject ):Boolean
{
return obj.transform.matrix.a / obj.scaleX == -1;
}
trace( isFlippedHorizontally( yourObject ) );
edit:
I should have accounted for the scaleX of the object; adjusted now.
Alternatively:
import fl.motion.MatrixTransformer;
function isFlippedHorizontally( obj:DisplayObject ):Boolean
{
return MatrixTransformer.getSkewYRadians( obj.transform.matrix ) / Math.PI == 1;
}
trace( isFlippedHorizontally( yourObject ) );
edit:
Last example accidentally had calculation for vertically flipped in stead of horizontally flipped.
A: I like fireeyedoy's solution more for it's compactness and simplicity but you can also do it with some bitmapdata comparison:
var bmd1:BitmapData = new BitmapData(mc1.width, mc1.height);
var bmd2:BitmapData = new BitmapData(mc2.width, mc2.height);
var cbmd1:BitmapData = new BitmapData(mc1.width, mc1.height);
var cbmd2:BitmapData = new BitmapData(mc2.width, mc2.height);
var cmatrix1:Matrix = new Matrix();
var cmatrix2:Matrix = new Matrix();
cmatrix1.tx = -mc1.x;
cmatrix1.ty = -mc1.y;
cmatrix2.tx = -mc2.x;
cmatrix2.ty = -mc2.y;
bmd1.draw(mc1);
bmd2.draw(mc2);
cbmd1.draw(this, cmatrix1);
cbmd2.draw(this, cmatrix2);
if(cbmd1.compare(bmd1))
{
trace("mc1 is flipped!");
}
else if(cbmd2.compare(bmd1))
{
trace("mc2 is flipped!");
}
This is assuming that your movieclips are top-left aligned. If not then you will have to add the appropriate tx and ty values in the matrix while drawing them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Algorithm to determine size of a room from video feed Does anybody know of a image analysis algorithm with which I can determine how large(approximately, in real-life measurements, let's say width in meters or something) a room is out of one(or multiple) video recordings of this room?
I'm currently using OpenCV as my image library of choice, but I haven't gotten very far in terms of learning image analysis algorithms, just a name drop would be fine.
Thanks
Edit: Okay, a little bit of clarification I just got from the people involved. I basically have no control how the video feed is taken, and can't guarantee that there are multiple data sources. I however have a certain points location in the room and I'm supposed to place something in relation to that point. So I would probably looking at trying to identify the edges of the room, then identifying how far procentual the given location is in the room and then guess how large the room is.
A: Awfully difficult (yet interesting!) problem.
If you are thinking in doing this in a completely automated way I think you'll have a lots of issues. But I think this is doable if an operator can mark control points in a set of pictures.
Your problem can be stated more generally as finding the distance between two points in 3D space, when you only have the locations of these points in two or more 2D pictures taken from different points of view. The process will work more or less like this:
*
*The pictures will come with camera location and orientation information. For example, let's say that you get two pictures, with the same camera orientation and where the two pictures were taken with the camera three feet apart horizontally. You will have to define a reference origin for the 3D space in which the cameras are located, for example, you can say that the left picture has the camera at (0,0,0) and the right picture at (3,0,0), and both will be facing forward, which would be an orientation of (0,0,1). Or something like that.
*Now the operator comes and marks the two corners of the room in both pictures. So you have 2 sets of 2D coordinates for each corner.
*You must know the details of your camera and lens (field of view, lens distortion, aberrations, etc.). The more you know about how your camera deforms the image the more accurate you can make your estimate. This is the same stuff panorama stitching software do to achieve a better stitch. See PanoTools for info on this.
*Here comes the fun part: you will now do the inverse of a perspective projection for each of your 2D points. The perspective projection takes a point in 3D space and a camera definition and computes a 2D point. This is used to represent tridimensional objects in a flat surface, like a computer screen. You are doing the reverse of that, for each 2D point you will try to obtain a 3D coordinate. Since there isn't enough information in a 2D point to determine depth, the best you can do from a single 2D point is obtain a line in 3D space that passes through the lens and through the point in question, but you don't know how far from the lens the point is. But you have the same 2D point in two images, so you can compute two 3D lines from different camera locations. These lines will not be parallel, so they will intersect at a single point. The intersection point of the 3D lines will be a good estimation of the location of the 3D point in space, and in the coordinates of your reference camera 3D space.
*The rest is easy. When you have the estimated 3D locations of the two points of interest, you just compute the 3D distance between them, and that's the number that you want.
Pretty easy, huh?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: validating dates in PHP can anyone taught me a function or a script or some related example where in it would only allow number of days to be inputted? I have a datepicker for choosing the date start and date end... I only want the user to input within a specified range of time/date and if the user overlaps, it will prompt the user that they could only input from a certain range of time.
Ex. I would only allow 28 days.
Scenario1:
Date from: 2011-09-01
Date to: 2011-09-31
Result: (prompt) you are only allowed to input within 28 days.
Scenario2:
Date from: 2011-09-01
Date to: 2011-09-20
Result: it will proceed to another page.
A: If you have >= PHP 5.3...
$startDate = new DateTime('2011-09-01');
$endDate = new DateTime('2011-09-31');
$diff = $startDate->diff($endDate);
if ($diff->d > 28) {
// More than 28 days.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mongoose failing to validate array properties I'm having some issues with validating an array property in Mongoose.
When I use the following definition, my shouldFail method never gets called, and the record always saves.
shouldFail = (val) ->
console.log "Fail method called with value:"
console.log val
return false
definitions:
english: [
type: String
validate: [ shouldFail, "testing" ]
required: true
]
However if I set up validation as the following, the function gets called and the record is not saved.
Sense.path('definitions.english').validate (val) ->
console.log "Validating English"
console.log val
return false
I'd prefer to use the former definition style if possible. I'm just wondering if I'm doing something wrong in my definition. Is that how you define validation for arrays?
Also I'm not sure if the way I'm setting english is affecting this. I'm just doing definitions.english = [ ] and trying to save.
A: I don't think you need the [] on english:, fiddling with the code on the coffeescript compiler it renders out way wrong if you include them. That is likely why your validation isn't working in that format. Try just:
definitions:
english:
type: String
validate: [ shouldFail, "testing" ]
required: true
A: I can see the question and chosen answer are quite old, but I think it may still be useful to elaborate a bit more.
It seems you can't validate a single element of an array. Instead run validation on entire array and loop through it's values if needed.
Assuming valid is a function to validate a single element:
definitions:
english:
type : [ String ]
validate :
validator : (values) ->
for value in values
if not (valid value) then return false
return true
msg : "At least one not valid"
]
By setting required flag I assume you wanted to make sure at least one element is in the array. To achive that, add another validate object like that:
definitions:
english:
type : [ String ]
validate : [
validator : (values) -> values.length # 0 is a falsy value
msg : "At least one required"
,
validator : (values) ->
for value in values
if not (valid value) then return false
return true
msg : "At least one not valid"
]
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Ajax requests are getting cancelled without being sent I am trying to hook up a script to Microsoft's World-Wide Telescope app. The latter listens on port 5050 for commands. It is running on the same machine as the browser (Chrome right now, but as far as I can tell the behavior is the same with Firefox 7 and IE 9).
I am sending a "Access-Control-Allow-Origin: *" header with the original html file to try to eliminate XSS restrictions as my problem.
My code to access WWT is as follows:
$.ajax({
type: 'POST',
url: url,
data: data,
crossDomain: true,
success: success,
dataType: dataType
});
url in this case is "http://127.0.0.1:5050/layerApi.aspx?cmd=new&..." (obviously ... is shorthand here for some additional parameters).
Looking at the network diagnostics in Chrome, I can see this:
Request URL:http://127.0.0.1:5050/layerApi.aspx?cmd=new&...
Request Headersview source
Accept:application/xml, text/xml, */*; q=0.01
Content-Type:application/x-www-form-urlencoded
Origin:http://gwheeler4
Referer:http://gwheeler4/conceptconnect.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1
The request is going out - I see WWT make a new layer. However, I don't get a callback. If I add an error callback that gets called, but the error property on the jqXHR object is just "error" and status is 0. If I look at the network request in Chrome I see "(cancelled)" as the status and no response.
If I take that same URL and paste it in a new browser tab, I can see that the response is the expected XML.
Of course, a difference here is that this is a GET not a POST, but I've tried that in my script and it makes no difference.
I'm pretty stumped by this and would appreciate any fresh ideas.
A: I had a similar problem. In my case, I'm trying to use a web service on a apache server + django (the service was written by myself). I was having the same output as you: Chrome says it was cancelled while FF does it okay. If I tried to access the service directly on the the browser instead of ajax, it would work as well.
Googling around, I found out that some newer versions of apache weren't setting the length of the response correctly in the response headers, so I did this manually. With django, all I had to do was:
response['Content-Length'] = len(content)
If you have control over the service you are trying to access, find out how to modify the response header in the platform you are using, otherwise you'd have to contact the service provider to fix this issue. Apparently, FF and many others browsers are able to handle this situation correctly, but Chrome designers decided to do it as specified.
A: Two possibilities are there when AJAX request gets dropped (if not Cross-Origin request):
*
*You are not preventing the element's default behavior for the event.
*You set timeout of AJAX too low, or network/application backend server is slow.
Solution for 1):
Add return false; or e.preventDefault(); in the event handler.
Solution for 2):
Add timeout option while forming the AJAX request. Example below.
$.ajax({
type: 'POST',
url: url,
timeout: 86400,
data: data,
success: success,
dataType: dataType
});
For Cross-origin requests, check Cross-Origin Resource Sharing (CORS) HTTP headers.
A: I had a similar issue. Using chrome://net-internals/#events I was able to see that my issue was due to some silent redirect. My get request was being fired in an onload script. The url was of the form, "http://example.com/inner-path" and the 301 was permanently redirecting to "/inner-path". To fix the issue I just changed the url to "/inner-path" and that fixed the issue. I still don't know why a script that worked a week ago was suddenly giving me issue... Hope this helps someone
A: (Using Web Forms ASP.NET)
My issue was I was trying to fire Ajax off the click event of a submit button that had a server side click event setup. I had to make the button just a simple button (i.e. <input type="button"> )
A: I have had the same problem, for me I was creating the iframe for temporary manner and I was removing the iframe before the ajax become completes, so the browser would cancel my ajax request.
A: Expanding on @Kazetsukai's answer, you may run into this problem if you are making your AJAX request from the user clicking on a link.
If you set up your link like so:
<a href="#" onclick="soAjax()">click me!</a>
And then a javascript handler like the following:
soAjax() {
$.ajax({ ... all your lovely parameters ... });
}
To prevent your browser from following the link and cancelling any requests in progress, you should add return false or e.preventDefault() to stop the click event from propagating:
soAjax() {
$.ajax({ ... etc ... });
return false;
}
Or:
soAjax(e) {
$.ajax({ ... etc ... });
e.preventDefault();
}
A: In my case I was having type='submit' so when I was submitting the form the page was reloading before the ajax hit going so a simple solution was to have type="button". If you don't specify a type it's submit by default so you've gotta specify type="button"
type='submit' => type='button'
OR
No type => type='button'
Or if you don't want to change the type or submit the form on click you can e.preventDefault() as the very first thing e.
<button>Submit</button>
<script>
$( "button" ).click(function( event ) {
event.preventDefault();
// AJAX Call here
});
</script>
A: For Dropzone.js case.
In my case it's was caused because of timeout option value was too low by default. So increase it by your needs.
{
// other dropzone options
timeout: 60000 * 10, // 10 minutes
...
}
A: If anyone else runs into this, the issue we had was that we were making the ajax request from a link, and not preventing the link from being followed. So if you are doing this in an onclick attribute, make sure to return false; as well.
A: If you're using Chrome you can't see enough information in the standard Chrome networking panel to determine the root cause of a (canceled) request.
You need to use chrome://net-internals/#events which will show you the gory detail of the request you are sending - including hidden redirects / security information about cookies being sent etc.
e.g. the following shows a redirect I wasn't seeing in the network trace - caused by my cookies not being sent cross sub-domain:
t=1374052796448 [st= 1] +URL_REQUEST_START_JOB [dt=261]
--> load_flags = 143540481 (DO_NOT_SAVE_COOKIES | DO_NOT_SEND_AUTH_DATA | DO_NOT_SEND_COOKIES | ENABLE_LOAD_TIMING | MAYBE_USER_GESTURE | REPORT_RAW_HEADERS | VALIDATE_CACHE | VERIFY_EV_CERT)
--> method = "GET"
--> priority = 2
--> url = "https://...."
...
t=1374052796708 [st=261] HTTP_TRANSACTION_READ_RESPONSE_HEADERS
--> HTTP/1.1 302 Moved Temporarily
Content-Type: text/html
Date: Wed, 17 Jul 2013 09:19:56 GMT
...
t=1374052796709 [st=262] +URL_REQUEST_BLOCKED_ON_DELEGATE [dt=0]
t=1374052796709 [st=262] CANCELLED
t=1374052796709 [st=262] -URL_REQUEST_START_JOB
--> net_error = -3 (ERR_ABORTED)
A: I got this error when making a request using http to a url that required https. I guess the ajax call is not handling the redirection. This is the case even with the crossDomain ajax option set to true (on JQuery 1.5.2).
A: In my case, I Apache's mod-rewrite was matching the url and redirecting the request to https.
Look at the request in chrome://net-internals/#events.
It will show an internal log of the request. Check for redirects.
A: I had the same problem, but in my case it turned out to be a cookie issue. The guys working on the back-end had changed the path of the JSESSIONID cookie that's set when we log in to our app, and I had an old cookie by that name on my computer, but with the old path. So when I tried logging in the browser (Chrome) sent two cookies called JSESSIONID, with different values, to the server - which understandably confused it - so it cancelled the request. Deleting the cookies from my computer fixed it.
A: I had this error in a more spooky way: The network tab and the chrome://net-internals/#events did not show the request after the js was completed. When pausing the js in the error callcack the network tab did show the request as (cancelled). The was consistently called for exactly one (always the same) of several similar requests in a webpage. After restarting Chrome the error did not rise again!
A: I had the cancelled in Firefox. Some ajax-calls working perfectly fine for me, but it failed for the coworker who actually had to use it.
When I checked this out via the Chrome tricks mentioned above, I found nothing suspicious. When checking it in firebug, it showed the 'loading' animation after the two mallicous calls, and no result tab.
The solution was mega simple: go to history, find the website, rightclick -> forget website.
Forget, not delete.
After that, no problems anymore. My guess is it has something to do with the .htaccess.
A: In my case, it was the missing trailing slash in the url.
Adding the trailing slash solved my problem.
A: Check for page reloads.
Problem:
In my case I was reloading the page using location.reload() inside click event, before Ajax being fired.
Also, there was second Ajax call in the success.
Solution:
I removed the the reload and put it inside success callback of last Ajax call and it worked.
A: I had this issue with a particular 3G network.
It would always fail on DELETE requests with net_error = -101 in chrome://net-internals/#events.
Other networks worked just fine so I assume there was a faulty proxy server or something.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
}
|
Q: Can I customize a BarChart for this purpose? I'm kind of new to using charts in Flex, so you'll have to forgive me if I'm asking something for which there's an obvious answer.
I have a need to create a BarChart which acts more like a List component, albeit it should still be a chart. I need items to look somewhat like this:
<s:HGroup width="100%">
<s:Button id="labelDisplay" label="Item Name"/>
<s:BARCHARTGRAPHTHING width="100%"/>
<s:Label text="{data.count}"/>
</s:HGroup>
Thus, an item should look kind of like this:
Is there a way to customize the MX BarChart component to allow me to provide a custom item renderer for the part that renders the label for the row? Is there also a way for me to add a total column next to the bar on the right?
Additionally, I need to be able to allow my chart to handle a lot of different rows of data. Can I make it act more like a list and add a scroller, keeping the ticks at the bottom above all bars?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting Up SVN for Atomic Commits and Restricted Access We're having a discussion at work currently and I was looking for some advice on SVN setup.
Our pattern is that we have a variety of projects checked into SVN, some of these projects depend on others. For example FooWebServices depends on FooCommons.
In the case where I'm working on a feature that requires changes in FooWebServices and FooCommons I want to be able to do an atomic commit across those two projects. If I've screwed up somehow and the commit fails for FooWebServices the whole ball of wax fails. That way I'm not screwing up any other devs or having to go back out changes while I track down whatever issue I had. The CI server also seems to be getting confused pretty frequently.
I can do a shallow checkout of the root (then FooWebServices and FooCommons under that) of our repo and get this behavior. Then I can get that atomic commit behavior.
The situation is complicated in that we have contractors also working in the repository. Currently they cannot check out a shallow copy of root so they can't get that behavior.
I'd like to set things up so that the contractors can check out root, FooWebServices, and FooCommons, and nothing else. I'd also like to prevent them from browsing root to seeing the projects we haven't granted them access to.
Is this possible? Am I overcomplicating the problem and atomic commits aren't even necessary?
A: I think it's too complicated - AND coupled.
You should not have a bi-directional relationship; if you do, you've got bigger problems. (They really are just one project in that case.)
Cycles should be avoided. Break them up with well-placed interfaces.
A better approach for related projects might be to have a one-way dependency. If project A depends on B you can work on project B, commit changes, then create a JAR file that's added to project A.
The beauty of this approach is that changes to A need not force a deployment of B; it can accept changes to A when it can by continuing to use the old JAR until the time is right to upgrade.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can i implement "doc" function in clisp? In clojure, i can use doc as below:
Clojure> (doc juxt)
-------------------------
clojure.core/juxt
([f] [f g] [f g h] [f g h & fs])
Alpha - name subject to change.
Takes a set of functions and returns a fn that is the juxtaposition
of those fns. The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]enter code here
It seems there is no such a function in clisp ? Then how can i implement such a function ?
Sincerely!
A: Lisp has Documentation Strings.
For example:
[1]> (defun sqr (x)
"Returns the square of x"
(* x x))
SQR
[2]> (documentation 'sqr 'function)
"Returns the square of x"
[3]>
Refer to the Hyperspec or this less detailed explanation for more details.
A: describe works:
(describe #'expt)
#<SYSTEM-FUNCTION EXPT> is a built-in system function.
Argument list: (#:ARG0 #:ARG1)
For more information, evaluate (DISASSEMBLE #'EXPT).nter code here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - events within events? I have a textfield and a button.
They have identical actionPerformed event listener. (e.g. when user clicks a button and when user hits ENTER).
Is there a way to avoid this kind of duplication of code? It just becomes a pain in the __ modifying the code in 2 places for each such case.
I was thinking would it be possible to call a button event inside of a textfield event, analogous like calling a function inside of another function?
EDIT:
Passing the same addActionPerformed method call to both textfield and button did the trick.
A: I assume you are complaining because you are using an anonymous inner class for both. So don't do that. Create a first-class class, and create an instance that you pass to both component's addActionListener.
A: ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//...
}
};
Button button = new Button();
button.addActionListener(actionListener );
TextField textField = new TextField();
textField.addActionListener(actionListener);
or not so elegant but possible call a third method doIt() in your both actionPerformed() methods
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PySide Signal "duplicating" behavior from PySide.QtCore import *
class Eggs(QObject):
evt_spam = Signal()
print "Loaded"
a = Eggs()
b = Eggs()
print a.evt_spam
print b.evt_spam
print a.evt_spam is b.evt_spam
outputs:
Loaded
<PySide.QtCore.Signal object at 0xa2ff1a0>
<PySide.QtCore.Signal object at 0xa2ff1b0>
False
"Loaded" only printing once (as expected; it is a class variable), but why are 2 instances of the signal being created (if it is also a class variable)?
A: It's not being printed when you create a class instance, but rather when the class scope is executed. This code will print "Loaded", even though I never made an instance of "Test".
class Test:
print "Loaded"
If you want to run code when the class is initialized, take a look at __init__(). This code will print "Loaded" when an instance is made, instead of when the class itself is defined.
class Test:
def __init__(self):
print "Loaded"
QT's QObject metaclass appears to be rewriting the class attributes to prevent duplicate signals when you initialize a new instance of the class. Perhaps you can assign the attribute like this:
class Test(QObject):
def __init__(self, signal):
self.evt_spam = signal
sig = Signal()
a = Test(sig)
b = Test(sig)
Or this:
class Test(QObject):
def signal(self, signal):
self.evt_spam = evt_spam
return self
evt_spam = Signal()
a = Test().signal(evt_spam)
b = Test().signal(evt_spam)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problems with Android CSS spritesheet webkit transforms and animations I'm relatively new to HTML5 and to Android, so any advice is useful. I'm trying to write a simple game in HTML5, mainly targetting mobile devices. I'm using spritesheets for the graphics, and "3d" webkit translation transforms to force hardware acceleration on iOS devices. It's working pretty well so far, runs pretty well on iOS devices, and also in Safari, Firefox and Chrome. My problem is with the browser on Android devices (testing with Android 2.3.3 on an HTC Desire) - I'd expect it to behave like Chrome, but apparently I'm wrong. It seems that Android supports webkit stuff, but has problems with 3d translate and CSS animations (even if they don't use 3D translates).
The following is my attempt to boil the problem down to its core. testimage.png can be anything, but for me it's a 3*3 grid showing numbers arranged like this:
012
345
678
The output on iOS, Chrome and Safari shows the parts of the texture corresponding to 0, 2 and 3 in a vertical line, with the 2 animating up and right. On Android, the animating "2" (and/or the 3d-transformed "1" if you uncomment the code) displays the whole image rather than the subset defined by the size of _spriteDiv, and whilst the animation is happening the "3" suffers the same problem.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Android Sprite Test</title>
<style>
@-webkit-keyframes testAnim { from { -webkit-transform:translate(32px, 96px) } to { -webkit-transform:translate(256px, 0px) } }
</style>
</head>
<body bgcolor = "#606060">
<script src="./scripts/test.js"></script>
</body>
</html>
JavaScript:
var MakeSprite = function() {
var me = {},
_width = 32,
_height = 32,
_spriteFrame = 1,
_spriteDiv = document.createElement('div'),
_spriteImg = document.createElement('img');
_spriteDiv.id = 'spriteDiv';
_spriteDiv.style.position = 'absolute';
_spriteDiv.style.overflow = 'hidden';
_spriteDiv.style.width = _width + 'px';
_spriteDiv.style.height = _height + 'px';
_spriteImg.id = 'spriteImg';
_spriteImg.src = './testimage.png';
_spriteImg.width = Math.floor(_width * 3);
_spriteImg.height = Math.floor(_height * 3);
_spriteImg.style.position = 'absolute';
_spriteDiv.appendChild(_spriteImg);
document.body.appendChild(_spriteDiv);
me.setFrame = function(n) {
_spriteFrame = n;
_spriteImg.style.left = (-_width * (_spriteFrame % 3)) + 'px';
_spriteImg.style.top = (-_height * Math.floor(_spriteFrame / 3)) + 'px';
};
// Works on iOS, Safari and Chrome - but not Android?
me.translate3d = function(x, y) {
_spriteDiv.style.webkitTransform = 'translate3d(' + x + 'px,' + y + 'px,0px)';
}
// Works on Android, but presumably lacks the hardware acceleration of the 3D version
me.translate2d = function(x, y) {
_spriteDiv.style.webkitTransform = 'translate(' + x + 'px,' + y + 'px)';
}
me.testAnim = function() {
_spriteDiv.style.webkitAnimation = 'testAnim 5s';
}
return me;
};
/////////////////////////////////
// TEST SPRITES
// 2D translate works fine, but is suboptimal
var testSprite = new MakeSprite();
testSprite.translate2d(64, 32);
testSprite.setFrame(0);
// 3D translate doesn't work (it shows the whole image rather than clipping it),
// and it also breaks anything that comes after it
/*
var testSprite2 = new MakeSprite();
testSprite2.translate3d(64, 64);
testSprite2.setFrame(1);
*/
// CSS Animation breaks the sprite in the same way that 3D translation does
// (even though the animation works on a 2D translate), and similarly breaks
// sprites that come after it
var testSprite3 = new MakeSprite();
testSprite3.translate2d(64, 96);
testSprite3.setFrame(2);
testSprite3.testAnim();
// This will look wrong if any preceding sprites use translate3d or testAnim.
var testSprite4 = new MakeSprite();
testSprite4.translate2d(64, 128);
testSprite4.setFrame(3);
Does anyone know how I can get round these problems, so I can use CSS animations (and, ideally, hardware-accelerated webkit transform) on current version of the Android browser? I've heard noises about the support for this kind of thing being less buggy in future versions of Android, but to be honest I could really do with something that works on the current versions.
A: I was looking into this, and I came across the following: http://caniuse.com/transforms3d. Apparently, anything version that's < 3 doesn't support 3D transforms, which is a little disappointing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jenkins - Using the results of one job, in another job I have a job that runs a makefile and generates some files. I then want another job that publishes these files to ivy.
I am aware of the clone workspace plugin, but is there any other options?
A: My personal preference is to do these sort of things without relying on the Jenkins internal file structure, though sometimes this mean knowing about the internal structure of your other build tools (e.g., Maven, or in your case Ivy).
If I were you, I'd do everything in one job - i.e., build, and then have an "Ivy Publisher" (if such a plug in exists) publish the artifact to the remote Ivy repository.
If that's not possible, have the first job "install" the artifact into the local repository/cache (I'm not sure what it's called on Ivy), and then have the second job pick it up from there.
I'm not sure this is necessarily the best approach, but it has worked well for me.
Edit I should mention - this doesn't work so well on distributed environments, unless like me, your distributed environment consists of multiple nodes that have access to a common NAS filesystem.
Edit 2 I have also used the Copy To Slave Plugin for distributed environments without a common filesystem.
A: You run a Makefile, and you're publishing to Ivy?
Ivy is part of Ant, and is a module that takes advantage of the worldwide Maven repository structure to grab required jarfiles and other dependencies.
Don't get me wrong, I've used a local remote Maven repository to publish C/C++ libraries (you can use wget to fetch the items) that other projects will depend upon. But, I didn't do that using Ivy.
If you're thinking of Apache Ivy, then you can publish using Maven. There's a Maven Release plugin that will copy your artifact to your Maven repository, but what you probably want to do is deploy.
In my Jenkins builds, I simply had Jenkins execute maven's deploy-file step from the command line. This allowed me to deploy files into my Maven Ivy repository without having to first create a pom.xml file. (Well, you want to create a pom.xml anyway because you want to include a dependency hierarchy.)
I usually did this in the same job as the job that created my jar/war/ear file. However, if you want a separate job to do this, you can use the Copy Artifact Plugin. This plugin allows Job B to copy any or all of the published artifacts from Job A. That's a lot faster and simpler than cloning a whole workspace if you just want the built jar files.
A: You have several options, one is Clone Workspace, which works fairly well, but doubles the disk space needed (which in our case is quite relevant). Most other ways are a variation of Clone Workspace.
What I have done instead is to use custom workspace locations. I.e. my first job builds everything then triggers a second job. In the second job I have set the custom workspace to the workspace of the first job, so the job performs other tasks on the same files. You have to check the option to prevent a build of the first job while the second job is running though, as both work on the same files, which is kind of a fine line.
However, if you need it and are careful, this can be a viable solution.
A: Use the Copy Artifact plugin to copy artifacts from Job A (compile) to Job B (publish).
A: I'd go with a master build file that handles both of the sub tasks. Ant has a set of Execution tasks that you can use to run another Ant build file, execute some command line commands, etc. Look here:
http://ant.apache.org/manual/tasksoverview.html
Perhaps you could kick off the make with an Exec command and handle the ivy publish by running an Ant build with the Ant command.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: JQuery and showing / hiding content Why does this not work? I have looked for tutorials online but they only show how to show/hide with a button. I want to toggle the height of an element.
$('.oldestinititives').mousedown(function() {
$(this).animate({"height": 450}, "slow");
$(this).addClass("pop");
});
$('.pop').mousedown(function() {
$(this).animate({"height": 250}, "slow");
$(this).removeClass("pop");
});
in the CSS, the block is 250px by default. Clicking the element does reveal the content, but clicking it again does not hide it. Using firebug I can see that the class 'pop' is added but it doesn't seem to target it. What is going on?
thanks,
Evan
A: As you are adding the class at runtime, are you using jquery live() to bind events? If not please use it:
http://api.jquery.com/live/
A: At the time you are hooking the mousedown event to the elements with the pop class, there are no elements matching this selector. You have to bind the event as you add the class for this to work. Or even better: use delegate or live to bind the events
A: try this (working example
http://jsfiddle.net/saelfaer/CyD2g/)
$('.oldestinititives').live("click", function() {
if($(this).is('.pop'))
{
$(this).animate({"height": 250}, "slow", function(){
$(this).toggleClass("pop");
});
}
else
{
$(this).animate({"height": 450}, "slow", function(){
$(this).toggleClass("pop");
});
}
});
i took the liberty to merge your two event handlers in one, as they could have been merged, depending on what you actually do inside the function you could make it even shorter without the big if-else structure...
the idea here is that you use .live("click", function(){}); this will bind the event to any item that ever will be a valid candidate for your selector. even when at the time of executing the code the element does not have the right class name or ID yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do we use eval to pop a new window? Here is the code that came across with:
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "','....;");
}
I don't understand why we are using eval in this case, seems like a lot of website are offering this as a solution to open a popup. Why are we not simply using:
var win = window.open("...");
Examples of this code:
Variable sized popup window
Check if popup window is already open
and more on google results
A: Because the original developer didn't understand you could use window['page' + id] there to assign an arbitrarily global variable (no var means it goes up the scope chain, eventually assigning it to the global object, window in a browser).
It's also bad practice, as it's assigning a global variable based on the time (which could be much simpler +new Date) which is never referenced again (at least in this example).
Even it were referenced, it should return a reference, not just assign one. The function should encapsulate its state, not assign a bunch of global variables.
My guess for using the time is so no two windows have the same reference (in theory, there is no guarantee, thanks RobG).
A: The only difference the eval is making there is setting an arbitrary variable... which you have no way of referencing again. I have no idea why anyone in their right mind would suggest this as a solution to opening a window, as your second piece of code demonstrates the "proper" way to do so.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS3 transitions + display none + prevent overscroll So if you're not already familiar, CSS3 transitions do not animate display: none since it removes the targeted element from the DOM altogether. So here's my issue. I have a sidebar with larger popup divs that appear on hover. Unfortunately Since I can only transition on visibility: hidden and opacity: 0 I have overscroll due to the visibly hidden divs being included in the layout and thus making a very long popup which is accounted for in the page's scrollbar.
Looking for some creative solutions for how I can still animate without having the scrollbar all screwed up.
I'm developing local so I don't have a live example to show, but you can see the problem in this screencast: http://dreamstarstudios.com/screencasts/2011-09-27_2111.swf
Thanks in advance!
A: I'm assuming your popup is absolutely positioned so you could do the following:
*
*While hidden, set the popup top to a huge negative value. This moves it off the screen and gets rid of the scrollbar.
*On hover, set the top to the correct value and transition the opacity value.
*Make sure that your CSS transition rules are only for the opacity property.
HTML
<a href="">Popup go now</a>
<div class="popup">
My cat's breath smells like cat food...
</div>
CSS
.popup {
position: absolute;
top: -2000px;
opacity: 0;
transition: opacity 1s ease-in-out;
}
a:hover + .popup,
.popup:hover {
top: 30px;
opacity: 1;
}
Here's the above in action.
Update: To add the left swing, and clean up the mouseout animation, you can use the following code:
.popup {
position: absolute;
top: -2000px;
width: 300px;
left: 0;
opacity: 0;
/* Animate opacity, left and top
opacity and left should animate over 1s, top should animate over 0s
opacity and left should begin immediately. Top should start after 1s. */
transition-property: opacity, left, top;
transition-duration: 1s, 1s, 0s;
transition-delay: 0s, 0s, 1s;
}
a:hover + .popup,
.popup:hover {
top: 30px;
left: 30px;
opacity: 1;
/* All animations should start immediately */
transition-delay: 0s;
}
It does this as follows:
*
*Animation for multiple properties are specified (opacity, left, top).
*transition-delay prevents the top value from being changed until the opacity and left animations are complete. The trick here is that when the element is :hover, there is no delay (opacity, left and top animations all start at once). However once :hover is no longer active, the top animation waits 1 second before starting. This gives opacity and left enough time to finish.
Here's the updated example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Strange segfault in C Ok, so I'm not really sure what is going on here. I have a simple function, int foo(char *filename), that takes filename and counts the words in a file.
int foo(char *filename){
FILE *inFile;
int wordCount = 0;
printf("foo\n"); // test printf() statement (currently prints)
char word[50];
inFile = (&filename, "r");
printf("infile\n"); // test printf() statement (currently prints)
while (1){
printf("while"); // test printf() statement (doesn't print)
fscanf(inFile, "%s", word);
if (feof(inFile))
break;
printf("%d", wordCount); //test printf() statement
wordCount++;
}
fclose(inFile);
return wordCount;
}
As you can see, I print "infile", but not "while". I get a segmentation fault. Does anyone have any idea why this doesn't work Also, is my inFile = (&filename, "r"); statement correct? I'm not that great with pointers.
A: I'm surprised this line actually compiles:
inFile = (&filename, "r");
If you're trying to open a file:
inFile = fopen(filename, "r");
EDIT:
And as mentioned, you need to end your printfs with \n or call fflush(stdout) or it will get buffered and not print.
A: What are you expecting this line to do?
inFile = (&filename, "r");
Because it looks like you're missing a functional call. I suspect you wanted something like this:
inFile = fopen(filename, "r");
That is, the fopen function expects a character pointer, and you have this:
int foo(char *filename){
So you don't need to use the & operator. The & operator returns the address of a variable, so by entering &filename you're ending up with (a pointer to (a pointer to (char)). You'll rarely use the & operator with strings; you'll usually see it used when a function needs to return multiple values (like the Unix wait() function).
There are a number of tutorials out there that talk about C pointers in more detail; a Google search for "c pointers" yields some likely results. And of course, read your K&R :).
A: The reason you don't see the "while" print is because it's not terminated with \n, thus is kept in the buffer and not printed out, by the time the seg fault occurs.
The seg fault occurs at fscanf, because you missed the fopen, and messed up your pointers. @Mystical explained how to fix it.
A: ALWAYS check the return value from fopen(), the call to which seems to be missing.
FILE *inFile = fopen(filename, "r");
if (inFile == 0)
...diagnose error...do not use inFile...
Note the absence of the & from filename in the call to fopen(); you simply don't need it.
The printf() before the fscanf() does not produce anything because the output string does not end with a newline; it is held over until you do print a newline, and the crash occurs before you do that.
The crash occurs because the string "r" is not a valid file stream; if you'd actually called fopen(), it would probably be because the open failed and you did not check it.
If your compiler did not give you warnings about the code, get a better compiler. If it did give you warnings, learn to heed them (and fix them) before posting to StackOverflow.
While you're at it, you might want to consider what happens if the word you get to read is 50 characters or longer. Happiness does not ensue. You should consider using:
while (fscanf("%49s", word) == 1)
wordCount++;
If a word is longer than 49 characters, it will at least now be split up into some number of 49-byte units (each counted as a word) without giving you buffer overflow problems (another source of crashes). If you need a diagnostic print in the loop, so be it; add the braces and print.
I have very, very seldom had cause to use feof() in my (25+ year) programming career. Code using it is generally suspect; I wonder if the person learned Pascal and hasn't unlearned it when learning C.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I fix this Rails AR query to get records that are at least 5 minutes old? What is the best way to write a Rails query that returns records that are at least 5 minutes old? I am using Rails 3.0.1, Ruby 1.9.2 and PostgreSQL. At the moment I have this:
Note.order('date DESC').where('private_note = ? AND (?-created_at) > 300',false, Time.now.utc)
which gets these errors:
Note Load (0.7ms) SELECT "notes".* FROM "notes" WHERE (private_note = 'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORDER BY date DESC
PGError: ERROR: operator does not exist: interval > integer
LINE 1: ...'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORD...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "notes".* FROM "notes" WHERE (private_note = 'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORDER BY date DESC
Completed in 214ms
ActiveRecord::StatementInvalid (PGError: ERROR: operator does not exist: interval > integer
LINE 1: ...'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORD...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "notes".* FROM "notes" WHERE (private_note = 'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORDER BY date DESC):
app/controllers/notes_controller.rb:17:in `public_stream_get_notes'
A sample created_at value is 2011-09-28 01:00:01 UTC
A: Note.where('created_at <= ?', 5.minutes.ago).where(:private_note => false).order('date DESC')
A: Note.where('created_at < ?', Time.now.utc - 5.minutes)
One thing to keep in mind with things like Time.now is that if you end up putting that into a scope, use a lambda instead of passing it directrly to the scope, otherwise Time.now will be constant.
scope :older_than_5_minutes, lambda { order(...).where('...', Time.now.utc - 5.minutes) }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Write stderr on iPhone to both file and console I'm following the suggestion in the answer here for redirecting NSLog output on an iOS device to a file, which works great. The problem is that it no longer shows up in the console on the device. What I'd really like is a way to tee the stderr stream to both the console and the file. Does anyone have an idea how to do that?
A: I found an acceptable answer on another thread (NSLog() to both console and file).
The solution provided there is to only redirect to a file if a debugger is not detected, like this:
if (!isatty(STDERR_FILENO))
{
// Redirection code
}
Thanks to Sailesh for that answer.
A: Once you freopen() the file descriptor, you can read from it and do as you please with the data. Some ideas from this will be useful to you.
You could either write it back out to stdout, or try to write directly to /dev/console. I've never tried to open /dev/console on an iPhone, but I'm guessing it's possible despite being outside of the sandbox. I'm not sure how the app review process will treat it.
A: Or you can redirect to a TCP socket and view on a remote telnet client. No need for XCode this way!
Basically:
*
*Create a standard C function which calls an Obj-C static method:
void tcpLogg_log(NSString* fmt, ...)
{
va_list args;
va_start(args, fmt);
[TCPLogger tcpLog:fmt :args];
va_end(args);
}
*The static Obj-C method:
(void)tcpLog:(NSString*)fmt :(va_list)args
{
NSLogv(fmt, args);
if(sharedSingleton != nil && sharedSingleton.socket != nil)
{
NSString *time = [sharedSingleton.dateFormat stringFromDate:[NSDate date]];
NSString *msg = [[NSString alloc] initWithFormat:fmt arguments:args];
mach_port_t tid = pthread_mach_thread_np(pthread_self());
NSString *str = [NSString stringWithFormat:@"%@[%X]: %@\r\n", time, tid, msg];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[sharedSingleton.socket writeData:data
withTimeout:NETWORK_CLIENT_TIMEOUT_PERIOD
tag:0];
}
}
*Then in your .pch file, add the following lines to override NSLog()
define NSLog(...) tcpLogg_log(__VA_ARGS__);
void tcpLogg_log(NSString* fmt, ...);
Of course more details are required to handle the TCP Socket. Working source code is available here:
https://github.com/driedler/iOS-TCP-Logger/wiki/About
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Combining Images in java Here's my code:
Image partNumberImage = Toolkit.getDefaultToolkit().getImage("D:/partNumber.png");
Image lotNumberImage = Toolkit.getDefaultToolkit().getImage("D:/lotNumber.png");
Image dteImage = Toolkit.getDefaultToolkit().getImage("D:/dte.png");
Image quantityImage = Toolkit.getDefaultToolkit().getImage("D:/quantity.png");
BufferedImage combinedImage = new BufferedImage(486,
151,
BufferedImage.TYPE_INT_RGB);
Graphics g = combinedImage.getGraphics();
combinedImage.createGraphics().setBackground(Color.white);
g.clearRect(0,0, 486, 151);
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);
g.dispose();
Iterator writers = ImageIO.getImageWritersByFormatName("png");
ImageWriter writer = (ImageWriter) writers.next();
if (writer == null) {
throw new RuntimeException("PNG not supported?!");
}
ImageOutputStream out = ImageIO.createImageOutputStream(
new File("D:/Combined.png" ));
writer.setOutput(out);
writer.write(combinedImage);
out.close();
}
My problem is the code will output this image:
what I need is to have white background for the image. Thanks!
A: This looks risky to me:
Graphics g = combinedImage.getGraphics(); // Graphics object #1
combinedImage.createGraphics().setBackground(Color.white); // Graphics object #2
// so now you've set the background color for the second Graphics object only
g.clearRect(0,0, 486, 151); // but clear the rect in the first Graphics object
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);
It appears to me that you may be creating two very distinct Graphics objects, one a Graphics2D object and one a Graphics object. And while you're setting the background color in the Graphics2D object, your clearing a rect in the Graphics object, so it could explain why your background is not white. Why not instead just create one Graphics2D object and use it for everything:
Graphics2D g = combinedImage.createGraphics();
g.setBackground(Color.white);
// Now there is only one Graphics object, and its background has been set
g.clearRect(0,0, 486, 151); // This now uses the correct background color
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);
A: Before you add the images, draw a white rectangle the size of your image:
g.clearRect(0,0, 486, 151);
g.setColor(Color.white);
g.fillRect(0,0,486,151);
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);
g.dispose();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: sql db mail problem while sending in bulk I am using db mail(sql server 2005) to send bulk email(>2000).
The code tat i use is,
exec msdb..sp_send_dbmail
@profile_name = 'My Profile',
@recipients = 'raghav.cinch@gmail.com',
@subject = 'test',
@body = 'test',
@body_format = 'HTML'
If i send few emails(less than 100), all emails are sent successfully. But only bulk emails give me error.
The error I get is,
The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 8 (2011-09-27T21:29:17). Exception Message: Cannot send mails to mail server. (Unable to send to all recipients.).
)
The error comes after 100 or 105 mails. The email addresses are correct and if i sent in cycles of 100, all mails are sent successfully.
I believe it should be some configuration settings tat need to be tweaked. Could someone pls help me in fixing it..
Thanks in advance.
A: Changed the iis6 settings, max queue length for the smtp server and this worked like charm.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Iphone: Does application freeze when run into background? I have an application that upload file to server using NSUrlConnection. It was placed on ViewDidLoad method. It did upload to server while the application is in foreground. Before I call the NSUrlConnection asynchronously, I create temporary file in application directory.
While the files were uploading, I clicked on the iPhone button so that the application will run in the background. First thing I thought the application freeze the upload, but it doesn't. The file still uploading during that time.
Does that mean the application still running normally at the background until the remaining time finished then the application quits?
A: Once the home button is pressed, every application runs in the background for a certain amount of time(usually few seconds) before it enters suspended mode. If you are required to complete a task(in your case file upload) before entering suspended mode, you can use Task completion API.
Even if you are using task completion API, only one thread of your application is running, but not the whole application. Here is the code recommended by apple:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nested INotifyPropertyChanged class won't work got some code what is getting unexpected results:
If i replace the nested class with the Myclass, then there is no problem. What do I miss?
It doesn't matter if I bind text (to an other control) or bind the image.
xaml code:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="DataTemplate_Level">
<Image Source="{Binding Path=MyClass.ImageSource}" Width="48" Height="48"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl x:Name="h" ItemTemplate="{DynamicResource DataTemplate_Level}"/>
</Grid>
</Window>
class code:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var myClass = new WrappedClass()
{
MyClass = new MyClass()
};
var image = new BitmapImage(new Uri("Tiles.png", UriKind.Relative));
int TileSize = 16;
var cropRectangle = new Int32Rect((int)0, 0, TileSize, TileSize);
var croppedBitmap = new CroppedBitmap(image, cropRectangle);
var observableCollection = new ObservableCollection<WrappedClass>();
observableCollection.Add(myClass);
observableCollection.Add(myClass);
observableCollection.Add(myClass);
h.ItemsSource = observableCollection;
}
public class WrappedClass : INotifyPropertyChanged
{
private MyClass _myClass;
public MyClass MyClass
{
get
{
return _myClass;
}
set
{
_myClass = value;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("MyClass"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MyClass : INotifyPropertyChanged
{
private ImageSource _imageSource;
private string _text = "test";
public MyClass()
{
var image = new BitmapImage(new Uri("Tiles.png", UriKind.Relative));
int TileSize = 16;
var cropRectangle = new Int32Rect((int)0, 0, TileSize, TileSize);
_imageSource = new CroppedBitmap(image, cropRectangle);
}
public string Text
{
get
{
return _text;
}
set
{
_text = value;
PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Text"));
}
}
public ImageSource ImageSource
{
get
{
return _imageSource;
}
set
{
_imageSource = value;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ImageSource"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
}
A: I'm guessing you are getting a null reference error, probably wrapped in an invocation error since it is likely happening in your constructor.
Don't do this:
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("MyClass"));
Instead, create a method with a null check:
public void FirePropertyChange(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And call it like so:
FirePropertyChange("MyClass");
A: A couple of things here
*
*Make sure all your classes implement the INotifyPropertyChanged. Especially when dealing with UserControls.
*I prefer not to hardcode the properties as strings - take a look at my post here on how to do this using reflection.
http://tsells.wordpress.com/2011/02/08/using-reflection-with-wpf-and-the-inotifypropertychanged-interface/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Printing a struct using description I would like to know if it is possible to use the description function in the Cocoa framework to log the contents of a struct. For example:
typedef struct {float a,b,c;}list;
list testlist = {1.0,2.5,3.9};
NSLog(@"%@",testlist); //--> 1.0,2.5,3.9
A: No. The description message is a method found in the NSObject protocol, so by definition, must be an object. There is, however, a more convenient way of log debugging, using a LOG_EXPR() macro. This will take objects and structs:
LOG_EXPR(testlist);
Which would output:
testlist = {1.0, 2.5, 3.9};
This code can be found here.
A: description is a method and as such can only be called on an object. In turn, the %@ format specifier only works for objects which respond to description.
You can write your own function to make a pretty NSString with the contents of your struct:
NSString * pretty_string_from_list( list l ){
return [NSString stringWithFormat:@"<list: [%f, %f, %f]>", l.a, l.b, l.c];
}
Then call that function when you log the struct:
NSLog(@"%@", pretty_string_from_list(testlist));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Set Up Route for Accessing Private S3 Content I've been following
https://github.com/thoughtbot/paperclip/wiki/Restricting-Access-to-Objects-Stored-on-Amazon-S3
and
Rails 3, paperclip + S3 - Howto Store for an Instance and Protect Access to try and get Paperclip's expiring links to work. I believe most of what I'm running into is one of the routing variety.
In my pieces_controller I put a method in like this
def download
redirect_to @asset.asset.expiring_url(1000)
end
And then in my routes, I put this:
match "pieces/download"
Then in my view I have:
<%= link_to download_asset_path(piece)%>
It would seem to be far from working, and I'm not sure what is messed up. I know I'm getting routing errors for one, but it's also telling me that my download_asset_path is undefined, which is likely also routing related... I feel like I'm doing everything all wrong.
Tearing my hair out. Thanks!
A: Try modifying your routes file to:
match 'pieces/download' => 'pieces#download', :as => 'download_asset'
Your match needs to tell which controller#action to go to, and the as option will allow you to name the route download_asset_path.
If your pieces controller is for a Piece resource it could be cleaner like:
resources :pieces do
member do
get :download
end
end
But then you would want to change the link to:
link_to 'Link text', download_piece_path(piece)
For further reading: http://guides.rubyonrails.org/routing.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I collect input from an external window using SDL? I'm currently trying to re-write my binder between Ogre and SDL in my game engine. Originally I used the method outlined in the Ogre Wiki here. I recently updated my version of SDL to 1.3 and noticed the "SDL_CreateWindowFrom()" function call and re-implemented my binder to allow Ogre to build the window, and then get the HWND from Ogre to be passed into SDL.
Only one window is made and I see everything renders properly, however no input is collected. I have no idea why. Here's the code I am currently working with (on windows):
OgreWindow = Ogre::Root::getSingleton().createRenderWindow(WindowCaption, Settings.RenderWidth, Settings.RenderHeight, Settings.Fullscreen, &Opts);
size_t Data = 0;
OgreWindow->getCustomAttribute("WINDOW",&Data);
SDLWindow = SDL_CreateWindowFrom(&Data);
SDL_SetWindowGrab(SDLWindow,SDL_TRUE);
I've tried looking around and there are a number of people that have done this to one degree of success or another(such as here or here). But no one seems to comment on handling the input after implementing this.
I originally thought that maybe since SDL does not own the window it wouldn't collect input from it by default, which is reasonable. So I searched the SDL API and only found that one function "SDL_SetWindowGrab()" that seems to relate to input capture. But calling that has no effect.
How can I get SDL to collect input from my Ogre-made window?
A: It has been a while, but I figured I would put in the answer for others that may need it. It turned out to be a bug/incomplete feature in SDL 1.3. The "CreateWindowFrom" method wasn't originally intended to be used exclusively as an input handler. At the time of this writing I know myself and another on my team wrote patches for Windows and Linux that permitted this use to work and submitted those patches to SDL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: If pre loader fails to load content We fetch some image data from Picasa, using yoxview and whilst the data is being fetched, which are image thumbnails.
We display a preloader image.
Now, the data is fetched dynamically, and at times the fetch url we are requesting parses no results. So the Image preloader for the div, keeps whirring away .. basically because the data has failed to load.
So my question is this, if no result is found within say 5 seconds, whilst the preloader is being displayed, can we initiate a timeout, and display a placeholder image overlaying the preloader, with say message .. unable to fetch feed content at this time ??
Our code is like this:
$(document).ready(function(){
$("#yoxview_picasa").yoxview({
dataUrl: 'http://picasaweb.google.com/lh/view?q=<?=$randomResult["suburb"];?>+<?=$randomResult["state"];?>',
dataSourceOptions: {
"max-results": 21,
imgmax: 800
},
onLoadBegin:function(){
$('.imagecontainerburbs').hide();
$('<div class="loading" style="width: 580px; height: 250px;position:relative;margin-top:100px;margin-bottom:-250px;"><center><img src="http://www.pathToPreloaderImage.com/css/images/422.gif" alt="loading"/><br /></center></div>').insertAfter('.imagecontainerburbs');
},
onLoadComplete:function(){
$('.loading').remove();
$('.imagecontainerburbs').find("img").css({'width':'64px','height':'64px'});
$('.imagecontainerburbs').find("img").createLoader();
$('.imagecontainerburbs').fadeIn();
}
});
});
As you can see, we use a nifty piece of php to propagate the data url, from our database.
Essentially the data is fetched like this.
url : picasa.google.com/lh/view? and we apend the query suburb and state to the url.
So if when we ping picasa for a random result, and it has no results .. currently the loader animation continuously displays, what I need to do is if no data is fetched, initiate a placeholder that states, Unable to Fetch Data at this time or whatever.
Any suggestions?
Edit/Update
Given the suggestion below, should I add my code like this?
onLoadBegin:function(){
timer = setTimeout(function() {
// get no data in 20 seconds perform something
$('<img src="http://path to image file.com/placeholder.png">'),
},20*1000);
A: I don't see any sort of timeout option in the yoxview documentation. If they have a timeout internally, it would probably trigger the handlers onLoadError or onLoadNoData. You can start by using handlers for those and see if it either gets called. You may also look at the source and see if they are using any timeouts.
If not, you could implement your own.
$(document).ready(function(){
$("#yoxview_picasa").yoxview({
var timer;
dataUrl: 'http://picasaweb.google.com/lh/view?q=<?=$randomResult["suburb"];?>+<?=$randomResult["state"];?>',
dataSourceOptions: {
"max-results": 21,
imgmax: 800
},
onLoadBegin:function(){
timer = setTimeout(function() {
// got no data in 20 seconds here, decide what to do
}, 20*1000);
$('.imagecontainerburbs').hide();
$('<div class="loading" style="width: 580px; height: 250px;position:relative;margin-top:100px;margin-bottom:-250px;"><center><img src="http://www.pathToPreloaderImage.com/css/images/422.gif" alt="loading"/><br /></center></div>').insertAfter('.imagecontainerburbs');
},
onLoadComplete:function(){
clearTimeout(timer);
$('.loading').remove();
$('.imagecontainerburbs').find("img").css({'width':'64px','height':'64px'});
$('.imagecontainerburbs').find("img").createLoader();
$('.imagecontainerburbs').fadeIn();
}
});
});
A: Ok we figured it out, quite bloody simple actually.
onNoData:function(){
$('.imagecontainerburbs').hide();
$('.loading').hide();
$('<div class="nodata" style="width: 580px; height: 250px;position:relative;margin-top:100px;margin-bottom:-250px;"><center><p>We cannot load data from this suburb, please refresh page and try again.</p><br /></center></div>').insertAfter('.imagecontainerburbs');
},
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Finding Connected Components and reading an adjacency matrix This is actually my first post here. I wasn't aware of this website, and I lurked around the questions and its certainly a place I want to keep coming to.
I'm in my Senior year for Computer Science but my programming skills are not that good, which makes me feel very disappointed in myself.
Anyways, I have a project due on Friday and I've been working on it since Saturday and I keep bashing my head making no progress.
I need to find the connected components in a graph and also read from a file an adjacency matrix.
I first tried in in python, using an igraph python library but I just kept having system errors. So after two days of trying to troubleshoot that, I gave up and moved onto Java where I'm trying to read the array.
Here is my current code that I have thus far, and I'm trying to google the best I can to find the answer. Right now I'm simply trying to read from a file and put the values into my 2d array. I commented out most of everything because I'm trying to simply figure out what I'm doing wrong.
package javaapplication1;
import java.io.*;
import java.util.Scanner;
import tio.*;
public class JavaApplication1 {
public static void adjMatrix() throws FileNotFoundException, IOException{
int i, j, n = 20;
int[][]array = new int[n][n];
String file = ("adjmatrix.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
System.out.println(in.readLine());
in.close();
/*
while(in.hasMoreElements()){
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
array[i][j] = in.readInt();
} // end inner for
} // end outer for
}
//Print array
System.out.println("Here is the matrix: ");
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
System.out.print(array[i][j]);
} // end innerfor
} //end outerfor
*/
} // endclass
/**
* @param args the command line arguments
*/
public static void main(String[] args)
throws IOException{
adjMatrix();
} // end main
} // end class
#
ERROR:
Exception in thread "main" java.io.FileNotFoundException: adjmatrix.txt
(The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:138)
at java.io.FileInputStream.(FileInputStream.java:97)
at java.io.FileReader.(FileReader.java:58)
at javaapplication1.JavaApplication1.adjMatrix(JavaApplication1.java:26)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:60)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
#
A: When you try to open a file without a direct path, Java will try to resolve it from the relative path. Here, since you simply put "adjmatrix.txt", it assumes that the text file is living in the same directory as the class file with the main method that you execute (JavaApplication1 in package JavaApplication1). You should either move the text file into the package right next to the class file or add a more specific path name as Kevin stated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Translating a lambda expression into an expression tree The real world problem I'm trying to solve: I have a database with a bunch of phone numbers stored as strings in an absolutely terrible format (eg "(02) 9971 1209"). The user of my program is going to start typing a phone number and as he types, what he is typing will be sent off and used to filter the list of phone numbers in the database using a "startswith" operation.
The problem is that if the user types "02997", it's not going to match anything because the numbers are stored with the location code enclosed in brackets. In order for this operation to work, the user would have to start every search by typing '('. This is not good.
tl;dr version at the bottom of the question
I took the problem out of it's real world context and into a smaller, sealed solution where I can focus on it without the distractions of a massive codebase. Under such conditions, my solution was to do some linq trickiness:
class Program
{
static string [] phones = {"(02) 9489 3048","(04) 1128 2148","(01) 9971 1208",};
static void Main(string[] args)
{
for (;;)
{
Console.WriteLine("Enter your number: ");
string input = Console.ReadLine();
Func<string, string> strip =
tehstring => tehstring.Where(x => char.IsDigit(x))
.Aggregate("", (x, y) => x + y);
var results = phones.Where(z => strip(z).StartsWith(strip(input)));
foreach (var x in results)
Console.WriteLine(x);
}
}
}
This is all good, works perfectly, does exactly what I need. But it only works in this isolated context: I can't port it back to the codebase where it needs to be implemented because I need to translate it to an expression tree.
The code where I need to wack it down:
static Expression GetOperationExpression(
StringFilterOperation operation,
Expression propertyExpression,
Expression valueExpression)
{
switch (operation)
{
case StringFilterOperation.StartsWith:
var startsWith = typeof(string)
.GetMethod("StartsWith", new Type[] { typeof(string) });
Contract.Assume(startsWith != null);
return Expression.Call(propertyExpression, startsWith, valueExpression);
//etc etc etc
I need to take propertyExpression, and somehow embed the property it is talking about (in this case the table of phone numbers in the external db) in my lambda function. Then I need to decompile the whole thing back to an Expression Tree and return that.
That's where I'm stuck. The best I can come up with is a super long and inelegant line of linq that doesn't even have the right type anyway:
Expression<Func<string[],string, IEnumerable<string>>> expr =
(db, uinput) => db.Where(z => z.Where(x => char.IsDigit(x))
.Aggregate("", (x, y) => x + y)
.StartsWith(uinput.Where(x => char.IsDigit(x))
.Aggregate("",(x,y) => x + y)));
I wanted to do something like this, which still doesn't solve the problem but is slightly neater:
Expression<Func<string, string>> strip =
tehstring => tehstring.Where(x => char.IsDigit(x))
.Aggregate("", (x, y) => x + y);
Expression<Func<string, string, string>> query =
(db, uinput) => db.Where(z => strip(z)
.StartsWith(strip(uinput)));
I've tried applying lots of little alterations to it but it refuses to compile.
tl;dr:
Long story short, what I need to do is take an expression representing a field on a table in a database and transform that expression into one that represents the same thing, but with a filter applied that strips all characters that aren't digits.
A: A lot of the expressions you'd want to use to get the stripped version of the phone numbers probably won't be supported by your LINQ provider.
I'd personally suggest making a database View that shows all the phone numbers in their stripped-down format. Then you can just do a standard StartsWith query against that view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GridView Sort - Is there a better way to perform a gridview sort in asp.net (for sharepoint)? Is there a better way to sort this datagrid?
This does work, however it seems a bit non-reusable.
If you have any ideas, or better ways to handle this, please let me know.
Below is the code. Please let me know if you have any ideas..
protected void grdPropMgrLeaseAgents_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = "A";
if (ViewState[e.SortExpression + "_sort"] != null)
{
sortExpression = ViewState[e.SortExpression + "_sort"].ToString();
}
List<Person> list = (List<Person>)ViewState["propertyManagersAndLeasingAgents"];
if (sortExpression == "A")
{
if (e.SortExpression == "EmpFullName") list.Sort((x, y) => string.Compare(x.EmpFullName, y.EmpFullName));
if (e.SortExpression == "FirstName") list.Sort((x, y) => string.Compare(x.FirstName, y.FirstName));
if (e.SortExpression == "LastName") list.Sort((x, y) => string.Compare(x.LastName, y.LastName));
if (e.SortExpression == "DepartmentName") list.Sort((x, y) => string.Compare(x.DepartmentName, y.DepartmentName));
if (e.SortExpression == "MarketName") list.Sort((x, y) => string.Compare(x.MarketName, y.MarketName));
if (e.SortExpression == "Title") list.Sort((x, y) => string.Compare(x.Title, y.Title));
if (e.SortExpression == "Roles") list.Sort((x, y) => string.Compare(x.Roles, y.Roles));
if (e.SortExpression == "CellPhone") list.Sort((x, y) => string.Compare(x.CellPhone, y.CellPhone));
if (e.SortExpression == "OfficePhone") list.Sort((x, y) => string.Compare(x.OfficePhone, y.OfficePhone));
if (e.SortExpression == "EmailAddress") list.Sort((x, y) => string.Compare(x.EmailAddress, y.EmailAddress));
if (e.SortExpression == "City") list.Sort((x, y) => string.Compare(x.City, y.City));
if (e.SortExpression == "State") list.Sort((x, y) => string.Compare(x.State, y.State));
if (e.SortExpression == "PropertyName") list.Sort((x, y) => string.Compare(x.PropertyName, y.PropertyName));
if (e.SortExpression == "PropertyStreet") list.Sort((x, y) => string.Compare(x.PropertyStreet, y.PropertyStreet));
if (e.SortExpression == "DisplayName") list.Sort((x, y) => string.Compare(x.DisplayName, y.DisplayName));
if (e.SortExpression == "ZipCode") list.Sort((x, y) => string.Compare(x.ZipCode, y.ZipCode));
}
else
{
if (e.SortExpression == "EmpFullName") list.Sort((y, x) => string.Compare(x.EmpFullName, y.EmpFullName));
if (e.SortExpression == "FirstName") list.Sort((y, x) => string.Compare(x.FirstName, y.FirstName));
if (e.SortExpression == "LastName") list.Sort((y, x) => string.Compare(x.LastName, y.LastName));
if (e.SortExpression == "DepartmentName") list.Sort((y, x) => string.Compare(x.DepartmentName, y.DepartmentName));
if (e.SortExpression == "MarketName") list.Sort((y, x) => string.Compare(x.MarketName, y.MarketName));
if (e.SortExpression == "Title") list.Sort((y, x) => string.Compare(x.Title, y.Title));
if (e.SortExpression == "Roles") list.Sort((y, x) => string.Compare(x.Roles, y.Roles));
if (e.SortExpression == "CellPhone") list.Sort((y, x) => string.Compare(x.CellPhone, y.CellPhone));
if (e.SortExpression == "OfficePhone") list.Sort((y, x) => string.Compare(x.OfficePhone, y.OfficePhone));
if (e.SortExpression == "EmailAddress") list.Sort((y, x) => string.Compare(x.EmailAddress, y.EmailAddress));
if (e.SortExpression == "City") list.Sort((y, x) => string.Compare(x.City, y.City));
if (e.SortExpression == "State") list.Sort((y, x) => string.Compare(x.State, y.State));
if (e.SortExpression == "PropertyName") list.Sort((y, x) => string.Compare(x.PropertyName, y.PropertyName));
if (e.SortExpression == "PropertyStreet") list.Sort((y, x) => string.Compare(x.PropertyStreet, y.PropertyStreet));
if (e.SortExpression == "DisplayName") list.Sort((y, x) => string.Compare(x.DisplayName, y.DisplayName));
if (e.SortExpression == "ZipCode") list.Sort((y, x) => string.Compare(x.ZipCode, y.ZipCode));
}
ViewState["propertyManagersAndLeasingAgents"] = list;
this.grdPropMgrLeaseAgents.DataSource = list;
this.grdPropMgrLeaseAgents.DataBind();
if (sortExpression == "A")
{
ViewState[e.SortExpression + "_sort"] = "D";
}
else
{
ViewState[e.SortExpression + "_sort"] = "A";
}
}
A: Have you tried SPGridView. I used SPGridView and LinqDataSource. All the functionality (sorting,paging,filtering) is taken care of.
Here is an example:-
a. The SpridView
<SharePoint:SPGridView runat="server" ID="spgvUserTrainingLists" AutoGenerateColumns="false"
DataSourceID="linqDsEmployeeTrainingLists" DataKeyNames="RowId" OnRowDataBound="spgvUserTrainingLists_RowDataBound"
AllowSorting="true" AllowPaging="true" PageSize="15" AllowFiltering="true" FilteredDataSourcePropertyName="Where"
FilteredDataSourcePropertyFormat='{1} == "{0}"' FilterDataFields=",TrainingType,,Trainer,Status">
<Columns>
<SharePoint:SPBoundField HeaderText="Ref #" SortExpression="RefNo" DataField="RefNo" />
<SharePoint:SPBoundField HeaderText="Type" SortExpression="TrainingType" DataField="TrainingType" />
<asp:TemplateField HeaderText="Training" SortExpression="TrainingTitle">
<ItemTemplate>
<asp:HyperLink ID="hlTrainingDetail" runat="server" Text='<%# Eval("TrainingTitle") %>'
NavigateUrl="#" />
</ItemTemplate>
</asp:TemplateField>
<SharePoint:SPBoundField HeaderText="Trainer" SortExpression="Trainer" DataField="Trainer" />
<SharePoint:SPBoundField HeaderText="Status" SortExpression="Status" DataField="Status" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgDelete" ImageUrl="~/_layouts/images/DELITEM.GIF" runat="server"
UseSubmitBehaviour="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No training yet.
</EmptyDataTemplate>
</SharePoint:SPGridView>
<SharePoint:SPGridViewPager ID="SPGridViewPager1" runat="server" GridViewId="spgvUserTrainingLists" />
<aspweb:LinqDataSource runat="server" ID="linqDsEmployeeTrainingLists" OnSelecting="linqDs_Selecting" />
b. SPGridView filter symbol
protected void spgvUserTrainingLists_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (!string.IsNullOrEmpty(spgvUserTrainingLists.FilterFieldName))
{
for (int i = 0; i < spgvUserTrainingLists.Columns.Count; i++)
{
DataControlField field = spgvUserTrainingLists.Columns[i];
if (field.SortExpression == spgvUserTrainingLists.FilterFieldName)
{
Image filterIcon = new Image();
filterIcon.ImageUrl = "/_layouts/images/filter.gif";
filterIcon.Style[HtmlTextWriterStyle.MarginLeft] = "2px";
Literal headerText = new Literal();
headerText.Text = field.HeaderText;
PlaceHolder panel = new PlaceHolder();
panel.Controls.Add(headerText);
panel.Controls.Add(filterIcon);
e.Row.Cells[i].Controls[0].Controls.Add(panel);
break;
}
}
}
}
}
c. LinqDataSource
protected void linqDs_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
object parameter = null;
if (e.SelectParameters.TryGetValue("employee", out parameter))
{
e.Result = DefaultBLL.GetEmployeeTrainingLists(parameter.ToString());
}
}
Give it a try since you are using SharePoint.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML Canvas Vs Stacked Div Performance basically i have a div set up like so:
<div class="pane">
<div class="banner">
<img class="original" src="images/picture.jpg" width="100%" height="100%" />
<div class="blurred"></div>
<div class="blurred_colour"></div>
<div class="focused"></div>
</div>
</div>
Ok my script hides .original and then gets the source of it and creates 3 different images for each of the divs. They are all canvas tags generated in javascript.
.blurred contains a desaturated and blurred version of the original. .blurred_colour contains a blurred version but in colour. .focused is just the original image.
Now i also put a border image on top of each div and position relative so it appears on top and not below the divs. So if your keeping track, thats 3 divs, 3 canvas images and 3 border images (png) positioned ontop of the 3 canvas images. And the 3 main divs are stacked on to each other. I animate using alot of opacity changes with jQuery animate.
As you can guess, some browsers display this animation fairly choppy and it will probably be worse with less powerful computers.
My question is, would it be possible to rewrite all of this with just 1 canvas tag while still having all of these animations but also have much better performance then how I am currently doing it?
A: It's difficult to say why, exactly, your code is slow here.
You don't have that many DOM elements so that is probably not the issue.
You should probably profile the code. F12 in Chrome or IE, go to profiler tab, run it, take a look at what is eating up all of the time.
What is it you are trying to accomplish, exactly? Some kind of blurring effect? Doing all of this in one canvas is probably preferable provided what you are attempting to do can easily be done that way.
What kind of animation? Are you physically moving DOM elements? That's bad. From a performance perspective, never do anything with the DOM if you can avoid it. If this is the case then putting everything in one canvas will probably help a lot. Again, its hard to say with such little detail.
Are you just doing blurring animation? In general, CSS blurring is faster (And easier to write) than Canvas blurring.
Anyway, the answer is probably not "Too many DOM elements." It is either too much DOM-heavy stuff or repeated work in the animation loop, or too much DOM interaction when all-in-canvas would be better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Help with debugging Error in android custom component EditText UPDATE
making the inner class 'static' fixed it
Please help me find out what the error is in the case below. I have a custom EditText inside an activity which implements the OnKeyListener. It is implemented as an inner class of the Activity
The reason i override plain TickerEditText to parent EditText is because in future i might modify EditText and also wanted to attach a OnKeyListener always to it.
I don't want to do this in Activity's onCreate().
Code compiles fine but I'm having runtime error when the application launches and inflates the view.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<view
class="com.example.android.ticker.TickerActivity$TickerEditText"
android:id="@+id/tickerText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Something !!"
/>
<com.example.android.ticker.customListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tickerListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/customListView"
android:scrollbars="vertical"
android:listSelector="@drawable/list_selector"
/>
</LinearLayout>
Usage
public class TickerActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ticker);
/** Get Reference to UI objects */
mTickerListView = (TickerListView)findViewById(R.id.tickerListView);
mTickerEditText = (EditText)findViewById(R.id.tickerText);
...
}
...
...
...
...
public class TickerEditText extends EditText implements OnKeyListener {
public TickerEditText(Context context) {
super(context);
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN)
if(keyCode == KeyEvent.KEYCODE_ENTER) {
//something
return true;
}
return false;
}
Thanks in advance
A: making the inner class 'static' fixed it
Also moved it as a separate class and called it using
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: in_array function fails I'm using this line:
'.((isset($imgRight) && in_array(1, $imgRight)) ? 'checked="checked"' : '').'
and, in some cases, $imgRight can be false. That's why there's isset(), but it still fails.
What do I need to do to avoid this warning?
A: Just because something is false doesn't mean it's not set:
$foo = false;
isset($foo); //true
You can just use:
($imgRight && in_array(1, $imgRight)) ? 'checked="checked"' : '')
or to be very safe (if imgRgiht might be null, or some non-falsey value that isn't an array):
((!empty($imgRight) && is_array($imgRight) && in_array(1, $imgRight)) ? 'checked="checked"' : '')
A: Change isset($imgRight) to is_array($imgRight). I'm assuming that the value for the checkbox is using array notation for its value.
A: $imgRight will pass isset() if it's false.
A: First, don't use short tags, it'll be deprecated soon!
But to your question: You need to check $imgRight for its state not for its existance (isset)! You can also shortcut some of your code here...and you should also check for it's existance though before you work with it:
if (isset($imgRight)) {
if ($imgRight != false && in_array(1, $imgRight)) {
$chk = 'checked="checked"' }
else { $chk = '';}
}
and in your checkbox element just do
echo $chk;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Qt: Using QTransform object for rotate differs from setting setRotation() in QGraphicsItem While setting a QGraphicsItem rotation, I get different results upon the transformation origin point while using setRotation() and using:
transform = QTransform()
transform.rotate(myAngle)
myItem.setTransform(transform)
In both portion of code, I set setTransformOriginPoint() to the same point.
Results are:
*
*While using setRotation() method, the item is rotated upon its transformation origin point.
*While using the QTransform object, the item is rotated upon item's origin, that is, point (0,0).
My code is more complex than that, but I think It applies the same. The QGraphicsItem is in fact a QGraphicsItemGroup and I can check the issue adding just one item, and in my rotation procedure change the setRotation() method for the QTransform object. The latter, ignores the setTransformOriginPoint().
I'm having this issue for a while, and I dig a lot of resources. I browse the Qt C++ code, and I can see that the setRotation() method modifies a field calles rotation (a real value) in the TransformData structure within the QGraphicsItem. The origin point is also a two field real value in such a structure called xOrigin and yOrigin respectively. The transformation is stored in the tranform field. All this information is used in a variable called: transformData.
So, I don't get why the transformation set in the transformData->transform field is ignoring the values transformData->xOrigin and transformData->yOrigin at the time of being applied.
The code I used to test that issue is the following relevant part (I have an rotate item that receives mouse inputs and applies rotation to the item itself):
# This method using QTransform object....
def mouseMoveEvent(self, event):
if self.pressed:
parent = self.parentItem()
parentPos = parent.boundingRect().center()
newPoint = event.scenePos()
iNumber = (newPoint.x()-parentPos.x())-((newPoint.y()-parentPos.y()))*1j
angle = cmath.phase(iNumber)+1.5*math.pi
self.appliedRotation = (360-math.degrees(angle))%360 - self.angleOffset
transform = QTransform()
transform.rotate(self.appliedRotation)
self.parentItem().setTransform(transform)
# ...Against this one using setRotation()
def mouseMoveEvent(self, event):
if self.pressed:
parent = self.parentItem()
parentPos = parent.boundingRect().center()
newPoint = event.scenePos()
iNumber = (newPoint.x()-parentPos.x())-((newPoint.y()-parentPos.y()))*1j
angle = cmath.phase(iNumber)+1.5*math.pi
self.appliedRotation = (360-math.degrees(angle))%360 - self.angleOffset
self.parentItem().setRotation(self.appliedRotation)
On both, previously the setTransformOriginPoint() is set, but it's not a relevant part to show the code, but just to know that it is done.
I'm getting frustrated to not find a solution to it. As it seems so straightforward, why setting a rotation transformation matrix does not use the transformation origin point that I have set and while using setRotation() method works fine? That question took me to the source code, but now is more confusing as rotation is keeping separated from the transformation applied...
A: I was solving the same problem. I found out that QGraphicsItem::setTransformOriginPoint() is accepted only for QGraphicsItem::setRotation(). It is ignored for QGraphicsItem::setTransform().
I use this code to reach the same behavior for QTransform():
transform = QtGui.QTransform()
centerX = item.boundingRect().width()/2
centerY = item.boundingRect().height()/2
transform.translate( centerX , centerY )
transform.rotate( -rotation )
transform.translate( -centerX , -centerY )
item.setTransform( transform )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: VB.NET Function - Return vs Assignment What is the difference between this two ways of returning value in a function in VB.NET?
Using Return Statement:
Public Function Foo() As String
Return "Hello World"
End Function
Using Assignment:
Public Function Foo() As String
Foo = "Hello World"
End Function
I'm using the first one then I saw someone using the second. I wonder if there's a benefit I could get using the second.
A: Think of it this way:
Public Function Foo() As String
Foo = "Hello World"
OtherFunctionWithSideEffect()
End Function
vs
Public Function Foo() As String
Return "Hello World"
OtherFunctionWithSideEffect()
End Function
Now can you see the difference?
In practice, modern VB.Net should almost always prefer the latter style (Return).
A: Testing this in LinqPad:
Public Function myString() As String
Return "Hello World"
End Function
Public Function myString2() As String
myString2 = "Hello World"
End Function
Here's the IL output:
myString:
IL_0000: ldstr "Hello World"
IL_0005: ret
myString2:
IL_0000: ldstr "Hello World"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ret
So in a sense the IL would add two more lines but this is a small diffence i think.
A: Both are valid but using Return saves having to add Exit Function if you want to return part way through a function so it is preferable:
If param.length=0 then
Msgbox "Invalid parameter length"
Return Nothing
End If
Compare with:
If param.length=0 then
Msgbox "Invalid parameter length"
Foo = Nothing
Exit Function
End If
Also If you use Return you don't have to remember to right click Rename to rename all instances of Foo to FooNew if you decide to change the name of your function.
A: Alongside the other answers, there is also a difference, as follows:
Public Function Test() As Integer
Try
Dim retVal as Integer = 0
retVal = DoSomethingExceptional()
Catch ex as Exception ' bad practice, I know
Finally
Test = retVal
End Try
End Function
You can't put a Return in a Finally block, but you can assign the value of the function there.
A: Its a legacy carry over from basic days.
Return will leave the scope immediately, while assignment wont.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Getting Selected values from Jquery multiselct in asp.net Looked and found solutions with broken links or that did not work for me, that said I am using the multiselect found here http://abeautifulsite.net/blog/2008/04/jquery-multiselect/ I need to get the selected checkboxes when I hit a button to use them in c#, I am totally stuck on this one and the example used in the demo that does it is in php :-(
JQuery:
$(document).ready(function () {
$("#EGM").multiSelect({ selectAll: false, oneOrMoreSelected: '*' });
});
Control:
<select id="EGM" multiple="multiple" style="width: 100px;">
<optgroup label="EGM">
<option>data</option>
<option>driven</option>
<option>dropdown</option>
</optgroup>
<optgroup label="System Type">SystemType
<option>data</option>
<option>driven</option>
<option>dropdown</option>
</optgroup>
</select>
Where I need my selected values in the code behind:
protected void SubmitButton_Click(object sender, EventArgs e)
{
//what goes here?!?
}
A: The proper way to do this would be to change <select ...> to <asp:ListBox ...> and update your script to
$(document).ready(function() {
$('#<%=this.EGM.ClientID%>').multiSelect(...);
});
But the <asp:ListBox> control doesn't natively support optgroup inner elements. There are workarounds using ControlAdapters (see: Dropdownlist control with <optgroup>s for asp.net (webforms)? - VB.NET). Using this, you can access the ListItems directly.
That said, a less proper yet less time consuming way, you could also just dump $('#EGM').val() into an <asp:HiddenField> by specifying a callback method in the multiSelect initializer and enumerate the array in the code behind.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: programatically install headers and dependent headers using scons I'm using scons as my build system and I'd like to install my project's development headers using scons as well. I'd like to avoid maintaining a list of all the needed headers and their include dependencies and instead use the built-in dependency parsing magic of scons to provide this list for me.
As an example I have 2 headers I want to install, explicitly, Foo1.h and Foo2.h:
/* Foo1.h */
#ifndef FOO1_H_
#define FOO1_H_
#include "Bar.h"
#include <somelibrary.h>
/* header contents */
#endif /* FOO1_H_ */
and
/* Foo2.h */
#ifndef FOO2_H_
#define FOO2_H_
/* header contents */
#endif /* FOO2_H_ */
Since Bar.h is required by Foo1.h, I want it to be installed too, automagically. somelibrary.h shouldn't be part of the installed headers. There has to be some way to accomplish this or there has to be some reason what I'm trying to do isn't advisable.
Thanks for any help!
A: Well, I figured out the answer. Here's the code snippet that'll do exactly what I was talking about:
def getDependentIncludes(environ, explicit_includes, search_path, depincludes):
for inc in explicit_includes:
if inc not in depincludes:
depincludes.add(inc)
incs = SCons.Defaults.CScan(inc, environ, search_path)
getDependentIncludes(environ, incs, search_path, depincludes)
# create a set of all the headers
development_headers = set()
# call function, with development_headers storing the result
getDependentIncludes(env,
external_facing_headers,
include_dirs, development_headers)
# print the glorious results
names = map(lambda x : '"./' + os.path.relpath(str(x), Dir("#").abspath) + '"', development_headers)
names.sort()
print " ".join(names)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC View and the System.Speech.Synthesis namespace This is very strange. An MVC View refuses to recognize the System.Speech namespace. What's the deal? And is there a work around for this? I have a ViewModel that has the VoiceAge and VoiceGender enum properties from this namespace, but the MVC view isn't playing ball.
Repro
*
*Create a new MVC 3 project
*Add the "System.Speech" reference
*Try to navigate to the System.Speech namespace in the view
In the Controller it's no problem:
using System.Speech.Synthesis;
using System.Web.Mvc;
namespace MvcApplication6.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
VoiceAge voiceAge = VoiceAge.Adult;
return View();
}
}
}
The View, not so much:
I've even added the namespace to the web.config, no luck:
<pages>
<namespaces>
<add namespace="System.Speech.Synthesis" />
A: Make sure that the System.Speech assembly is present in the <assemblies> section of your web.config:
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Speech, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
Once it is added there make sure you recompile, close and re-open the .aspx view and then, normally, it should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: oneToMany bidirectional does not work when datasource has transactions set as serializable i have a app that uses Spring,Struts, Hibernate and JPA. So i have two entities, Company and Location. Company is in oneToMany relation with Location, and location in ManyToOne to Company.
Location Entity:
@Entity<br>
@Table(name = "locations")<br>
@Access(AccessType.PROPERTY)<br>
public class Location implements Serializable, Comparable<Location> {
private Company company;
@ManyToOne
@JoinColumn(name="company_id")
public Company getCompany(){
return this.company;
}
public void setCompany(Company c){
this.company = c;
}
}
Company Entity:
@Entity
@Access(AccessType.PROPERTY)
@Table(name = "company")
public class Company implements Serializable {
private Integer id;
private String name;
private List<Location> locations;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy="company")
public List<Location> getLocations(){
return this.locations;
}
public void setLocations(List<Location> l){
this.locations = l;
}
public void addLocation(Location l){
if (locations == null)
locations = new ArrayList<Location>();
if (!locations.contains(l))
locations.add(l);
if (l.getCompany()!=this)
l.setCompany(this);
}
public void removeLocation(Location l){
if (locations != null){
if (locations.contains(l))
locations.remove(l);
}
}
}
and then when i want to add a new location i have a method in locationService :
GenericService:
public abstract class GenericService {
protected Logger logger = Logger.getLogger(getClass());
@PersistenceContext(type = PersistenceContextType.EXTENDED,unitName = "MyPU")
protected EntityManager em;
public void setEntityManager(EntityManager em) {
this.em = em;
}
public EntityManager getEntityManager() {
return em;
}
}
Location Service:
@Transactional
public class LocationServiceImpl extends GenericService implements iLocationService {
@Override
public Boolean saveLocation(LocationForm lf) {
Location l = new Location();
Company c = companyService.getCompany(lf.getCompanyForm().getId());
// set all location properties here from LocationForm Obj
l.setCompany(c);
this.em.persist(l);
c.addLocation(l);
return true;
}
}
I have to specify that as a conection pool i use glassfish JDBC Connection Pool where i have enabled transactions with repetable read level. Everything is ok now, but if a switch from repetable read to serializable saveLocation method works no more.
This is the debug log when i run saveLocation() with serialize transaction level:
INFO: DEBUG [http-thread-pool-8080(5)] (SQLStatementLogger.java:111) -
insert
into
locations
(company_id, emailTransfer, liveTransfer, name, outbound_prefix, queue_id, smsTransfer, welcomeMessage)
values
(?, ?, ?, ?, ?, ?, ?, ?)
INFO: DEBUG [http-thread-pool-8080(5)] (SQLStatementLogger.java:111) -
select
locations0_.company_id as company9_153_1_,
locations0_.id as id1_,
locations0_.id as id146_0_,
locations0_.company_id as company9_146_0_,
locations0_.emailTransfer as emailTra2_146_0_,
locations0_.liveTransfer as liveTran3_146_0_,
locations0_.name as name146_0_,
locations0_.outbound_prefix as outbound5_146_0_,
locations0_.queue_id as queue6_146_0_,
locations0_.smsTransfer as smsTrans7_146_0_,
locations0_.welcomeMessage as welcomeM8_146_0_
from
locations locations0_
where
locations0_.company_id=?
So then i get :
INFO: WARN [http-thread-pool-8080(5)] (JDBCExceptionReporter.java:233) - SQL Error: 1205, SQLState: 41000
INFO: ERROR [http-thread-pool-8080(5)] (JDBCExceptionReporter.java:234) - Lock wait timeout exceeded; try restarting transaction
some parts from applicationContext.xml
<bean id="txManagerVA" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emfVA" />
</bean>
<bean id="emfVA" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="vsDS" />
<property name="persistenceUnitName" value="MyPU"/>
</bean>
<jee:jndi-lookup id="vsDS" jndi-name="jdbc/MyJndiDS"/>
<tx:annotation-driven transaction-manager="txManagerVA" />
It seems that after that insert the table is locked and no other operation can be performed upon it. As i said before if i change the Transaction Isolation to Repetable Read everything is ok.
Can someone explain me this behavior ?
Thanks
A: Add cascade level
@OneToMany(mappedBy="company", cascade = CascadeType.ALL)
public List<Location> getLocations(){
return this.locations;
}
Then add locations to company where ever and save company not the locations.You are running into a deadlock otherwise.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to elegantly deal with timezones I have a website that is hosted in a different timezone than the users using the application. In addition to this, users can have a specific timezone. I was wondering how other SO users and applications approach this? The most obvious part is that inside the DB, date/times are stored in UTC. When on the server, all date/times should be dealt with in UTC. However, I see three problems that I'm trying to overcome:
*
*Getting the current time in UTC (solved easily with DateTime.UtcNow).
*Pulling date/times from the database and displaying these to the user. There are potentially lots of calls to print dates on different views. I was thinking of some layer in between the view and the controllers that could solve this issue. Or having a custom extension method on DateTime (see below). The major down side is that at every location of using a datetime in a view, the extension method must be called!
This would also add difficulty to using something like the JsonResult. You could no longer easily call Json(myEnumerable), it would have to be Json(myEnumerable.Select(transformAllDates)). Maybe AutoMapper could help in this situation?
*Getting input from the user (Local to UTC). For example, POSTing a form with a date would require converting the date to UTC before. The first thing that comes to mind is creating a custom ModelBinder.
Here's the extensions that I thought of using in the views:
public static class DateTimeExtensions
{
public static DateTime UtcToLocal(this DateTime source,
TimeZoneInfo localTimeZone)
{
return TimeZoneInfo.ConvertTimeFromUtc(source, localTimeZone);
}
public static DateTime LocalToUtc(this DateTime source,
TimeZoneInfo localTimeZone)
{
source = DateTime.SpecifyKind(source, DateTimeKind.Unspecified);
return TimeZoneInfo.ConvertTimeToUtc(source, localTimeZone);
}
}
I would think that dealing with timezones would be such a common thing considering a lot of applications are now cloud-based where the server's local time could be much different than the expected time zone.
Has this been elegantly solved before? Is there anything that I'm missing? Ideas and thoughts are much appreciated.
EDIT: To clear some confusion I thought add some more details. The issue right now isn't how to store UTC times in the db, it's more about the process of going from UTC->Local and Local->UTC. As @Max Zerbini points out, it's obviously smart to put the UTC->Local code in the view, but is using the DateTimeExtensions really the answer? When getting input from the user, does it make sense to accept dates as the user's local time (since that's what JS would be using) and then use a ModelBinder to transform to UTC? The user's timezone is stored in the DB and is easily retrieved.
A: In the events section on sf4answers, users enter an address for an event, as well as a start date and an optional end date. These times are translated into a datetimeoffset in SQL server that accounts for the offset from UTC.
This is the same problem you are facing (although you are taking a different approach to it, in that you are using DateTime.UtcNow); you have a location and you need to translate a time from one timezone to another.
There are two main things I did which worked for me. First, use DateTimeOffset structure, always. It accounts for offset from UTC and if you can get that information from your client, it makes your life a little easier.
Second, when performing the translations, assuming you know the location/time zone that the client is in, you can use the public info time zone database to translate a time from UTC to another time zone (or triangulate, if you will, between two time zones). The great thing about the tz database (sometimes referred to as the Olson database) is that it accounts for the changes in time zones throughout history; getting an offset is a function of the date that you want to get the offset on (just look at the Energy Policy Act of 2005 which changed the dates when daylight savings time goes into effect in the US).
With the database in hand, you can use the ZoneInfo (tz database / Olson database) .NET API. Note that there isn't a binary distribution, you'll have to download the latest version and compile it yourself.
At the time of this writing, it currently parses all of the files in the latest data distribution (I actually ran it against the ftp://elsie.nci.nih.gov/pub/tzdata2011k.tar.gz file on September 25, 2011; in March 2017, you'd get it via https://iana.org/time-zones or from ftp://fpt.iana.org/tz/releases/tzdata2017a.tar.gz).
So on sf4answers, after getting the address, it is geocoded into a latitude/longitude combination and then sent to a third-party web service to get a timezone which corresponds to an entry in the tz database. From there, the start and end times are converted into DateTimeOffset instances with the proper UTC offset and then stored in the database.
As for dealing with it on SO and websites, it depends on the audience and what you are trying to display. If you notice, most social websites (and SO, and the events section on sf4answers) display events in relative time, or, if an absolute value is used, it's usually UTC.
However, if your audience expects local times, then using DateTimeOffset along with an extension method that takes the time zone to convert to would be just fine; the SQL data type datetimeoffset would translate to the .NET DateTimeOffset which you can then get the universal time for using the GetUniversalTime method. From there, you simply use the methods on the ZoneInfo class to convert from UTC to local time (you'll have to do a little work to get it into a DateTimeOffset, but it's simple enough to do).
Where to do the transformation? That's a cost you are going to have to pay somewhere, and there's no "best" way. I'd opt for the view though, with the timezone offset as part of the view model presented to the view. That way, if the requirements for the view change, you don't have to change your view model to accommodate the change. Your JsonResult would simply contain a model with the IEnumerable<T> and the offset.
On the input side, using a model binder? I'd say absolutely no way. You can't guarantee that all the dates (now or in the future) will have to be transformed in this way, it should be an explicit function of your controller to perform this action. Again, if the requirements change, you don't have to tweak one or many ModelBinder instances to adjust your business logic; and it is business logic, which means it should be in the controller.
A: This is just my opinion, I think that MVC application should separate well data presentation problem from data model management. A database can store data in local server time but it's a duty of the presentation layer to render datetime using local user timezone. This seems to me the same problem as I18N and number format for different countries.
In your case, your application should detect the Culture and timezone of the user and change the View showing different text, number and datime presentation, but the stored data can have the same format.
A: After several feedbacks, here is my final solution which I think is clean and simple and covers daylight saving issues.
1 - We handle the conversion at model level. So, in the Model class, we write:
public class Quote
{
...
public DateTime DateCreated
{
get { return CRM.Global.ToLocalTime(_DateCreated); }
set { _DateCreated = value.ToUniversalTime(); }
}
private DateTime _DateCreated { get; set; }
...
}
2 - In a global helper we make our custom function "ToLocalTime":
public static DateTime ToLocalTime(DateTime utcDate)
{
var localTimeZoneId = "China Standard Time";
var localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(localTimeZoneId);
var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, localTimeZone);
return localTime;
}
3 - We can improve this further, by saving the timezone id in each User profile so we can retrieve from the user class instead of using constant "China Standard Time":
public class Contact
{
...
public string TimeZone { get; set; }
...
}
4 - Here we can get the list of timezone to show to user to select from a dropdownbox:
public class ListHelper
{
public IEnumerable<SelectListItem> GetTimeZoneList()
{
var list = from tz in TimeZoneInfo.GetSystemTimeZones()
select new SelectListItem { Value = tz.Id, Text = tz.DisplayName };
return list;
}
}
So, now at 9:25 AM in China, Website hosted in USA, date saved in UTC at database, here is the final result:
5/9/2013 6:25:58 PM (Server - in USA)
5/10/2013 1:25:58 AM (Database - Converted UTC)
5/10/2013 9:25:58 AM (Local - in China)
EDIT
Thanks to Matt Johnson for pointing out the weak parts of original solution, and sorry for deleting original post, but got issues getting right code display format... turned out the editor has problems mixing "bullets" with "pre code", so I removed the bulles and it was ok.
A: Not that this is a recommendation, its more sharing of a paradigm, but the most agressive way I've seen of handling timezone information in a web app (which is not exclusive to ASP.NET MVC) was the following:
*
*All date times on the server are UTC.
That means using, like you said, DateTime.UtcNow.
*Try to trust the client passing dates to the server as little as possible. For example, if you need "now", don't create a date on the client and then pass it to the server. Either create a date in your GET and pass it to the ViewModel or on POST do DateTime.UtcNow.
So far, pretty standard fare, but this is where things get 'interesting'.
*
*If you have to accept a date from the client, then use javascript to make sure the data that you are posting to the server is in UTC. The client knows what timezone it is in, so it can with reasonable accuracy convert times into UTC.
*When rendering views, they were using the HTML5 <time> element, they would never render datetimes directly in the ViewModel. It was implemented as as HtmlHelper extension, something like Html.Time(Model.when). It would render <time datetime='[utctime]' data-date-format='[datetimeformat]'></time>.
Then they would use javascript to translate UTC time into the clients local time. The script would find all the <time> elements and use the date-format data property to format the date and populate the contents of the element.
This way they never had to keep track of, store, or manage a clients timezone. The server didn't care what timezone the client was in, nor had to do any timezone translations. It simply spit out UTC and let the client convert that into something that was reasonable. Which is easy from the browser, because it knows what timezone it is in. If the client changed his/her timezone, the web application would automatically update itself. The only thing that they stored were the datetime format string for the locale of the user.
I'm not saying it was the best approach, but it was a different one that I had not seen before. Maybe you'll glean some interesting ideas from it.
A: For output, create an display/editor template like this
@inherits System.Web.Mvc.WebViewPage<System.DateTime>
@Html.Label(Model.ToLocalTime().ToLongTimeString()))
You can bind them based on attributes on your model if you want only certain models to use those templates.
See here and here for more details on creating custom editor templates.
Alternatively, since you want it to work for both input and output, I would suggest extending a control or even creating your own. That way you can intercept both the input and outputs and convert the text/value as needed.
This link will hopefully push you in the right direction if you want to go down that path.
Either way, if you want an elegant solution, its going to be a bit of work. On the bright side, once you have done it once you can keep it in your code library for future use!
A: This is probably a sledgehammer to crack a nut but you could inject a layer between the UI and Business layers which transparently converts datetimes to the local time on returned object graphs, and to UTC on input datetime parameters.
I imagine this could be achieved using PostSharp or some inversion of control container.
Personally, I'd just go with explicitly converting your datetimes in the UI...
A: I wanted to store dates as DateTimeOffset so that I could maintain the Time Zone Offset of the user that writes to the database. However, I wanted to only use DateTime inside of the application itself.
So, local time zone in, local time zone out. Regardless of who/where/when the user is looking at the data, it will be a local time to the observer - and changes are stored as UTC + local offset.
Here is how I achieved this.
1.
Firstly, I needed to get the web client's local time zone offset and store this value on the web server:
// Sets a session variable for local time offset from UTC
function SetTimeZone() {
var now = new Date();
var offset = now.getTimezoneOffset() / 60;
var sign = offset > 0 ? "-" : "+";
var offset = "0" + offset;
offset = sign + offset + ":00";
$.ajax({
type: "post",
url: prefixWithSitePathRoot("/Home/SetTimeZone"),
data: { OffSet: offset },
datatype: "json",
traditional: true,
success: function (data) {
var data = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("SetTimeZone failed");
}
});
}
The format is intended to match that of the SQL Server DateTimeOffset type.
SetTimeZone - just sets the value of Session variable. When the user logs on, I incorporate this value into the User profile cache.
2.
As a user submits a change to the database, I filter the DateTime value through a utility class:
cmdADO.Parameters.AddWithValue("@AwardDate", (object)Utility.ConvertLocal2UTC(theContract.AwardDate, theContract.TimeOffset) ?? DBNull.Value);
The Method:
public static DateTimeOffset? ConvertLocal2UTC(DateTime? theDateTime, string TimeZoneOffset)
{
DateTimeOffset? DtOffset = null;
if (null != theDateTime)
{
TimeSpan AmountOfTime;
TimeSpan.TryParse(TimeZoneOffset, out AmountOfTime);
DateTime datetime = Convert.ToDateTime(theDateTime);
DateTime datetimeUTC = datetime.ToUniversalTime();
DtOffset = new DateTimeOffset(datetimeUTC.Ticks, AmountOfTime);
}
return DtOffset;
}
3.
When I and reading in the date from the SQL Server, I am doing this:
theContract.AwardDate = theRow.IsNull("AwardDate") ? new Nullable<DateTime>() : DateTimeOffset.Parse(Convert.ToString(theRow["AwardDate"])).DateTime;
In the controller, I modify the datetime to match the local time of the observer. (I am sure someone can do better with an extension or something):
theContract.AwardDate = Utilities.ConvertUTC2Local(theContract.AwardDate, CachedCurrentUser.TimeZoneOffset);
The method:
public static DateTime? ConvertUTC2Local(DateTime? theDateTime, string TimeZoneOffset)
{
if (null != theDateTime)
{
TimeSpan AmountOfTime;
TimeSpan.TryParse(TimeZoneOffset, out AmountOfTime);
DateTime datetime = Convert.ToDateTime(theDateTime);
datetime = datetime.Add(AmountOfTime);
theDateTime = new DateTime(datetime.Ticks, DateTimeKind.Utc);
}
return theDateTime;
}
In the View, I am just displaying/editing/validating a DateTime.
I hope this helps someone who has a similar need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "153"
}
|
Q: Solr not matching. Threshold setting, or something weird? I'm using solr to search for articles. I created 2 test "body" sentences which have the common word "tall", but there is no match.
The Query---> Body:"There are tall people outside" AND !UserId:2
Does not match a post with:
Body: the KU tower is really tall
UserId:3
Is this just simply a very low matching score? or is there something else going on here? In the case of a low matching score should it really be that low? The body sentences are very short and share a common word, I would have expected some match.
EDIT: I think the matching isn't happening as a result of having the !UserId: 2 condition. If I try to match body sentences without that, its very liberal. Can anyone explain this? and perhaps how to best structure a query to avoid this type of specific behavior?
Thanks!
A: I have seen some funky behavior with the ! operator with Solr. I would suggest you use the - (negative indicator) instead as shown in the SolrQuerySyntax Wiki Page. Try changing your original query to Body:"There are tall people outside" AND -UserId:2 to see if that works as you are expecting.
A: For those who come after me, I found a solution however not necessarily an explanation for its behavior.
The Solr query:
(PostBody:There are tall people outside) AND !UserId:2
worked as I desired above. Note that if the quotes are added around the body, it does not match. I believe Solr attempts to match such a query as a single string rather than individual words.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP walking and print multi dimensional array anyone can help me with some coding here?
I got the following array config:
$array[1]['areaname'] = 'Area 1';
$array[1][1]['areaname'] = 'Sub Area 1';
$array[1][2]['areaname'] = 'Sub Area 2';
$array[1][3]['areaname'] = 'Sub Area 3';
$array[2]['areaname'] = 'Area 2';
$array[2][1]['areaname'] = 'Sub Area 1';
I want display the following:
<ul>
<li>
Area 1
<ul>
<li>Sub Area 1</li>
<li>Sub Area 2</li>
<li>Sub Area 3</li>
</ul>
</li>
<li>
Area 2
<ul>
<li>Sub Area 1</li>
</ul>
</li>
</ul>
I need a code where I can have as many sub area as I want. Example:
$array[1][1][2][3][4]['areaname'];
There are also another condition. The array got other elements such as $array[1]['config'], $array[1][2][3]['link'] or $array[1][another array of elements that should not be into the loop] ... I only need print the areaname.
A: $array = array();
$array[1]['areaname'] = 'Area 1';
$array[1][1]['areaname'] = 'Sub Area 1';
$array[1][2]['areaname'] = 'Sub Area 2';
$array[1][3]['areaname'] = 'Sub Area 3';
$array[2]['areaname'] = 'Area 2';
$array[2][1]['areaname'] = 'Sub Area 1';
function generate_html_list_recursive( &$data, $labelKey )
{
// begin with an empty html string
$html = '';
// loop through all items in this level
foreach( $data as $key => &$value )
{
// where only interested in numeric items
// as those are the actual children
if( !is_numeric( $key ) )
{
// otherwise continue
continue;
}
// if no <li> has been created yet, open the <ul>
$html .= empty( $html ) ? '<ul>' : '';
// extract the label from this level's array, designated by $labelKey
$label = isset( $value[ $labelKey ] ) ? $value[ $labelKey ] : '';
// open an <li> and append the label
$html .= '<li>' . $label;
// call this funcion recursively
// with the next level ($value) and label key ($labelKey)
// it will figure out again whether that level has numeric children as well
// returns a new complete <ul>, if applicable, otherwise an empty string
$html .= generate_html_list_recursive( $value, $labelKey );
// close our currently open <li>
$html .= '</li>';
}
// if this level has <li>'s, and therefor an opening <ul>, close the <ul>
$html .= !empty( $html ) ? '</ul>' : '';
// return the resulting html
return $html;
}
echo generate_html_list_recursive( $array, 'areaname' );
A: You can try to use array_walk() or array_walk_recursive().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: maximum and minimum allowed memory Can you point me to an API or method used to retrieve the maximum and allowed minimum video graphics memory of my local system ? I have looked into WMI and found none to help me with this. For my laptop it is reported a range of 8-256 MB, I can only get 256. Where is that 8 coming from ? Please ask if you think my question is unreal.
A: unless you are trying to get the hardware spec related to graphic.
I don't think its practical to ask the OS about the min and max, as they can use virtual mem/mem-management to dymanically adjust that as needed.
A: I guess 8 is the minimum value required so that video card will be able to display a GUI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flash Builder 4.5 list issue I have list populated with different data from PHP and when pressed it opens a URL, but when I return to the list from the browser, it has the selection I made to go to browser still selected. So how do I reset the selection? By the way, its a flex mobile app.
A: When you want to reset the List uses
list.selectedIndex = -1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't get $.proxy to work, what am I doing wrong? I'm trying to use proxy inside the jQuery UI Dialog for a $.post AJAX call, but I can't seem to get it to work, it's not running the alert box, but the post is working successfully.
Here's were I'm at, this is the create button on the dialog.
'Create Category' : function(){
var newCategory = $('#new-category-name').val();
if(newCategory != ''){
var data = {category:newCategory, ci_csrf_token: $("input[name=ci_csrf_token]").val()};
$.post('/create/category', data, $.proxy(this.ajaxSuccess, this),'json');
}
ajaxSuccess = function(data)
{
alert ("Here");
// Handle Data
$(this).dialog('close');
}
},
'Cancel' : function(){
$(this).dialog('close');
}
I've also tried this.ajaxSuccess = function(data) and ajaxSuccess: function(data) in the dialog initialization with no luck.
Any help would be appreciated.
I've also setup this fiddle if you need it: http://jsfiddle.net/CubedEye/CfmtJ/
A: If I understood correctly, you could reuse your logic to handle the data and close the dialog with something like this:
function handleData(data, dg) {
alert(data);
$(dg).dialog('close');
}
//$('#add-category-dialog').ajaxSuccess(function(){
// $(this).dialog('close');
//});
$('#add-category-dialog').dialog({
modal: true,
buttons: {
'Create Category' : function(){
$.post('/', {}, function(data){
handleData("test",$('#add-category-dialog'))
});
},
'Cancel': function(){
$(this).dialog('close');
}
},
});
A: You need to declare the function before using it. Also, you may want to do that with the var keyword, so the variable is not in the global scope. See this in action: http://jsfiddle.net/william/CfmtJ/5/.
You can also achieve this without using $.proxy(); you can use $.ajax() with the context option. So, the original $.post() would look like this:
$.ajax({
type: 'POST',
context: this,
data: {},
success: ajaxSuccess
});
See this in action: http://jsfiddle.net/william/CfmtJ/6/.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: List Activity Null Pointer Exception. Force Close on Emulator Start Up Here is the code for my ListActivity:
public class CornellRSS extends ListActivity {
private final static String rssUrl = "http://news.cornellcollege.edu/rss";
RSSParser parser;
ArrayList<Message> messages;
private ProgressDialog pd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
messages = new ArrayList<Message>();
parser = new RSSParser(rssUrl);
loadMessages();
String[] titles = new String[messages.size()];
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, titles));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String keyword = (String) ((TextView) view).getText();
Message target = getMessage(keyword);
Bundle b = new Bundle();
b.putString(RSSHandler.TITLE, target.getTitle());
b.putString(RSSHandler.DESCRIPTION, target.getTitle());
b.putString(RSSHandler.LINK, target.getTitle());
b.putString(RSSHandler.PUB_DATE, target.getTitle());
Intent intent = new Intent(view.getContext(), RSSFeed.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
I keep getting the null pointer exception and can't find a solution. Any help?
EDIT!
The arraylist messages is modified in the method load messages.
The LogCat message at the top is just: "09-28 01:45:06.726: ERROR/AndroidRuntime(755): java.lang.NullPointerException"
The full error is: 09-28 01:45:06.726: ERROR/AndroidRuntime(755):
FATAL EXCEPTION: main 09-28 01:45:06.726: ERROR/AndroidRuntime(755):
java.lang.NullPointerException 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
09-28 01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.ArrayAdapter.getView(ArrayAdapter.java:323) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.AbsListView.obtainView(AbsListView.java:1430) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.ListView.makeAndAddView(ListView.java:1745) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.ListView.fillDown(ListView.java:670) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.ListView.fillFromTop(ListView.java:727) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.ListView.layoutChildren(ListView.java:1598) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.AbsListView.onLayout(AbsListView.java:1260) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.view.View.layout(View.java:7175) 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
android.widget.FrameLayout.onLayout(FrameLayout.java:338) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.view.View.layout(View.java:7175) 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
09-28 01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
09-28 01:45:06.726: ERROR/AndroidRuntime(755): at
android.widget.LinearLayout.onLayout(LinearLayout.java:1047) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.view.View.layout(View.java:7175) 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
android.widget.FrameLayout.onLayout(FrameLayout.java:338) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.view.View.layout(View.java:7175) 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
android.view.ViewRoot.performTraversals(ViewRoot.java:1140) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.view.ViewRoot.handleMessage(ViewRoot.java:1859) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.os.Handler.dispatchMessage(Handler.java:99) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
android.os.Looper.loop(Looper.java:123) 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
android.app.ActivityThread.main(ActivityThread.java:3683) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
java.lang.reflect.Method.invokeNative(Native Method) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
java.lang.reflect.Method.invoke(Method.java:507) 09-28 01:45:06.726:
ERROR/AndroidRuntime(755): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-28 01:45:06.726: ERROR/AndroidRuntime(755): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-28
01:45:06.726: ERROR/AndroidRuntime(755): at
dalvik.system.NativeStart.main(Native Method) 09-28 01:45:08.624:
ERROR/InputDispatcher(72): channel '4093eaf0 cc.rss/cc.rss.CornellRSS
(server)' ~ Consumer closed input channel or an error occurred.
events=0x8 09-28 01:45:08.636: ERROR/InputDispatcher(72): channel
'4093eaf0 cc.rss/cc.rss.CornellRSS (server)' ~ Channel is
unrecoverably broken and will be disposed!
Sorry for not making this available sooner.
A: On the String[] titles = new String[messages.size()]; you need to actually put some values on the titles. The null pointer is probably happening when the ArrayAdapter tries to access your titles and just finds a null pointer.
If that doesn't work them please update your question with the logcat message.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Preloaded database corruption issue in Android application I have an android application that begins by downloading a large database to the sdcard (a little over 50mb) in an asynctask. The download code is as follows.
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
if(filePath.exists() && filePath.length() > 10000.00)
{
downloaded = (int) filePath.length();
conexion.setRequestProperty("Range", "bytes=" + (filePath.length()) + "-");
}
else
conexion.setRequestProperty("Range", "bytes=" + downloaded + "-");
conexion.setDoInput(true);
conexion.setDoOutput(true);
conexion.setUseCaches(false);
conexion.connect();
...
try {
totalFileLength = lengthOfFile + downloaded;
progressDialog.setMax(lengthOfFile + downloaded);
// downlod the file
input = new BufferedInputStream(conexion.getInputStream());
output = (downloaded==0)? new FileOutputStream(filePath): new FileOutputStream(filePath,true);
bout = new BufferedOutputStream(output, 1024);
byte data[] = new byte[1024];
while ((count = input.read(data, 0, 1024)) >= 0 && running) {
downloaded += count;
// publishing the progress....
//onProgressUpdate((int)(downloaded*100/lengthOfFile));
progressDialog.setProgress(downloaded);
bout.write(data, 0, count);
}
} catch (Exception e) {
...
} finally {
try {
input.close();
bout.flush();
bout.close();
} catch(IOException e) {
...
}
}
After downloading the file completely I open the database and add a table to it.
try {
myDbHelper.myDataBase.execSQL("CREATE TABLE IF NOT EXISTS FAVORITES (_id integer primary key autoincrement, MushroomID INTEGER)");
success = true;
} catch (SQLException sqle) {
throw sqle;
}
Now, this code works wonderfully on every device I run it on, but several of my users are getting this error on the execSQL line. It seems like it is not working on the Samsung Galaxy SII alone (there hasn't been a complaint and subsequent stacktrace with this error with any other phone) but I'm not entirely sure its just this phone.
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.daleroy.fungifieldguide/net.daleroy.fungifieldguide.activities.FungiFieldGuide}: android.database.sqlite.SQLiteDatabaseCorruptException: database disk image is malformed: CREATE TABLE IF NOT EXISTS FAVORITES (_id integer primary key autoincrement, MushroomID INTEGER)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3691)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteDatabaseCorruptException: database disk image is malformed: CREATE TABLE IF NOT EXISTS FAVORITES (_id integer primary key autoincrement, MushroomID INTEGER)
at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1904)
at net.daleroy.fungifieldguide.services.MushroomService.MakeFavoriteTable(MushroomService.java:118)
at net.daleroy.fungifieldguide.services.MushroomService.OpenDB(MushroomService.java:64)
at net.daleroy.fungifieldguide.activities.FungiFieldGuide.onCreate(FungiFieldGuide.java:73)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
I've received a copy of the database downloaded from a user with a sgs2 and the checksum of the file is off. I also cannot see any data or data structure in the file when I open with sqlite manager (firefox plugin). I let him download a copy of the database directly and place it in his data folder and the application works fine. So the problem is somewhere in the download process.
A: are you calling flush and close on your outputstream? Like this:
while ((count = input.read(data, 0, 1024)) >= 0 && running) {
downloaded += count;
progressDialog.setProgress(downloaded);
bout.write(data, 0, count);
}
bout.flush();
bout.close();
If not I would start with that. I downloaded a video with similar code and found that for some devices and some videos not calling flush was corrupting and making it unplayable
A: Starting from the API level 9 (Android 2.3) you can use DownloadManager to handle long-running HTTP downloads:
The download manager is a system service that handles long-running
HTTP downloads. Clients may request that a URI be downloaded to a
particular destination file. The download manager will conduct the
download in the background, taking care of HTTP interactions and
retrying downloads after failures or across connectivity changes and
system reboots.
Here is the example project which demonstrates DownloadManager usage: Android DownloadManager Example.
I think you can even try to backport DownloadManager to the previous Android versions (if you need to support them). Its source code can be found here: DownloadManager.java
A: Here is another question that talks about this kind of database corruption Android - database disk image is malformed.
If you can't fix the database when its in this state, maybe you can try to download it again if and when this error occurs (assuming that this problem is rare and downloading the database again can fix the problem).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to use the same datasource twice in JasperReports/iReport I'm trying to work out how best to do reports with a chart then a table representing the same dataset. I need to overcome the positioning of the summary is at the bottom, so intend to use subreports and table-subreports. I am experimenting with two tables and a chart in one detail band.
If I set the datasourceexpression for to $P{REPORT_DATA_SOURCE} only the chart displays data (presumably the first subreport type item) and the tables are empty. Seems the data can be consumed only once?
If I use a Dataset to query the database it works however it executes the Query three times, once for each table/chart. That will be a massive overhead.
Obviously I am not doing this right but I cannot find any examples of using the same dataset more than once.
A: There is no simple answer so I have raised a feature request http://jasperforge.org/projects/jasperreports/tracker/view.php?id=5487
The suggested workarounds were:
*
*implement a custom query executer to retrieve data from a cached datasource
*generate a rewindable datasource based on the retrieved result set
Thanks to sanda aka shertage on the jasperforge forum for these suggestions.
A: An alternative solution, cloning the dataset:
http://code.google.com/p/cloning/
Cloner cloner=new Cloner();
ArrayList clone = cloner.deepClone(getSomeArrayList());
final JRDataSource ds = new JRBeanCollectionDataSource(AnotherBean);
HashMap parameters = new HashMap();
parameters.put("PARAM_A", new JRBeanCollectionDataSource(getSomeArrayList()));
parameters.put("PARAM_B", new JRBeanCollectionDataSource(clone));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: boost-python select between overloaded methods Assume exist some class Foo with two overloaded methods:
class Foo
{
...
void m1(A& a);
void m1(B& b);
I need expose one of these methods over boost-python:
boost::python::class_<Foo>("Foo")
.def("m1", &Foo::m1)
How should I specify that signature of m1(A&a) should be used over m1(B&b)
A: You can use static_cast to specify which signature to use. With this method, you do not need to create a named function pointer while also keeping your overload resolution within the context of a single line.
boost::python::class_<Foo>("Foo")
.def("m1", static_cast<void (Foo::*)(A&)>(&Foo::m1))
.def("m1", static_cast<void (Foo::*)(B&)>(&Foo::m1))
A: Just for completion, it is also possible to have both of them exposed at python side:
void (Foo::*m1_a)(A&) = &Foo::m1;
void (Foo::*m1_b)(B&) = &Foo::m1;
boost::python::class_<Foo>("Foo")
.def("m1", m1_a)
.def("m1", m1_b)
A: void (Foo::*m1)(A&) = &Foo::m1;
boost::python::class_<Foo>("Foo")
.def("m1", m1)
A: While the other answers are correct there is no need to do any shenanigans with temporary variables or static_cast.
The def function prototypes look like this:
template <class Fn>
class_& def(char const* name, Fn fn);
template <class Fn, class A1>
class_& def(char const* name, Fn fn, A1 const&);
template <class Fn, class A1, class A2>
class_& def(char const* name, Fn fn, A1 const&, A2 const&);
template <class Fn, class A1, class A2, class A3>
class_& def(char const* name, Fn fn, A1 const&, A2 const&, A3 const&);
As you can see the first template parameter (Fn) is the type of the function pointer you want to wrap. Usually, all the template parameters are deduced by the compiler for you. However, if there is an ambiguity you need to help the compiler. If the function pointer is ambiguous due to an overloaded function you have to provide the proper type explicitly. In your case:
boost::python::class_<Foo>("Foo")
.def<void (Foo::*)(A&)>("m1", &Foo::m1)
.def<void (Foo::*)(B&)>("m1", &Foo::m1)
;
Simple, isn't it? No need to cast or capture outside. The same thing is valid for creating free standing function at the module level, i.e. using boost::python::def.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: colorbox and preventdefault not working together? I'm calling a colorbox using jquery and trying to prevent the address from changing but it seems to trigger an address change every time. Here is my current code:
<div style='display:none'>
<div id='send_alert_div' class="wysiwyg_container">
<h2>Contact Us</h2>
....
</div>
</div>
<a class="contact" href="#" >Contact</a>
my javascript code to handle the click event for Contact
$(".contact").click(function(e){
e.preventDefault();
$(".contact").colorbox({width:"600px", height: "420px", inline:true, href:"#send_alert_div"});
});
Does anyone see why this wouldn't work? It triggers an address change every time it's clicked.
A: I don't know what you are talking about with address changes. That must be controlled by some piece of script that you haven't included. Furthermore, colorbox already applies e.preventDefault(); So you could simplify the above code to simply this:
$(".contact").colorbox({width:"600px", height: "420px", inline:true, href:"#send_alert_div"});
Your other issue sounds unrelated. It's going to be difficult to instruct you on what to do without seeing what code is causing your 'address change', but if it is a simple event binding, you may be able to prevent it by replacing your above code with the following:
$(".contact").unbind('click').colorbox({width:"600px", height: "420px", inline:true, href:"#send_alert_div"});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hiding page loading My HTML markup looks like that
<html>
<body>
<div id="loading"><img src="core/design/img/load/load.gif" /></div>
<div id="wrap"></div>
<div id="footer"></div>
</body>
</html>
I'm trying to hide whole page loading process with following solution.
CSS Rules:
#loading {
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
background-image:url("img/load/tr.png");
z-index:100;
}
#loading img {position: absolute; margin-left:-110px; margin-top:-9px; left:50%; top:50%}
And Jquery
$(document).ready(function(){
$('#loading').fadeOut(500);
});
Now, the problem is page loads like that:
*
*first ugly draft of page (for 1-2 seconds)
*appears loading div
*loading whole content
*disappears loading div
You can see it in action
I don't understand why loading div appears after 1-2 seconds?
I want to prevent 1).
A: I think this is a pretty simple one.
First make sure jQuery is called in your section.
First, wrap all the content of your page (except the loading div) in a div called
<div id="content-wrapper">
CONTENT HERE
</div>
Then using CSS set:
#content-wrapper {
visibility:hidden;
}
Then just make the jQuery into a function like this:
$(window).load(function(){
document.getElementById("content-wrapper").style.visibility="hidden";
$('#loading').fadeOut(500, function()
{
document.getElementById("content-wrapper").style.visibility="visible";
});
});
and I can see you're using Nivo Slider. Me too ;)
Edit: I fixed it, now it works perfectly. (You don't need the onload event in your body tag anymore)
Check out the example here: JSFiddle
A: Try moving the styles for loading to be inline instead of relying on the full external css file to load. If you look at Google Chrome Developer Tools and the Network tab, or a similar tool, you'll see the content of the page loads first, as expected, but then you have to wait until the external css is loaded and downloaded, and then the referenced image in the css file is loaded. Placing the style inline should assist in getting the loading element to display as soon as it can, or at least sooner.
<div id="loading" style="position: fixed;left: 0;top: 0;
width: 100%;height: 100%;background-image: url(core/design/img/load/tr.png);z-index: 100;"><img src="core/design/img/load/load.gif"></div>
A: Why not start everything else inside a <div style="display: none;" id="loaded">, and then when the loading has finished use $("#loaded").fadeIn()?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how can I create DLL without having class can anyone give me some steps to create DLL without using class which means it will just have methods in the header file and source file would be only DLLmain() plus other methods. I'm using Visual Studio 2005 to create MFC DLL, but it always generates class. I never create DLL before but I was told that I can create DLL without class/object oriented concepts, just plain functions.
thanks.
A: For a regular Win32 DLL:
In the New Project wizard, under Visual C++ / Win32, choose Win32 Project.
Then in the next page, choose DLL as application type.
You may want to select Export functions as well to get sample code of exported variables, functions and classes.
From there on, simply delete what you dont need (such as classes).
I no longer have the Windows Mobile SDK installed, but I'm pretty sure you'll find the same kind of wizard to create a Windows Mobile DLL project.
Of course, if you don't want C++ classes, forget about MFC!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Controlling number of lines to be written to the output file I am new to Hadoop programming.
I have a situation in which I want to stop writing <k3,v3> to my output file after n-lines.
In my program, I am sure that the output file will be sorted according to k3, but I don't want the entire list. I only want the first n.
Is there a mechanism in Hadoop to do this?
A: I couldn't find an Class/API for the same.
But, you could increment a Counter when the OutputCollector.collect() is called in the Reduce function. When the counter reaches the a certain value, stop calling the OutputCollector.collect().
It's a waste of CPU cycles because the reduce tasks keeps on running even after n lines are written to the o/p. There might be a better approach for the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What's the technology behind Skype's anit-shake video recording? Skype added an anti-shake feature in it's video conference app on iPhone. How can that be done?
A: This is quite a complicated thing to pull off, but it's probably a combination of some powerful blur detection/removal algorithms, and the gyroscope. I would start by looking into how to detect motion with the iPhone, and see what kind of results you can get with that. If it's not enough, start looking into shift/blur direction detection algorithms. This is not a trivial problem, but is something that you could probably accomplish given enough time. Hope that Helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: GLES2 Is glBindAttribLocation() Necessary? This might be a noob question. As I understand it, glBindAttribLocation(..., AAA, ...) will bind an attribute within the program to the location ID of AAA, as long as AAA is unique. If I have the following code:
glBindAttribLocation(..., 0, "XXX");
glBindAttribLocation(..., 1, "YYY");
This will bind my two variables to location ID 0 and 1. I would then call:
glBindBuffer(GL_ARRAY_BUFFER, VBId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBId);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void *) 0 + sizeof(float) * 3);
glEnableVertexAttribArray(1);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
Up to this point, I understand that the IDs of 0 and 1 are passed into glVertexAttribPointer() as the first parameter.
Would it be safe to assume that if I obtained the location IDs of the attributes (as above) through glGetAttribLocation() calls, such that the IDs returned were 5 and 6 instead of 0 and 1, could I pass 5 and 6 into glVertexAttribPointer() and glEnableVertexAttribArray() instead of 0 and 1??
A: glGetAttribLocation() returns the correct index. So yes, it is safe to use those values in glVertexAttribPointer() and glEnableVertexAttribArray().
But calling glGetAttribLocation for each shader might be expensive if you don't cache it. Using glBindAttribLocation() allows to use a convention, position always in 0, normal in 1 and so on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: dynamically adding a select box with options populated by php to a form I have a send message form, with a list of recipients populated by a PHP query to the database. I want to be able to include multiple recipients by dynamically adding select boxes to the form, depending on how many people they wish to send the message to.
I don't know javascript all that well and I have been researching the web to see how I can dynamically add a select box to a form with the options populated by PHP, but the only thing I seem to be able to find is how to populate the options depending on what was selected in the previous select box.
This is my Javascript:
<script type="text/javascript">
function add_recipient_field(){
var container=document.getElementById('addanother');
var to_field=document.createElement('select');
to_field.name='to[]';
to_field.type='file';
container.appendChild(to_field);
var br_field=document.createElement('br');
container.appendChild(br_field);
}
</script>
This is my PHP :
$tosql = "SELECT UserID, FirstName, LastName FROM users WHERE Active = 'yes' ORDER BY LastName ASC";
$query = mysqli_query($dbc, $tosql) or die("Error: ".mysqli_error($dbc));
$tobox .= "<option value=\"None\">None</option>\n";
while ($row = mysqli_fetch_array($query)) {
if ($row['UserID'] == $to) {
$tobox .= "<option value=\"$row[UserID]\" selected=\"selected\">$row[LastName], $row[FirstName]</option>";
} else {
$tobox .= "<option value=\"$row[UserID]\">$row[LastName], $row[FirstName]</option>";
}
}
This is my HTML:
<div id="addanother"><li><label for="to">To: </label><select name="to[]" id="to">$tobox</select><a href="javascript:void(0);" onClick="add_recipient_field();">add more</a>$toerror</li></div>
When I click on the "add more" link, it adds another select box, however there are no options in the box so it appears empty. I know I'm missing something fairly simple, but if someone could help or point me in the direction of a tutorial I would very much appreciate it.
A: All add_recipient_field does is add an empty select. I know that's your quandary, but my point is that according to the function you have listed above, adding an empty select is what it SHOULD do since that's what it is written to do. You still have to fill the data somehow.
Keep in mind that PHP ONLY runs on the server and does not interact with the currently loaded page in the browser. You can use Javascript to call PHP on the server and use the returned data to modify the page in place, but PHP itself cannot change the document after it has been loaded.
You have 3 primary options.
*
*You can reload the page every time the user selects "add more" and have php rebuild the page with the new select. Keep in mind that for proper usability, you'll have to pass all your form data every time and refill it as you rebuild the form.
*You can build the selects entirely from Javascript, which means the Javasript on the page will need to have all the required data at hand. PHP's json_encode method can be very helpful for doing this quickly. You load all your data into a javascript object at the top of the page and then every time you add a new select, you fill that new select from that data.
*You can read up on what's generally referred to as "AJAX" where the javascript on the page interacts with PHP on the server in order to dynamically load your data upon request and change the already loaded page without a refresh. This is something of a mix of the two prior options and is probably the more advanced method, but the most rewarding to learn.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to stop the event bubble In have two div in the page,the outer and the inner.
I bind the mousemove event to the outer div,when user mousemove in the outer div,it will show the clientX and clientY of the mouse.
Also I make the inner div dragable,here is the live example.
1) I do not want the outer's mousemove event trigger when I drag the inner div.
Of course I can set the "outer.onmousemove=null" when I drag the inner div,but I do not think it is the best way since the event on the outer div maybe binded by other people.
I try to use the event.cancalBubble,but it seems that it does not work.
2) when I drag the inner div,it will select the text in the firefox,how to stop it?
A: There are two functions that can be called to make sure that the event bubble stops:
event.stopPropagation();
event.preventDefault();
If you make sure to call both of those then it should prevent both the parent div being selected and the text being selected.
Edit:
Looking more closely at your code I see a few problems. The first thing is that you use the onmousemove event for registering the mouse coordinates in the "outer" div. Then you use the documents onmousemove to drag to "inner" div around. That means that if you stop the propagation for the onmousemove event when you start dragging, it will never bubble up to the document node and in turn will result in the draggable div never being dragged untill you actually move the mouse outside the "inner" div area.
One solution is to set the _mouseMove function on the moveable div instead of the document and then stop the propagation like this:
/* Remove this */
//document.onmousemove=_mouseMove;
//document.onmouseup=_mouseUp;
/* Add this */
move_ele.onmousemove=_mouseMove;
move_ele.onmouseup=_mouseUp;
e.stopPropagation();
e.preventDefault();
This will make it work like you mention except when you drag so fast that the cursor leaves the "inner" div area, then it will stop dragging untill the cursor enters the div area again.
Another solution is to handle it all in the "outer" divs onmousemove event to see if the mouse is actually moving over that div and not the "inner" like this:
out.onmousemove=function(e){
/* Check to see if the target is the "outer" div */
if(e.target == this){
e=e==null?window.event:e;
note.innerHTML=e.clientX+','+e.clientY;
}
}
This will also work like you mention but it will also stop the coordinates from being updated as soon as you move the cursor over the inner div even though you have not started dragging.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to find if a JavaScript code is running on it's own domain? I work on an analytics website and I want to put an analyzer code specific for each website. Is it possible to check if a user uses his own JavaScript code?
Is it necessary and enough to put a customer code in each JavaScript and check it with domain name to be sure about this? Or do I need something like session or so?
A: You can access the src attribute of the script tags:
// returns all script tags
var all_script_tags = document.getElementsByTagName("script");
// returns the src attribute of the first script
var src_script = all_script_tags[0].src; // tag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Explicitly specifying parameter types in F# I'm writing an F# function that factorises a number into prime factors.
let factors primes i =
let mutable j = i
for p in primes do
while (j>1) && (j%p=0) do
j <- j/p
printfn "prime: %i" p
It works for int values of i, but not int64 values. The parameter primes is a set of int values.
I understand why this is the case - type inference is assuming that the function only takes int parameters - but I want to explicitly specify the parameter type as int64.
Is it possible to write this function so that it will work for both int and int64?
A: You will have to do something like
let inline factors (primes :^a list) (i:^a) =
let zero:^a = LanguagePrimitives.GenericZero
let one:^a = LanguagePrimitives.GenericOne
let mutable j = i
for p in primes do
while (j>one) && (j%p=zero) do
j <- j/p
printfn "prime: %i" p
I don't have the compiler, so my syntax may be slightly off
A: If you want to work only on int64 values, just replace 1 and 0 with 1L and 0L respectively. jpalmer's answer covers the generic case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Anywhere to download Repo script http://source.android.com/source/downloading.html directs users to download the repo script from kernel.org, but, the 'android.git.kernel.org is currently down. Are there any other mirrors?
Code:
$ curl https://android.git.kernel.org/repo > ~/bin/repo
Error:
curl: (6) Couldn't resolve host 'android.git.kernel.org'
A: While kernel.org is down you can find the full Android sources at http://github.com/android and the repo script can be found at https://github.com/android/tools_repo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I need some tutorials about CFNetwork in iphone I am developing a stock software,the client will receive the data from the server,so I want to use the CFNetwork.
and where can I find the tutorial "getting Started with networking",thank you
A: try these link i hope u get what u want.
http://mobileorchard.com/tutorial-networking-and-bonjour-on-iphone/
http://oreilly.com/iphone/excerpts/iphone-sdk/network-programming.html
http://www.raddonline.com/blogs/geek-journal/iphone-sdk-testing-network-reachability/
A: Go to xcode => Organizer => Documentation => iOS 4.x Library => Frameworks => CFNetwork there are 2 Programming Guides.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using Enumeration in C# I'm writing my first ever C# application, for Windows Phone Mango. It's designed to be an extremely simple flashlight app.
Previously, it wasn't possible to access the camera's flash on Windows Phone, but in this latest version, it is. Here's the documentation about it:
http://msdn.microsoft.com/en-us/library/microsoft.devices.flashmode(v=vs.92).aspx
Unfortunately, that makes absolutely no sense to me. I have the button set up and and the if-then statements working to switch the button icon and text on click. I just can't figure out how to actually turn the flash on and off. I'd appreciate a clear example so I can finish this up.
For those of you who don't want o leave the site...That link basically says this:
public enum FlashMode
Members: On, Off, Auto, RedEyeReduction
A: The FlashMode enumeration is just a set of values representing valid values for FlashMode. FlashMode, however, seems to define how the flash behaves when you take a picture. "On" seems to mean that the flash will always flash. It doesn't seem to mean that the light itself is "on" in the sense of producing light continuously.
A bit of evidence in favor of this: the FlashMode documentation says that FlashMode.On means "The camera flash is enabled."
A: Did you see this link?
http://msdn.microsoft.com/en-us/library/hh202949(v=vs.92).aspx
If there is a variable called "cam" available to you (DISCLAIMER: I know nothing of mobile devices) you need to change the FlashMode property. So on your button click, you would do
cam.FlashMode = FlashMode.On
EDIT: After looking a bit further it appears the "cam" variable is an instance of PhotoCamera class. So this may need to be constructed in your app somehwere. This link may also be of some help in doing so.
http://msdn.microsoft.com/en-us/library/hh202956(v=vs.92).aspx
A: There is a great explanation at MSDN on enum so I won't try to recreate that here, but essentially a new type has been created to ease the value assignment. Rather than having to remember that (for example) 'On' is equal to 0, and 'Off' is equal to 1, you can just use FlashMode.On instead. Of course, these enums only represent values so you will still need to assign it to something.
For example I found this in a link from within the link you provided:
cam.FlashMode = FlashMode.On;
This looks like fun so Good luck!
A: If you are trying to make some kind of flashlight app, there is no API for the LED according to this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How slice Numpy array by column value I have an array like this numpy array
dd =[[0.567 2 0.611]
[0.469 1 0.479]
[0.220 2 0.269]
[0.480 1 0.508]
[0.324 1 0.324]]
I need 2 seperate array dd[:,1] ==1 and dd[:,1] ==2
These array are what I am after:
na =[[0.469 1 0.479]
[0.480 1 0.508]
[0.324 1 0.324]]
na2 =[[0.567 2 0.611]
[0.220 2 0.269]]
I have tried np.where did really work
A: You could use numpy fancy indexing:
[~/repo/py]
|32>dd[dd[:,1] == 1]
[32]
array([[ 0.469, 1. , 0.479],
[ 0.48 , 1. , 0.508],
[ 0.324, 1. , 0.324]])
[~/repo/py]
|33>dd[dd[:,1] == 2]
[33]
array([[ 0.567, 2. , 0.611],
[ 0.22 , 2. , 0.269]])
Alternatively you could use a list comprehension:
[~/repo/py]
|21>np.array([row for row in dd if row[1] == 1])
[21]
array([[ 0.469, 1. , 0.479],
[ 0.48 , 1. , 0.508],
[ 0.324, 1. , 0.324]])
[~/repo/py]
|22>np.array([row for row in dd if row[1] == 2])
[22]
array([[ 0.567, 2. , 0.611],
[ 0.22 , 2. , 0.269]])
edit:
how to time these things in ipython:
[~/repo/py]
|36>timeit dd[dd[:,1] == 1]
100000 loops, best of 3: 6 us per loop
[~/repo/py]
|37>timeit np.array([row for row in dd if row[1] == 1])
100000 loops, best of 3: 11.5 us per loop
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SQL query to find latest acivity across tables We have timestamps for various things across the site. I'm looking for a way to get users who are "online" or have been active in the past 20 minutes. Im also trying to sort them by an intersection of the latest timestamp in multiple columns across multiple tables.
SELECT user.userID, user.username, GREATEST(
(SELECT MAX(notifications.noteTime) FROM notifications WHERE notifications.creatorID = user.userID),
challengesRead.lastRead,
notificationsRead.lastRead) AS realtime
FROM user
LEFT JOIN challengesRead ON challengesRead.userID = user.userID
LEFT JOIN notificationsRead ON notificationsRead.userID = user.userID
LEFT JOIN notifications ON notifications.creatorID = user.userID
LEFT JOIN challenges ON challenges.userID = user.userID
WHERE timestampdiff(minute, realtime, now()) < 20
GROUP BY user.userID
ORDER BY realtime DESC
My questions.
1) Timestampdiff doesn't seem to recognize realtime? However, recalculating GREATEST() in timestampdiff does work but seems repetitive.
2) Yikes, this beast takes forever to run, whats the best way to optimize?
3) What is a better way to do this?
A: you could make a new table like 'latest_activity' and add triggers to populate with user_id and timestamp... that would at least give you one place to query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Amazon EC2: Jetty Unaccessible I'm trying to install jetty in an Amazon EC2 instance running Ubuntu. The installation seems OK
$ sudo apt-get install jetty
After that I made the parameter NO_START=0 in /etc/default/jetty
Finally
$ sudo service jetty start
Starting Jetty servlet engine. jetty
Jetty servlet engine started, reachable on http://ip-xx-xxx-xxx-xxx:8080/
...
Nevertheless, when I write in the browser (external computer):
http://ec2-xxx-xx-xx-xx.compute.amazonaws.com:8080
The browser could not connect to the address using the given port. I don't know if something is missing during the installation or the URL is wrong.
Thanks for your time and help :-) ,
- Carolina
A: Each instance on amazon has a security group assigned to it. In the AWS console, select the instance and the security group is shown in the lower pane. Then select security groups on the left and select the group for that instance from the table. In the lower tab, select inbound, these are the IPs addresses/ports allowed in. If 8080 isn't allowed, that's your problem, you need to add it. Enter 8080 in the port range box and 0.0.0.0/0 for the source. Then "add rule" and make sure you "apply rule change" lastly.
A: I found the answer here:
Jetty (mis)configuration: it wont respond from an external machine... why?
You need to change /etc/default/jetty to have JETTY_HOST=0.0.0.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: ERROR getting 'android:label' attribute: attribute is not a string value I have this error "ERROR getting 'android:label' attribute: attribute is not a string value" when trying to publish my application to android market.
Some time ago this app was already published successfully on market, but when I apply minor changes in AndroidManifest.xml (changing versionCode and versionName) I get this error constantly.
I looked to all similar topics here, such as:
Android Market Publishing Issues
"ERROR getting 'android:icon' attribute: attribute is not a string value" when trying to upload to the Android Market
The file is invalid: ERROR getting 'android:name' attribute: attribute is not a string value
but none of these solution helped me. Do you know any other reason of such an error?
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.samsung.att.deskhome" android:versionCode="12" android:versionName="2.3">
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<application android:icon="@drawable/mainmenu_icon_homemount" android:label="@string/app_name">
<activity android:name=".CradleMain" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" android:launchMode="singleTask" >
<meta-data android:name="android.dock_home" android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
<activity android:name=".CradleHomeSettings" android:label="@string/cradle_home_settings" android:launchMode="singleTask" android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
<activity android:name=".CradleWeatherSettings" android:label="@string/cradle_weather_settings" android:launchMode="singleTask" android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
<activity android:name=".CradleWallpaperChooser" android:label="@string/pick_wallpaper" android:screenOrientation="nosensor" android:finishOnCloseSystemDialogs="true" android:configChanges="locale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-sdk android:maxSdkVersion="10" />
</manifest>
A: Whenever you get an error from the play store while uploading make sure to execute that same command locally to get proper output. The output retrieved from the online console is misleading.
An example from my own code, this is what I got on the online console:
Failed to run aapt dump badging:
W/ResourceType( 4560): Failure getting entry for 0x7f0601c6 (t=5 e=454) in package 0 (error -75)
ERROR getting 'android:label' attribute: attribute is not a string value
And a local run of that same tool (found at build-tools in sdk dir)
aapt dump badging /path/to/your/apk
revealed useful information like the position where the check failed:
package: name='X' versionCode='X' versionName='X'
sdkVersion:'7'
targetSdkVersion:'17'
uses-permission:'android.permission.INTERNET'
...
uses-permission:'android.permission.WRITE_EXTERNAL_STORAGE'
uses-feature-not-required:'android.hardware.camera'
uses-feature-not-required:'android.hardware.camera.autofocus'
application-label:'Photo Tools'
application-label-zh:'摄影工具'
application-label-nl:'Photo Tools'
application-label-fr:'Photo Tools'
application-label-es:'Photo Tools'
application-label-it:'Photo Tools'
application-label-ru:'Photo Tools'
application-icon-160:'res/drawable/phototools_icon.png'
application-icon-240:'res/drawable/phototools_icon.png'
application-icon-320:'res/drawable/phototools_icon.png'
application-icon-480:'res/drawable/phototools_icon.png'
application: label='Photo Tools' icon='res/drawable/phototools_icon.png'
launchable-activity: name='be.hcpl.android.phototools.PhotoToolsActivity' label='Photo Tools' icon=''
W/ResourceType(30945): Failure getting entry for 0x7f0601c6 (t=5 e=454) in package 0 (error -84)
ERROR getting 'android:label' attribute: attribute is not a string value
A: To investigate, I followed the following methodology:
*
*comment out the activities one by one
*build the signed release
*run aapt dump badging /path/to/your/apk
*see errors and repeat
This allowed me to narrow down to the root the of my problem. Just a string without resource instead the label was not being used in the app. I removed the label attribute as a fix.
A: read @hcpl answer, if you cannot finsd the error look for the next activity listed in manifest. in his post:
launchable-activity: name='be.hcpl.android.phototools.PhotoToolsActivity' label='Photo Tools' icon=''
W/ResourceType(30945): Failure getting entry for 0x7f0601c6 (t=5 e=454) in package 0 (error -84)
ERROR getting 'android:label' attribute: attribute is not a string value
You might think the problem is related to PhotoToolsActivity but it is about the next activity which does not get log because it aapt crashes
A: Check the values/strings.xml and values-xx/strings.xml
You should be sure that everyone word in values/strings.xml must have corresponding word under values-xx/strings.xml .
A: In my case, the default string.xml was missing, accidentally deleted from the project.
I use:
disable 'ExtraTranslation'
disable 'MissingTranslation'
in the gradle, so I've no evidence of the missing string.xml file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Is it possible to get an object by its primary key in django-nonrel / Google App Engine? I'm trying to retrieve a model object like the code below:
(r'^album/(?P<album_id>\w+)/$', 'core.views.album'),
def album(request, album_id):
album = Album.objects.get(pk=album_id)
The problem is that the PK is not an integer:
>>> a = Album.objects.all()[0]
>>> a.pk
46L
The error I'm getting when I run the view:
ValueError at /album/46L/
invalid literal for int() with base 10: '46L'
Ideas? Thanks.
A: 46L is a long integer, not a string, so you should treat it as a number and not a word in urls.py:
(r'^album/(?P<album_id>\d+)/$', 'core.views.album'),
then the url /album/46/ will end up calling:
def album(request, album_id):
#album = Album.objects.get(pk=46L)
album = Album.objects.get(pk=album_id)
Or if you need to keep the 'L' in the url for some reason, cast it as a long before using it:
album = Album.objects.get(pk=long(album_id))
A: The problem was unrelated with the urls / views. Everytime I executed "runserver" my local datastore was being erased. So the data I was able to retrieve when using "shell" was not synced correctly.
This happened because, for some weird reason, I commented this line (and forgot about it) on settings.py:
AUTOLOAD_SITECONF = 'indexes'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Random time delay I'm trying to send signals between processes and I need to allow a random time delay of between 0.01 and 0.1 seconds in my signal generation loop. So this is what I'm doing and it is most certainly not between 0.01 and 0.1, but comes out as 1 second. Not sure what I'm missing here.
sleepTime = 100000L+(long)((1e6-1e5)*rand()/(RAND_MAX+1.0));
usleep(sleepTime);
A: If you've got C++11:
#include <thread>
#include <random>
#include <chrono>
int main()
{
std::mt19937_64 eng{std::random_device{}()}; // or seed however you want
std::uniform_int_distribution<> dist{10, 100};
std::this_thread::sleep_for(std::chrono::milliseconds{dist(eng)});
}
It may not be what your prof is looking for. :-)
A: All of your constants are 10x too large! Try
sleepTime = 10000L+(long)((1e5-1e4)*rand()/(RAND_MAX+1.0));
A: Three things:
1) 100000L is 100 msec, not 10 msec
2) usleep is only guaranteed to sleep for at least the argument time, with no guarantee about how long it will sleep. Read the manpage: all sleep functions make that assertion.
3) How are you measuring how long it takes? Are you using a timer that has milli or microsecond resolution?
A: The easiest thing is to generate a random number between 0 and 1, then use a lerp function to move the number to being between 0.01 and 0.1.
// returns random between 0 and 1
float randFloat() ;
// you are "val" % of the way from min to max
float lerp( float val, float min, float max ) ;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Acceptable ways to release a property Assume there is a class with the following interface:
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
}
@property (nonatomic, retain) NSDate* myDate;
-(void)foo;
@end
and the following implementation:
#import "MyClass.h"
@implementation MyClass
@synthesize myDate = _myDate;
- (void)dealloc
{
[_myDate release];
[super dealloc];
}
-(void)foo
{
NSDate* temp = [[NSDate alloc] init];
self.myDate = temp;
[temp release];
}
@end
1) In the function foo will releasing like this ensure that the retain count of the objects is properly maintained (i.e. no memory is leaked and no unnecessary releases are performed).
NSDate* temp = [[NSDate alloc] init];
self.myDate = temp;
[temp release];
2) Same question as in 1) except applied to the following technique:
self.myDate = [[NSDate alloc] init];
[self.myDate release]
3) Same question as in 1) except applied to the following technique:
self.myDate = [[NSDate alloc] init] autorelease];
4) Same question as 1) but applied to the following technique:
self.myDate = [[NSDate alloc] init];
[_myDate release]
5) Same question as 1) but applied to the following technique:
[_myDate release];
_myDate = [[NSDate alloc] init];
A: 1) Just fine.
2) Possibly unsafe, and will trigger warnings in the latest LLVM static analyzer. This is because the object returned by the getter method may not be the same one you passed to the setter. (The setter may have made a copy, for example, or may have failed validation and set a nil instead.) This would mean you were leaking the original object and over-releasing the one the getter gave back to you.
3) Just fine; similar to 1 but the release will come when the current autorelease pool is drained instead of immediately.
4) Possibly unsafe, but will not trigger warnings that I've seen. The issue is similar to the one described in 2; the object in the ivar may not be the one you passed to the setter.
5) Safe, but will not use the setter method or notify any observers of the property.
In the case where the property is a retain type, and both the getter and setter are just the synthesized versions, all of the above examples will work. However, they don't all represent best practice, and may trigger analysis warnings. The goal should be that the -foo method works correctly regardless of how myDate is managing its memory. Some of your examples above don't do that.
If, for example, you decided to change the property to copy later, you should not be required to change any other code to make it work correctly. In cases 2 and 4, you would be required to change additional code because the foo method is assuming that the setter will always succeed and always set the original object.
A: 5) is a bug - it leaks the old instance as it doesn't get released but just reassigned.
1) is clean and the best way to go.
4) is ok but puts some burden on the memory system - the object might live longer than needed.
2) technically ok, but you shouldn't directly retain/release the property - that's what the syntactic sugar is for!
3) technically ok, but also bypasses the property and relies on implementation details.
2) and 3) are discouraged and ask for trouble in the future when some part of code changes.
Edit: New code doesn't leak in 5). It has the same downsides, though.
There's a reason why we got support for properties, and it does a great and consistent use. You should only consider bypassing them if your time profile gives very clear hints that this is a bottle neck (unlikely).
A: First, if you want to avoid the alloc, release, autorelease etc... you can call a date factory method which doesn't start with alloc.
For example:
self.myDate = [NSDate date];
The date class factory method does an autorelease according to the convention rules. Then the property retains it.
*
*Alloc will give it a retain count of 1, then assigning the property will retain it. Since your class is now retaining it from the property, you can release it to counter act the alloc.
*Ditto but that's a wierd round about way to do it.
*3 is equivalent to the code I had above ([NSDate date]);
*In this case, the property will retain it (after alloc incremented the retain count), then you're going under the covers to decrement it. Works but I wouldn't recommend doing that since you're synthesized (retain) property will do that for you.
A: the pattern of release and renew is merely a semantic. You get a retain count for each of the following.
myObject = [Object alloc]
objectCopy = [myObject copy]
myNewObject = [Object newObjectWithSomeProperties:@"Properties"] // Keyword here being new
// And of course
[myObject retain]
a property with the modifier (retain) or (copy) will have retain count on it.
the backing store _myDate is merely where the object is actually stored.
when you get a retain count you need to release.
Either immediately with the [myObject release] message or let the pool release it with [myObject autorelease]
Whatever the case, Any retain you are given (implicit or explicit) will need to be released. Otherewise the garbage collector will not collect your object and you will have a memory leak.
the most common usage in
Object myObject = [[[Object alloc] init] autorelease]; // Use this when you dont plan to keep the object.
Object myObject = [[Object alloc] init];
self.myProperty = [myObject autorelease]; // Exactally the same as the Previous. With autorelease
// Defined on the assignment line.
self.myProperty = [[[Object alloc] init] autorelease]; // Same as the last two. On one line.
I will demonstrate other possibilities
// Uncommon. Not incorrect. But Bad practice
myObject = [[Object alloc] init];
self.myProperty = myObject;
// Options
[_myProperty release] // Bad practice to release the instance variable
[self.myProperty release] // Better practice to Release the Property;
// releasing the property or the instance variable may not work either.
// If your property is using the (copy) modifier. The property is copied rather then retained.
// You are still given a retain count.
// But calling release on a copy will not release the original
[myObject release]; // Best Practice. Good when Threading may run the autorelease pool
[myObject autorelease]; // As good as the previous.
// But may leave your object in memory during long operations
Essentially, your object given a retain will be the same object in the Property the Variable and the Instance Variable. Releasing on any of them will release it.
However. Best practice says that if you retain an object. Best to call release on the same variable of that object. Even if Autorelease and retain is called on the other side.
// Other items that give you a retain count.
Core Media or Core Anything Functions that have Create Or Copy in the name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android - ImageView margins not appearing in LinearLayout Right now, I'm struggling to accomplish something as simple as adding margin space between my child ImageViews within a custom LinearLayout (modified RadioGroup that is designed to take in a custom ImageView that implements Checkable, didn't override onMesarue). Long story short, these images are of a fixed dimension (60x60dip), and since they are dynamic (from the web), I had to add them dynamically like so:
for(int i = 0; i < num; i++){
ImageViewRadioButton childImage = new ImageViewRadioButton(mContext);
float imagehWidthHeight = getResources().getDimension(R.dimen.image_width_and_height);
LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams((int) imageWidthHeight, (int) imageWidthHeight);
int imageSpacing = Utils.dipsToPixels(10, mContext);
int innerPadding = Utils.dipsToPixels(5, mContext);
imageParams.leftMargin = imageSpacing;
imageParams.rightMargin = imageSpacing;
childImage.setAdjustViewBounds(true);
childImage.setLayoutParams(imageParams);
childImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_pressed));
childImage.setPadding(innerPadding, innerPadding, innerPadding, innerPadding);
childImage.setClickable(true);
//other non-image properties...
imageContainer.addView(childImage);
}
The only thing that does work is the padding, which it spaces it out properly. However, I am not seeing any space between the padding of each child (margins). Am I doing this correctly, or is there a better way of doing it short of overriding onMeasure to factor in each child's margins?
A: You had create imageParams but you are not using that parameters in your code instead of imageParams you are using swatchParams parameter. And you had not put a code of swatchParams parameter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP: How do I prevent include/require to add numbers in a loop? Every time I try to assign an include/require to a variable, it adds a number at the end.
I would like to do it without that stupid number.
I tried file_get_contents but it does not work the same way.
If it's not possible to do it with require, is there an EASY and SHORT (Single function and single line of code) way to do it with another function?
Please help me, because it's driving me crazy.
For example:
FILE 1 (div.php):
<div><?php echo $x; ?></div>
FILE 2:
<?php
$x = "Example 1";
$file = include('div.php');
echo $file;
$x = "Example 2";
$file = include('div.php');
echo $file;
?>
OUTPUT:
Example 1
1
Example 2
1
A: This is because the default return value of include and require is true, or 1.
When you include the file, it automatically outputs your content in the included file. When you echo $file, you are echoing the return value of the include, which is true.
As a note, if you put return false; or return "<div>$x</div>"; in your included file, that would then become the value of $file. Whatever you return from your included file, that is passed to the variable.
For example:
FILE 1 (monkey_do.php):
<?php
return "I am a monkey";
FILE 2 (main.php):
<?php
$monkey_see = include 'monkey_do.php';
echo $monkey_see; // prints "I am a monkey"
A: You could use output buffering:
$x = 'Example 1';
ob_start();
include ('div.php');
$file = ob_get_contents();
ob_end_clean();
echo $file;
EDIT: I just saw this example in the manual that defines a function to do this: http://php.net/manual/en/function.include.php#example-131
A: If you use FILE1 as the template, just include it. Also you can use output buffering as @grossvogel answered.
<?php
$x = "Example 1";
include('div.php');
$x = "Example 2";
include('div.php');
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery Auto-complete List Css So, I'm NOT using the jQuery UI AutoComplete as I have a simple application.
However, in my final touches on the input box, I'm stuck on a simple CSS issue.
I want the list-item(s) (created by the jQuery .post) to highlight on hover.
HTML:
<div id="wrapper">
<div id="input"><input id="name" type="text" /></div>
<div id="links"></div>
<div id="space"></div>
</div>
jQuery:
<script type="text/javascript">
$('#name').keyup(function(){
var name = $('#name').val();
$.post(
'process.php',
{name:name},
function(output){
$('#links').html(output).show();
});
});
</script>
PHP:
require('config.php');
if(isset($_POST['name'])){
$name = mysql_real_escape_string(strtolower($_POST['name']));
if($name==NULL)
echo "Please Enter a Name";
else{
$qName = '%'.$name.'%';
$query = "SELECT name FROM table WHERE name LIKE '$qName'";
$result = mysql_query($query);
$rowCount = mysql_num_rows($result);
if($rowCount==0)
echo "No Matches Found!";
else{
$name = ucfirst($name);
echo '<ul>';
while ($row = mysql_fetch_assoc($result)) {
echo '<li><a href="#">' . $row["name"] . '</a></li>';
}
echo '</ul>';
}
}
}
Finally, CSS
#links ul {
list-style-type:none;
width:150px;
}
#links li a {
color:#000;
background-color:#EEE;
display:block;
text-decoration:none;
}
* html #links li a { /* make hover effect work in IE */
width: 150px;
}
#links li a:hover {
background:#CCC;
}
Here is what chrome reports after the AJAX request:
A: So the <div id="space"></div> was simply getting in the way.
Remove and adjust with padding
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get Selenium server working with htmlunit? I downloaded selenium-server-standalone-2.7.0.jar and ran it like this to get a list of supported browsers:
java -jar selenium-server-standalone-2.7.0.jar -interactive
cmd=getNewBrowserSession
Unfortunately, htmlunit isn't in that list, but when I look at the documentation, it says it supports it quite clearly, yet I've had little success so far.
Does anyone know how to get htmlunit working with Selenium Server?
A: You need to use htmlunit webdriver or webdriver backed selenium. You can utilise QAF (formerly ISFW) as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Exclude category on query_post custom taxonomy I need to exclude a category from showing up posts.
I registered the taxonomy: portfolio-category
and added a category: accessories (cat ID 19) under portfolio-category
How do I exclude posts from accessories category from showing up?
I tried: 'category' => -19, but it didn't work
here's my code:
<?php
$args=array(
'post_type' => 'items',
'post_status' => 'publish',
'showposts' => intval( get_anolox_option_by('an_homep_count', 3) ),
'caller_get_posts' => 1,
'category' => -19,
'paged' => $paged,
);
query_posts($args);
$end = array(3,6,9,12,15,18,21,24,27,30,33,36,39,42,45);
$i = 0;
while (have_posts()): the_post();
global $post;
$i++;
?>
MY CODE HERE, NO NEED TO SHOW SINCE IT'S VERY LONG
<?php endwhile; ?>
<?php wp_reset_query(); ?>
edit// I tried this code, but still it didn't work:
<?php
$args=array(
'post_type' => 'items',
'post_status' => 'publish',
'showposts' => intval( get_anolox_option_by('an_homep_count', 3) ),
'caller_get_posts' => 1,
'paged' => $paged,
'tax_query' => array(
'taxonomy' => 'portfolio-category',
'terms' => 'accessories',
'field' => 'slug',
'operator' => 'NOT IN')
);
query_posts($args);
A: $args = array(
'post_type'=>'items',
'order'=>'ASC',
'posts_per_page'=>3
'tax_query' => array(
array(
'taxonomy' => 'portfolio-category',
'field' => 'id',
'terms' => 19,
'operator' => 'NOT IN',
),
)
));
query_posts($args);
items= custom post type
portfolio-category = my custom taxonomy
for multiple category exclude use 'terms' => array( '19,20' ),
A: The category argument is meant for the built in category taxonomy. Change your $args like so to reference your custom taxonomy:
$args=array(
'post_type' => 'items',
'portfolio-category' => 'accessories',
'post_status' => 'publish',
'showposts' => intval( get_anolox_option_by('an_homep_count', 3)),
'paged' => $paged
);
This assumes the following:
*
*You've got a custom post type called items.
*The portfolio-category taxonomy is registered to it.
*accessories is added to the portfolio-category taxonomy.
Update: Whoops...getting late. To answer OP's actual question of how to exclude the accessories portfolio category (rather than include it as the above does), you can use the tax_query argument. Code would be as follows to exclude accessories:
$args=array(
'post_type' => 'items'
'post_status' => 'publish',
'showposts' => intval( get_anolox_option_by('an_homep_count', 3)),
'paged' => $paged,
'tax_query' => array(
'taxonomy' => 'portfolio-category',
'terms' => 19,
'field' => 'id',
'operator' => 'NOT IN'
)
);
A: The issue seems to be a layer of nesting. Try changing
$args=array(
'post_type' => 'items'
'post_status' => 'publish',
'showposts' => intval( get_anolox_option_by('an_homep_count', 3)),
'paged' => $paged,
'tax_query' => array(
'taxonomy' => 'portfolio-category',
'terms' => 19,
'field' => 'id',
'operator' => 'NOT IN'
)
);
To:
$args=array(
'post_type' => 'items'
'post_status' => 'publish',
'showposts' => intval( get_anolox_option_by('an_homep_count', 3)),
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'portfolio-category',
'terms' => 19,
'field' => 'id',
'operator' => 'NOT IN'
)
)
);
This worked for me. :-/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Nhibernate with 2 front end servers, any issues with this out of the box? If I have 2 front end servers accessing a single db server, how will nhibernate operate in this scenerio?
Are there any things to watch out for?
Will running things using stateless sessions help?
A: If you make use of the second level cache, you'll need to select a provider that allows for distributed usage, such as the Memcached one.
To address the second part of your question, the stateless session only ignores the first level cache, so you won't need to worry about those.
A: This is no different then a single web front end accessing the db. You'll just have normal concurrency issues to deal with. If two people edit the same record at the same time.. that kind of thing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replacing all occurences of a specific word which are not enclosed with the words OPEN and CLOSE? I have the following string:
OPEN someone said hello CLOSE im saying hello people OPEN some said
hello OPEN they said hello again CLOSE i have to go now though CLOSE hello again!
I'm trying to match all occurences of hello (that are not enclosed in the OPEN and CLOSE words) and replace them with another word, possibly with a regex and PHP's preg_replace function (although I'm open to other methods as I can't think of any).
So from the above string the below will match (I've placed them in brackets with italics to help you distinguish):
OPEN someone said hello CLOSE im saying (hello) people OPEN some said
hello OPEN they said hello again CLOSE i have to go now though CLOSE (hello) again!
Not really sure how to go by doing this.
Edit perhaps this will clarify the nesting structure abit better:
OPEN
text
CLOSE
OPEN
text
OPEN
text
CLOSE
text
CLOSE
As you can see from above, the hello is not being notice because its within OPEN...CLOSE (so they are ignored) whereas the others which arent are going to be replaced.
A: I numbered the hellos, so hello2 and hello5 are the ones that should get replaced.
$s0 = 'OPEN someone said hello1 CLOSE im saying hello2 people OPEN some said hello3 OPEN they said hello4 again CLOSE i have to go now though CLOSE hello5 again!';
$regex='~
hello\d
(?=
(?:(?!OPEN|CLOSE).)*+
(?:
(
OPEN
(?:
(?:(?!OPEN|CLOSE).)*+
|
(?1)
)*
CLOSE
)
(?:(?!OPEN|CLOSE).)*+
)?
$
)
~x';
$s1=preg_replace($regex, 'goodbye', $s0);
print($s1);
output:
OPEN someone said hello1 CLOSE im saying goodbye people OPEN some said hello3 OPEN they said hello4 again CLOSE i have to go now though CLOSE goodbye again!
demo
The lookahead uses the recursive subpattern construct, (?1) to try and match zero or more complete, nested OPEN...CLOSE structures between the currently-matched word and the end of the string. Assuming all the OPENs and CLOSEs are properly balanced, that means the hello\d it just matched is not inside such a structure.
A: Alan's answer works great. However, since I already took the time to compose it, here is another way to do it using a callback function and the PHP (?R) recursive expression:
function highlightNonNestedHello($str) {
$re = '/# Two global alternatives. Either...
( # $1: Non-O..C stuff.
(?: # Step through non-O..C chars.
(?!\b(?:OPEN|CLOSE)\b) # If not start of OPEN or CLOSE,
. # then match next char.
)+ # One or more non-O..C chars.
) # End $1:
| # Or...
( # $2: O..C stuff.
\bOPEN\b # Open literal delimiter.
(?R)+ # Recurse overall regex.
\bCLOSE\b # Close literal delimiter.
) # End $1:
/sx';
return preg_replace_callback($re, '_highlightNonNestedHello_cb', $str);
}
function _highlightNonNestedHello_cb($matches) {
// Case 1: Non-O...C stuff. Highlight all "hello".
if ($matches[1]) {
return preg_replace('/\bhello\b/', '(HELLO)', $matches[1]);
}
// Case 2: O...C stuff. Preserve as-is.
return $matches[2];
}
A: Well this is my attempt, tell me if it works for you or not:
<?php
$str = 'OPEN someone said hello CLOSE im saying hello people OPEN some said hello OPEN they said hello again CLOSE i have to go now though CLOSE hello again!';
echo "<p>$str</p>"; //before
//first replace all of them
$str = str_replace('hello', '(hello)', $str);
//then replace back only those within OPEN CLOSE
function replace_back($match){return str_replace('(hello)', 'hello', $match[0]);}
$str = preg_replace_callback('/OPEN.*?\(hello\).*?CLOSE/', 'replace_back', $str);
echo "<p>$str</p>"; //after
?>
<style>p{width:500px;background:#F1F1F1;padding:10px;font:13px Arial;}</style>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Could some one explain what does these IComparer, IEnumerable etc stand for I am pretty new to .Net. In classes I have seen objects as IComparer, IEnumerable etc. Could some one explain what does these stand for?
Thanks for your help.
A: They are interfaces. An interface ensures that an object has certain methods, regardless of it's class. They are useful when you have code that requires a few common methods, but doesn't need to know all of the details of the class.
Object(), System.Collections.ArrayList and System.Collections.Queue all implement IEnumerable. If you have a function that asks for an IEnumerable, you can pass an object of any of these classes to the function, and the function is confident that the object implements all of the IEnumerable members.
Try the following code in a console application. These three different classes are all acceptable to pass to PrintAll(items).
Public Sub PrintAll(items As IEnumerable)
For Each item In items
Console.WriteLine(item)
Next
End Sub
Public Sub Main()
Dim objects As Object() = {1, 2, 3}
Dim list As New ArrayList({4, 5, 6})
Dim queue As New Queue({7, 8, 9})
PrintAll(objects)
PrintAll(list)
PrintAll(queue)
Console.ReadLine()
End Sub
A: These are interfaces. The "I" usually denotes this. These contain method contracts that any class implementing the specific interface must implement. In other words, if you have a class that implements IEnumerable then you need to have the methods in your class that are contained in the interface.
Interfaces (and object oriented programming) can get very deep, but that's a broad explanation hopefully simple enough to understand.
Please let me know if I can clarify.
A: I would start by looking into the idea of an interface since these are both interfaces as is evidenced by their naming conventions. It would require a potentially long-winded answer to impart complete understanding but the idea is that the interface provides the signatures of methods so that the inheriting class knows which methods to implement. I realize that was a lot of potentially unfamiliar concepts but think of the interface as a recipe. You are given the guidelines to create something. 1 C of flour, 1 T of sugar, etc. When you want to make the item you make sure you can meet the requirements, throw it all together and you have a finished product. Sorry if this is a terrible analogy, but hope it helps.
In your case, the names of the interfaces provided by Microsoft give a small idea of what they're intended to represent. If you inherit IComparer, for instance, you end up with a class that can compare two objects. It's important to note that the type of objects are not necessarily defined by the interface. It is up to the implementation to dictate the types. Only the "framework" is provided by the interface.
Good luck!
A: ICompare is for comparing stuffs. classes that related to sorting/comparing(obviously) may implement this.
IEnumerable is for collection, listing, linq stuffs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: zend url rewrite problem with .htaccess on windows 2003 I am having a problem setting up my Zend framework project.
I have xampp/htdocs/quickstart
my server name is mydomain.com. I want to access my project at https://mydomain.com/quickstart(note that i am using https, dont think if this could be a problem)
i used the following .htaccess
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R,L]
RewriteRule ^\.htaccess$ - [F]
RewriteCond %{REQUEST_URI} =""
RewriteRule ^.*$ /public/index.php [NC,L]
RewriteCond %{REQUEST_URI} !^/public/.*$
RewriteRule ^(.*)$ /public/$1
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [NC,L]
RewriteRule ^public/.*$ /public/index.php [NC,L]
And i am getting a 404 error , why does this happen?
I am sorry, i am no expert in configuring .htaccess. All i want to do is route all the requests in quickstart to quickstart/public. and to access my zend project at https://mydomain.com/quickstart/
i am getting a 404 error with above .htaccess(found on Internet)
My problem is is i already ahve other apps running on the server and i want to build a project on /quickstart. i also cannot create a subdomain. Can you please help me with proper .htaccess config.
A: Try with this,
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: correct way to model in Rails 3 / ActiveRecord - compound foreign key I have a set of locations which have a relationship to a global_identificiation table which has id, arc_id (the object_id) and arc_type (the object_type) (ie a compound foreign key). How would I set up the association so that this global information is eagerly loaded on each find of Location? such that:
@l=Location.find(23)
@l['id']=23
@l['name']='some place'
@l['global_info']['id']=145
@l['global_info']['arc_id']=23
@l['global_info']['arc_type']='Location'
Right now, for saving, I just do an after_save callback which is how it gets into database but don't have any other associations with it.
thx for any help
edit:
perhaps this could just be done as an after_find on the classes that need it?
A: Either use after_find, or just create a method in your model to call, then just pass in the data as params.
Or better yet make a module that all your location based classes can include, then this module can define all sorts of location based methods.
module Locations
def find_with_data(id)
x = Location.find(id)
x['id']=id
x['name']='some place' #you could pass this in params
x
end
end
class Location < ActiveRecord::Base
include Locations
end
then call
new_loc = Location.new
new_loc.find_with_data(35)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Phonegap not scaling properly between iPad and iPhone I developed an app for iPad using Phonegap 0.9.6.
Seems to be working fine.
The main element in the app is 768 px wide, so scaling has not been a problem one way or the other.
Now I am experimenting with running the same thing on an iPhone.
I have this meta tag at the top of my html in the 'head' section:
<meta name="viewport" content="user-scalable=no, width=device-width">
It seems to work fine on the iPhone browser: I can point the browser to my locally-running server, the page gets scaled appropriately so it fits in the iPhone screen.
If I make a 'Home Screen" version of the page so it's more of a WebApp (still not using PhoneGap) I still get scaling, although now it's a little off: the image is a little too wide, a small strip on the right winds up offscreen.
But when I try things in Phonegap I am getting no scaling at all. The page always shows up at normal resolution, so I am seeing just the top quarter of it.
I have tried all of the following:
* Changing Summary->Devices from iPad to Universal in XCode target settings.
* Mucking with the 'enable display scaling' widget under the 'info' tab of the 'run' item on the scheme for this build.
* Every permutation of trick I can think of for the meta 'viewport' tag: setting min/max scaling, setting initial scale, setting width to fixed numbers, etc.
For that last item, I can see tweaks I make reflected in the Browser on the iPhone (and the HomeScreen version), but the PhoneGap never budges: I always get the same upper-right corner. I can't seem to make that move at all.
A: The appropriate way to fit iPhone screen is not to scale and shrink the whole page, but to use scalable html structure and styles for your app, for instance, use 100% instead of 768px. You should always avoid scaling the page. Insert this line to the head tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
It's better to write same css for both iPhone and iPad, but if you really want to apply different styles for them each, you can use media queries, for example, ipad-specific style is like this:
<link rel="stylesheet" media="screen (max-device-width: 1024px)" href="ipad.css" />
You will also want to assign different css files for low-resolution screen and retina screen. Still use media queries.
<link href="static/iphone.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="static/retina.css"
media="screen and (-webkit-device-pixel-ratio: 2)" />
A: You should be able to control the scaling trough HTML by putting the following in your PhoneGap.plist file:
EnableViewportScale : YES
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: reading objects from plist to NSArray I wanted to have an NSMutableArray of patients, however I don't want to hard code the patients info (name, dob, etc). I want to store that in a plist and then be able to have an NSArray of Patients object. How can I do this? I know how to do if it's just an NSString array, but what if it's an NSArray of objects?
A: If you're storing and retrieving a list of patients, then over time as your app matures you will likely need to access them in various ways. CoreData and/or Sqlite offer more robust storage mechanisms that offer rich querying, indexing and CRUD operations.
CoreData will offer a designer to design your logical objects and take care of the persistance to sqlite for you. If you want more control, you can work with sqlite and if you do, fmdb is a good wrapper class.
Unless you're doing this as a learning sample to learn plists, I wouldn't recommend tracking patients in a plist. If that's the case, then here's another SO article on persisting arrays to plists:
How to read data structure from .plist file into NSArray
From that post:
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
Hope that helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL ORACLE ORA-00969: missing ON keyword? I have two different tables : Table_a and Table_b, both have same columns PartNo and Material_Desc. I want the Material_Desc in Table_b to update the Material_Desc in Table_a when PartNo are equals. This is my query
MERGE INTO Table_b
USING ( SELECT t1.rowid AS rid
, t2.Material_Desc
FROM Table_b t1
JOIN Table_a t2
ON Table_b.PartNo = Table_a.PartNo )
ON rowid = rid
WHEN MATCHED THEN
UPDATE
SET Table_a.Material_Desc = Table_b.Material_Desc;
I know Oracle doesn't support joins for update statement so I tried the above query. Still it gives me ORACLE ORA-00969: missing ON keyword error
A: First of all, the syntax problem: when you merge using a subquery, you have to alias it to something. But more importantly, you don't need to use a subquery.
MERGE INTO Table_a USING Table_b ON (Table_a.PartNo = Table_b.PartNo)
WHEN MATCHED THEN UPDATE SET Table_a.Material_Desc = Table_b.Material_Desc
First of all, you have to put the table you want to update into the INTO portion. Second, doing the join in a subselect and merging on rowids won't offer you any benefit that I can think of.
A: You might put "(" and ")". So write :
ON ( rowid = rid )
A: perhaps not as efficient as a merge statment, but should do the work:
update table_b tb
set tb.Material_Desc = (select ta.Material_Desc
from table_a ta
where ta.PartNo = tb.PartNo
and rownum = 1
)
where tb.rowid in (
SELECT t1.rowid
FROM Table_b t1
, Table_a t2
WHERE t1.PartNo = t2.PartNo
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Using the Timer2 of a PIC32 to Set a Delay I'm pretty much brand new to the PIC32 and its programming in C, so I'm a bit stumped on how to go about the following problem. I've been asked to toggle an LED of the PIC32 on and off, which I can do fine; however, I now wish to add a 0.25s delay between toggling. I've been told to assume that I'm making use of a 72MHz system clock and a 36MHz peripheral bus clock. I know now that Timer2 is a Type B Timer, and that I should configure it for 16 bit ungated operation. I figured I can first set the initial values of TMR2, PR2 and other bits in T2CON as needed before setting TON to start the time, ending it by clearing TON and resetting the initial values.
Well, if that above sounds right, how might I do this with C? What I can gather from the reference manual is that it might look something like the following:
T2CON = 0x0; // Stop Timer and clear control register,
// set prescaler at 1:1, internal clock source
TMR2 = 0x0; // Clear timer register
PR2 = 0xFFFF; // Load period register
T2CONSET = 0x8000; // Start Timer
Now, how might I set the prescale and what not so that I can achieve my 0.25s delay? I'm just not good at covering what I need to C, and I'm still not that great at performing this kind of thing in assembly to begin with... Any guidance is appreciated. Here's my code thus far:
#include <p32xxxx.h>
int main()
{
while(1)
{
PORTDbits.RD0 = 1; // Turns LED On?
// Delay...?
PORTDbits.RD0 = 0; // Turns LED Off?
// Delay...?
}
return 0;
}
Header File: p32mx360f512l.h, if that is of any use.
A: the name of the header file IS of use ... based on that filename i guess this is the chip you have to work with ... http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en532441
on that page you can find some code samples in c, so that should cover questions like "how to work with this chip in c"
so for your general approach:
a loop is a nice idea, but since you are given a type b timer in ungated mode, i think that should be a hint to use interrupt handlers to do the work ... have a look at http://ww1.microchip.com/downloads/en/DeviceDoc/61105E.pdf (section 14.4) on how to set this up
in the ISR compare the timer/counter value with a value you will have to calculate based on the clock freq and the prescaler setting, so you will know when the desired time has come to flip the bit
after the bit is flipped, reset the timer for the next cycle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple User IDs from multiple Request IDs Like said on the facebook developer reference here: http://developers.facebook.com/docs/reference/dialogs/requests/
i can retrieve multiple User IDs from multiple Request IDs with this javascript code:
function getMultipleRequests(requestIds) {
FB.api('', {"ids": requestIds }, function(response) {
console.log(response);
});
}
But it doesn't work for me, and i can't find any real example over the web.
This is my code:
function newInvite()
{
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'message',
title: 'title',
},
function(res){
if (!res || !res.request_ids) { /* user canceled */ return; }
FB.api('',{"ids": res.request_ids }, function(response) {
console.log(response);
});
}
)}
I receive the following error in firebug console:
(#803) Some of the aliases you requested do not exist: ["2451125555242","254271541274626"]
type: "OAuthException"
Any ideas?
Thank you very much
A: found the solution:
var requests = res.request_ids.join(',');
FB.api('',{"ids": requests }, function(response) {
console.log(response);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!" I get this error when I try to access localhost/phpmyadmin:
Wrong permissions on configuration file, should not be world writable!
I have already chmoded every file to 555 from 777. What should I do next? I run Ubuntu 11.04.
A: Try this it will work
sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
A: I just solved this problem myself, and this question/answer pair was not helpful to me in particular, so I will add what solved it for me in my specific case.
For starters, I have just began to use a repository so I "chmod 777 -R"'ed my entire /opt/lampp directory to make sure that permissions were not an issue for the pushing of the repository. Then I got two errors, but I think I only saw one of them and the next one showed up after fixing the first one it. I suppose one error was upstaging the other.
The first one was ./lampp/etc/my.cnf A chmod 700 on that file fixed it in my case although, 755 seems to be the better choice that I found in my research.
One file down, one more to go. The other file, which is the one causing the specific error message in this question is ./lampp/phpmyadmin/config.inc.php.
Solution: "$ chmod 755 -R /opt/lampp/phpmyadmin"
A: Try
sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
This command fixed the issue having on my Ubuntu 14.04.
A: This is because of wrong permission of phpMyAdmin directory and the file config.inc.php
On *nix like OS set the permission of the directory and the file as follows
chmod -R 755 /path/to/phpMyAdmin
chmod 644 /path/to/phpMyAdmin/config.inc.php
If like me you run a Linux Virtual Machine which mount a Windows folder where phpMyAdmin sources are located, edit config.inc.php and add this line
$cfg['CheckConfigurationPermissions'] = false;
A: I got the same problem as you. I fixed this problem by following this post :D
But I didn't change the permission from 777 to 755 :O
http://blog.elijaa.org/index.php?post/2013/02/19/Solve-Wrong-permissions-on-configuration-file%2C-should-not-be-world-writable!-error-on-phpMyAdmin
A: all you need is to
*
*open terminal type
opt/lampp/lampp start
to start it and then
*sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
then visit in your browser
localhost/phpmyadmin
it will work fine.
A: I run my system on top of a XAMPP instalation on a OS X.
A few days ago I faced the same problem. I was getting a lot of permission problems when installing and managing CMS test platforms, so I decided to set the entire htdocs subtree to a+rwX permissions, and got the same error.
Although my decision to set the entire subtree to those permissions is generally a mistake, that I made knowingly because this system is only accessable by localhost and otherwise unreachable, the only file that needs permission changing to solve this issue is config.inc.php, and you can leave the rest with the permissions you think you need.
The problem is fixed with:
chmod 644 config.inc.php, or sudo chmod 644 config.inc.php, depending on the system.
(issued inside the phpmyadmin folder)
A: This error occured because phpmyadmin directory has all permissions (777).
you can resolved this problem by executing the following command.
sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
A: For Mac
sudo chmod 755 /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php
Worked for me
A: This worked for me: $ pkexec chmod 755 -R /etc/phpmyadmin
A: For Mac OS users:
Find the file named config.inc.php, usually located in /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php
(this is the filepath on my Mac)
Then click the right mouse click -> Click on Get Info, at the bottom of the box you will find permissions-> click on the Lock icon (bottom right corner)
Put your System Admin Password ->
-> where it says everyone, modify this permission to READ ONLY -> click back on the Lock icon and try to open
http://localhost/phpMyadmin http://localhost/phpmyadmin
A: You should not be making them 777 (which is writeable by everyone). Try 644 instead, which means user has read and write and group and others can only read.
A: Just in case, someone out there having same issue but changing file permission doesn't solve the issue, add this line to your config.inc.php file
<?php
// other config goes here . . .
$cfg['CheckConfigurationPermissions'] = false;
And you're good to go.
In my case, I'm using windows 10 WSL with phpmyadmin installed on D: drive. There's no way to (for now) change file permission on local disk through WSL unless your installation directory is inside WSL filesystem it-self. There's updates according to this issue, but still on insider build.
Cheers.
A: Do the following in your terminal
sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
After this you have to restart your server
A: try if install lampp
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin/*
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin
or if install phpmyadmin
sudo chown www-data:www-data -R /etc/phpmyadmin/*
sudo chown www-data:www-data -R /etc/phpmyadmin
A: What the hell? errors say that the file should not be 755 but everyone says should be 755.
You should change the permission of the file into 444 to protect it from the edit.
run this command:
sudo chmod 444 /opt/lampp/phpmyadmin/config.inc.php
A: Mac/ MAMP:
sudo chmod -R 755 /Applications/MAMP/bin/phpMyAdmin
worked for me.
A: On My Mac using XAMPP i simply did
sudo chmod 755 /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php
A: These problem arises due to permission we can't give the all permission of our database config
If you are using ubuntu and you have the path like this /opt/lampp then type the following command in terminal.
sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
A: For me, the error just appaered this morning, without doing any updates.
If your using the official docker container without Your own config.inc.php, You can find the file located in /etc/phpmyadmin
So the solution would be
docker exec nameofyourphpmyadmincontainer chmod 0644 /etc/phpmyadmin/config.inc.php
or mount an external config.inc.php into docker container on start.
A: *
*Goto lampp folder and change the owner back to root
*Change permission to 755 -> This will start the phpmyadmin working again
*Goto htdocs folder and make your user as owner of the folder and give 777 permission so that you can start the localhost project
*If with step 3 error such as write access denied comes, then for htdocs folder, right click and give permissions to all files/folders recursively
Hope this helps.
A: To restrict access on this file /phpmyadmin/config.inc.php and he will work.
Simple tape this : sudo chmod 750 /phpmyadmin/config.inc.php !
A: If you are using ubutu and you have the path like this /opt/lampp then type the following command in terminal.
sudo pkexec chmod 755 -R /opt/lampp/phpmyadmin
Hope this will find out your solution.
A: you should change the owner of the server
by chown command
from home you can run this command
sudo chown {userName} -R ../../opt
If it does not work yet, run this command
sudo chmod 777 -R ../../opt
It should work now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
}
|
Q: Single step a process by one assembly instruction When you execute a single step operation using ptrace does the process do one "line" of code or does it do one line of assembly instead. If it's the former case is there a way to step a process in linux by one processor instruction only?
I mean to do this within the kernel but the GDB source is kind of large and it's hard to track exactly what it's doing to do it's ASM singlestepping. I want to single step a process it's just that I'm not sure what the exact behavior of ptrace's single step is (just 1 instruction or more?)
A: It does one line of assembly. You can verify this by opening two sessions, in one session you can have your program running which displays the contents of IP register( EIP in 32 bit and RIP in 64 bit) and in other run objdump using the following command - objdump -d -j.code | less and verify
A: Use gdb: http://condor.depaul.edu/glancast/373class/docs/gdb.html#Running_the_Program_being_Debugged
If you have access to the source code or debug symbols, you can step one line at a time. If you don't, you'll have to step one instruction at a time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC3 - File upload controller / handler not receiving the image I am using http://valums.com/ajax-upload/
File uploader plugin to do ajax image upload and i see the request in fiddler go through, with the image in it when i pick a local image. The fiddler request has the PNG file in it.
From fiddler -
POST http://localhost:16169/client/account/uploadimage/202?qqfile=logo_l.png HTTP/1.1
Host: localhost:16169
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
X-Requested-With: XMLHttpRequest
X-File-Name: logo_l.png
Content-Type: application/octet-stream
Referer: http://localhost:16169/client/events/edit/202
Content-Length: 32660
Pragma: no-cache
Cache-Control: no-cache
�PNG
���
IHDR�����������¯�C���gAMA����
�a��� pHYs�����&�?���tEXtSoftware�Microsoft Office�5q��IDATx^��G�=���8,����@p
�ݓ�@�$��������.+��T���H���ϗ}��<��ܹsgg�O�����6111A���A2�@J�%�K!��K��)����ζ)�Mm��@�{�;ˤ�
ˤt�d���FK���og�Ц�6�a �=�eR�?�eR:m2�@J�%�F���m
hS@��0�����2)��2)�6b �ђa����6�)�MvHv�og���Oa��N�1��hɰ���l���&;$����L����LJ�M�Hi�d�h�v�Mm
I have truncated the request but you get the idea that the image is being transmitted in the post body.
But when i do
var image = WebImage.GetImageFromRequest();
in the controller that handles this post request. Image comes out to be null, Looking at the debugger all other values are present.
Request.Files.Count = 0
as well.
Anyone gone through this, or can help me debug this will be greatly appreciated. Thanks.
A: Found the solution..
WebImage image = new WebImage(Request.InputStream);
instead of -
var image = WebImage.GetImageFromRequest();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android: Is it possible to detect if user hanged up call or callee? I know there are similar questions like mine, but they are pretty old. I hope there is some solution to this problem.
One of my clients wants the application to be able to detect if the call was hanged up by the caller or the callee? Can someone tell me if this is possible or just tell me that it's impossible to do it at all?
I thought about to detect if the user pressed the hang-up button while in a call, but I don't know if that is possible to detect either.
A: I had similar question like you that I want an event that receiver receives the call.I had searched on net and I knew that You can not get any event that receiver receives the phone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When using areas, does it make sense to have controllers in a non-area? If I decide to use areas in mvc3, in a new application, does it make sense to have controllers in a non-area?
Or will that make things inconstant?
This is a new project, and i havent' worked with areas so not sure of how things will end up so looking for advice now.
So far I have an /admin area setup.
I can have code organized into areas, and still have the url with the area name prefixed correct?
A: You can have your controllers in your main app if you so choose, with other areas separated out. Its up to you, there's no reason you can't or shouldn't.
"I can have code organized into areas, and still have the url with the area name prefixed correct?"
Absolutely
A: I've done something similar to this in the past. In my solution I had several area's which may or may not contain the controller required. When registering the area you can use the UseNamespaceFallback option. This allows the controller factory to look at other namespaces in the event that the controller isn't found in the area.
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional},
new[] {"Proj.Web.Controllers.Areas.Admin"}
).DataTokens["UseNamespaceFallback"] = true;
Then in the Global.asax file add the namespaces for the default controllers.
ControllerBuilder.Current.DefaultNamespaces.Clear();
ControllerBuilder.Current.DefaultNamespaces.Add("Proj.Web.Controllers");
ControllerBuilder.Current.DefaultNamespaces.Add("Proj.Web.Controllers.Areas.Base");
If you want an area to only use controllers within it, simply do DataTokens["UseNamespaceFallback"] = false. This method has worked great in our solution as it's a very generic based implementation with large amounts of code reuse.
A: I think it often does make sense to have controllers in a non-area.
For example, if you ever implement a base abstract controller that your area-based controllers will inherit from, I would put something like this in the root (non-area) controllers folder.
Depending on your app, you may also find that you have controllers which span multiple areas. For example, you might have a controller with child actions for navigation. Putting this into a dedicated Navigation area might be overkill, if the area would contain only 1 controller.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pausing an Application in Android I am having a buttong in my Android App and I want that pressing that button should stop the application at the same point. While clicking again on the same button should resume the App.
How to do this?
A: You are asking the wrong question. You should never pause and resume your app manually, that's for the system to do for you.
A: What does your application do? In any case, you will have to store and re-create your application state. You can store it in a file, SharedPreferences or an SQLite database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The default document (default.aspx) in IIS is not working after adding MVC and routing to a WebForms project I have an existing ASP.NET 3.5 WebForms project and have added ASP.NET MVC to the project. The existing pages work fine and so do the new controllers & views. However, when I deploy to IIS 7 the default document (default.aspx) is no longer working. I can get to it if I type it in explicitly but 'xyz.com' doesn't work - I get a 404. In contrast, it does work fine in Cassini.
How do I get the default document working again while still retaining the new MVC stuff.
A: I added the following to the Global.asx.cs file and the default document works again.
public static void RegisterRoutes(RouteCollection routes)
{
// *** This Line ***
routes.IgnoreRoute(""); // Required for the default document in IIS to work
// *****************
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start(Object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
A: Do you have Default Documents enabled for your IIS application, and is default.aspx in the list? Just double-check those, I can't think of anything else that would affect the serving of the default.aspx page. IIS should look something like this:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do I chain devise_for calls in my route file? - Rails 3.1 I am trying to use OmniAuth, and according to Ryan Bates, I should override the Devise Registration controller by specifying the following devise_for scope in my routes.rb file:
devise_for :users, :controllers => {:registrations => 'registrations'}
However, according to Devise's documentation, if I am to customize the path_names, so instead of doing mydomain.com/users/sign_up/, I can do mydomain.com/register, I would have to do something like this:
devise_for :users, :path_names => { :sign_up => "register", :sign_in => "login", :sign_out => "logout", :settings => "settings", :newpass => "newpass", :changepass => "changepass" }
I tried to chain both of them like this:
devise_for :users, :controllers => {:registrations => 'registrations'}, :path_names => { :sign_up => "register", :sign_in => "login", :sign_out => "logout", :settings => "settings", :newpass => "newpass", :changepass => "changepass" }
But that doesn't work. In order for me to go to the view in my views/registrations/new.html.erb, I have to go to mydomain.com/users/register. If I go to mydomain.com/register it still serves it from /views/devise/registrations/new.html.erb.
How do I get mydomain.com/register to point to /views/registrations/new.html.erb?
Thanks.
A: Write this in you routes file instead of adding :path_name
devise_scope :user do
get "register", :to => "devise/registrations#new"
get "login", :to => "devise/sessions#new"
get "logout", :to => "devise/sessions#destroy"
end
_edit2__
If you want to override the controllers then you need to copy the devise controller folder from your gem into your application under app/controllers. In this case You also need to write below lines in routes.rb file. If you don't want to override the default functionality for devise controllers then there is no need to adding below lines in routes.rb file.
devise_for :users, :controllers => {
:registrations => 'devise/registrations',
:sessions => 'devise/sessions',
:passwords => 'devise/passwords',
:confirmations => 'devise/confirmations',
:unlocks => 'devise/unlocks'
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you save nested objects in redis? Can you save nested objects in redis?
I'm using the node.js driver. One of my key-values is an array of objects. If I dont stringify it results in the string "[object Object]" if i stringify it I get this error:
{
stack: [Getter/Setter],
arguments: undefined,
type: undefined,
message: 'ERR wrong number of arguments for \'hmset\' command'
}
A: stringifying json is not the right way of using redis. you should generate your own redis hashsets
user:ejder name ejder
user:ejder:details:0 age 32
user:ejder:details:1 age 25 (i wish)
that way you can query your data redis-way. Stringifying json is nothing but saving a string and if you use large datasets it will decrease the performance very bad
A: Stringifying simple object to it's JSON representations should work and it seems that you have some syntax error in your code (can you please update your question with corresponding code where you are doing the HMSET command?). If you are not ok with stringified version, then each of your object in array should have dedicated hash structure where their data would be located.
Alternatively you can try to use node.js implementation of a object-hash mapping library for redis.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: error with inserting data into sqlite database table in android I have a db table :
create table recentMovies5 (_id integer primary key autoincrement, line1 text, line2 text, title text , Tags text , ImageLink text , XMLLink text, entryTime numeric);
and am inserting values like this:
Insert into recentMovies5 (line1, line2, title, Tags,ImageLink,XMLLink,entryTime) Values ("3 min ", "Japan", "Ahsan", "38", "www.ahsan.com/aha.jpg", "www.ahsan.com/aha.xml",1317172213);
java code for inserting:
String select="Insert into recentMovies5 (line1, line2, title, Tags,ImageLink,XMLLink,entryTime) Values (\"3 min \", \"Japan\", \"Ahsan\", \"38\", \"www.ahsan.com/aha.jpg\", \"www.ahsan.com/aha.xml\",1317172213)";
SQLiteDatabase db = savedInfoDbHelper.getReadableDatabase();
Cursor c=db.rawQuery(select, null);
startManagingCursor(c);
before I added the column entryTime numeric, everything was working fine. Now, no data is being inserted and I get no error message! Any help ?
edit 1: changing entryTime from numeric to integer doesnt seem to help :(
edit 2: using this code to open the database:
public SavedMoviesDbAdapter open() throws SQLException {
dbHelper = new RecentMovieDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
edit 3: checked with both isOpen and isReadOnly =>> is open and not readonly.
A: You are trying to insert into a readable only DB.
Use openDatabase with OPEN_READWRITE flag instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.