text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: PHP upload errors I have an upload script that's causing me some problems and I can't for the life of me figure out why. Here's the php code:
mysql_connect('localhost', 'root', '');
mysql_select_db('uploads');
if (isset($_FILES["file"]["type"]) && isset($_FILES["file"]["size"])) {
if (($_FILES["file"]["type"] == "image/png")) {
if ($_FILES["file"]["size"] < 500120) {
if ($_FILES["file"]["error"] > 0) {
echo $_FILES["file"]["error"];
} else {
if (file_exists("uploads/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
$name = $_FILES["file"]["name"];
mysql_query("INSERT INTO uploads (name) VALUES ('$name')");
if (isset($_POST['title']) && isset($_POST['desc'])) {
$title = $_POST['title'];
$desc = $_POST['desc'];
mysql_query("INSERT INTO uploads (title, desc) VALUES ('$title', '$desc')");
echo $title;
echo $desc;
}
}
}
} else {
echo "File is too big";
}
} else {
echo "Wrong file type";
}
}
I know that my file paths and form input are correct and if I echo the $title or $desc variables they return with the correct values. My problem is this: for some reason it won't enter the $title and $desc values into the database. The first mysql query works fine but not the second. Any idea why?
A: This is likely because desc is a MySQL reserved keyword, and it must be enclosed in backquotes in your query statement. Always check mysql_error() to find the cause of a failed query.
$success = mysql_query("INSERT INTO uploads (title, `desc`) VALUES ('$title', '$desc')");
if (!$success) echo mysql_error();
Please also escape $title and $desc before insert, as they are coming directly from $_POST.
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
And do the same for $name in the earlier query:
$name = mysql_real_escape_string($_FILES["file"]["name"]);
A: You are creating 2 records in the uploads table, for 1 file. Probably the name column is set to not null, and this causes second query not to work.
It have to be:
$name = mysql_escape_string($_FILES["file"]["name"]);
$title = isset($_POST['title'])?mysql_escape_string($_POST['title']) : '';
$desc = isset($_POST['desc'])?mysql_escape_string($_POST['title']) : '';
mysql_query("INSERT INTO uploads (`name`, `title`, `desc`) VALUES ('$name', $title, $desc)");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Data-bound WPF ComboBox not displaying selected value I have a ComboBox, bound to a DataTable. The ComboBox displays a list of values, pulled from the "wellId" column of the DataTable. The ComboBox is also styled so that I can insert a custom item into the list simply by adding a dummy row to the DataTable with the wellId field set to "(settings)".
<ComboBox IsEditable="True" Name="comboWell" ItemsSource="{Binding}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Content" Value="{Binding wellId}" />
<Style.Triggers>
<DataTrigger Binding="{Binding wellId}" Value="(settings)">
<Setter Property="Content" Value="Customize..." />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
For the most part, this works great. It shows the list, and all items (including the dummy items) are selectable in the drop-down list.
However, after selecting an item from the list, whether it is a real item or a dummy item, the ComboBox doesn't show the selected item properly. Rather than showing the same value displayed in the drop-down list (the "wellId" column from the DataTable), it instead just displays the string "System.Data.DataRowView". No matter what I select, it always displays the same thing.
If I specifically set the DisplayMemberPath on the ComboBox to "wellId", then it displays the selected item properly. However, this messes up all of the other styling I have applied, resulting in the drop-down list being filled with blank entries.
How do I get the ComboBox to display the selected item properly?
A: Change your ComboBox to set the ItemTemplate instead of the ItemContainerStyle, and remove IsEditable=True. If IsEditable=True then the SelectedItem will get displayed in a TextBox, and if a TextBox.Text is bound to an item, it will display the .ToString() of that item
<ComboBox Name="comboWell" ItemsSource="{Binding }">
<ComboBox.ItemTemplate>
<DataTemplate>
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Content" Value="{Binding wellId}" />
<Style.Triggers>
<DataTrigger Binding="{Binding wellId}" Value="(settings)">
<Setter Property="Content" Value="Customize..." />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a way in either sql or web developer to all deleting say from a gridview all but the last row? I have a web portal set up where customers can add company contacts, etc to a sql database thru gridviews and detail views i created with microsoft Web Developer. I need to have it set up, where although customers that have rights can edit and delete contact records, they cannot delete the last one. There must be one left in the system. I know this sounds like a strange request, but it is a needed one. Is this something that can be done thru VB, SQL, or thru one of web developers objects such as the Details View?
Thank you!
A: Not a strange request, as I understand the need. The solution we employed is the actual default Admin account did not show up on the delete list, as it was "system generated". That may not be a retooling you can do.
What you can't do is use the automagic drag and drop crap and institute this type of functionality. You will have to either pair down the request to remove the last requested item, write a trigger on the database or write custom code to not delte the last item.
As an example of pairing down: with datasets, since they are disconnected, you can remove the last row prior to sending your delete request. With LINQ and EF, you have similar options to shaping the return data.
Then, if you desire to explicitly control your code (good), you can roll through the items and ensure the last one does not delete.
If you want to make this as "safe" as possible, you might consider a trigger on the table that checks if the delete is last administrator user for a particular organization and abort if so. Then the user might say "delete all" on the web, but the database protects them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Android XML parsing, can't connect to website? Been stuck all day long with this problem, been trying to retrieve XML from this website:
http://www.teamliquid.net/video/streams/?xml=1&filter=live
But I just can't connect, I can find connect to it via google etc, but when I try to connect via the emulator using XML parsing, it won't work. But I can connect to Google weather etc..
Here is what says if you wanna use the XML document:
Thinking of scraping this page for stream data? Please use our XML feed instead: http://www.teamliquid.net/video/streams?xml=1&filter=live
gzip encoding is required, please also send a valid User-Agent with the name of your application / site and contact info. This page and the XML are updated every five minutes, please do not poll more frequently than every five minutes or you may risk being IP banned. If you have any questions, please PM R1CH.
So I'ave tryed it 2 ways, 1st code example, using a XMLReader:
private void DownloadXML()
{
URL website;
try{
website = new URL("http://www.teamliquid.net/video/streams/?xml=1&filter=live");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
rp = new RetrievePlayers();
xr.setContentHandler(rp);
xr.parse(new InputSource(website.openStream()));
}catch(Exception e) {
setText(""+e);
}
}
2nd Example, using a GZIPInputStream, seing as it said somthing about GZIP encryption.
private void DownloadXML()
{
InputStream in = null;
GZIPInputStream gin = null;
URL website;
try{
website = new URL("http://www.teamliquid.net/video/streams/?xml=1&filter=live");
in = website.openStream();
gin = new GZIPInputStream(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(gin));
setText(reader.readLine());
}catch(Exception e) {
setText(""+e);
}
}
Both these codes generate a java.io.Exception.FileNotFoundException
Why can't I get it? I can see the XML file with Google chrome :>
Sorry, I'm pretty new to XML, only spent 2 days working with it :/
A: I am going to be that guy, could it be that you do not have internet permission set in your manifest? I mean, you are parsing from a website, so if you do not have permission to get to the web, then you won't get a parsing response.
Just a Theory and I am trying to help you problem solve :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Apache mod-proxy ProxyErrorOverride for specific URL patterns I am using Apache 2.2 with mod-proxy and I have configured it with several ProxyPass statements to proxy from remote URL to local URL. I need to have custom error documents returned from Apache for these proxied URLs so I set "ProxyErrorOverride On" in my mod-proxy configuration along with some ErrorDocument directives (with local URL path) to return custom error pages for a few HTTP status codes of interest. However, when a status code is returned for which I have NOT created an ErrorDocument directive for, Apache replaces the response body with a default error page instead of leaving the original response body intact. This won't work with the application. So I really have 2 questions:
1) Is it possible to configure Apache to leave the original response body intact for a particular status code if I don't have an ErrorDocument override defined for it?
2) Is it possible to have the ProxyErrorOverride directive only apply to some of the URLs in my ProxyPass statements?
A: As arober11 pointed out in the comment above:
Afraid the answer is: No and No. If the directive could be limited to
a location, directory, or set of URL's, then there would be something
in the "Context" section, of the man page:
httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxyerroroverride
on the other hand: you can always add it to mod_proxy.c yourself.
A: For question 2:
Definitely doable. Using internal redirects to either new host or port this is possible. Brief outline using hosts (add noErrorOverrideUrl,doErrorOverrideUrl in DNS or /etc/hosts of apache-machine):
NameVirtualHost *:80
<VirtualHost *:80>
RewriteEngine On
RewriteRule ^(/noErrorOverrideUrl/.*) http://noErrorOverrideUrl$1 [L,P]
RewriteRule ^(/doErrorOverrideUrl/.*) http://doErrorOverrideUrl$1 [L,P]
</VirtualHost>
<VirtualHost *:80>
ServerName noErrorOverrideUrl
ProxyErrorOverride Off
ProxyPass ...
...
</VirtualHost>
<VirtualHost *:80>
ServerName doErrorOverrideUrl
ProxyErrorOverride On
ProxyPass ...
...
</VirtualHost>
Brief outline using ports:
Listen 80
Listen 81
Listen 82
<VirtualHost *:80>
RewriteEngine On
RewriteRule ^(/noErrorOverrideUrl/.*) http://server:81$1 [L,P]
RewriteRule ^(/doErrorOverrideUrl/.*) http://server:82$1 [L,P]
</VirtualHost>
<VirtualHost *:81>
ProxyErrorOverride Off
ProxyPass ...
...
</VirtualHost>
<VirtualHost *:82>
ProxyErrorOverride On
ProxyPass ...
...
</VirtualHost>
A: You can upgrade apache and use the If sentence avaible on 2.4+
<VirtualHost *:80>
...
<If "%{REQUEST_URI} =~ m#^\/QA(.*)$#">
ProxyErrorOverride Off
</If>
..
</VirtualHost>
Documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: force absolute positioned div not to overlap I have a header bar that is positioned using position:absolute; and I cannot seem to get it to not overlap my content.
Here is the html i'm using for my example:
<div class="ui-page ui-page-active">
<div class="ui-header">
<div class="ui-title ui-title-h1">
Page Title 1
</div>
</div>
<div class="ui-content">
<a href="#pg-two">Page Two</a>
</div>
<div class="ui-footer">
<div class="ui-title ui-title-h3">
Page Footer 1
</div>
</div>
</div>
and here is my css
html,body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.ui-page {
background-color: #bbb;
height: 100%;
width: 100%;
display: block;
position: relative;
}
.ui-page-inactive {
display: none;
}
.ui-page-active {
display: block;
}
.ui-header {
position: absolute;
top: 0;
background-color: #000;
width: 100%;
display: inline-block;
}
.ui-content {
}
.ui-footer {
position: absolute;
bottom: 0;
background-color: #000;
width: 100%;
display: inline-block;
}
.ui-title {
text-align: center;
color: #fff;
padding: 4px;
line-height: 150%;
}
.ui-title-h1 {
font-size: 1.5em;
font-weight: 900;
}
My end goal is to have a header bar always at the top, a footer bar always at the bottom and for the content to fill the centre. The content div does not actually need to fill 100%, I just don't want it to be blocked by either the header or footer.
A: An easy way would be to have either padding-top or margin-top (I'm not sure which) on .ui-content set to the height of your header, that would push .ui-content down so there isn't overlap.
A: If the header and footer are a fixed-height (like, for example "80px") then you can make the content absolute with the top-and-bottom margins (position:absolute;overflow-y:scroll;top:80px;bottom:80px;) and make the header and footer fixed (position:fixed;height:80px;top:0;left:0;right:0;overflow:hidden; for the header and position:fixed;height:80px;bottom:0;left:0;right:0;overflow:hidden; for the footer)
Something like that might work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: YouTube API: How to specify an API callback after an uploaded video has finished encoding? I am uploading videos using the YouTube/Gdata API (in python).
After a video has been uploaded via the API, I receive the a response with data about the video (Youtube link, id, etc). However, the video is not publicly available while it is being encoded by YouTube (typically a few minutes).
Can I specify a callback url that YouTube can post to after it finishes processing the video?
A: No.
You need to poll using the video id to and check the 'state' of the video to detect when 'processing' is no longer present.
A: With Youtube's V3 API, you need to do something similar, but slightly different.
GET https://www.googleapis.com/youtube/v3/videos?part=processingDetails&id={VIDEO_ID}&key={YOUR_API_KEY}
Further details here:
https://developers.google.com/youtube/v3/docs/videos/list
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Best practice to limit event queue I am looking for advice and help regarding a specific use case of an application.
Here's the use case:
A user our our WPF application goes crazy and starts clicking all over, triggering a number of events before the first (or previous) event(s) have to finish.
Currently, WPF queues any and all clicks and queues them for sequential execution. Ideally we would like to queue up to 3 events and drop and disregard any and all clicks (user interactions) after the first 3.
What would be the best approach to solving this issue, what is the best practice for this use case. Any documentation, code and/or help would be much appreciated.
A: Since this really is a windows issue and not specifically a WPF issue, the only thing I can think of is hooking the message queue and discarding clicks within a certain time unless you write specific handlers into each control. The other option is to write the application such that feedback is provided to the user during an operation and input is disabled.
What does WPF use to capture mouse and keyboard input?
A: If you'd use MVVM all UI actions are bound to ViewModel commands or properties. In the ViewModel you'd have full control over how many and how frequently you want to process what comes from the UI. It will probably involve some sort of producer consumer queue.
Also if your user actions block the UI, you need to process them outside the UI thread as much as possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: using tree node class in c# I have a tree node and the tree node can be checked. The thing is that I need to be able to gray out or disable a specific node programmatically. So for instance
[] Head Node
[sub Node]
[sub Node]
[] another node 1
[] another node 2
So lets say that I check "another node 2" then it should not dissapear but instead appear grayed out or disabled but still visible
so it would look like this
[] Head Node
[sub Node]
[sub Node]
[] another node 1
[X] another node 2 //and this would be disabled but still visible
I hope you understand what I want to do just not sure how to disable it and still keep it visible.
Thank you
A: There doesn't seem to be a way to "disable" an ASP.NET tree node. What you can do is disable its select action, and change its style.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RAILS3: Set query parameters to post in functional tests? I have a Rails3 app that has Workflows, and they have many WorkAssignments. WorkAssignments have a field, work_sent_date, the date work was sent to the person. On the Workflow edit screen I display a work sent date field, but Workflow does not have an attribute work_sent_date. If any work assignments have a date, I display the most recent one and it can't be edited. If all are blank, I display a text box that is editable and in WorkflowController#update, if that date is filled it, the work assignments' work_sent_date field get that date.
It works when I test it manually. I suppose I could just create an attribute for it, but I'm trying to be slick and not have redundant data.
I'm trying to write a test for this. First I assert that the WorkAssignment#work_sent_date is blank for all work assignments. Then I try a "post :update" and I can't figure out how to pass in the work_sent_date value, which is a form field but not an attribute. What I want to do is something like.
test "setting work_sent_date in wf sets it in wa" do
@workflow.work_assignments.each do |wa|
assert wa.work_sent_date.blank?
end
get :edit, :id => @workflow.id
assert_response :success
post :update, :workflow => @workflow.attributes, :parameters => {'work_sent_date' => Date.today.to_s}
@workflow.work_assignments.each do |wa|
assert_equal(wa.work_sent_date, Date.today)
end
end
But that parameters field doesn't work. There's no error, but I keep getting failures because wa.work_sent_date is still nil, so it's not getting passed in correctly. How do I pass today's date in as an extra parameter?
(Or maybe there's a better way to do the whole thing, which I would gladly consider.)
I know this is complicated. I hope I explained it well. Any suggestions would be appreciated. I've googled to death and can't find anything.
A: Found my problem. Syntax way wrong. Here's what it should be. This works.
put :update, :id => @workflow.id, :workflow => @workflow.attributes, :work_sent_date => Date.today.to_s
A: You can also refactor out the create and edit as follows:
protected
def edit_workflow(workflow, options = {})
post :update, :id => workflow.id, :workflow => workflow.attributes.merge(options)
end
def create_workflow(options = {})
post :create, :workflow => {}.merge(options)
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sharing an iOS app for Enterprise in XCode 4.1 In articles like this: http://aaronparecki.com/How_to_Distribute_your_iOS_Apps_Over_the_Air as well as the official Apple Documentation: http://developer.apple.com/library/ios/#featuredarticles/FA_Wireless_Enterprise_App_Distribution/Introduction/Introduction.html it says things similar to: "The manifest file is a file in XML plist format. It’s used by an iOS 4 device to find, download, and install apps from your web server. The manifest file is created by Xcode, using information you provide when you share an archived app for enterprise distribution."
However, in the organizer for XCode 4.1, there is no "share for enterprise option". The only options listed are the ones pictured here: http://developer.apple.com/library/mac/#documentation/ToolsLanguages/Conceptual/Xcode4UserGuide/DistApps/DistApps.html
which are "iOS App Store package (ipa)" and "Archive".
Can someone tell me how I actually get to the "Enterprise Sharing" option?
Thank you
A: Just follow the instruction in the documentation
until you arrive the "To share your iOS application."
Once you arrive this step, the next screen will ask you for a file name, and an option "Save for entreprise Distribution" will be available (refer image), check for this box and it is here you enter all the information including the most importantly, application URL that must be the same as your bundle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Specify the INSTALLLOCATION of packages in WiX inside the Burn managed bootstrapper I have a WiX 3.6 bundle (using Burn) and managed bootstrapper that install several MSI packages. Some of the packages install to a common location (C:\program files\MyApp).
I want to let the user choose the install location inside the managed bootstrapper application (C# WPF, especially because the application is large to install; about 1 GB). How can I specify the INSTALLLOCATION for each MSI packages inside my bundle?
A: Use an MsiProperty child for each MsiPackage to specify INSTALLLOCATION=[BurnVariable]. Then use Engine.StringVariables to set BurnVariable.
For example, in your bundle you set:
<Bundle ...>
<Variable Name='BurnVariable' Value='bar' />
...
<Chain>
<MsiPackage Source='path\to\your.msi'>
<MsiProperty Name="INSTALLLOCATION" Value="[BurnVariable]" />
</MsiPackage>
</Chain>
</Bundle>
See also the FireGiant explanation on this topic.
Then in the managed bootstrapper you can do something similar to this:
Engine.StringVariables["BurnVariable"] = "C:\program files\MyApp";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Hex to Ascii conversion problem What is the ascii representation of this hex value: 0x80487d2 every converter gives me a different answer, hopefully someone can help.
Thanks
A: 0x80487d2 has no ASCII representation.
ASCII can only have characters in the range 0 and 127 (inclusive). The hex value 0x80487d2 is well above 127.
That hex value can be split into multiple bytes but the way this is done depends on whether the machine is little or big endian, and regardless, not all of those bytes have an ASCII representation. You won't find 0xd2 on any ASCII character chart (http://www.asciitable.com/).
A: Assuming that is a literal number (i.e. not some weird or little-endian encoding) the decimal representation is 134514642.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users? There is a known issue with opening a PDF in Internet Explorer (v 6, 7, 8, 9) with Adobe Reader X (version 10.0.*). The browser window loads with an empty gray screen (and doesn't even have a Reader toolbar). It works perfectly fine with Firefox, Chrome, or with Adobe Reader 10.1.*.
I have discovered several workarounds. For example, hitting "Refresh" will load the document properly. Upgrading to Adobe Reader 10.1.*, or downgrading to 9.*, fixes the issue too.
However, all of these solutions require the user to figure it out. Most of my users get very confused at seeing this gray screen, and end up blaming the PDF file and blaming the website for being broken. Honestly, until I researched the issue, I blamed the PDF too!
So, I am trying to figure out a way to fix this issue for my users.
I've considered providing a "Download PDF" link (that sets the Content-Disposition header to attachment instead of inline), but my company does not like that solution at all, because we really want these PDF files to display in the browser.
Has anyone else experienced this issue?
What are some possible solutions or workarounds?
I'm really hoping for a solution that is seamless to the end-user, because I can't rely on them to know how to change their Adobe Reader settings, or to automatically install updates.
Here's the dreaded Gray Screen:
Edit: screenshot was deleted from file server! Sorry!
The image was a browser window, with the regular toolbar, but a solid gray background, no UI whatsoever.
Background info:
Although I don't think the following information is related to my issue, I'll include it for reference:
This is an ASP.NET MVC application, and has jQuery available.
The link to the PDF file has target=_blank so that it opens in a new window.
The PDF file is being generated on-the-fly, and all the content headers are being set appropriately.
The URL does NOT include the .pdf extension, but we do set the content-disposition header with a valid .pdf filename and the inline setting.
Edit: Here is the source code that I'm using to serve up the PDF files.
First, the Controller Action:
public ActionResult ComplianceCertificate(int id){
byte[] pdfBytes = ComplianceBusiness.GetCertificate(id);
return new PdfResult(pdfBytes, false, "Compliance Certificate {0}.pdf", id);
}
And here is the ActionResult (PdfResult, inherits System.Web.Mvc.FileContentResult):
using System.Net.Mime;
using System.Web.Mvc;
/// <summary>
/// Returns the proper Response Headers and "Content-Disposition" for a PDF file,
/// and allows you to specify the filename and whether it will be downloaded by the browser.
/// </summary>
public class PdfResult : FileContentResult
{
public ContentDisposition ContentDisposition { get; private set; }
/// <summary>
/// Returns a PDF FileResult.
/// </summary>
/// <param name="pdfFileContents">The data for the PDF file</param>
/// <param name="download">Determines if the file should be shown in the browser or downloaded as a file</param>
/// <param name="filename">The filename that will be shown if the file is downloaded or saved.</param>
/// <param name="filenameArgs">A list of arguments to be formatted into the filename.</param>
/// <returns></returns>
[JetBrains.Annotations.StringFormatMethod("filename")]
public PdfResult(byte[] pdfFileContents, bool download, string filename, params object[] filenameArgs)
: base(pdfFileContents, "application/pdf")
{
// Format the filename:
if (filenameArgs != null && filenameArgs.Length > 0)
{
filename = string.Format(filename, filenameArgs);
}
// Add the filename to the Content-Disposition
ContentDisposition = new ContentDisposition
{
Inline = !download,
FileName = filename,
Size = pdfFileContents.Length,
};
}
protected override void WriteFile(System.Web.HttpResponseBase response)
{
// Add the filename to the Content-Disposition
response.AddHeader("Content-Disposition", ContentDisposition.ToString());
base.WriteFile(response);
}
}
A: It's been 4 months since asking this question, and I still haven't found a good solution.
However, I did find a decent workaround, which I will share in case others have the same issue.
I will try to update this answer, too, if I make further progress.
First of all, my research has shown that there are several possible combinations of user-settings and site settings that cause a variety of PDF display issues. These include:
*
*Broken version of Adobe Reader (10.0.*)
*HTTPS site with Internet Explorer and the default setting "Don't save encrypted files to disk"
*Adobe Reader setting - disable "Display PDF files in my browser"
*Slow hardware (thanks @ahochhaus)
I spent some time researching PDF display options at pdfobject.com, which is an EXCELLENT resource and I learned a lot.
The workaround I came up with is to embed the PDF file inside an empty HTML page. It is very simple: See some similar examples at pdfobject.com.
<html>
<head>...</head>
<body>
<object data="/pdf/sample.pdf" type="application/pdf" height="100%" width="100%"></object>
</body>
</html>
However, here's a list of caveats:
*
*This ignores all user-preferences for PDFs - for example, I personally like PDFs to open in a stand-alone Adobe Reader, but that is ignored
*This doesn't work if you don't have the Adobe Reader plugin installed/enabled, so I added a "Get Adobe Reader" section to the html, and a link to download the file, which usually gets completely hidden by the <object /> tag, ... but ...
*In Internet Explorer, if the plugin fails to load, the empty object will still hide the "Get Adobe Reader" section, so I had to set the z-index to show it ... but ...
*Google Chrome's built-in PDF viewer also displays the "Get Adobe Reader" section on top of the PDF, so I had to do browser detection to determine whether to show the "Get Reader".
This is a huge list of caveats. I believe it covers all the bases, but I am definitely not comfortable applying this to EVERY user (most of whom do not have an issue).
Therefore, we decided to ONLY do this embedded option if the user opts-in for it. On our PDF page, we have a section that says "Having trouble viewing PDFs?", which lets you change your setting to "embedded", and we store that setting in a cookie.
In our GetPDF Action, we look for the embed=true cookie. This determines whether we return the PDF file, or if we return a View of HTML with the embedded PDF.
Ugh. This was even less fun than writing IE6-compatible JavaScript.
I hope that others with the same problem can find comfort knowing that they're not alone!
A: I don't have an exact solution, but I'll post my experiences with this in case they help anyone else.
From my testing, the gray screen is only triggered on slower machines [1]. To date, I have not been able to recreate it on newer hardware [2]. All of my tests have been in IE8 with Adobe Reader 10.1.2. For my tests I turned off SSL and removed all headers that could have disabled caching.
To recreate the gray screen, I followed the following steps:
1) Navigate to a page that links to a PDF
2) Open the PDF in a new window or tab (either via the context menu or target="_blank")
3) In my tests, this PDF will open without error (however I have received user reports indicating failure on the first PDF load)
4) Close the newly opened window or tab
5) Open the PDF (again) in a new window or tab
6) This PDF will not open, but instead only show the "gray screen" mentioned by the first user (all subsequent PDFs that are loaded will also not display -- until all browser windows are closed)
I performed the above test with several different PDF files (both static and dynamic) generated from different sources and the gray screen issue always occurs when following the above steps (on the "slow" computer).
To mitigate the problem in my application, I "tore down" the page that links to the PDF (removed parts piece by piece until the gray screen no longer occurred). In my particular application (built on closure-library) removing all references to goog.userAgent.adobeReader [3] appears to have fixed the issue. This exact solution won't work with jquery or .net MVC but maybe the process can help you isolate the source of the issue. I have not yet taken the time to isolate which particular portion of goog.userAgent.adobeReader triggers the bug in Adobe Reader, but it is likely that jquery might have similar plugin detection code to that used in closure-library.
[1] Machine experiencing gray screen:
Win Server '03 SP3
AMD Sempron 2400+ at 1.6GHz
256MB memory
[2] Machine not experiencing gray screen:
Win XP x64 SP2
AMD Athlon II X4 620 at 2.6 GHz
4GB memory
[3] http://closure-library.googlecode.com/svn/docs/closure_goog_useragent_adobereader.js.source.html
A: I ran into this issue around the time MVC1 was first released. See Generating PDF, error with IE and HTTPS regarding the Cache-Control header.
A: For Win7 Acrobat Pro X
Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.
FYI: Below is the order in which I stepped through the repair.
*
*Go to Control Panel > folders options under each of the General, View and Search Tabs
click the Restore Defaults button and the Reset Folders button
*Go to Internet Explorer, Tools > Options > Advanced > Reset ( I did not need to delete personal settings)
*Open Acrobat Pro X, under Edit > Preferences > General.
At the bottom of page select Default PDF Handler. I chose Adobe Pro X, and click Apply.
You may be asked to reboot (I did).
Best Wishes
A: In my case the solution was quite simple.
I added this header and the browsers opened the file in every test.
header('Content-Disposition: attachment; filename="filename.pdf"');
A: I had this problem. Reinstalling the latest version of Adobe Reader did nothing. Adobe Reader worked in Chrome but not in IE. This worked for me ...
1) Go to IE's Tools-->Compatibility View menu.
2) Enter a website that has the PDF you wish to see. Click OK.
3) Restart IE
4) Go to the website you entered and select the PDF. It should come up.
5) Go back to Compatibility View and delete the entry you made.
6) Adobe Reader works OK now in IE on all websites.
It's a strange fix, but it worked for me. I needed to go through an Adobe acceptance screen after reinstall that only appeared after I did the Compatibility View trick. Once accepted, it seemed to work everywhere. Pretty flaky stuff. Hope this helps someone.
A: Hm, would it be possible to simply do this:
The first time your user opens a pdf, using Javascript you make a popout that basically says "If you cannot see your document, please click HERE". Make "HERE" a big button where it will explain to your user what's the problem. Also make another button "everything's fine". If the user clicks on this one, you remember it, so it isn't displayed in the future.
I'm trying to be practical. Going to great lengths trying to solve this kind of problem "properly" for a small subset of Adobe Reader versions doesn't sound very productive to me.
A: Experimenting more, the underlying cause in my app (calling goog.userAgent.adobeReader) was accessing Adobe Reader via an ActiveXObject on the page with the link to the PDF. This minimal test case causes the gray screen for me (however removing the ActiveXObject causes no gray screen).
<!DOCTYPE html>
<html lang="en">
<head>
<title>hi</title>
<meta charset="utf-8">
</head>
<body>
<script>
new ActiveXObject('AcroPDF.PDF.1');
</script>
<a target="_blank" href="http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf">link</a>
</body>
</html>
I'm very interested if others are able to reproduce the problem with this test case and following the steps from my other post ("I don't have an exact solution...") on a "slow" computer.
Sorry for posting a new answer, but I couldn't figure out how to add a code block in a comment on my previous post.
For a video example of this minimal test case, see: http://youtu.be/IgEcxzM6Kck
A: I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.
A: We were getting this issue even after updating to the latest Adobe Reader version.
Two different methods solved this issue for us:
*
*Using the free version of Foxit Reader application in place of Adobe Reader
*But, since most of our clients use Adobe Reader, so instead of requiring users to use Foxit Reader, we started using window.open(url) to open the pdf instead of window.location.href = url. Adobe was losing the file handle on for some reason in different iframes when the pdf was opened using the window.location.href method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: Telling git its ok to remove untracked files
Possible Duplicate:
How do you remove untracked files from your git working copy?
Is it possible to tell git to remove untracked files? Mainly something that is similar to a reset?
example:
git checkout -- index.php <-- revert my file
git checkout -- master <-- this would revert the entire repo back to the last commit on master, removing (deleting) any and all untracked files as well as reverting committed ones.
I know this is trivial to do on the shell. But I'd like to know if this can be done in Git?
A: You need git clean but add the -df to enable removing files that are in directories from where you are. Add x to include ignored files.
So to completely clean your working directory leaving only what is in source control, issue this command:
git clean -xdf
A: You may be looking for git clean. This will delete all untracked files. By default this ignores (does not delete) patterns in .gitignore, but git clean -x cleans those files too.
From the git clean man page:
-x
Don't use the ignore rules. This allows removing all untracked
files, including build products. This can be used (possibly in
conjunction with git reset) to create a pristine working directory
to test a clean build.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
}
|
Q: Strange issues with texture mapping I am attempting to use texture coordinates from a pre-generated PNG file on a 3d world of quads loaded into Java with LWJGL's slick-util extension.
The texture file is 192x96pixels, and properly formatted. It's composed of 6x3 32x32 tiles.
The 3d quads are 1.5f wide and long. They are spaced apart properly.
I am having issues getting the right texture coordinates. When I put 0.0f to 0.333333f as the y coordinates, I get slightly more than the top tile's height displayed. However, if I put 0.0f-0.25f, I get exactly 1/3rd, which is my tile's height. I have yet to find a magic number for the X coordinates, but maybe someone could explain to me why 1/4 of 96 is 24 according to textures coordinates, or what I'm doing wrong? I'm suspecting it could be a clash between my quad size and textures.
The tops of the cubes are using the texture coordinates (0.0, 0.0f), (0.0, 0.333333f), (0.166666f, 0.333333f), (0.166666f, 0.0f), which is applied moving anticlockwise from the top left to the top right. Again, the main texture file is 32x32 tiles arranged to make 192x96(96 is the height).
Notice I placed a white line at the top of one of the tiles to see its border, and black line at it's bottom, then a white line for the top of the next one below it. The texture 'bleeds' too far down. The other textures have their own even stranger coordinates, as you can see.
Arranging texture coordinates with the assumption the top of the image is 1.0 rather than the bottom produces odd squares with a rectangular hole in the center where quads should be.
I am using TEX_ENV GL_MODULATE.
A: Texture sizes are usually a power of 2. I suspect something resized your 192x96 texture as a 256x128 or 256x256 texture. This doesn't really explain the values you found however... But, I think, if you resize your texture to 256x256(increase the size, don't scale!) and calculate your texture coordinates based on that, your problem will go away.
A: I don't know about java but with my image atlases in objective C and openGL ES you need to make the textures smaller than what you are referring to when selecting them from the atlas.
Have you left a sufficient gap between the texture images to prevent 'bleeding?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convention For Gem with Common Name I recently authored a gem called 'setting' (found here). The extends ActiveRecord with a module named 'Setting'. I understand that gems are supposed to use the namespace they are named, however when testing this caused collisions with ActiveRecord models with the same name (a Setting model). Does a standard exist for creating a private module namespace? I don't need users of the gem to ever access the module outside the extension in ActiveRecord. Do I have any options outside of picking a less common name?
A: Since you're writing an Active Record extension, you could place your module inside the ActiveRecord namespace:
module ActiveRecord
module Setting
end
end
Other than that, no, there's no practical namespace solution for gems with very common names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Show contents in Modal Popup In SharePoint 2010 i've seen many people are using Modal Popup window to show list contents. How to achieve this in sharepoint 2010.
A: You want to look for information on the Dialog Framework.
This training module should help you get started: Module 10: Creating Dialogs and Ribbon Controls for SharePoint 2010
A: I think you are looking for the Shapoint 2010 ECMA Script Modal Dialog:
http://www.chakkaradeep.com/post/Using-the-SharePoint-2010-Modal-Dialog.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delete focus from toolbar item I have a toolbar with custom items. When i click on item, left item get a focus. How to delete focus from toolbar item?
A: It looks like you have "Full Keyboard Access" set to "All controls". You can press tab a few times until the focus goes away from the toolbar item.
If you want to disable the ability to focus on other objects other than text boxes and lists (so you can no longer focus on toolbar items and such), you can do that two ways: 1) press Control + F7, or 2) go to System Preferences, Keyboard preference pane, select the Keyboard Shortcuts tab, and change the "Full Keyboard Access" radio button from "All Controls" to "Text boxes and lists only".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: svn command line equivalent of 'git log -p'? Is there an equivalent of git log -p using the svn command line tool? svn log -v shows file names but not changes.
I would like to see the patches introduced by prior commits. If not possible, is there a way to get the patch (not compared to head, just the changeset) introduced by a single previous commit?
A: There's not an exact match; because, git deals with files while svn deals with filesystems. However, there are close matches.
svn diff does most of what git log -p does. Someone else has already written up a nice tutorial on how to make and apply patches using svn commands. I think you might find it useful.
Note that while the tutorial makes a patch file of local changes against the last checked out version, you can also use the -r 4:7 options to construct a patch of all changes between revisions 4 and 7. Some combination of svn log to identify the specific revisions and svn diff probably will give you exactly what you want.
A: svn log --diff is the equivalent of git log -p.
For a single revision you can use svn diff -c <revision> which in git would be git show <revision>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: What's RunDll32ShimW for in mscoree.dll? I was looking at the exports in mscoree and notice that it exports a function named RunDll32ShimW. The docs on MSDN here aren't particularly helpful. Anyone know what this was for?
I checked out the disassembly of it (it's not in the SSCLI) and it looks like it takes an assembly name and function, loads the DLL with mscoree!LoadLibraryShim, and calls the function on it.
A: The key sentence from the documentation is this:
This function has been deprecated in the .NET Framework version 4.
As to what it does, I would make an educated guess that it calls ShellExecute or CreateProcess and was meant to be invoked by rundll32.exe.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to rename some file of same pattern in shell scripting I want to write a code is shell scripting which will rename all the files of extension .txt in a current directory to extension .c .Suppose my current directory contains some 100 .txt file. This number is not fixed.
A: See man rename. You can rename multiple files providing regexp substitution.
rename 's/\.txt$/.c/' *.txt
If you don't have rename in you system, you can use find:
find . -name '*.txt' | while read FILE; do echo mv "$FILE" "$(echo "$FILE" | sed 's/\.txt$/.c/g')"; done
Remove echo when you verify it does what you want.
A: for f in *.txt; do echo mv "$f" "${f%.txt}.c"; done
Remove "echo" when you're satisfied it's working. See the bash manual for the meaning of "%" here.
A: awk can do this trick too:
kent$ ls *.txt|awk '{o=$0;gsub(/txt$/,"c"); print "mv "o" "$0;}'|sh
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Float an image between 2 columns of text I'd like to know if it's possible to reproduce in CSS/HTML the effect you see in this magazine, with an image floated between 2 columns of text and the text wrapping around it:
I know only modern browsers support 2-column layouts, so my questions are:
*
*Can this be done in modern browsers? If so, how? We are essentially doing a "float:both" but ofc that directive doesn't exist....
*Is there any backward compatible hack to sort of do it in older browsers?
Finally, if you can do this in HTML/CSS, I would think the image would still have to be square, so that the wrapping effect would not be as organic as it is here. Would it be possible to reproduce the effect exactly, rather than having the image square with whitespace, eg, to the left and right of Ron Paul's head? Would you have to slice up the image to accomplish that?
A: It's not easily doable (especially for dynamic text). All the techniques have various downsides.
Here's one possible technique for "float center":
http://css-tricks.com/9048-float-center/
For modern browsers, there's a jQuery plugin that can do it precisely:
http://www.jwf.us/projects/jQSlickWrap/
Here's the tedious, manual version that inspired the above jQuery plugin:
http://www.alistapart.com/articles/sandbags
A: Curvelicious Otherwise known as a ragged float by Eric Meyer.
Also Sandbags
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Change URL using PHP e.g. i have page with url http://mysite.com?page=3&var=10 also there is form on page.
When form submitted there some actions in php but i need to remove this ?page=3&var=10 after form was submitted somehow is there way compatible with all browsers trough PHP without mod_rewrite?
A: This is an old topic, but just in case anyone else is searching for this in the future, you can use the javascript replaceState to change the history and browser bar label. A simple php function to do this:
function set_url( $url )
{
echo("<script>history.replaceState({},'','$url');</script>");
}
Then would simply call this function with the desired url (presumably dropping the post variables):
set_url("http://example.com");
A page reload or a back after calling another page will now have the new url location in the history.
I think that using POST may be a more elegant solution, but if you must use GET this is a work around.
A: Yeah, the solution is quite simple (even if not really SEO friendly):
<?php
header("Location: http://mysite.com")
?>
just for information...why do you need it?
A: If you're using action=index.php, then all values will be posted to index php, ?page=3&var=10 will be automatically removed.
If you want to post to the same page you can either use 'action=index.php?page=3&var=10' or action=<?php echo $_SERVER['PHP_SELF'] ?>
You can check at the beginning of the page if something submitted and then redirect to whatever you want with header('Location: http://www.example.com/'); More about header function http://php.net/manual/en/function.header.php
A: use parse_str to get the query string as an associative array that is easy to modify. Then use http_build_query to convert the associative array into a query string.
$queryString = $s['QUERY_STRING'];
$params = array();
parse_str($queryString, $params);
//change $params as needed
$queryString = http_build_query($params);
if ($queryString) {
$queryString = '?'.$queryString;
}
return preg_replace("/\\?.*/s","",$s['REQUEST_URI']).$queryString;
preg_replace("/\\?.*/s","",$s['REQUEST_URI']) removes the original query string allowing you to replace it.
A: Does this work for you?
header('Location:/');
A: mod_rewrite cannot affect what's displayed in the user's browser address bar, UNLESS the rewrite does an externally visible redirect. Otherwise it only rewriting things within the webserver, and that's invisible to the user.
If you want to affect the user's address bar, you'll have to do a redirect via header('Location: ...') after the form's finished processing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Silverlight 4 Assembly Caching for Project References I have several Silverlight utility and control projects that I re-use in several different applications with-in my web application. These are all worked on in the same solution. Each Silverlight application has it's own page.
Example Setup
*
*Utilities
*CommonResources
I've strong name keyed and created extmap for these projects, but the dll's are still in the xaps. The version is defnied as 1.0.0.0 in the assembly.cs.
CommonResources
1.0.0.0
{public key here}
Silverlight.Common.CommonResources.dll
These all reference Utilities and CommonResources
- ManageFoo
- ManageBar
- etc
Can I assembly cache the utilities and CommonResources dll?
A: I don't see why you couldn't in this scenario. In fact it seems to be the ideal candidate.
You'll need to make sure you generate extmap files for your Utilities and CommonResources dlls. The file looks like this:
<?xml version="1.0"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<assembly>
<name>System.Windows.Controls.Data.DataForm.Toolkit</name>
<version>2.0.5.0</version>
<publickeytoken>31bf3856ad364e35</publickeytoken>
<relpath>System.Windows.Controls.Data.DataForm.Toolkit.dll</relpath>
<extension downloadUri="System.Windows.Controls.Data.DataForm.Toolkit.zip" />
</assembly>
</manifest>
and has the name of the form:
<dllname>.extmap.dll
and must be in the same location as the dll itself.
A: You may try adding an XML file (e.g. named Common.CommonResources.extmap.xml) to the CommonResources project, and set “Copy to Output Directory” to “Copy if newer”, with the following content:
<?xml version="1.0"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<assembly>
<name>Common.CommonResources</name>
<version>*.*.*.*</version>
<publickeytoken>*</publickeytoken>
<relpath>Common.CommonResources.dll</relpath>
<extension downloadUri="Common.CommonResources.zip" />
</assembly>
</manifest>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get the connection string associated with an nHibernate GenericADOException for logging purposes? I need to log the server name from the connection string that was in use when the nHibernate GenericADOException was thrown.
Anyone know how to do this? I've looked high and low on the web and haven't found anything that looks promising.
A: Grab the ISession.
ISession session = SessionFactory.OpenSession();
string connectionString = session.Connection.ConnectionString;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Command Argument in Runtime created imagebutton doesn't work? Hello i am creating new image button something like this ;
e.row.cells[0].text= string.empty; //clearing the cells
Imagebutton img1= new ImageButton();
img1.Id="imgInput";
img1.ImageUrl="~/sample.jpg";
img1.CommandArgument= varID; // fetching the ID
img1.click+= new ImageClickEventHandler(imgInput_Click);
e.row.controls.add(img1)
I have written the above code in gridview rowdatabound event which.
Now in the click event (imgButton_Click; handled in second last line) i wish to put the command argument value in session;
protected void imgInput_Click(object sender, EventArgs e)
{
Session["idvalue"]= imgInput.CommandArgument;
}
But the varID here is coming as null. Why so? What am i missing here?
Please guide! Thanks
A: You need to use the ImageButton.Command event.
Example:
img1.Command += ImageButton_OnCommand;
protected void ImageButton_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Sort" && e.CommandArgument == "Ascending")
Label1.Text = "You clicked the Sort Ascending Button";
else
Label1.Text = "You clicked the Sort Descending Button";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to perform a somewhat complicated ActiveRecord scope query for a polymorphic association? So, I have a Notification model that is polymorphic, and I want to be able to filter out notifications that are of a notifiable_type Comment where comment.user == current_user. In other words, I want all notification records--except for ones referring to comments that were made by the current user.
class Notification
belongs_to :notifiable, :polymorphic => true
scope :relevant, lambda { |user_id|
find(:all, :conditions => [
"notifiable_type != 'Comment' OR (notifiable_type = 'Comment' AND " <<
"comments.user_id != ?)",
user_id ],
:include => :comments
)
}
end
What I don't understand is what I need to do to get access to comments? I need to tell ActiveRecord to outer join the comment model on notifiable_id.
A: First, lambda scopes with parameters are deprecated. Use a class method instead:
class Notification
belongs_to :notifiable, polymorphic: true
def self.relevant(user_id)
# ...
end
end
I usually move scope functions into their own module, but you can leave it there.
Next, find(:all) is deprecated, as is :conditions. We use ActiveRelation queries now.
Unfortunately, the ActiveRecord::Relation API isn't quite robust enough to do what you need, so we'll have to drop down to ARel instead. A little bit tricky, but you definitely don't want to be doing string substitution for security reasons.
class Notification
belongs_to :notifiable, polymorphic: true
def self.relevant(user_id)
n, c = arel_table, Comment.arel_table
predicate = n.join(c).on(n[:notifiable_id].eq(c[:id]))
joins( predicate.join_sql ).
where{ ( notifiable_type != 'Comment' ) |
(( notifiable_type == 'Comment' ) & ( comments.user_id == my{user_id} ))
}
end
end
I'm using a combination of ARel and Squeel here. Squeel is so good it should be a Rails core feature. I tried writing that where clause without Squeel, but it was so difficult I gave up.
Hard to test something like this without your project handy, but hopefully that should at least get you closer.
A: Oops, your code has :include => :comments, plural, which threw me off. How about this?
class Notification
belongs_to :notifiable, :polymorphic => true
scope :relevant, lambda { |user_id|
find(:all, :conditions => [
"notifiable_type != 'Comment' OR (notifiable_type = 'Comment' AND " <<
"comments.user_id != ?)",
user_id ],
:include => :notifiable
)
}
end
...then Notification.relevant.first.notifiable should work. From the docs:
Eager loading is supported with polymorphic associations.
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
A call that tries to eager load the addressable model
Address.find(:all, :include => :addressable)
This will execute one query to load the addresses and load the
addressables with one query per addressable type. For example if all
the addressables are either of class Person or Company then a total of
3 queries will be executed. The list of addressable types to load is
determined on the back of the addresses loaded. This is not supported
if Active Record has to fallback to the previous implementation of
eager loading and will raise
ActiveRecord::EagerLoadPolymorphicError. The reason is that the
parent model’s type is a column value so its corresponding table name
cannot be put in the FROM/JOIN clauses of that query.
(Emphasis mine.)
A: This is what I've resorted to..... I am still hoping someone can show me a better way.
Notification.find_by_sql( "SELECT * from Notifications " <<
"INNER JOIN comments ON notifiable_id = comments.id " <<
"WHERE notifiable_type != 'Comment' " <<
"OR (notifiable_type = 'Comment' AND comments.user_id = '#{user_id}')"
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PHP Action each function preforms I have the following situation.
I have a class with a lot of functions. Each function starts with executing the same method. Is there a way that I can like implement this method into the function so that it is executed automatically?
Here is an example:
class test
{
static function_1($param) {some_method($param); other stuff....}
static function_2($param) {some_method($param); other stuff then function 1....}
static function_3($param) {some_method($param); other stuff then function 1 and function 2....}
}
So is there a way to execute some_method(); automaticly without declaring it in each function?
Thanks in advance!
Whole code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* The Assets Library
*
* This class let's you add assets (javascripts, stylesheets and images) way easier..
*/
class Assets {
private $css_url;
private $js_url;
private $img_url;
public function __construct()
{
$CI =& get_instance();
$CI->config->load('assets');
$asset_url = base_url() . $CI->config->item('assets_dir');
$this->css_url = $asset_url . $CI->config->item('css_dir_name');
$this->js_url = $asset_url . $CI->config->item('js_dir_name');
$this->img_url = $asset_url . $CI->config->item('img_dir_name');
}
// Returns the css html link
public function css_html_link($filename)
{
// Check whether or not a filetype was given
$filename = $this->_add_filetype($filename, 'css');
$link = '<link type="text/css" rel="stylesheet" href="' . $this->css_url . $filename . '" />';
return $link;
}
// Returns the css link
public function css_link($filename)
{
$filename = $this->_add_filetype($filename, 'css');
return $this->css_url . $filename;
}
// Returns the js html link
public function js_html_link($filename)
{
$filename = $this->_add_filetype($filename, 'js');
$script = '<script type="text/javascript" src="' . $this->js_url . $filename . '"></script>';
return $script;
}
// Return the js link
public function js_link($filename)
{
$filename = $this->_add_filetype($filename, 'js');
return $this->js_url . $filename;
}
// Returns the image html tag
public function img_html_link($filename, $rel = NULL)
{
// Get the filename without the filetype
$alt_text = substr($filename, 0, strpos($filename, '.')+1);
$alt_text = 'alt="'.$alt_text.'"';
// If relation is giving, use it
$img_rel = ($rel !== FALSE) ? 'rel="' . $rel . '"' : '';
$image = '<img src="' . $this->img_url . $filename . '" '.$rel.' ' . $alt_text . '/>';
return $image;
}
// Return the image link
public function img_link($filename)
{
return $this->img_url . $filename;
}
// Check whether or not a filetype was specified in $file, if not, it will be added
private function _add_filetype($file, $type)
{
if(strpos($file, '.' . $type) === FALSE)
{
$file = $file . '.' . $type;
}
return $file;
}
}
/* End of file assets.php */
/* Location: ./application/libraries/assets.php */
A: every time you initiate the class, it calls the __construct() function, or in PHP 4 (I hope you are not using php 4) it uses the function with the same name as the class
If you do this, it should work for every initiate of the class:
function __construct($param){
some_method($param);
}
if you call multiple functions in the same initiation of the class, you could do this:
var $param;
function __construct($param){
$this->param = $param;
}
function doMethod(){
some_method($this->param);
}
function function_1()
{
$this->doMethod();
}
Calling the class multiple times, with different params. Perhaps try this approach:
function __call($function, $param){
some_method($param);
switch ($function){
case 'function1':
$this->function1($param);
break;
/// etc..
}
}
A: I'm afraid that in this case the answer is 'no'.
You're not 'declaring' some_method() each time, you are calling it. If you don't call it, it can't run, so you have to call it each time.
Cut & paste.....
Why not paste your actual code here, some refactoring may help.
Edit after seeing actual code
I can't see the problem with your existing code. It is clear and you will know what it does in a year's time. I would keep it as it is. The answer you accepted will work, but it is obfuscating your code. You will have problems working out what you did and why you did it in when you come back to maintain your code in the future.
A: You could create a class containing an instance of the class test (composition) and implement its __call magic method. Something akin to:
class testWrapper
{
private $test;
function __construct()
{
$this->test = new Test();
}
function __call($name, $args)
{
call_user_func_array(array($this->test, 'some_method'), $args);
call_user_func_array(array($this->test, $name), $args);
}
}
You then call methods from the test class on the instance object of testWrapper.
You can further refine the logic in the __call method to only call some_method() based on the passed-in method name, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VIM loses syntax highlighting when using split command So I have created my own syntax highlighting file and it works well if there is only one file opened. However, if I do :split otherFile, the other buffer that gets opened does not have syntax highlighting. I have tried various things, like :syntax on etc. What can be the problem?
I am running Ubuntu 11.04, 64-bit version.
VIM version: VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Mar 24 2011 07:07:34)
I have created a simple syntax highlighting file and put it in ~/.vim/plugin/syntax.vim
The last line of the syntax highlighting file is let b:current_syntax = "sth".
I haven't done any kind of wiring, like specifying the file location in .vimrc, the syntax works automatically (for one file opened).
A: I had this problem recently and much more generally. That is, the problem appeared for all filetypes. After debugging a bit, I discovered that the filetype was being properly recognized, but that for new splits, syntax was somehow becoming unset.
I'm still not 100% sure how this happened, but for future Google visitors, I'll write down what fixed the trouble for me: I moved set syntax = on much earlier in my .vimrc. After years of accretion, the line with set syntax = on had drifted down until it was below a number of other things. Moving it back up to (nearly) the top of the file fixed things for me. Here's what the start of my .vimrc looks like now:
" First two uncommented lines only useful if you use Tim Pope's vim-pathogen.
" https://github.com/tpope/vim-pathogen
execute pathogen#infect()
execute pathogen#helptags()
" Most general settings first
set nocompatible " Vim rather than Vi; implied by this file
syntax on " Syntax highlighting on
filetype plugin indent on " Filetype detection
" ... etc.
A: Syntax files belong into ~/.vim/syntax/sth.vim, not ~/.vim/plugin/syntax.vim. The latter is sourced only once on startup, that's probably why it only works for the first loaded file.
For your syntax to become active, you need to :setf sth, or insert a corresponding modeline into your files, or write a filetype detection for your syntax to automate that.
A: Resurrecting this, as I just observed the same behavior. The solution that I found was to add the filetype on setting to my .vimrc file. fwiw, I added it immediately after syntax on. syntax on happened to be at the top of my .vimrc file already. So, here are the first few lines of my .vimrc:
1 " Activates Syntax Highlighting
2 syntax on
3
4 " Filetype on
5 filetype on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Tool to convert an XPath to a jQuery selector? Firebug is able to display the xpath for any DOM element in the HTML view. I was wondering if there's a way to convert the xpath to a jQuery selector? (I prefer not to do this manually)
This will greatly save me time to find the correct selector for elements which don't have an id & are way deep in the DOM hierarchy. For example the fifth TD in the 20th TR
AFAIK, xpath support in jQuery is dropped so I can't use the xpath straight in jQuery?
A: There's a 'copy css path' in Firebug when right-clicking an element. It can be used to create a selector.
A:
https://addons.mozilla.org/en-US/firefox/addon/firepath/
A: I'm not sure if you are asking a general question abotu converting XPath to CSS selector, but I found this post jquery: selecting xpath or converting xpath to css? which might be of help. It reccomends using "eq" method to select an element by index. So the fifth TD in the 20th TR would be
$('tr').eq(20).find('td').eq(5)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: URL scheme to open Videos from a browser on iPad I can create an link to an iBooks document using the "itms-books://book-name" URL scheme, use that link in an html anchor tag accessible via a browser. When I click the link, it launches iBooks and opens the document.
How can I create a similar link to launch the Videos app to play a specific video in my local library? I've seen discussions about getting an asset URL from within another app, but I need something I can access via html in a browser.
A: There is videos:// which open the Videos Application, but I yet don't know how to use it. If I ever find something, I will let you know.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: New to SAS - need help getting started My department maintains all sorts of jobs and reports based on SAS, in a mainframe/batch environment (ie ugly JCL green screens).
I have been enrolled in an expensive training program from the SAS Institute. One of the first parts of the training asks me to install files from a zip file. "Open SAS" and run some files. I can't "open SAS" because I don't have it. It is embedded on the mainframe.
They provide some extremely limited instructions to work in z/OS. but I can't even figure out the basics like how to make a dataset to put the learning file into. They really give no guidance. They assume you already know how to use SAS.
Anyway, the training shows examples in Windows using SAS Enterprise Guide. I would like to get that and use it instead, at least for learning the SAS language. But when I called SAS just to find out if that is a free download, or if not how much it would cost, they said they would call me back and never did. So I just want to know a ballpark for how much it would cost me to get this tool. Also, if I had that tool, would I be able to use it to access the jobs on the Base SAS that I already have (on the mainframe) or would I have to purchase another Base SAS for Windows? I haven't been able to find answers to these questions via a Google search, and the SAS company didn't call me back. Can anyone with more knowledge about this help me out?
A: As far as I know, SAS Institute does not provide their software to individuals. They work with organizations and the yearly licence could cost tens to hundreds thousand dollars, depending on the components included and the number of processors or users.
There was crippleware SAS Learning Edition but they discontinued it.
I wonder if you can ask for refund for your expensive training program. Alternatively, you can try to run SAS scripts in batch mode on your mainframe. There are some third-party solutions for IDE like EMACS Speaks Statistics (ESS). You will lose functionality like dataset viewer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: jQuery Hide / Show (div with modified id attr) I'm having truoble doing this:
<div id="show-menu">Show Menu</div>
<script type="text/javascript">
$(document).ready(function() {
$('#show-menu').click(function() {
$(this).animate({marginRight:'70px'}, 500);
$('#menu').animate({width:'300px'}, 500);
$('.menu-menu-principal-container, #header h1').animate({marginRight:'70px'}, 500);
$(".menu-menu-principal-container, #header h1").show("slow");
$("#show-menu").hide("slow");
$("#hide-menu").show("slow");
$(this).text('Hide Menu');
$(this).attr('id', 'hide-menu');
});
$('#hide-menu').click(function() {
$(this).animate({marginRight:'-70px'}, 500);
$('#menu').animate({width:'100px'}, 500);
$('.menu-menu-principal-container, #header h1').animate({marginRight:'-70px'}, 500);
$(".menu-menu-principal-container, #header h1").hide("slow");
$(this).text('Show Menu');
$(this).attr('id', 'show-menu');
});
})
</script>
If I click on Show Menu (#show-menu) it shows correctly, but when I click again in the Hide Menu (#hide-menu) it wont hide? It does nothing.
A: You need to use jQuery delegate() or live()
Preferably I would use delegate like this
$('body').delegate('#show-menu', 'click', function() { ... your code ... });
$('body').delegate('#hide-menu', 'click', function() { ... your code ... });
Remember you can delegate from a different position in the DOM instead of $('body').delegate(); you could use $('#myparentContainer').delegate();
The alternative would be to use live events like this
$('#show-menu').live('click', function() { ... your code ...});
$('#hide-menu').live('click', function() { ... your code ...});
A: hide-menu does not exist during the document ready function call, and hence will not be bounded.
you would need to use live to have the event bounded as it appears.
A: What .click() does is to bind a function to the click event to the selector. Since you're doing $('#hide-menu').click(function() before a #hide-menu html element exist, it won't work, you should place the $('#hide-menu').click(function() { after $(this).attr('id', 'hide-menu');
$(document).ready(function() {
$('#show-menu').click(function() {
$(this).animate({marginRight:'70px'}, 500);
$('#menu').animate({width:'300px'}, 500);
$('.menu-menu-principal-container, #header h1').animate({marginRight:'70px'}, 500);
$(".menu-menu-principal-container, #header h1").show("slow");
$("#show-menu").hide("slow");
$("#hide-menu").show("slow");
$(this).text('Hide Menu');
$(this).attr('id', 'hide-menu');
$('#hide-menu').click(function() {
$(this).animate({marginRight:'-70px'}, 500);
$('#menu').animate({width:'100px'}, 500);
$('.menu-menu-principal-container, #header h1').animate({marginRight:'-70px'}, 500);
$(".menu-menu-principal-container, #header h1").hide("slow");
$(this).text('Show Menu');
$(this).attr('id', 'show-menu');
});
});
})
you can also use live() since it "binds now or in the future" but that's less efficient, since you "know" when the #hide-menu attribute appear in the DOM, you should bind the event there
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I host RavenDB inside my self-contained process? Is it possible to host RavenDB from within my own process? I do not want to use a separate IIS site or run a separate server .exe.
Looking for something pseudo-code like RavenDB.Server.Start(8080) (8080 being the port).
A: Yes...
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "Data",
UseEmbeddedHttpServer = true
};
See this link for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Setting up a service at start-up as non-root user I would like to have a service start at boot, as a non-root user on Fedora 15.
I have placed the script into /etc/init.d/, used chkconfig --add and chkconfig --level to get it all set up and it is working correctly.
What do I need to do to have it launched as non-root?
Thank you!
Kate
A: If your current invocation of the service is:
/path/to/service -o -K /var/adm/log/service.log
then use 'su' or 'sudo' to change to a non-root user:
sudo -u non-root -- /path/to/service -o -K /var/adm/log/service.log
su non-root -c "/path/to/service -o -K /var/adm/log/service.log"
The double-dash is important to separate the 'options to sudo' from the 'options to your service'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails: How to create a file from a controller and save it in the server? For some strange reason I need to save a file (normally downloaded directly) in the server. In my case I have a PDF file created with PDFKit that I need to keep.
# app/controllers/reports_controller.rb
def show
@report = Report.find(params[:id])
respond_to do |format|
format.pdf { render :text => PDFKit.new(report_url(@report)).to_pdf }
end
end
If I go to reports/1.pdf I get the report I am expecting but I want to keep it in the server.
Is there a Raily way to save a file in the server from a respond to?
A: Just a quick note before I get to the actual answer: It looks like you're passing a fully-qualified URL (report_url(@report)) to PDFKit.new, which is a waste--it means PDFKit has to make a request to the web server, which in turn needs to go through Rails' router and so on down the line to fetch the contents of the page. Instead you should just render the page inside your controller with render_to_string and pass it to PDFKit.new, since it will accept an HTML string. Keeping that in mind...
This is covered in the "Usage" section of PDFKit's README. You would do something like this:
def show
@report = Report.find(params[:id])
kit = PDFKit.new render_to_string(@report) # pass any options that the
pdf_file = kit.to_file '/some/file/path.pdf' # renderer needs here (same
# options as `render`).
# and if you still want to send it to the browser...
respond_to do |format|
format.pdf { render :file => pdf_file.path }
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does adding a NSObject into MainMenu.xib creates a singleton object? Let say I have a NSObject AppController:NSObject. Using IB, I drag an NSObject control into MainMenu.xib and points the class to AppController. Since MainMenu.xib is loaded once and objects inside MainMenu.xib are in memory for the life of the app, does it make the AppController object a singleton?
Then I can drag an IBOutlet to AppDelegate to access this singleton object. This looks like a quick way. Is this a good practice or to be discouraged?
The standard method I supposed is to add a static AppController *sharedInstance inside the class and use a +(AppController *)sharedAppController for access.
A: No, it's not a singleton because nothing stops you from creating another instance of the same class in code.
It's just a convenient way to create a single instance.
and objects inside MainMenu.xib are in memory for the life of the app
This is not true. If nobody retains these objects (or holds a strong reference to them under GC), they will get deallocated. This is true. See Peter Hosey's comment below.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Switch statement in C++ Consider:
#include <iostream>
using namespace std;
int main()
{
int score;
char grade;
cout << "Enter your score: " << endl;
cin >> score;
if (score >= 90)
grade = 'a';
if (score >= 80)
grade = 'b';
if (score >= 70)
grade = 'c';
if (score >= 60)
grade = 'd';
else
grade = 'f';
cout << grade << endl;
switch (grade) {
case 'a':
cout << "Good job" << endl;
break;
case 'c':
cout << "Fair job" << endl;
break;
case 'f':
cout << "Failure" << endl;
break;
default:
cout << "invalid" << endl;
}
cin.get();
return 0;
}
Why is it giving my default switch case when I enter 95 when I should be getting case 'a'?
A: You're missing a bunch of elses, or doing the comparisons in the wrong order.
95 is greater than 90, but it's also greater than 80, 70 and 60. So you'll get a 'd'.
(And you're not handling 'd' in your switch.)
A: I believe you want
if (score >= 90)
grade = 'a';
else if (score >= 80)
grade = 'b';
else if (score >= 70)
grade = 'c';
else if (score >= 60)
grade = 'd';
else
grade = 'f';
What you have does not mutually exclude any but the last two cases, 60 and above and lower. Your code doesn't short circuit; it checks all of 1 through 5.
if (score >= 90) // 1.
grade = 'a';
if (score >= 80) // 2.
grade = 'b';
if (score >= 70) // 4.
grade = 'c';
if (score >= 60) // 5.
grade = 'd';
else
grade = 'f';
A: I think you want to use 'else if'. It is falling down to the last if "score >= 60" which is true, and grade then equals "d", which produces the default case in your switch statement.
A: You have specified it such that your 95 satisfies all the cases: 95 is bigger than 90, but also bigger than 80, than 70, etc.
In this case, the last one wins.
You can solve it by either using elses, or by wrapping it in a function and returning as soon as you know the grade you need:
char grade(int score) {
if (score >= 90) return 'a';
if (score >= 80) return 'b';
...
}
A: The if branches are ordered wrong (or you need to provide else branches like so:)).
See it live here: http://ideone.com/2uSZT
#include <iostream>
using namespace std;
int main()
{
int score;
char grade;
cout << "Enter your score:" << endl;
cin >> score;
if (score >= 90)
grade = 'a';
else if (score >= 80)
grade = 'b';
else if (score >= 70)
grade = 'c';
else if (score >= 60)
grade = 'd';
else
grade = 'f';
cout << grade << endl;
switch (grade)
{
case 'a':
cout << "Good job" << endl;
break;
case 'c':
cout << "Fair job" << endl;
break;
case 'f':
cout << "Failure" << endl;
break;
default:
cout << "invalid" << endl;
}
cin.get();
return 0;
}
A: It's because of your if statements up top. You should be using else ifs instead of individual ifs. Your if for 90 is following through, and then so are all the others. Your letter "a" is essentially being overwritten because 95 is >= to all of the other conditions. Using an else if will break the rest of the checks when a true one is found.
if (score >= 90)
grade = 'a';
else if (score >= 80)
grade = 'b';
else if (score >= 70)
grade = 'c';
else if (score >= 60)
grade = 'd';
else
grade = 'f';
A: Because all score comparisons are not combined with if/else if conditions. They are independent if statements. Thus grade gets overwritten for 95.
A: You need to improve your if conditions.
You are checking score >= no. The input 95 executes all the if statements and the last executed statement was the d. Now in your switch statement, case d is not present so it executes the default one.
A: You've gotten some answers already, but I think I'll suggest a slightly different possibility that gets rid of most of the control flow and substitutes a bit of math:
char grades[] = "00000012344";
char *messages[] = {
"Excellent Job",
"Good job",
"Average job",
"Mediocre Job",
"Failure"
};
if (score < 0 || score > 100)
std::cout << "Invalid score";
else {
int grade = grades[score/10];
std::cout << messages[grade];
}
So, we use score/10 to turn scores of 0-100 to 0-10. We then look up the appropriate grade for a score, with f=0, d=1, c=2, b=3 and a=4. We use that to select and print out the appropriate message. I've added messages (that may or may not be quite what you want) for the letters you skipped.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to make AutoMapper create an instance of class I have the following source type:
public class Source
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
I have the following destination types:
public class Destination
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address HomeAddress { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
I created a mapping:
Mapper.CreateMap<Source, Destination>();
How do I configure my mapping so it will create an instance of Address and map the Address.PostalCode property using the Source property ZipCode?
A: With AfterMap, you can specify how to map entities further after AutoMapper has done it's mapping.
Mapper.CreateMap<Source, Destination>()
.AfterMap((src, dest) =>
{
dest.HomeAddress = new Address {PostalCode = src.ZipCode};
}
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: SciPy LeastSq Goodness of Fit Estimator I have a data surface that I'm fitting using SciPy's leastsq function.
I would like to have some estimate of the quality of the fit after leastsq returns. I'd expected that this would be included as a return from the function, but, if so, it doesn't seem to be clearly documented.
Is there such a return or, barring that, some function I can pass my data and the returned parameter values and fit function to that will give me an estimate of fit quality (R^2 or some such)?
Thanks!
A: If you call leastsq like this:
import scipy.optimize
p,cov,infodict,mesg,ier = optimize.leastsq(
residuals,a_guess,args=(x,y),full_output=True)
where
def residuals(a,x,y):
return y-f(x,a)
then, using the definition of R^2 given here,
ss_err=(infodict['fvec']**2).sum()
ss_tot=((y-y.mean())**2).sum()
rsquared=1-(ss_err/ss_tot)
What is infodict['fvec'] you ask? It's the array of residuals:
In [48]: optimize.leastsq?
...
infodict -- a dictionary of optional outputs with the keys:
'fvec' : the function evaluated at the output
For example:
import scipy.optimize as optimize
import numpy as np
import collections
import matplotlib.pyplot as plt
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])
def sigmoid(p,x):
x0,y0,c,k=p
y = c / (1 + np.exp(-k*(x-x0))) + y0
return y
def residuals(p,x,y):
return y - sigmoid(p,x)
Param=collections.namedtuple('Param','x0 y0 c k')
p_guess=Param(x0=600,y0=200,c=100,k=0.01)
p,cov,infodict,mesg,ier = optimize.leastsq(
residuals,p_guess,args=(x,y),full_output=True)
p=Param(*p)
xp = np.linspace(100, 1600, 1500)
print('''\
x0 = {p.x0}
y0 = {p.y0}
c = {p.c}
k = {p.k}
'''.format(p=p))
pxp=sigmoid(p,xp)
# You could compute the residuals this way:
resid=residuals(p,x,y)
print(resid)
# [ 0.76205302 -2.010142 2.60265297 -3.02849144 1.6739274 ]
# But you don't have to compute `resid` -- `infodict['fvec']` already
# contains the info.
print(infodict['fvec'])
# [ 0.76205302 -2.010142 2.60265297 -3.02849144 1.6739274 ]
ss_err=(infodict['fvec']**2).sum()
ss_tot=((y-y.mean())**2).sum()
rsquared=1-(ss_err/ss_tot)
print(rsquared)
# 0.996768131959
plt.plot(x, y, '.', xp, pxp, '-')
plt.xlim(100,1000)
plt.ylim(130,270)
plt.xlabel('x')
plt.ylabel('y',rotation='horizontal')
plt.grid(True)
plt.show()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: About Youtube views count I'm implementing an app that keeps track of how many times a post is viewed. But I'd like to keep a 'smart' way of keeping track. This means, I don't want to increase the view counter just because a user refreshes his browser.
So I decided to only increase the view counter if IP and user agent (browser) are unique. Which is working so far.
But then I thought. If Youtube, is doing it this way, and they have several videos with thousands or even millions of views. This would mean that their views table in the database would be overly populated with IP's and user agents....
Which brings me to the assumption that their video table has a counter cache for views (i.e. views_count). This means, when a user clicks on a video, the IP and user agent is stored. Plus, the counter cache column in the video table is increased.
Every time a video is clicked. Youtube would need to query the views table and count the number of entries. Won't this affect performance drastically?
Is this how they do it? Or is there a better way?
A: I would leverage client side browser fingerprinting to uniquely identify view counts. This library seems to be getting significant traction:
https://github.com/Valve/fingerprintJS
I would also recommend using Redis for anything to do with counts. It's atomic increment commands are easy to use and guarantee your counts never get messed up via race conditions.
This would be the command you would want to use for incrementing your counters:
http://redis.io/commands/incr
The key in this case would be the browser fingerprint hash sent to you from the client. You could then have a Redis "set" that would contain a list of all browser fingerprints known to be associated with a given user_id (the key for the set would be the user_id).
Finally, if you really need to, you run a cron job or other async process that dumps the view counts for each user into your counter cache field for your relational database.
You could also take the approach where you store user_id, browser fingerprint, and timestamps in a relational database (mysql?) and counter cache them into your user table periodically (probably via cron).
A: If you want to store all the IP's and browsers, then make sure you have enough DB storage space, add an index and that's it.
If not, then you can use the rails session to store the list of videos that a user has visited, and only increment the view_count attribute of a video when he's visiting a new video.
A: First of all, afaik, youtube uses BigTable, so do not worry about querying the count, we don't know the exact structure of the database anyway.
Assuming that you are on a relational model, create a column view_count, but do not update it on every refresh. Record the visists and periodically update the cache.
Also, you can generate hash from IP, browser, date and any other information you are using to detect if this is an unique view, and do not store the whole data.
Also, you can use session/cookie to record the view being viewed. Since it will expire, it won't be such memory problem - I don't believe anyone is viewing thousand of videos in one session
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: line break in ant mail message body how can I put a line break into an ant mail task section ? I've tried almost all possible things so far, like :
<property name="break" value="line break : ${line.separator} \\n\\n"/>
<echo message="${break}"/>
<mail mailhost="" mailport="25" subject="INSTALL BASE on WINDOWS " messagemimetype="text/html">
<from name="The automation system" address=""/>
<replyto address=""/>
<to address=""/>
<message>
build ${LATEST} installed successfully on Windows - silent mode.
${break}
${break}
</message>
</mail>
but it does not work.
A: You are trying to send html mail with messagemimetype="text/html". When html is rendered, any run of whitespace is compressed into a single space, so when you view this message it will all appear on a single line. The line breaks will still be there, try viewing the source of the message in your mail reader.
Since you are creating html mail, adding newline is simply a matter of adding the html <br> element to your message. Note that you will need to escape the < characters as you are embedding the message in the xml of the build file:
<message>
build ${LATEST} installed successfully on Windows - silent mode.<br>
Another line here<br>
Last line
</message>
Alternately wrap the whole message in a CDATA block:
<message><![CDATA[
build ${LATEST} installed successfully on Windows - silent mode.<br>
Another line here<br>
Last line
]]></message>
Since this is message generated by a build script and therefore I assume the recipient is a developer, you might want to send the message as plain text instead. In my experience most developers prefer plain text emails, and may have the email reader setup not to display html messages at all (or may be reading mail from a client that can't handle html like a command line reader). If you want to do this just delete messagemimetype="text/html". Newlines will then appear as expected.
A: Please remove the mimetype attribute and try to use this :
<message>
Test... Test...
</message>
This should get you going. If you indeed want to use the html attribute then you are better of using passing an html file with the correct encoding. THERE the element will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is possible to declare string type with restricted length that doesn't start from 0/1? In Delphi it is possible to declare subranges for integer values. For example:
type
myInt = 2..150
Which restricts values of myInt type to values from 2 to 150. But what if I want to restrict the length of a string?
If I write:
type
myString = string [150]
I declare mystring to be 150 bytes long and restrict the length to be from 0, 1, 2, etc. up to 150. But how do I restrict the length to between 2 and 150, for example?
Of course, I can check the length of a string and raise an exception, but does Delphi include some syntax specific to this situation, similar in style to subranges?
This obviously does not work, but I would like something like:
type
myString = string[2..150]
If it is not possible, then I can just check length, raise exception, etc.
trying this code:
var
str1, str2, str3: TRestrictedString;
begin
str1.Create(2, 5, 'pp');
str2.Create(2, 5, 'aaaa');
str3.Create(2, 10, str1 + str2);
writeln (str3.getstring)
end
or:
var
str1, str2, str3: TRestrictedString;
begin
str1.Create(2, 5, 'pp');
str2.Create(2, 5, 'aaaa');
str3.Create(2, 10);
str3.SetString(str1 + str2);
writeln (str3.getstring)
end
or:
var
str1, str2, str3: TRestrictedString;
begin
str1.Create(2, 5, 'pp');
str2.Create(2, 5, 'aaaa');
str3.Create(2, 10);
str3 := str1 + str2;
writeln(str3.GetString);
end
All of these raise an exception. Is possible to solve this? For multiple operations on a string is it necessary to split the function into more parts?
In the constructor, is it better to add a check that minlength < maxlength? If I set minlength > maxlength it raises an exception.
A: I would do
type
TRestrictedString = record
strict private type
TBounds = record
MinLength,
MaxLength: integer;
end;
strict private
FStr: string;
public
Bounds: TBounds;
procedure SetString(const AString: string);
function GetString: string;
constructor Create(AMinLength, AMaxLength: integer); overload;
constructor Create(AMinLength, AMaxLength: integer; const AString: string); overload;
constructor Create(const AString: string); overload;
class operator Implicit(S: string): TRestrictedString;
class operator Implicit(S: TRestrictedString): string;
class operator Equal(const A, B: TRestrictedString): boolean;
class operator NotEqual(const A, B: TRestrictedString): boolean;
class operator Add(const A, B: TRestrictedString): TRestrictedString;
end;
{ TRestrictedString }
constructor TRestrictedString.Create(AMinLength, AMaxLength: integer);
begin
Bounds.MinLength := AMinLength;
Bounds.MaxLength := AMaxLength;
FStr := '';
end;
constructor TRestrictedString.Create(AMinLength, AMaxLength: integer;
const AString: string);
begin
Bounds.MinLength := AMinLength;
Bounds.MaxLength := AMaxLength;
SetString(AString);
end;
class operator TRestrictedString.Add(const A,
B: TRestrictedString): TRestrictedString;
begin
result.Bounds := A.Bounds;
result.SetString(A.GetString + B.GetString);
end;
constructor TRestrictedString.Create(const AString: string);
begin
Bounds.MinLength := 0;
Bounds.MaxLength := MaxInt;
FStr := AString;
end;
class operator TRestrictedString.Equal(const A, B: TRestrictedString): boolean;
begin
result := A.GetString = B.GetString;
end;
function TRestrictedString.GetString: string;
begin
result := FStr;
end;
class operator TRestrictedString.Implicit(S: TRestrictedString): string;
begin
result := S.GetString;
end;
class operator TRestrictedString.NotEqual(const A,
B: TRestrictedString): boolean;
begin
result := A.GetString <> B.GetString;
end;
class operator TRestrictedString.Implicit(S: string): TRestrictedString;
begin
result.Create(S);
end;
procedure TRestrictedString.SetString(const AString: string);
begin
with Bounds do
if (length(AString) < MinLength) or (length(AString) > MaxLength) then
raise Exception.Create('Invalid length of string.');
FStr := AString;
end;
Now you can do very natural things, like
procedure TForm1.Button1Click(Sender: TObject);
var
str: TRestrictedString;
begin
str.Create(5, 10); // Create a string w/ length 5 to 10 chrs
str.SetString('Testing!'); // Assign a compatible string
ShowMessage(str); // Display the string
end;
You can also do just
str.Create(5, 10, 'Testing!');
ShowMessage(str);
You can add string the usual way:
var
s1, s2, s3: TRestrictedString;
begin
s1.Create(2, 10, 'Hi ');
s2.Create(2, 10, 'there!');
s3 := s1 + s2;
ShowMessage(s3);
end;
or even
var
s1, s3: TRestrictedString;
begin
s1.Create(2, 10, 'Hi ');
s3 := s1 + 'there!';
ShowMessage(s3);
When you add two TRestrictedStrings, or one TRestrictedString and a string, the result will have the same restriction as the first operand. You can try
var
str: TRestrictedString;
begin
str.Create(5, 10);
str.SetString('Testing!');
str := str + '!!';
ShowMessage(str);
which will work, but not
var
str: TRestrictedString;
begin
str.Create(5, 10);
str.SetString('Testing!');
str := str + '!!!';
ShowMessage(str);
Just beware that assigning a string to a TRestrictedString will also assign the 'bounds' of the string, that is, the TRestrictedString will have bounds set to 0 and MaxInt. Thus, no matter how a s: TRestrictedString is restricted, an assignment s := 'some string' will always work.
Update: Chris Rolliston used this answer as inspiration for a very interesting article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Select by "name" in JSoup I have multiple div's in a webpage URL that I have to parse which have the same class name but different names with no id's.
for eg.
<div class="answer" style="display: block;" name="yyy" oldblock="block" jQuery1317140119108="11">
and
<div class="answer" style="display: block;" name="xxx" oldblock="block" jQuery1317140119108="11">
I want to select data and parse from only one of the div's say namely (name="yyy") (the content inside the div's are <href> links which differ for each class.
I've looked up the selector syntax in the Jsoup webpage but can't get a way to work around it. Can you please help me with this or let me know if I'm missing something?
A: Use the [attributename=attributevalue] selector.
Elements xxxDivs = document.select("div.answer[name=xxx]");
// ...
Elements yyyDivs = document.select("div.answer[name=yyy]");
// ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: adjusted bootstrap confidence intervals (BCa) with parametric bootstrap in boot package I am attempting to use boot.ci from R's boot package to calculate bias- and skew-corrected bootstrap confidence intervals from a parametric bootstrap. From my reading of the man pages and experimentation, I've concluded that I have to compute the jackknife estimates myself and feed them into boot.ci, but this isn't stated explicitly anywhere. I haven't been able to find other documentation, although to be fair I haven't looked at the original Davison and Hinkley book on which the code is based ...
If I naively run b1 <- boot(...,sim="parametric") and then boot.ci(b1), I get the error influence values cannot be found from a parametric bootstrap. This error occurs if and only if I specify type="all" or type="bca"; boot.ci(b1,type="bca") gives the same error. So does empinf(b1). The only way I can get things to work is to explicitly compute jackknife estimates (using empinf() with the data argument) and feed these into boot.ci.
Construct data:
set.seed(101)
d <- data.frame(x=1:20,y=runif(20))
m1 <- lm(y~x,data=d)
Bootstrap:
b1 <- boot(d$y,
statistic=function(yb,...) {
coef(update(m1,data=transform(d,y=yb)))
},
R=1000,
ran.gen=function(d,m) {
unlist(simulate(m))
},
mle=m1,
sim="parametric")
Fine so far.
boot.ci(b1)
boot.ci(b1,type="bca")
empinf(b1)
all give the error described above.
This works:
L <- empinf(data=d$y,type="jack",
stype="i",
statistic=function(y,f) {
coef(update(m1,data=d[f,]))
})
boot.ci(b1,type="bca",L=L)
Does anyone know if this is the way I'm supposed to be doing it?
update: The original author of the boot package responded to an e-mail:
... you are correct that the issue is that you are doing a
parametric bootstrap. The bca intervals implemented in boot are
non-parametric intervals and this should have been stated
explicitely somewhere. The formulae for parametric bca intervals
are not the same and depend on derivatives of the least favourable
family likelihood when there are nuisance parameters as in your
case. (See pp 206-207 in Davison & Hinkley) empinf assumes that the
statistic is in one of forms used for non-parametric bootstrapping
(which you did in your example call to empinf) but your original
call to boot (correctly) had the statistic in a different form
appropriate for parametric resampling.
You can certainly do what you're doing but I am not sure of the
theoretical properties of mixing parametric resampling with
non-parametric interval estimation.
A: After looking at the boot.ci page I decided to use a boot-object constructed along the lines of an example in Ch 6 of Davison and Hinkley and see whether it generated the errors you observed. I do get a warning but no errors.:
require(boot)
lmcoef <- function(data, i){
d <- data[i, ]
d.reg <- lm(y~x, d)
c(coef(d.reg)) }
lmboot <- boot(d, lmcoef, R=999)
m1
boot.ci(lmboot, index=2) # I am presuming that the interest is in the x-coefficient
#----------------------------------
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 999 bootstrap replicates
CALL :
boot.ci(boot.out = lmboot, index = 2)
Intervals :
Level Normal Basic
95% (-0.0210, 0.0261 ) (-0.0236, 0.0245 )
Level Percentile BCa
95% (-0.0171, 0.0309 ) (-0.0189, 0.0278 )
Calculations and Intervals on Original Scale
Warning message:
In boot.ci(lmboot, index = 2) :
bootstrap variances needed for studentized intervals
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Facebook Canvas/Tab app, fb_sig_profile_id, fb_sig_app_id With the changes for Facebook Apps coming on October 1st, I am having trouble confirming that our Canvas/Tab app will/will not work as expected.
When a user first loads the tab with the app, I'm expecting facebook to send me parameters of "fb_sig_profile_id" (which I believe should be the ID of the Page) and "fb_sig_app_id" (the ID of the APP).
I DO NOT need/want to authenticate users or access UserData/Graph etc. I am simply displaying content on my end based on these parameters.
If this is no longer the case and Facebook is not going to be sending me these parameters, can someone point me in the direction of how I can get this data.
Thanks
A: When building Apps On Facebook kind of apps, Facebook will send a signed_request which will contain the data you need:
When a user navigates to the Facebook Page, they will see your Page
Tab added in the next available tab position. Broadly, a Page Tab is
loaded in exactly the same way as a Canvas Page. Read more about this
in the Canvas Tutorial. When a user selects your Page Tab, you will
receive the signed_request parameter with one additional parameter,
page. This parameter contains a JSON object with an id (the page id of
the current page), admin (if the user is a admin of the page), and
liked (if the user has liked the page). As with a Canvas Page, you
will not receive all the user information accessible to your app in
the signed_request until the user authorizes your app.
Reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenCV PCA question I'm trying to create a PCA model in OpenCV to hold pixel coordinates. As an experiment I have two sets of pixel coordinates that maps out two approximate circles. Each set of coordiantes has 48 x,y pairs. I was experimenting with the following code which reads the coordinates from a file and stores them in a Mat structure. However, I don't think it is right and PCA in openCV seems very poorly covered on the Internet.
Mat m(2, 48, CV_32FC2); // matrix with 2 rows of 48 cols of floats held in two channels
pFile = fopen("data.txt", "r");
for (int i=0; i<48; i++){
int x, y;
fscanf(pFile, "%d%c%c%d%c", &x, &c, &c, &y, &c);
m.at<Vec2f>( 0 , i )[0] = (float)x; // store x in row 0, col i in channel 0
m.at<Vec2f>( 0 , i )[1] = (float)y; // store y in row 0, col i in channel 1
}
for (int i=0; i<48; i++){
int x, y;
fscanf(pFile, "%d%c%c%d%c", &x, &c, &c, &y, &c);
m.at<Vec2f>( 1 , i )[0] = (float)x; // store x in row 1, col i in channel 0
m.at<Vec2f>( 1 , i )[1] = (float)y; // store y in row 1, col i in channel 1
}
PCA pca(m, Mat(), CV_PCA_DATA_AS_ROW, 2); // 2 principle components??? Not sure what to put here e.g. is it 2 for two data sets or 48 for number of elements?
for (int i=0; i<48; i++){
float x = pca.mean.at<Vec2f>(i,0)[0]; //get average x
float y = pca.mean.at<Vec2f>(i,0)[1]; //get average y
printf("\n x=%f, y=%f", x, y);
}
However, this crashes when creating the pca object. I know this is a very basic question but I am a bit lost and was hoping that someone could get me started with pca in open cv.
A: Perhaps it would be helpful if you described in further detail what you need to use PCA for and what you hope to achieve (output?).
I am fairly sure that the reason your program crashes is because the input Mat is CV_32FC2, when it should be CV_32FC1. You need to reshape your data into 1 dimensional row vectors before using PCA, not knowing what you need I can't say how to reshape your data. (The common application with images is eigenFace which requires an image to be reshaped into a row vector). Additionally you will need to normalize your input data between 0 and 1.
As a further aside, usually you would choose to keep 1 less principal component than the number of input samples because the last principal component is simply orthogonal to the others.
I have worked with opencv PCA before and would like to help further. I would also refer you to this blog: http://www.bytefish.de/blog/pca_in_opencv which helped me get started with PCA in openCV.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is Spring MVC a Replacement for Servlet/JSP/Beans MVC Model I apologize for the "noobness" of this question, but I've recently been studing JSP/Servlets that I will be using primarily to build web applications/dynamic websites. I really like the design model of using servlets to do the business logic (code), jsp to design and display, and beans to display the dynamic content in the jsp page.
I've been reading a lot about Spring MVC and i'm confused on whether or not its a replacement for the design model I just described, or is it geared more towards desktop java apps or perhaps something else.
Any insight or advice would be well received.
A: Actually those 2 are quite different. The Java way of using JSPs and servlets is the Model2 paradigm, in which you'd have you JSP as views, your servlets as controllers and standard Java beans as models. MVC is a more comprehensive paradigm, you still have a model a view and a controller but they're not stuck to being Java beans, JSPs and servlets respectivelly. Spring MVC offers a nice implemententation of the paradigm, allowing you to have whatever you want as controller, multiple technologies besides JSP as views, and the model is pretty free too. Plus it gives you a lot of extra stuff besides the MVC, like the abiltity to make wizards, etc.
A: A portion of Spring is a web framework, though Spring can also be used for non-web apps. It can definitely be a replacement for what you desribed, but it can also be so much more. I encourage you to read the spring docs at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/
A: Spring MVC framework provides rich functionality for building robust Web Applications.
Its MVC modeled and acts as an wrapper over servlets, providing a neat easy to use interface.
All interfaces are tightly coupled to the Servlet API. This coupling makes sure that the features of the Servlet API remain available to developers while offering a high abstraction framework to ease working with said API.
Also bundled with it is the bean model.
You can still use JSP as the view layer with Spring MVC, as it does not have its own view language.
It provides option for velocity, freemarker and much more.
More info @ http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add points in google maps v3 with jQuery callback? var url = 'http://tw.tranews.com/map/dStores.asp?x1=' + latlng.x1 + '&x2=' + latlng.x2 + '&y1=' + latlng.y1 + '&y2=' + latlng.y2;
$.get('proxy.php', {url: url}, function (resp) {
console.log(resp);
}, 'XML');
Excuse me guys, I want to add points in google maps v3 with jQuery callback, but I don't know how can do it. I've searched over the web, but I can't find anything. I need your help!!!!!! plz!
A: Have you used the maps api at all?
Generally this is pretty simple:
*
*Have your MAP in JS globally visible
*Your request should return JSON (echo '{lat:1,long:1}')
*And then add a marker to your map
Look around in the google api to fine
TO add a marker to the map you go like this:
var myLatlng = new google.maps.LatLng(resp.lat,resp.long);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map); //whereas map is your map object
That's the way i'd do it, to find out more look up the google maps api:
http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/overlays.html
http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/reference.html#Marker
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get a list of members in a Python module, or how should I create plugins? I'm writing a sort of dashboard-esque program in Python to make tasks that I do frequently here at work a little better/easier.
What I currently have set up is an actions module. actions contains an actionlist that is a list of classes. Each of my classes has a .title, .icon (base-64 encoded string for use with tkinter.PhotoImage), and a .action function.
Using tkinter I create a new button for each of these actions, with the appropriate icon, text, and the command of the button set to the .action. So far it works quite nicely, but if I want to create a new action, I have to go into my actions module, create a new class, and then put that class in my actionlist.
What I would like to do is be able to dynamically generate this actionlist based on what files are present in my module. So I would like to have something like this:
actions/
__init__.py
someaction.py
do_another_thing.py
do_all_the_things.py
chop_down_the_tree_with_a_herring.py
And whenever I would like to create a new action, I just put a .py script in my actions folder and then it would automagically generate the list of actions for me, however I can't seem to find any good way of creating this list. I've thought of using something like os.listdir to get the list of files, but neither that or the other methods of introspection (dir, and inspect.getmembers) seemed to have quite what I wanted. Of course, it's possible that I just missed the features that I need.
In any case, pointers in the right direction would be great. Thanks!
SOLUTION:
Lennart's solution, with some slight adaptations worked for me.
Inside my __init__.py I have the following code:
plugins = []
__all__ = [
'do_all_the_things',
'do_another_thing',
'someaction',
'chop_down_the_tree_with_a_herring',
'seek_the_grail',
]
Then inside each of my plugins I have something like this:
from actions import plugins
class SeekTheGrail:
def __init__(self):
self.text = 'We Seek The Grail'
self.icon = b'R0lGODlhkABJAPcAABsVGH6DWWaElDxIdU1LM8mxc2RnQ3iFaLi8mLmQZqxpOy4rPq28y41NNTMvJIujl5qbakpMTdubSWJoV4KhxOfTnkBYoL+EQ26FgF84LtzZyaRoTFdbPLm/sK+hnHF5WbqGUbmgbeLEglxnbyUdJEBALHFMM6ivg4aRasfMybyQUa+gfVleUKGxnXV4S9Wzf6t6Q5NYRDQwL4+df2GEv2FFPM3EsohoSIFpVNKgao+Lgqp6UNrClT89PVJojk9tp4l7Vy0mJickG45eOZ6nhJ6zwUZ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OADjiBtA4YAjKIBMiI9iUIP0mw+m1hJZokwWuKdWqjcJEZUlmpMIwIBGeM+uAed+eEnU3IcSfZgEAaAFWpgEGiCGBZbGqwoIADs='
def action(self):
print('I am Arthur, King of the Britons!')
plugins.append(SeekTheGrail())
and now I just have to modify the __all__ collection when I want to add or remove the actions from loading.
A: The way to create plugins is to have a plugin registry, and register plugins there. This can be done from the amazingly simple, like just defining a global list in a module:
plugins = []
And then registering the plugins with:
class APlugin(object):
blahblah
from themodule import plugins
plugin.add(APlugin())
This can be made more flexible by having types of plugins and registering them with a name etc. But then you are on the path to complexity, and then you might want to take a look at the Zope Component Architecture, which simply speaking is a very powerful system for making your application pluggable.
It should be noted that in any case it's best to have a list of what plugins should be activated instead of auto-discovering them. This can be as simple as a list in a text file or a setting in a config file. This enables you to easily activate and disactivate the plugins.
A: You can use something like this:
actions = {}
for filename in os.listdir('somepath/actions'):
actions[filename] = __import__('actions.'+filename)
for name,class in actions:
createButton(name,class)
Where in the createButton you create your tk_inter button and assign it the functions from the class. The important bit i suppose is that you can use __import__ to import a class using its string name and save it as a variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why Invoke method of constructed delegate class is virtual? I've seen in CLR via C# and in codeproject article Delegate Behind the Scenes that when C# compiler sees this
public delegate void MyDelegate(int intValue);
it actually generates something like this
class MyDelegate : System.MulticastDelegate
{
public virtual void Invoke(Int32 intValue);
...
}
Question is, why Invoke method is virtual? Can this generated delegate type be inherited? From the CLR point of view looks like it can. But why? Why not generating sealed class so there will be no virtual methods lookup penalty at runtime?
A: This is quacks-like-a-duck typing. Similar kind of typing that makes System.Int32, a value type, derived from ValueType, a reference type. Makes no sense, illegal in C#, but actually behaves that way. The real implementation of a delegate's Invoke method is buried in the CLR and is a static function written in C++.
But sure, annotating it as virtual makes somewhat sense because it behaves like a virtual method. The actual code that executes is not fixed like it is with a non-virtual class method. Even harder to reason out is what the proper model should be for a delegate that's bound to a static method. A virtual method that's static?
It is just a virtual duck.
Reading up on function pointers as used in C could help you get a better mental model for delegates. A delegate is a function pointer with bells on, it can also store the target object. C# lacks the syntax to express this another way.
A: Here's an interesting quote from Eric Lippert about inheritance in .NET:
I am occasionally asked "but how can a value type, like int, which is
32 bits of memory, no more, no less, possibly inherit from object? An
object laid out in memory is way bigger than 32 bits; it's got a sync
block and a virtual function table and all kinds of stuff in there."
Apparently lots of people think that inheritance has something to do
with how a value is laid out in memory. But how a value is laid out in
memory is an implementation detail, not a contractual obligation of
the inheritance relationship!
There are a number of "special" inherited types in .NET: System.ValueType, System.Enum,System.Void, and System.Delegate, amongst others I'm sure.
Taking a look at the internals of System.Delegate with Reflector.NET I can see a number of calls like this:
[MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
internal static extern MulticastDelegate InternalAlloc(RuntimeType type);
I suspect that we're dealing with a different implementation detail that doesn't require delegates to use the same virtual look up tables that virtual methods need to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Ubuntu Netbeans 6.9 is ugly The fonts and everything is just ugly in Ubuntu 11.04. Do you know how to change it, to make it look like in Windows? Or maybe you know other good PHP editor?
A: Maby you could try Aptana as an editor: http://aptana.com/products/studio3/download
A: Manually edit the netbeans.conf file, located in the /etc folder. Add the switchs: -J-Dswing.aatext=true and -J-Dawt.useSystemAAFontSettings=on to the section netbeans_default_options
A: try to install sun java or switch to it
other good php editor - phpStorm ( not free )
A: I wasn't a huge fan of the way the netbeans editor part looked, and I had trouble with the fonts as well. I switched to DejaVu LGC Sans mono, and it looks better. I also started using the 'twilight' theme that someone made (http://taylorpennock.com/netbeans-check-a-great-twilight-theme-for-net)
You may also want to update to 7 or whatever the current version is. I have some issues with 6.9.1 that I've found are fixed in 7.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to skip pre header lines with csv.DictReader? I want to csv.DictReader to deduce the field names from the file. The docs say "If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.", but in my case the first row containts a title and the 2nd row which contains the names.
I can't apply next(reader) as per Python 3.2 skip a line in csv.DictReader because the fieldname assignment takes place when initializing the reader (or I'm doing it wrong).
The csvfile (exported from Excel 2010, original source):
CanVec v1.1.0,,,,,,,,,^M
Entity,Attributes combination,"Specification Code
Point","Specification Code
Line","Specification Code
Area",Generic Code,Theme,"GML - Entity name
Shape - File name
Point","GML - Entity name
Shape - File name
Line","GML - Entity name
Shape - File name
Area"^M
Amusement park,Amusement park,,,2260012,2260009,LX,,,LX_2260009_2^M
Auto wrecker,Auto wrecker,,,2360012,2360009,IC,,,IC_2360009_2^M
My code:
f = open(entities_table,'rb')
try:
dialect = csv.Sniffer().sniff(f.read(1024))
f.seek(0)
reader = csv.DictReader(f, dialect=dialect)
print 'I think the field names are:\n%s\n' % (reader.fieldnames)
i = 0
for row in reader:
if i < 20:
print row
i = i + 1
finally:
f.close()
Current results:
I think the field names are:
['CanVec v1.1.0', '', '', '', '', '', '', '', '', '']
Desired result:
I think the field names are:
['Entity','Attributes combination','"Specification Code Point"',...snip]
I realize it would be expedient to simply delete the first row and carry on, but I'm trying to get as close to just reading the data in situ as I can and minimize manual intervention.
A: After f.seek(0), insert:
next(f)
to advance the file pointer to the second line before initializing the DictReader.
A: I used islice from itertools. My header was in the last line of a big preamble. I have passed preamble and used hederline for fieldnames:
with open(file, "r") as f:
'''Pass preamble'''
n = 0
for line in f.readlines():
n += 1
if 'same_field_name' in line: # line with field names was found
h = line.split(',')
break
f.close()
f = islice(open(i, "r"), n, None)
reader = csv.DictReader(f, fieldnames = h)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: CSS-sprite menu and jQuery addClass() method I've created CSS sprite menu based on this tutorial:
http://buildinternet.com/2010/01/how-to-make-a-css-sprite-powered-menu/
Now I'd like to assign .selected class to the 'a' which was clicked as last one. I've added sipmle script:
<script>
$("a").click(function(){
$(this).addClass("selected");
});
</script>
but the class .selected appears only during loading the page. After loading whole page menu item returns to its normal state. Could you help me with this issue? TIA
Have a nice day:)
A: Clicking a will take you to a different page, so this event is not gonna work for you. To add selected class to the current link you have to code like below:
<script>
$(function(){ //short form of $(document).ready(function(){
$("a").each(function(){
path=window.location;
path=String(path).split('/')['3']; //if you use absolute URLs then disable this line
if($(this).attr('href')==path)
{
$(this).addClass("selected");
}
});
});
</script>
It will add class selected to link(s) if it's href matches the current URL of the browser.
A: I believe you are making this more complicated than it needs to be. Here's a quick solution using CSS instead of bulky JS :)
First off, your body tags should have classes assigned to them.
<body class="products">
for example.
Now, in your menu, assign each <li> (I'm guessing/hoping you are using a list, you didn't supply any code so I don't know...) with classes as well.
<li class="products"><a href="/products/">Products</a></li>
for example.
Now, in your CSS, simply do this:
body.products ul#menu li.products a { /* Define how the "selected" button should look, here. */ }
These CSS rules will then only be "used" when the visitor is on the "selected" page.
This technique is the msot used as it is without a doubt the quickest and very SEO friendly as the code in your main navigation always stays the same across the site.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to improve ESRI/ArcGIS database performance while maintaining normalization? I work with databases containing spatial data. Most of these databases are in a proprietary format created by ESRI for use with their ArcGIS software. We store our data in a normalized data model within these geodatabases.
We have found that the performance of this database is quite slow when dealing with relationships (i.e. relating several thousand records to several thousand records can take several minutes).
Is there any way to improve performance without completely flattening/denormalizing the database or is this strictly limited by the database platform we are using?
A: There is only one way: measure. Try to obtain a query plan, and try to read it. Try to isolate a query from the logfile, edit it to an executable (non-parameterised) form, and submit it manually (in psql). Try to tune it, and see where it hurts.
Geometry joins can be costly in term of CPU, if many (big) polygons have to be joined, and if their bounding boxes have a big chance to overlap. In the extreme case, you'll have to do a preselection on other criteria (eg zipcode, if available) or maintain cache tables of matching records.
EDIT:
BTW: do you have statistics and autovacuum? IIRC, ESRI is still tied to postgres-8.3-something, where these were not run by default.
UPDATE 2014-12-11
ESRI does not interfere with non-gis stuff. It is perfectly Ok to add PK/FK relations or additional indexes to your schema. The DBMS will pick them up if appropiate. And ESRI will ignore them. (ESRI only uses its own meta-catalogs, ignoring the system catalogs)
A: When I had to deal with spatial data, I tended to precalulate the values and store them. Yes that makes for a big table but it is much faster to query when you only do the complex calculation once on data entry. Data entry does take longer though. I was in a situation where all my spacial data came from a monthly load, so precalculating wasn't too bad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing parameters to a4j:ajax method I am trying to use <a4j:ajax> to feed a method with a value just entered on the form;
<h:selectOneMenu id="aa" value="#{colorClass.color}">
<f:selectItems value="#{myChoices.colorOptions}"/>
<a4j:ajax event="change" render="colorCode"
execute="#{myChoices.getColorCode(colorClass,colorClass.color)}"/>
</selectOneMenu>
Color on the form is selected correctly;
my problem is that when I pass colorClass.color as part of the execute, it is blank;
if I replace colorClass.color with a literal
<a4j:ajax event="change" render="colorCode"
execute="#{myChoices.getColorCode(colorClass,'green')}"/>
the method is called, finds the colorCode and repaints the form
How can I "grab" the value just entered so that I can pass it as a parameter to the method?
A: You need listener attribute instead of execute attribute. The execute attribute should point to a collection of client IDs which are to be submitted (which defaults to @this in <f:ajax> and @form in <a4j:ajax>). However in your particular case it returns void and keeps the execute empty. The listener attribute is supposed to point to a bean action listener method. Fix it accordingly:
<a4j:ajax event="change" render="colorCode"
listener="#{myChoices.getColorCode(colorClass,colorClass.color)}"/>
Note that the colorClass argument seems superfluous here, or at least the colorClass.color as you could also just do colorClass.getColor() inside the getColorCode() method. Just passing one of them ought to be sufficient. Passing colorClass.color would be preferable so that your myChoices bean is not tight coupled with the colorCode bean.
<a4j:ajax event="change" render="colorCode"
listener="#{myChoices.getColorCode(colorClass.color)}"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Creating Java Spring MVC 3 based application with services, I am new to Spring MVC3 framework in java but I am familiar with java coding.
I want to write two application using this framework.
*
*First application recieves requests through a SOAP web services and sends response in form of SOAP XML Object.
*Second application have a simple servlet to recieve request and send responces.
I have studied Java MVC3 framework. It requires view to be called who are mapped against which controller will handles its request. But,
How I can do this using a webservice, so that when a specific method using SOAP services is called, I can forward that request to its relevant servlet and sends response back as a SOAP xml file.
How can I do this for my second application as well that recieves request through a servlet.
I hope all this make sense.
regards,
Aqif
A: If you want to stick with Spring, you can use Spring Web Services for application 1. Application 2 would be a more traditonal Spring Web app (uses a servlet, but framework does not require you to work in the servlet...instead you will work in more fine grained components).
If you dont want to stick with Spring for the web services, you can always use something like Apache Axis
A: The usual structure is as follows:
*
*you have spring-mvc controllers to handle your browser requests
*you have other components that handle the SOAP requests
*both of the above invoke the same underlying services which serve them with the data that is to be sent to the user. The data is in java objects, which are later transformed to whatever is required
For the 2nd point you can pick some JAX-WS implementation, like CXF (it has nice spring support as well)
A: Spring Web Services specifically supports a Spring MVC-like model for responding to SOAP calls, as you describe.
the second one is Spring MVC directly. Heck, it sounds like - though I can't be sure without more information - that you're trying to build RESTful web services. There, too, Spring MVC is the right choice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use eclipse CDT for jni debugging? How to use Eclipse CDT along with JDT to debug the jni code?
Using Eclipse, is there a way by which we can debug the native code without the use of visual studio?
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Select attribute values into a list I have the following xml:
<ListOfItems>
<item myval='123' />
<item myval='342' />
<item myval='233' />
<item myval='444' />
</ListOfItems>
I'm parsing/traversing it with jQuery. What is a selector that would give me a list of all values in the attribute 'myval' of 'item' nodes. I'm looking for something that would give me back a list of values only. Maybe an array [ '123, '342', '233', '444' ]
A: Bearing in mind that I don't think those are valid elements, I'd suggest:
var listOfValues = [];
$('ListOfItems > item').each(
function(){
listOfValues.push($(this).attr('myval'));
});
Given the desire to use a single selector, the following is possible:
var myvals = $('li').map(
function(){
return this.getAttribute('myval');
}).get().join(', ');
JS Fiddle Demo.
A: You would need to iterate through the list of items. For example:
var itemsArray = [];
$("ListOfItems").each(function(index) {
itemsArray[index] = $(this).attr('myval');
});
A: var data = new Array();
$(xml).find('item').each(function() {
data.push($(this).attr('myval'));
});
where xml is your xml content.
or:
var array = $(xml).find('item').map(function() {
return $(this).attr('myval');
}).get();
A: Make use of the .map() function.
var listOfItems = $('ListOfItems items').map(function() {
return $(this).attr('myval');
});
It's a really nifty function (along with $.map()) that a lot of people miss out on.
Just keep in mind that that returns a jQuery object, so if you want to get your hands on the raw returned array, you'll have to get to it via listOfItems.get().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue uploading images/non text files to Rackspace Cloudfiles (MisMatchedChecksumException) via PHP API I am having an issue uploading to Rackspace Cloudfiles.
I am able to upload anything that is text based (text/html, text/plain etc) but anything else I try fails with the MisMatchedChecksumException which, as I understand it, means the md5_file() on my end doesn't match their computation at their end?
If I don't set the etag (and so this check is not made) the file is uploaded but not correctly, so for example images have the same size but just don't render?
Does anyone have any tips for how to get past this?
A: The following code works fine for me, can you show a snippet that doesn't work?
$fname = basename('test.jpg');
$md5 = md5_file($fname);
$container = $conn->get_container('my_container');
$o2 = $container->create_object($fname);
$o2->content_type = "image/jpeg";
$o2->set_etag($md5);
$result = $o2->load_from_filename($fname);
assert('!is_null($result)');
assert('$o2->getETag() == $md5');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UIActivityindicatorView in MPMoviePlayerController I am downloading videos and playing with MPMoviePlayercontroller, i want to display uiactivityindicatorview in mpmovieplayercontroller while video is being downloaded as in YouTube app.
How can i achieve that?
A: Something like this?:
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.center = myMPMoviePlayercontroller.center;
activityIndicator.hidesWhenStopped = YES;
[activityIndicator startAnimating];
[myMPMoviePlayercontroller.view addSubview:activityIndicator];
myMPMoviePlayercontroller addSubview:activityIndicator];
See the UIActivityIndicatorView Class Reference for more info.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linux USB Application using libusb I am trying to write an application to read and write to a connected USB device. I am using libusb. It seems after I find the device, configuration fails. I am following the developers guide for libusb at http://libusb.sourceforge.net/doc/index.html. Which states that:
usb_set_configuration sets the active configuration of a device. The configuration parameter is the value as specified in the descriptor field bConfigurationValue. Returns 0 on success or < 0 on error.
I demonstrate in my source (below) that I use the bConfigurationValue as the configuration parameter, but my return value from usb_set_configuration is always -1. I don't understand why?
The output:
[user@local workspace]$ ./application
Device Found @ Address 005
Vendor ID 0x018d1
Product ID 0x04e12
INFO: bConfigurationValue = 1
config status =-1
claim status =-1
alt status =-22
TX status =-1
RX status =-1 -> RX char = 0
[user@local workspace]$
The source:
int main(int argc, char *argv[])
{
struct usb_bus *bus;
struct usb_device *dev;
struct usb_dev_handle *android_handle;
int status;
unsigned char send_data = 0x51;
unsigned char receive_data = 0;
usb_init();
if ((handle = locate_device()) == 0)
{
printf("Error: Could not open the device\n");
return (-1);
}
printf("INFO: bConfigurationValue = %d\n", config_val);
status = usb_set_configuration(handle, config_val);
printf("config status = %d\n", status);
status = usb_claim_interface(handle, 0);
printf("claim status = %d\n", status);
open_status = usb_set_altinterface(handle, 0);
printf("alt status = %d\n", status);
status = usb_bulk_write(handle, 4, &send_data, 1, 500);
printf("TX status = %d\n", status);
usb_bulk_read(handle, 3, &receive_data, 1, 500);
printf("RX status = %d -> RX char = %d\n", status, receive_data);
usb_close(handle);
return 0;
}
usb_dev_handle *locate_device(void)
{
...
config_val = dev->config[myDeviceIndex].bConfigurationValue;
...
}
EDIT:
The following error codes are returned when the application is ran as root:
Device Found @ Address 005
Vendor ID 0x018d1
Product ID 0x04e12
INFO: bConfigurationValue = 1
config status = -16
claim status = -16
alt status = -22
TX status = -16
RX status = -16 -> RX char = 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: need help converting label to string to output in another label box for summary: C# strFirstName = txtFirstName.Text;
strLastName = txtLastName.Text;
lblSummary = "FirstName:" + strFirstName + Environment.NewLine +
"Last Name:" + strLastName + Environment.NewLine +
"Gross Income:" + decGrossIncome.ToString("c") + Environment.NewLine +
"Taxes Due:" + decTaxesDue.ToString("c") + Environment.NewLine +
"Total Payments:" + decTotalPayments.ToString("c") + Environment.NewLine +
"Total Amount Due:" + decTotalAmountDue.ToString("c");
lblSummary.Text = strSummary;
*note*the following contains the error
"Total Amount Due:" + decTotalAmountDue.ToString("c");
The error I get is:
Error 1 Cannot implicitly convert type 'string' to 'System.Windows.Forms.Label' E:\CIS 162 AD\CS03\CS03\CS03\Form1.cs 79 37 CS03
A: You're trying to assign a string value straight to a Label variable. I suspect you meant this:
string strSummary = "FirstName:" + strFirstName + Environment.NewLine +
"Last Name:" + strLastName + Environment.NewLine +
"Gross Income:" + decGrossIncome.ToString("c") + Environment.NewLine +
"Taxes Due:" + decTaxesDue.ToString("c") + Environment.NewLine +
"Total Payments:" + decTotalPayments.ToString("c") + Environment.NewLine +
"Total Amount Due:" + decTotalAmountDue.ToString("c");
lblSummary.Text = strSummary;
I would personally advise using string.Format, and ditching the pseudo-Hungarian naming by the way.
string summary = string.Format("First Name: {1}{0}" +
"Last Name: {2}{0}" +
"Gross Income: {3:c}{0}" +
"Taxes Due: {4:c}{0}" +
"Total Payments: {5:c}{0}" +
"Total Amount Due: {6:c}",
Environment.NewLine, firstName, lastName,
grossIncome, taxesDue, totalPayments,
totalAmountDue);
// I'm not so hot on naming controls, so I'm not saying this is great - but I
// prefer it not to be control-type-specific; what's important is that it's a
// control we're using to output the summary.
summaryOutput.Text = summary;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Image Object - Handle onload Event I'm trying to preload image on click event:
// new image object
var imgObject = new Image();
// assign the path to the image to the src property
imgObject.src = document.URL + 'image/image.jpg';
// check if image has loaded
if (imgObject.complete) {
But the complete call never returns true on the first click - any idea what I'm missing here?
A: .complete is a property of the image object, not an event that you can attach to. Use the onload event:
var image = new Image();
image.onload = function() {
alert('image loaded');
};
image.src = document.URL + 'image/image.jpg';
Note: Be sure to attach to the onload hander before setting the source attribute.
Note Explanation: Image caching. If the image is cached then the onload event will fire immediately (sometimes before setting the handler)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there a method like onrotate() or something with a similar functionality in Android? I call a method based on a boolean value. I try setting that value in onRetainNonConfigurationInstance() to handle screen rotation but somehow it does not call the function correctly. What is the best method to call that will allow me to this:
public void methodName() //ideally something like onRotate()
{
if (booleanValue == true)
{
booleanValue2 = false;
method1();
}
else
{
booleanValue2 = true;
method2();
}
}
here
A: Maybe you're looking for this: http://developer.android.com/reference/android/view/OrientationListener.html
onOrientationChanged(int)
Called when the orientation of the device has changed. orientation
parameter is in degrees, ranging from 0 to 359. orientation is 0
degrees when the device is oriented in its natural position, 90
degrees when its left side is at the top, 180 degrees when it is
upside down, and 270 degrees when its right side is to the top.
ORIENTATION_UNKNOWN is returned when the device is close to flat and
the orientation cannot be determined.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Quick Recursive search of all indexes within an array Ok, so say I have an array as follows:
$buttons = array(
'mlist' => array(
'title' => 'Members',
'href' => $scripturl . '?action=mlist',
'show' => $context['allow_memberlist'],
'sub_buttons' => array(
'mlist_view' => array(
'title' => 'View the Member List',
'href' => $scripturl . '?action=mlist',
'show' => true,
),
'mlist_search' => array(
'title' => 'Search for Members',
'href' => $scripturl . '?action=mlist;sa=search',
'show' => true,
'is_last' => true,
),
),
),
'home' => array(
'title' => 'Home',
'href' => $scripturl,
'show' => true,
'sub_buttons' => array(
),
'is_last' => $context['right_to_left'],
),
'help' => array(
'title' => 'Help',
'href' => $scripturl . '?action=help',
'show' => true,
'sub_buttons' => array(
),
),
);
I need to sort through this array and return all indexes of it in another array as an index, and the values of these arrays will be the title. So it should return an array as follows:
array(
'mlist' => 'Members',
'mlist_view' => 'View the Member List',
'mlist_search' => 'Search for Members',
'home' => 'Home',
'help' => 'Help',
);
How can this be achieved easily? Basically, need the key of each array if a title is specified and need to populate both within another array.
A: The following snippet loops over all of the arrays (recursively) to extract the key/title pairs.
$index = array();
$iterator = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($buttons)), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (array_key_exists('title', $value)) {
$index[$key] = $value['title'];
}
}
var_dump($index);
A:
How can this be achieved easily?
*
*initialize an empty, new array
*foreach the $buttons array with key and value
*
*extract title from value
*set the key in the new array with the title
*done.
Edit: In case a recursive array iterator catches too much (identifying elements as children while they are not - just being some other array), and you don't want to write an extension of the recursive iterator class, stepping through all children can be solved with some "hand written" iterator like this:
$index = array();
$childKey = 'sub_buttons';
$iterator = $buttons;
while(list($key, $item) = each($iterator))
{
array_shift($iterator);
$index[$key] = $item['title'];
$children = isset($item[$childKey]) ? $item[$childKey] : false;
if ($children) $iterator = $children + $iterator;
}
This iterator is aware of the child key, so it will only iterate over childs if there are some concrete. You can control the order (children first, children last) by changing the order:
if ($children) $iterator = $children + $iterator;
- or -
if ($children) $iterator += $children;
A: I'm sure my answer is not most efficient, but using many foreach loops and if checks, it can be done. However, with my solution if you nested another array inside of say 'mlist_view' that you needed to get a title from, it would not work. My solution works for a max of 2 arrays inside of arrays within buttons. A better (and more general purpose solution) would probably involve recursion.
$result = array();
foreach($buttons as $field => $value) {
foreach($value as $nF => $nV) {
if($nF === 'title') {
$result[$field] = $nV;
}
if(is_array($nV)) {
foreach($nV as $name => $comp) {
if(is_array($comp)) {
foreach($comp as $nnF => $nnV) {
if($nnF === 'title') {
$result[$name] = $nnV;
}
}
}
}
}
}
}
foreach($result as $f => $v) {
echo $f.": ".$v."<br/>";
}
A: This works for your value of $buttons, fairly simple:
function get_all_keys($arr) {
if (!is_array($arr)) return array();
$return = array();
foreach (array_keys($arr) as $key) {
if (is_array($arr[$key])
&& array_key_exists('title', $arr[$key]))
$return[$key] = $arr[$key]['title'];
$return = array_merge($return, get_all_keys($arr[$key]));
}
return $return;
}
echo "<pre>";
print_r(get_all_keys($buttons));
echo "</pre>";
Which returns:
Array
(
[mlist] => Members
[mlist_view] => View the Member List
[mlist_search] => Search for Members
[home] => Home
[help] => Help
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it considered good practice to change the protection level of a method? In other words if I have a class
class A
{
public:
A() { .. }
virtual void somemethod() { .. }
};
is it ok to write
class B : public A
{
public:
B() { .. }
protected:
virtual void somemethod() { .. }
};
or are there some drawbacks with this approach?
A: The main drawback with that approach is that one can always take a pointer/reference to A and invoke somemethod where is public. Why would you want to do such thing? If B is an A, and As have a public somemethod then so do Bs.
A: I would say this defeats the purpose of polymorphism, because when you write a function that accepts a polymorphic type, the derived type should work equally well with it:
void fun(A* a){
a->somemethod();
}
...
A* a = new B();
fun(a); // Shouldn't this work?!
// According to Liskov Principle, you are doing it wrong!
// but really who cares, it depends on your justification
// of a solution to the the problem at hand.
IMHO, it depends on the specific problem you are trying to solve because I don't believe in "always" successful "best practice".
A: There is no drawback with this approach. The only limitation is that B::somemethod() cannot be called with B object/pointer/reference. It can be now invoked only using A's pointer or reference.
In fact, I have seen that sometimes this limitation is introduced intentionally. Such scenarios are when the developer of class B wants to convey the message that, somemethod() is meant to be called only polymorphically using base class handle.
A: No drawback.
But no real advantage to do this.
You still have accesses to somemethod() via a pointer to the case class.
So no drawback and no advantages on the technical side.
So now we move onto how easy it is to use you object. Here there is a downside as you are confusing the user of the object (why is it protected at this level but not the lower level)? So you are creating work for yourself in documenting why you made this decision and what you are trying to achieve by using this technique.
What is it that you really trying to achieve?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Maven dependency resolution and scope overriding Disclaimer
(I originally asked the question in a very detailed manner over here. I've excerpted it here as the maven-users mailing list has gone quiet on this question.) (not just another newbie question)
Reference
My reference material is
http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management; please let me know in this discussion if this is outdated or wrong.
Question
There is a section in that document that begins with "A second, and very important...". In what follows I'll refer to that section's projects A and B, and will excerpt from them.
In that section, you will see that project A has a <dependencyManagement> section that--among other things--defines an artifact, c, as having scope compile:
<!-- In A's pom.xml; condensed for brevity -->
<dependencyManagement>
<dependency>
<groupId>test</groupId>
<artifactId>c</artifactId>
<version>1.0</version>
<scope>compile</scope> <!-- look: compile scope -->
</dependency>
</dependencyManagement>
Then you will see a pom.xml for project B that (a) inherits from project A (thus inheriting its dependencyManagement section) and (b) establishes a dependency on artifact c, without having to specify its version. You will also notice that the dependency on artifact c overrides the scope of c to be runtime, not compile:
<!-- In B's pom.xml, whose parent is A's pom.xml (above); condensed for brevity -->
<dependencies>
<dependency>
<groupId>test</groupId>
<artifactId>c</artifactId>
<scope>runtime</scope> <!-- look: runtime scope -->
</dependency>
</dependencies>
Again, you'll note that there is no <version> element, but there is a <scope>runtime</scope> element.
My interpretation of this is that when all is said and done, B will depend on version 1.0 of artifact c in runtime scope, not compile scope.
Is that correct? My maven-ear-plugin bug rests on the fact that this is the expected behavior. It is not what happens when the maven-ear-plugin builds an .ear file.
Next, if that's correct, I would also expect that if artifact c had any transitive runtime dependencies they would be available in B's runtime classpath (as defined by the somewhat baffling table in http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope).
Is that correct?
A: Running mvn dependency:tree on the sample project posted in the bug link specified above,
[INFO] Building MEAR-143 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.3:tree (default-cli) @ mear-143 ---
[INFO] ljnelson:mear-143:pom:1.0-SNAPSHOT
[INFO] \- junit:junit:jar:4.8.2:test
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MEAR-143 Leaf 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.3:tree (default-cli) @ mear-143-leaf ---
[INFO] ljnelson:mear-143-leaf:jar:1.0-SNAPSHOT
[INFO] \- junit:junit:jar:4.8.2:test
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MEAR-143 Middle 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.3:tree (default-cli) @ mear-143-middle ---
[INFO] ljnelson:mear-143-middle:jar:1.0-SNAPSHOT
[INFO] +- ljnelson:mear-143-leaf:jar:1.0-SNAPSHOT:runtime
[INFO] \- junit:junit:jar:4.8.2:test
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MEAR-143 EAR 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.3:tree (default-cli) @ mear-143-ear ---
[INFO] ljnelson:mear-143-ear:ear:1.0-SNAPSHOT
[INFO] +- ljnelson:mear-143-middle:jar:1.0-SNAPSHOT:runtime
[INFO] | \- ljnelson:mear-143-leaf:jar:1.0-SNAPSHOT:test (scope managed from ru
ntime)
[INFO] \- junit:junit:jar:4.8.2:test
The dependency scope of mear-143-leaf in mear-143-middle, where the dependency is explicitly defined is indeed runtime, overriding the test scope defined in the dependencyManagement section of parent pom, mear-143.
In mear-143-ear, mear-143-leaf gets included transitively. Here the test scope defined in dependencyManagement of mear-143 takes precedence over the inherited runtime scope.
This, I guess is in line with what is specified in the second bullet point in the section you have referred above. Quoting it here and highlighting in bold and italics the relevant parts:
b is defined in B's parent's dependency management section and since
dependency management takes precedence over dependency mediation for
transitive dependencies, version 1.0 will be selected should it be
referenced in a or c's pom. b will also have compile scope
A: The selected answer is good enough to clarify the key point that whether dependencyManagement takes precedence relies on whether the child dependency is declared explicitly or transitively.
As a plus, I just created a summary concerned with version & scope resolution to kill this problem totally:
Assuming that a dependency A is declared eight times in different ways, and each with a different version... which version will win last?
just remember the three rules in the picture:
*
*explicit declaration > dependency-management declaration > implicit transitive declaration
*1st declaration > 2nd declaration
*child declaration > parent declaration
and you will figure out the priority sequence shown as red numbered list in the picture.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: Expand/Collapse set height divs with same class using jQuery
Possible Duplicate:
jQuery div content partial hide, show all
I know this has been done and I have seen in peoples websites but I can't find it. So I am here.
I need to set up or list multiple divs (4 or 5) on a page with the same class and set each div about 50 pixels tall. I need them to expand to the div to the full height of the content. Assuming using show/hide or slideUp/slideDown. And when the collapse happens, collapse the div back down to the 50 pixels. Again I want multiple divs with the same class and fire independently from each other.
Anybody seen this before. I saw this solution but was not quite what I need. I need an expand and close, as well as, all divs need to start out the same height then once the expand is clicked, that specific div needs to expand. Each can be open independent of each other.
Any ideas?
A: If you've got HTML structured like this:
<div class='expandable'>
<p>Some content</p>
</div>
<div class='expandable'>
<p>Some more content</p>
</div>
You can make that work with a bit of joint jQuery and CSS.
First, this CSS would force each .expandable to have a minimum height of 50px:
.expandable { min-height:50px; }
Then to take care of the expanding/collapsing, you can do something like:
jQuery(function($) {
$('.expandable').bind('click', function () {
$(this).children().toggle();
});
});
This would hide/show the .expandable DIV's content everytime it is clicked. When the content is hidden, the CSS above would prevent the DIV from collapsing on itself smaller than 50px.
This would allow your .expandable to "expand" to it's content's true height when the content is shown as well. Take note that the content has to be in HTML DOM elements for this to work (predictably).
<!-- This should work -->
<div class='expandable'>
<p>foo</p>
</div>
<!-- This probably won't -->
<div class='expandable'>
bar
</div>
A: css class:
.toggledivs {height:50px;}
.max {height:150px;}
Then toggle the classes
$('.toggledivs').click(function(){
$(this).toggleClass('max');
});
In that case they are all independent of each other. The initial HTML should be set up like
<div class="toggledivs">foo</div><div class="toggledivs">foo</div>
If you want to have like the first container (or any of em) add class 'max' to the element lika:
<div class="toggledivs max">foo</div><div class="toggledivs">foo</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how to write a c function which creates an empty queue? I am new to C. I have no idea about how to write a C function which creates an empty queue and return a void pointer.
void* queue_open(void)
I also want to know how to write a C function which puts an element at end of a queue.
void queue_put(void *p, void *elementp)
Thanks for your help!
A: If you are coming from an object oriented background (as your method signatures seem to indicate).
Object oriented idea -> good way to do it in C
Object creation -> malloc a struct, then pass it into an initialization function
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
queue_initialize(q);
if you want, you can wrap this in a function, like so
struct queue* queue_construct() {
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
queue_initialize(q);
return q;
}
Note that these pointer shouldn't point to void*, let C do at least some of the type checking for you.
Implement a method -> create a function that takes a struct pointer to the "almost this" struct.
struct user* user = ... whatever we do here ...;
queue_add(q, (void*)user);
As far as how to actually implement a queue, I suggest a good data structures or algorithms book, as there are many ways to go about it; and, the specific techniques you choose will have different impacts on performance and reliability. There's no one best way, it depends heavily on how the queue is to be used, and which aspects of performance are more important.
The book I recommend is Introduction to Algorithms. This book is overkill for most situations, with very detailed listings of nearly every major data structure you are likely to encounter in the first few years of programming. As such, it makes a great reference, despite its attempt at a language neutral approach, which now looks odd when compared to common programming languages.
Once you understand what is going on, you can do it in nearly any language.
A: You need to decide what a queue element should look like, what a queue is, and what it means for a queue to be empty. If you know those things, writing queue_open and queue_put should be pretty easy. I'd suggest that you start by defining a structure that represents your queue element.
A: You can learn about queues here:
http://en.wikipedia.org/wiki/Queue_(data_structure)
While you could easily copy and paste the sample code from the link above and with little modification solve your homework problem, you are not going to learn a lot by doing that.
After understanding a queue conceptually, I recommend you try to implement it yourself, then use the sample code from the link above as a reference when you get stuck.
The best thing you could do is pair up with another student in your class who is smarter than you. Then pair program ( http://en.wikipedia.org/wiki/Pair_programming ) with him/her to solve the problem. You'll become a better programmer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Namespaces in web.config file not working
Possible Duplicate:
How to add namespaces in web.config file?
I am trying to add namespace in web.config file, so that I can use it in all web pages (in code behind). But it is not working.
Has anybody tried it ? I have asked this before but not get any suitable answer.
To better understand here is code behind file
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.BackColor = Color.Red;// It is not working.
}
}
}
This is web.config file
<?xml version="1.0"?>
<configuration>
<system.web>
<pages>
<namespaces>
<clear/>
<add namespace="System.Drawing" />
</namespaces>
</pages>
</system.web>
</configuration>
Edit
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Label1.BackColor = Color.Red;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:label ID="Label1" runat="server" text="Label"></asp:label>
</div>
</form>
</body>
</html>
A: The <namespaces> element only applies to aspx pages.
Unlike VB.Net, C# has no mechanism to automatically include namespaces in ordinary code files.
A: The namespaces configuration section is for pages, not code behind. A code behind file express all namespace imports within itself. The namespaces included in configuration will be included in the dynamic class that is generated from your .aspx page.
A: You should try this and then try.
<configuration>
<system.web>
<pages>
<namespaces>
<clear/>
<add namespace="System.Drawing" />
<add namespace="System" />
</namespaces>
</pages>
</system.web>
</configuration>
A: As SLaks says, that will not work. If you're looking for a shortcut to always having a namespace included, consider editing the default VS templates, so that it's always there when you create a new one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Format a datetime into a string with milliseconds How can I format a datetime object as a string with milliseconds?
A: To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'
Or slightly shorter:
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
A: import datetime
# convert string into date time format.
str_date = '2016-10-06 15:14:54.322989'
d_date = datetime.datetime.strptime(str_date , '%Y-%m-%d %H:%M:%S.%f')
print(d_date)
print(type(d_date)) # check d_date type.
# convert date time to regular format.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
<<<<<< OUTPUT >>>>>>>
2016-10-06 15:14:54.322989
<class 'datetime.datetime'>
06 October 2016 03:14:54 PM
2016-10-06 03:14:54 PM
2016-10-06 15:14:54
A: In python 3.6 and above using python f-strings:
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
print(f"{dt:%Y-%m-%d %H:%M:%S}.{dt.microsecond // 1000:03d}")
The code specific to format milliseconds is:
{dt.microsecond // 1000:03d}
The format string {:03d} and microsecond to millisecond conversion // 1000 is from def _format_time in https://github.com/python/cpython/blob/master/Lib/datetime.py that is used for datetime.datetime.isoformat().
A: @Cabbi raised the issue that on some systems (Windows with Python 2.7), the microseconds format %f may incorrectly give "0", so it's not portable to simply trim the last three characters. Such systems do not follow the behavior specified by the documentation:
Directive
Meaning
Example
%f
Microsecond as a decimal number, zero-padded to 6 digits.
000000, 000001, …, 999999
The following code carefully formats a timestamp with milliseconds:
>>> from datetime import datetime
>>> (dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
>>> "%s.%03d" % (dt, int(micro) / 1000)
'2016-02-26 04:37:53.133'
To get the exact output that the OP wanted, we have to strip punctuation characters:
>>> from datetime import datetime
>>> (dt, micro) = datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.')
>>> "%s%03d" % (dt, int(micro) / 1000)
'20160226043839901'
A: Using strftime:
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
'20220402055654344968'
A: I assume you mean you're looking for something that is faster than datetime.datetime.strftime(), and are essentially stripping the non-alpha characters from a utc timestamp.
You're approach is marginally faster, and I think you can speed things up even more by slicing the string:
>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267
>>> def replaceutc(s):
... return s\
... .replace('-','') \
... .replace(':','') \
... .replace('.','') \
... .replace(' ','') \
... .strip()
...
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067
>>> def sliceutc(s):
... return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
...
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694
A: With Python 3.6+, you can set isoformat's timespec:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
'2019-05-10 09:08:53.155'
A: Use [:-3] to remove the 3 last characters since %f is for microseconds:
>>> from datetime import datetime
>>> datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]
'2013/12/04 16:50:03.141'
A: from datetime import datetime
from time import clock
t = datetime.utcnow()
print 't == %s %s\n\n' % (t,type(t))
n = 100000
te = clock()
for i in xrange(1):
t_stripped = t.strftime('%Y%m%d%H%M%S%f')
print clock()-te
print t_stripped," t.strftime('%Y%m%d%H%M%S%f')"
print
te = clock()
for i in xrange(1):
t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
print clock()-te
print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')"
print
te = clock()
for i in xrange(n):
t_stripped = str(t).translate(None,' -:.')
print clock()-te
print t_stripped," str(t).translate(None,' -:.')"
print
te = clock()
for i in xrange(n):
s = str(t)
t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
print clock()-te
print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] "
result
t == 2011-09-28 21:31:45.562000 <type 'datetime.datetime'>
3.33410112179
20110928212155046000 t.strftime('%Y%m%d%H%M%S%f')
1.17067364707
20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
0.658806915404
20110928212130453000 str(t).translate(None,' -:.')
0.645189262881
20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
Use of translate() and slicing method run in same time
translate() presents the advantage to be usable in one line
Comparing the times on the basis of the first one:
1.000 * t.strftime('%Y%m%d%H%M%S%f')
0.351 * str(t).replace('-','').replace(':','').replace('.','').replace('
','')
0.198 * str(t).translate(None,' -:.')
0.194 * s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] +
s[20:]
A: I dealt with the same problem but in my case it was important that the millisecond was rounded and not truncated
from datetime import datetime, timedelta
def strftime_ms(datetime_obj):
y,m,d,H,M,S = datetime_obj.timetuple()[:6]
ms = timedelta(microseconds = round(datetime_obj.microsecond/1000.0)*1000)
ms_date = datetime(y,m,d,H,M,S) + ms
return ms_date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
A: python -c "from datetime import datetime; print str(datetime.now())[:-3]"
2017-02-09 10:06:37.006
A: datetime
t = datetime.datetime.now()
ms = '%s.%i' % (t.strftime('%H:%M:%S'), t.microsecond/1000)
print(ms)
14:44:37.134
A: The problem with datetime.utcnow() and other such solutions is that they are slow.
More efficient solution may look like this one:
def _timestamp(prec=0):
t = time.time()
s = time.strftime("%H:%M:%S", time.localtime(t))
if prec > 0:
s += ("%.9f" % (t % 1,))[1:2+prec]
return s
Where prec would be 3 in your case (milliseconds).
The function works up to 9 decimal places (please note number 9 in the 2nd formatting string).
If you'd like to round the fractional part, I'd suggest building "%.9f" dynamically with desired number of decimal places.
A: If you are prepared to store the time in a variable and do a little string manipulation, then you can actually do this without using the datetime module.
>>> _now = time.time()
>>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)),
... str('%.3f'%_now).split('.')[1])) # Rounds to nearest millisecond
Time : 05/02/21 01:16:58.676
>>>
%.3f will round to out put the nearest millisecond, if you want more or less precision just change the number of decimal places
>>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)),
... str('%.1f'%_now).split('.')[1])) # Rounds to nearest tenth of a second
Time : 05/02/21 01:16:58.7
>>>
Tested in Python 2.7 and 3.7 (obviously you need to leave out the brackets when calling print in version 2.x).
A: Field-width format specification
The UNIX date command allows specifying %3 to reduce the precision to 3 digits:
$ date '+%Y-%m-%d %H:%M:%S.%3N'
2022-01-01 00:01:23.456
Here's a custom function that can do that in Python:
from datetime import datetime
def strftime_(fmt: str, dt: datetime) -> str:
tokens = fmt.split("%")
tokens[1:] = [_format_token(dt, x) for x in tokens[1:]]
return "".join(tokens)
def _format_token(dt: datetime, token: str) -> str:
if len(token) == 0:
return ""
if token[0].isnumeric():
width = int(token[0])
s = dt.strftime(f"%{token[1]}")[:width]
return f"{s}{token[2:]}"
return dt.strftime(f"%{token}")
Example usage:
>>> strftime_("%Y-%m-%d %H:%M:%S.%3f", datetime.now())
'2022-01-01 00:01:23.456'
NOTE: %% is not supported.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "329"
}
|
Q: Get latitude / longitude / Reverse Geocoding without displaying maps Using a website, I am trying to capture user's latitude / longitude point and based on that grab his current address.
I am able to do this using Google Maps API: geolocation and Reverse GeoCoding. But, my requirement is to get this information without displaying the map. As far as I have read, Google Maps Term of Use prohibits such thing.
Can anyone let me know if there is any other service which can serve my purpose without displaying maps or does Google Maps allow such thing? I am not sure about Bing, Yahoo.
EDIT: On page load, I need to grab user's latitude and longitude and based on that get address information. I am planning to use this address information for displaying nearby locations/places to visit. I have to achieve this without displaying any map.
A: Yahoo PlaceFinder does it. If you pass through the latitude and longitude in the location parameter and gflags=R, it should return address data.
You'll have to get a Yahoo APP id, but its free and pretty easy to set up.
EDIT: I see you want to do geolocation too, if you can't use google I would investigate html5 geolocation and or use freegeoip.net to geolocate by ip address.
A: I don't know if Im mistaken this post, but if you read this:
(viii) store or allow end users to store map imagery, map data or geocoded location information from the Yahoo! Maps APIs for any future use;
(ix) use the stand-alone geocoder for any use other than displaying Yahoo! Maps or displaying points on Yahoo! Maps;
It's mean that you can't store the information, or make use of it, without maps.
So the google api and the yahoo api need to have a map...
note- I take that lines from the terms of yahoo: http://info.yahoo.com/legal/us/yahoo/maps/mapsapi/mapsapi-2141.html
EDIT - Now I'm trying to use http://www.geonames.org/export/reverse-geocoding.html It's easy, and works fine for me. I just need the city and maybe a postal code.
A: I don't think Yahoo requires you to show a map and it also has a higher quota.
http://developer.yahoo.com/geo/placefinder/
A: There are a number of geolocation APIs - here is a really good one:
https://geoip.nekudo.com/
You merely make a GET request to
http://geoip.nekudo.com/api/{ip}/{language}/{type}
where ip, language and type are optional.
E.g. in Angular 5, using HttpClient:
this.http.get('http://geoip.nekudo.com/api/')
.subscribe(
data => { console.log('SUCCESS! Your coords are lat:', data.location.latitude, 'long:', data.location.longitude); },
error => { console.log('ERROR!', error); }
);
Also, note that the geoip service is written in PHP and open source (https://github.com/nekudo/shiny_geoip) so you can house your own implementation to reduce third party dependencies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Tumblr API Blog methods return 401 "Not Authorized", but User methods works perfect So, there is a code that uses xAuth authentication to call tumblr API methods:
import urllib
import urlparse
import oauth2 as oauth
consumer_key = "..."
consumer_secret = "..."
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
resp, content = client.request('https://www.tumblr.com/oauth/access_token', "POST", urllib.urlencode({
'x_auth_mode': 'client_auth',
'x_auth_username': '...@yandex.ru',
'x_auth_password': '...'
}))
token = dict(urlparse.parse_qsl(content))
print token
token = oauth.Token(token['oauth_token'], token['oauth_token_secret'])
client = oauth.Client(consumer, token)
response, data = client.request('http://api.tumblr.com/v2/blog/good.tumblr.com/followers', method='GET')
print data
It works perfect with User methods from tumblr API that require OAuth authentication.
But it fails when i try to call any Blog method with OAuth authentication (/followers for example):
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
Except one thing. If i use my blog name as {base-hostname} parameter it works without any errors.
Weird. How is that possible? Is something wrong with the code?
A: Well that is because your OAuth access token grants you access to your blogs. OAuth can't give you permission to access Blog methods that you do not own because then you could post to them.
A: When you make POST request the enctype must be "multipart/form-data".
I had the same problem with Zend_Oauth (php), but is resolved now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I capture and print stderr and/or stdout correctly on Windows? Thanks to hammar I have the beginnings of a job management server running on windows. The intent is that a unix-side daemon will be sending commands to and receiving stderr/stdout from windows-side. Problem is, I can't get the windows-side server to either print to stderr/stdout on the windows side, nor can I send the stream to the handle connected to the unix side (using telnet client for now).
Here is my attempt. I'm only using stdout in this example, but neither stdout nor stderr works. runJob is the IO action where I am making my attempt. I would appreciate guidance in fixing this problem.
Edit: I ran a haskell test script in place of the .bat file, and it captures stdout/stderr. Below I am including the batch file. What puzzles me is when I run the batch file manually it produces stdout and stderr to screen. Can't figure out what is happening. Perhaps I should replace the batch file with a haskell script.
> import Network.Socket
> import Control.Monad
> import Network
> import System.Environment (getArgs)
> import System.Process
> import System.IO
> import Control.Concurrent (forkIO)
> import Control.Exception (bracket)
> import Data.Maybe
> main :: IO ()
> main = withSocketsDo $ do
> putStrLn ("up top\n")
> [port] <- getArgs
> bracket (prepareSocket (fromIntegral $ read port))
> sClose
> acceptConnections
> prepareSocket :: PortNumber -> IO Socket
> prepareSocket port = do
> sock <- socket AF_INET Stream defaultProtocol
> let socketAddress = SockAddrInet port 0000
> bindSocket sock socketAddress
> listen sock 1
> putStrLn $ "Listening on " ++ (show port)
> return sock
> acceptConnections :: Socket -> IO ()
> acceptConnections sock' = do
> forever $ do
> (sock, sockAddr) <- Network.Socket.accept sock'
> handle <- socketToHandle sock ReadWriteMode
> sockHandler sock handle
> sockHandler :: Socket -> Handle -> IO ()
> sockHandler sock' handle = do
> hSetBuffering handle LineBuffering
> -- Add the forkIO back if you want to allow concurrent connections.
> {- forkIO $ -}
> commandProcessor handle
> return ()
> commandProcessor :: Handle -> IO ()
> commandProcessor handle = untilM (hIsEOF handle) handleCommand >> hClose handle
> where
> handleCommand = do
> line <- hGetLine handle
> let (cmd:arg) = words line
> case cmd of
> "echo" -> echoCommand handle arg
> "runjob" -> runJob handle arg
> _ -> do hPutStrLn handle "Unknown command"
> echoCommand :: Handle -> [String] -> IO ()
> echoCommand handle arg = do
> hPutStrLn handle (unwords arg)
> runJob :: Handle -> [String] -> IO ()
> runJob handle jobNumber = do
>
> -- let batchDirectory = "fookit"
> (_, Just hout, Just herr, jHandle) <-
> createProcess (proc testJob []) { cwd = Just batchDirectory,
> std_out = CreatePipe,
> std_err = CreatePipe }
> stdOUT <- hGetLine herr
> hPutStrLn stdout stdOUT
> hPutStrLn handle stdOUT
> exitCode <- waitForProcess jHandle
> -- stdErr <- hShow hout
> --hPutStrLn handle stdOUT
> return ()
> batchDirectory = "C:\\Users\\ixia\\Documents"
> testJob = "C:\\Users\\ixia\\Documents\\680batch.bat"
> untilM cond action = do
> b <- cond
> if b
> then return ()
> else action >> untilM cond action
Here's the batch file I mentioned. It does what's expected when run manually
"C:\Program Files (x86)\Ixia\Tcl\8.4.14.0\bin\tclsh.exe" 680template.tcl
A: Let's try to narrow this down and make it easier to test by eliminating all the network code, as it really has nothing to do with capturing the output of a process. Here is a small test program extracted from your code.
import System.IO
import System.Process
main = do
(_, Just hout, Just herr, jHandle) <-
-- Replace with some other command on Windows
createProcess (proc "/bin/date" [])
{ cwd = Just "."
, std_out = CreatePipe
, std_err = CreatePipe
}
putStrLn "First line of stdout:"
hGetLine hout >>= putStrLn
exitCode <- waitForProcess jHandle
putStrLn $ "Exit code: " ++ show exitCode
This works as expected on Ubuntu, at least. (I don't have a Windows box nearby at the moment).
$ runghc RunJob.hs
First line of stdout:
Wed Sep 28 22:28:37 CEST 2011
Exit code: ExitSuccess
I would start by testing that this works with your job. That should hopefully give you some clues on how to proceed from there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Remove duplicates (1 to many) or write a subquery that solves my problem Referring to the diagram below the records table has unique Records. Each record is updated, via comments through an Update Table. When I join the two I get lots of duplicates.
*
*How to remove duplicates? Group By does not work for me as I have more than 10 fields in select query and some of them are functions.
*Write a sub query which pulls the last updates in the Update table for each record that is updated in a particular month. Joining with this sub query will solve my problem.
Thanks!
Edit
Table structure that is of interest is
create table Records(
recordID int,
90more_fields various
)
create table Updates(
update_id int,
record_id int,
comment text,
byUser varchar(25),
datecreate datetime
)
A: Here's one way.
SELECT * /*But list columns explicitly*/
FROM Orange o
CROSS APPLY (SELECT TOP 1 *
FROM Blue b
WHERE b.datecreate >= '20110901'
AND b.datecreate < '20111001'
AND o.RecordID = b.Record_ID2
ORDER BY b.datecreate DESC) b
A: Based on the limited information available...
WITH cteLastUpdate AS (
SELECT Record_ID2, UpdateDateTime,
ROW_NUMBER() OVER(PARTITION BY Record_ID2 ORDER BY UpdateDateTime DESC) AS RowNUM
FROM BlueTable
/* Add WHERE clause if needed to restrict date range */
)
SELECT *
FROM cteLastUpdate lu
INNER JOIN OrangeTable o
ON lu.Record_ID2 = o.RecordID
WHERE lu.RowNum = 1
A: Last updates per record and month:
SELECT *
FROM UPDATES outerUpd
WHERE exists
(
-- Magic part
SELECT 1
FROM UPDATES innerUpd
WHERE innerUpd.RecordId = outerUpd.RecordId
GROUP BY RecordId
, date_part('year', innerUpd.datecolumn)
, date_part('month', innerUpd.datecolumn)
HAVING max(innerUpd.datecolumn) = outerUpd.datecolumn
)
(Works on PostgreSQL, date_part is different in other RDBMS)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Datatables doesn't process page changes I must be doing something wrong, but my code is very basic, hardly even deviating from their example on the web.
I'm using server-side paging, and what I'm experiencing is that on the immediate page load it's pulling in the data from the server and rendering the table just fine. However paging, or changing the number of records on the page does make the AJAX call, but fails to actually process.
If I change line 3562 of jquery.dataTables.js (v 1.8.2) the problem ceases.
if ( false )//json.sEcho*1 < oSettings.iDraw )
Some context for that line:
function _fnAjaxUpdateDraw ( oSettings, json )
{
if ( typeof json.sEcho != 'undefined' )
{
/* Protect against old returns over-writing a new one. Possible when you get
* very fast interaction, and later queires are completed much faster
*/
if ( false )//json.sEcho*1 < oSettings.iDraw )
Just to demonstrate how straightforward my setup is:
<script type="text/javascript">
$(function(){
$('#recTable').dataTable({
"bProcessing":true,
"bServerSide": true,
"sAjaxSource": "/recordings/partPageCallRecordings/",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false },
null,
null,
null,
{ "bSortable": false }
]
});
});
</script>
and the HTML:
<table id='recTable' class='vmTable' >
<thead>
<tr class='vmHeader'>
<th><input id='selectAll' type='checkbox'></input></th>
<th class='sortHead'>Date</th>
<th class='sortHead'>File Name</th>
<th class='sortHead'>Type</th>
<th class='sortHead'>Playback</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
A: It looks like you are returning the sEcho data to the client since it gets past the first if block. Are you editing it in any way on the server side? Have you tried putting a breakpoint in firebug on that line to see what sEcho returns? I is basically saying is this request an old request denoted by the sEcho value compared to the up to date iDraw integer.
Without seeing what your json response looks like I can only guess. But my guess would be that sEcho variable is not being set correctly on the server side.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: centering jquery-ui button Strange thing. I center a div inside another div, and all is fine until the inner div is changed to .button. Then it is not centered any more.
html:
<div style='width:100%;'>
<div id='bt_click_me' class='button'>Click</div>
</div>
css:
#bt_click_me
{
width:100px;
margin: 0 auto !important;
}
When bt_click_me is a regular div with just a text, all is fine. when I do $('.button').button() then it changes into a nice jquery-ui button, but also moves to the left side of the outer div. Any clues?
A: I'm pretty sure this has to do with jQuery's CSS altering the behavior of the div by applying the ui-button class, which switches the div from a block to an inline-block, thus making the margin: 0 auto; style no longer a valid way to center it (inline elements cannot be centered with margin).
Try adding display: block; to your style, or add text-align: center; to your wrapper div.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Vim: Set Color/Theme based off time of day I have one of those super glossy monitors, so during the day I can see my own reflection better than my code on Dark themes. So I thought it'd be great if I could have a simple if switch in my vimrc to set either a dark theme or a light theme based on the time of day.
Alas, I don't know enough about vimrc syntax and googling came up short.
Anyone wanna take a crack at this?
A: Something like the following should do the trick:
if strftime("%H") < 12
set background=light
else
set background=dark
endif
Obviously you should choose the hour based on your needs
A: Try the werewolf.vim plugin:
Werewolf changes your vim colorscheme automatically based on the time of day, allowing you to use a light theme during the day but "transform" to a dark theme once the sun goes down.
If you use often different color schemes, you can set several pairs of light/dark color schemes, and it will automatically switch to the matching scheme.
A: This is not strictly a Vim answer but you could try to install f.lux which adjusts your monitor colours to the time of the day.
Here is a demo. It has a warm yellowish glow during the day, and blueish one during the night.
Disclaimer : I have not tried it myself (but I am tempted).
A: You can source a .vimrc.local in your vimrc. Then you could use cron to overwrite that file according to the time of day. no scripting :-)
A: My night-and-day plugin is a "vim theme scheduler". You can divide the day into any number of intervals and assign a theme to each. Themes will automatically change if vim is open when a new interval begins.
A: I understand that this is now an old question with an accepted answer, but if you are looking to achieve the same functionality using lua instead of vimscript, here is how I accomplished it.
local hr = tonumber(os.date('%H', os.time()))
if hr > 6 and hr < 21 then -- day between 6am and 9pm
vim.opt.background = 'light'
else -- night
vim.opt.background = 'dark'
end
Note that this answer assumes that your preferred color scheme supports light and dark backgrounds.
A: I have figured out another way of changing color and background
exe 'colo' ((strftime('%H') % 18) >= 6 ? 'gruvbox' : 'kolor')
exe 'set background='. ((strftime('%H') % 18) >= 6 ? 'light' : 'dark')
Using the rest of division gives more control over the time I want to change background. We can use this shell loop to see why:
for ((i=1;i<=23;i++)){
echo "Rest of dividing $ i by 18 equal to: $(( $i % 18 ))"
}
If I use something like <14, instead of the rest of the division, what happens is that after midnight my color scheme changes to "light". So I make the comparison of the rest of the division of the hour by 6.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: how to preserve the orgianl backgroundColor when hovering? below is the code that works fine but the only problem i have is : its overriding the alternative row with backgroundColor='white' how can i have my orginal alternative color when onmouseout ?
<AlternatingRowStyle BackColor="#DEEEE9" Font-Size="8pt" />
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#C2D69B'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
e.Row.Attributes.Add("style", "cursor:pointer;");
}
A: I don't get it, why not just take out the "e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");" and set it to the color of the original alternate???
A: instead of specifying a specific color, use the hover css attributes.
See:
http://www.codeproject.com/KB/webforms/MouseHoverUsingCSS.aspx
A: You can specify what color exactly should be restored on onmouseout:
if (e.Row.RowType == DataControlRowType.DataRow)
{
string bgcolor = "white"
if (e.Row.RowState == DataControlRowState.Alternate)
{
bgcolor = "#DEEEE9";
}
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#C2D69B'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='" + bgcolor + "'");
e.Row.Attributes.Add("style", "cursor:pointer;");
}
A: Try something like this:
var color = "<%=System.Drawing.ColorTranslator.ToHtml(GridView1.AlternatingRowStyle.BackColor)%>";
A: This works well with much less code. Create a custom attribute in the mouseover before setting the backgroundColor and use it on the mouse out. Works perfectly for alternating row colors.
row.Attributes["onmouseover"] = this.originalstyle=this.style.backgroundColor;this.style.cursor='hand';this.style.backgroundColor='#ffccff';";
row.Attributes["onmouseout"] = "this.style.textDecoration='none';this.style.backgroundColor=this.originalstyle;";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Used normal text in combination with normal text in plot UPDATE: I actually found the solution myself, see below.
In R I want to add a label to a plot containing both subscript and normal text. To be more precise, I would like to use mtext() (or any other method that does the trick) to add a text below a plot. The text should look like this:
This can easily done in latex with $B\pm t_{a/2}SE(B)$
In R I come as far as mtext(expression(B%+-%t[a/2])), which does print
But the difficulty is in geting the SE(B) part after it, because of expression treating SE(B) as a function. I've tried several combinations with paste, but to no avail. I'm sure there must be a simple solution to this, but I wasn't able to find one after quite a long search.
UPDATE:
Wow, found the solution myself. As I said I have tried combinations of expression and paste and was sure I tried this before, but apparently, I did not. The solution is this:
mtext(expression(paste(B%+-%t[a/2],"SE(B)")))
A: I see you have solved this, but your final solution is much more nicely and succinctly handled by dropping the use of paste() and using the ~ operator to add spacing:
expression(B %+-% t[a/2] ~ SE(B))
e.g.:
plot(1:10, xlab = expression(B %+-% t[a/2] ~ SE(B)))
which gives
You can add extra spacing by using multiple ~: ~~~ for example. If you just want to juxtapose two parts of an equation, using the * operator, as in:
plot(1:10, xlab = expression(B %+-% t[a/2] * SE(B)))
which gives:
It isn't immediately clear from your Q which one is preferable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to produce X values of a stretched graph? I'm trying to "normalize" monthly data in a way.
What I mean by that is, I need to take daily values and check the data from each month against the data in another month.
The only problem with this is that some months are longer than others. So I have come up with a way that I want to do this, but I'm kind of confused as to exactly how to do it...
Basically, I'm looking at this website: http://paulbourke.net/miscellaneous/interpolation/ and trying to transform each set of coordinates into a graph with 31 X- and Y-values (I would like to use the Cosine interpolator, but I'm still trying to figure out what to do with it).
Now, the X values have a function. I can pass in something like (1..28) and morph it into 31 values...simple enough code, something like this works for me:
def total = (1..30)
def days = 28
def resize = {x, y->
result = []
x.each{ result << (it * (y/x.size())}
return result
}
resize(total,days)
Which returns a list of 31 Y-values spanning from 0 to 28.
My question is: How do I translate a list of the corresponding Y values to these values? I'm having a really hard time wrapping my head around the concept and could use a little help.
My first thought was to simply run the Y-values through this function too, but that returns values that are all lower than the original input.
I'm looking for something that will retain the values at certain points, but simply stretch the graph out horizontally.
For example, at the x value at (1/3) of the graph's length, the value needs to be the same as it would be at (1/3) of the original graph's length.
Can anyone help me out on this? It's got me stumped.
Thanks in advance!
A: Not sure where the problem lies with this, so I made up some data
I think your algorithm is correct, and you only need to normalize the x-axis.
I came up with this code (and some plots) to demonstrate what I believe is the answer
Define some x and y values:
def x = 1..30
def y = [1..15,15..1].flatten()
Then, generate a list of xy values in the form: [ [ x, y ], [ x, y ], ...
def xy = [x,y].transpose()
If we plot this list, we get:
Then define a normalize function (basically the same as yours, but it doesn't touch the y value)
def normalize( xylist, days ) {
xylist.collect { x, y -> [ x * ( days / xylist.size() ), y ] }
}
Then we can normalize our list to 28 days
def normalxy = normalize( xy, 28 )
Now, if we plot these points, we get
As you can see, both plots have the same shape, they are just different widths...
Have I missed the point?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails way to generate site navigation Navigation for most websites takes the form of an html unordered list with anchors inside of the list elements. Typing out all of these item tags doesn't seem like the rails DRY way to create a list for navigation.
I ask how you create a list for navigation the rails way and if you could help me develop the method I'm attempting described below...
what I've done is create a hash in my application_helper and then added a quick iteration code in my erb file to generate the list for me.
app helper:
$navPages = {
'top1' => "top1_path",
'top2' => "top2_path",
'top3' => "top3_path",
}
html.erb iteration code:
<ul>
<% $navPages.each do |ntext,npath| %>
<li><%= link_to ntext, self.send(npath.to_sym) %></li>
<% end %>
</ul>
List output:
<ul>
<li><a href="/">top1</a></li>
<li><a href="/">top2</a></li>
<li><a href="/">top3</a></li>
</ul>
That seems VERY rails to me.... I'm having a problem expanding on this for lists with "sub-items" or lists within lists.
I created the hash:
$myHash = {
'top1' => { :location => "top1_path"},
'top2' => { :location => "top2_path", :members => {
"sub1-1" => { :location => "sub1_path"},
"sub1-2" => { :location => "sub2_path"},
"sub1-3" => { :location => "sub3_path"},
}
},
'top3' => { :location => "top3_path", :members => {
"sub2-1" => { :location => "sub1_path"},
"sub2-2" => { :location => "sub2_path"},
"sub2-3" => { :location => "sub3_path"},
}
}
}
I have tried many way to convert that hash into an unorded list with anchors but I haven't found a clean solution that works perfectly. Any thoughts on how to do this? The reason I like hashes for this task is that I can capture the association of items as well as other useful information such as the link location I've stored in the :location symbol.
I'm thinking that the hash could/should be traded in for something with less typing... like
top1 loc
member1 loc
member2 loc
top2 loc
not sure where to stat on that though :(
so... to Generate an HTML list with this information just doesn't seem very railsy to me... what is everyone on rails doing?
Thanks!
thanks!
A: My recommendation is to look into using the Simple Navigation Gem. This has a nice DSL for defining navigation, and you have complete control over highlighting, submenu display and classes and ids used.
Here is an example of the DSL
A: Common practice is to have couple erb files, something like shared/_nav.html.erb, shared/_subnav.html.erb for the reasons:
*
*premature abstraction is not good
*navigation changes not often
What means Rails way, is:
*
*DRY
*Conventions over configuration
*Patterns set, like MVC, Delegate, Proxy, Observer, STI and so
*Fat models, skinny controllers
*Human readable coding standards
*Unobtrusive JS
So Rails do not cover specific client-side representation things, then you can do it to make code clear and simple.
My own opinion is better to build navigation with JS, because it's easier to do mobile markup based on it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# Finding Next Active Day of Week I've got a C# class I'm working with representing a profile that includes some scheduling information indicating how many updates during the day, and which days to update with boolean values for each day of the week. I've seen some posts here and on other sites to find the next instance of a given weekday, etc. but not something where which days one is looking for can vary.
For example, I might be given an object with Monday, Wednesday, and Thursday as true. What's the best way to find the next instance of the next true day of the week?
I can think of some long and drawn out ways to find the next "true" day of the week, but is there something cleaner built in that I'm unfamiliar with that would do the trick? I'd prefer not to use any third party libraries, as that requires lots of special approval from information assurance folks.
A: Given that it's hardly going to take a long time to loop, that's going to be the simplest approach:
DateTime nextDay = currentDay.AddDays(1);
while (!profile.IsActive(nextDay.DayOfWeek))
{
nextDay = nextDay.AddDays(1);
}
(That's assuming you've already validated that the profile is active on at least one day... otherwise it'll loop forever.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Tracking nested items in CSS I'm going out of my mind trying to figure out where these 4 <br> tags are coming from.
The CMS is doing this:
<div style="width:100%; border: solid 1px;">
<br>
<br>
<br>
<br>
<table style="display:block; width: 99%; height: auto; margin: 0px; vertical-align: top; border: solid 1px;" border="0">
<colgroup>
<col style="text-align: left;"></colgroup>
<colgroup><col style="text-align: center;"></colgroup>
<colgroup><col style="text-align: center;"></colgroup>
<colgroup><col style="text-align: center;"></colgroup>
<tbody>
The code for the page as it stands goes:
<div style="width:100%; border: solid 1px;">
<table style="display:block; width: 99%; height: auto; margin: 0px; vertical-align: top; border: solid 1px;" border="0">
<colgroup>
<col style="text-align: left;"/>
<col style="text-align: center;"/>
<col style="text-align: center;"/>
<col style="text-align: center;"/>
</colgroup>
<tbody>
Now, it seems something in the CMS css code is telling it to put those tags in before the table. The div at the front is going all the way to the top, but as soon as I put in a table those 4 <br> tags come in. I've done my absolute best trying to scour the css for the call off, but to no avail. Is there an easier way of tracking this through the css? All I want to do is force the inline style so there are no more <br> tags above the table.
Thanks for any help!
edit Sorry this is Drupal, with the Chrysalis theme. Can't CSS do before: or after: to add stuff? That's what I was kinda assuming was going on. Also, I don't have access to mess with the external CSS. Just assume I have to respect the current CSS and only make inline changes if neccessary.
A: It almost definitely isn't the CSS putting those tags in, but some template in your CMS.
Nevertheless, if you just wrap your table in a div with a class, say, 'tablewrapper' and add some CSS like
.tablewrapper br { display: none; }
It should hide the br's on the page.
A: BNL you are correct, it was the CMS module inserting those. It was the 'Line Break Converter' that was doing this.
Just go to:
Administer->Site configuration->Input formats
and disable the 'Line Break Converter'.
It's pretty similar to this:
http://drupal.org/node/689908
.
Thanks for getting me back on the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamically adding and selecting a menuitem in XUL I'm using a Javascript object containing a list of phone codes to generate a dropdown menu in XUL. My object has this form:
var CountryCodes = {
"Afghanistan":"+93",
"Albania":"+355",
"Algeria":"+213"
}
The code for populating the menupopup looks like this:
var docfrag = document.createDocumentFragment();
for( var country in CountryCodes ) {
var this_country = document.createElementNS(XUL_NS,'menuitem');
this_country.setAttribute( 'label', country );
this_country.setAttribute( 'value', CountryCodes[ country ] );
docfrag.appendChild( this_country );
}
$('countryCodePopup').appendChild( docfrag );
$('countryCode').setAttribute( 'selectedIndex', 0 );
and my XUL looks like this:
<menulist id="countryCode">
<menupopup id="countryCodePopup"></menupopup>
</menulist>
However, when I run it on the page, the menuitem gets created properly, but the first element of the menu doesn't get selected. I tried to set a selected attribute on one of the fields, but the result is the same. What am I missing here?
Thanks!
Luka
Update: As it turns out, I was setting selectedIndex incorrectly. It should have been done like so:
$('countryCode').selectedIndex = 10;
A: Try like this:
document.getElementById("countryCode").selectedIndex = 10;
For reference, please check this:
https://developer.mozilla.org/en/XUL_Tutorial/Manipulating_Lists
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How show or appears the TitleBar? (I'd set NoTitleBar in Manifest.xml) I'm looking for to set the default titlebar in one layout into my app. But I'd set the Theme of the app to NoTitleBar.
How can I add by code to set/appear the titlebar?
Thx.
A: You can specify the theme for each activity in your AndroidManifest.xml file:
<activity android:name="Activity1" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>
<activity android:name="Activity" android:label="@string/app_name"
android:theme="@android:style/SOMETHING_ELSE"/>
A: You can override a theme set on <application>, by defining theme on <activity>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Entering app debug/test mode - best practices We've delivered the app to the customer. Part of the app's functionality involves talking over HTTP to a set of production URLs. The customer would like the ability for the app to enter a debug or test mode, in which the app connects to parallel test servers rather than the production servers.
We can implement this easily enough. What I'm struggling with is the best way to enter this special mode. I'm wondering if there is any experience in implementing some gesture which is not easily discoverable by the user nor likely to be hit upon by accident.
Has anyone felt the need to implement anything like this, and, if so, what did you use for your "secret gesture"?
A: To really keep people out you can use an RSA key pair with a message and an Unlock app. From the Unlock app send an Intent with a string extra encoded by an RSA private key to your app, which will decode it with the public key and compare it to whatever you decide. (Could be a simple secret string or converted to a one-way hash that is verified by a server, it just depends on the security level you want). Then your app can unlock the debug functionality.
Another possibility is to use this API: Debug.isDebuggerConnected() but it is not very effective in the field because debugging is required.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to run WEBrick for Rails application, but keep getting error: "Only one usage of each socket..." Info: Rails 3.0.9; Ruby 1.8.7; Windows 7
I just switched from mysql to postgresql in my Rails environment, and I cannot for the life of me get around this error when trying to run rails s on port 3000:
WARN TCPServer Error: Only one usage of each socket address (protocol/network address/port) is normally permitted. - bind(2)
I'm developing back and forth between two computers using dropbox, and everything works just fine on my home computer. But at work, this issue is driving me crazy.
I've researched this question all over the internet, and I don't feel any of the answers have applied. The obvious answer is that the port is occupied. But I can't identify anything in my processes or using netstat in the command prompt that would be using this port.
This link http://oldwiki.rubyonrails.org/rails/pages/MysteryProcessHoldsOntoWebrickPort describes my problem exactly, but none of the solutions have worked. I've tried changing the port to 3001 using the -p option, but then I get this error:
could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432?
This same message also appears if I try to run rake db:migrate.
So aside from the methods I've already mentioned, I have no idea how identify and remedy the cause of this error.
I'm somewhat new to programming, so I may be overlooking something. Any help would be much appreciated.
A: I just had a very similar version of your problem.
Rake db:migrate didn't migrate, it ran and gave no errors or migrating msgs. , the problem seemed to be a discrepancy between rake 9.2.2 and rake 8.7 abbr. If u run bundle exec rake db:migrate , it may work but didn't not in my case. I ran sudo gem uninstall rake and the bundle install. It still didn't work. I uninstalled pg 8.7 and reinstalled pg 9.1.1 using homebrew and opened a new RoR file with --freeze and that file rake db:migrates ... But I can't validate in the model. The Validation throws a 500 internal server error - string can't be coerced to integer. The reason I mention all this is because I have just migrated computer to Mac lion and to postgresql. Changing computers we are both. It seems connecting postgresql is the common thread among these errors. A lot differing opinions about where to put pg files and how best to configure ... I'm on 5432 btw , saves, queries , just don't validate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: spim simulator pcspim : error setting value at an address Hi I am using spim simulator pcspim and I am trying to set a value at an address using the set value option under the simulator menu.
When I try to set a value which has an msb of 1 for ex. oxb1234567 the value at that address is defaulted to 7fffffff, can anyone explain the reason for this behaviour.
Any help appreciated
A: In MIPS, addresses starting with 1 (MSB = 1) indicate kernel memory space. You cannot access kernel space from user space (which has MSB = 0) without using syscalls.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Help making an eraser for a paint program in java Making a very basic paint program for a class and one of the requirements is that we must make an eraser. Not sure how to do that, We are using a bufferedimage that is then getting pasted to our jframe. Any ideas on how this could be done/ any code examples? Someone told me to try clearRect but maybe I was just using it wrong but i could not get it to accept it. Any help / code examples would be great, here is my code, its all one class.
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class PaintProgram extends JPanel implements MouseListener,ActionListener
{
public static int stroke, eraser = 0;
private int xX1, yY1 , xX2, yY2, choice ;
public static void main(String [] args)
{
new PaintProgram();
}
PaintProgram()
{
JFrame frame = new JFrame("Paint Program");
frame.setSize(1200, 800);
frame.setBackground(Color.WHITE);
frame.getContentPane().add(this);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu help = new JMenu("Help");
menuBar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(this);
JButton button1 = new JButton("Clear");
button1.addActionListener(this);
JButton color = new JButton("Color");
color.addActionListener(this);
JButton erase = new JButton("Erase?");
erase.addActionListener(this);
JButton button2 = new JButton("Empty Rect");
button2.addActionListener(this);
JButton button3 = new JButton("Filled oval");
button3.addActionListener(this);
JButton button4 = new JButton("Filled Rect");
button4.addActionListener(this);
JButton button5 = new JButton("Empty oval");
button5.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
JRadioButton thin = new JRadioButton("Thin Line");
thin.addActionListener(this);
JRadioButton medium = new JRadioButton("Medium Line");
medium.addActionListener(this);
JRadioButton thick = new JRadioButton("Thick Line");
thick.addActionListener(this);
ButtonGroup lineOption = new ButtonGroup( );
lineOption.add(thin);
lineOption.add(medium);
lineOption.add(thick);
this.add(button1);
this.add(color);
this.add(erase);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(button5);
this.add(button6);
this.add(thin);
this.add(medium);
this.add(thick);
addMouseListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if(grid == null){
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage)(this.createImage(w,h));
gc = grid.createGraphics();
gc.setColor(Color.BLUE);
}
g2.drawImage(grid, null, 0, 0);
check();
}
BufferedImage grid;
Graphics2D gc;
public void draw()
{
Graphics2D g = (Graphics2D)getGraphics();
int w = xX2 - xX1;
if (w<0)
w = w *(-1);
int h = yY2-yY1;
if (h<0)
h= h*(-1);
switch(choice)
{
case 1:
check();
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
if (stroke == 0)
gc.setStroke(new BasicStroke (1));
if (stroke == 1)
gc.setStroke(new BasicStroke (3));
if (stroke == 2)
gc.setStroke(new BasicStroke (6));
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
repaint();
Color temp = gc.getColor();
gc.setColor(Color.WHITE);
gc.fillRect(0, 0, getWidth(), getHeight());
gc.setColor(temp);
repaint();
break;
case 7:
if (eraser == 1)
{
gc.clearRect(xX1, yY1, w, h);
}
else
{
}
break;
}
}
public void check()
{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 =z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Color"))
{
Color bgColor
= JColorChooser.showDialog(this,"Choose Background Color", getBackground());
if (bgColor != null)
gc.setColor(bgColor);
}
if (e.getActionCommand().equals("About"))
{
System.out.println("About Has Been Pressed");
JFrame about = new JFrame("About");
about.setSize(300, 300);
JButton picture = new JButton(new ImageIcon("C:/Users/TehRobot/Desktop/Logo.png"));
about.add(picture);
about.setVisible(true);
}
if (e.getActionCommand().equals("Empty Rect"))
{
System.out.println("Empty Rectangle Has Been Selected~");
choice = 1;
}
if (e.getActionCommand().equals("Empty oval"))
{
System.out.println("Empty Oval Has Been Selected!");
choice = 2;
}
if (e.getActionCommand().equals("Filled Rect"))
{
System.out.println("Filled Rectangle Has Been Selected");
choice = 3;
}
if (e.getActionCommand().equals("Filled oval"))
{
System.out.println("Filled Oval Has Been Selected");
choice = 4;
}
if (e.getActionCommand().equals("Line"))
{
System.out.println("Draw Line Has Been Selected");
choice = 5;
}
if (e.getActionCommand().equals("Thin Line"))
{
stroke = 0;
}
if (e.getActionCommand().equals("Medium Line"))
{
stroke = 1;
}
if (e.getActionCommand().equals("Thick Line"))
{
stroke = 2;
}
if(e.getActionCommand().equals("Erase?"))
{
eraser = 1;
choice = 7;
}
if (e.getActionCommand().equals("Clear"))
{
System.out.println("Clear All The Things!!!");
choice = 6;
draw();
}
}
public void mouseExited(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mousePressed(MouseEvent evt)
{
xX1 = evt.getX();
yY1= evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
xX2 =evt.getX();
yY2=evt.getY();
draw();
eraser = 0;
}
}
A: I have added comments where I added/changed the code.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class PaintProgram extends JPanel implements MouseListener, ActionListener,
/**
* CHANGE BY S AQEEL : implement mouse motion listener
*/
MouseMotionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static int stroke, eraser = 0;
private int xX1, yY1, xX2, yY2, choice;
/**
* CHANGE BY S AQEEL : Define a constant for background color, because we are using it at a lot of places
*/
private static final Color BACKGROUND_COLOR = Color.WHITE;
/**
* CHANGE BY S AQEEL : Also define variables for eraser width and height. In a more usable implementation you can allow user to change eraser size
*/
private int eraserWidth = 40;
private int eraserHeight = 40;
public static void main(String[] args)
{
new PaintProgram();
}
PaintProgram()
{
JFrame frame = new JFrame("Paint Program");
frame.setSize(1200, 800);
/**
* CHANGE BY S AQEEL : Use constant instead of hardcoding
*/
frame.setBackground(BACKGROUND_COLOR);
frame.getContentPane().add(this);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu help = new JMenu("Help");
menuBar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(this);
JButton button1 = new JButton("Clear");
button1.addActionListener(this);
JButton color = new JButton("Color");
color.addActionListener(this);
JButton erase = new JButton("Erase?");
erase.addActionListener(this);
JButton button2 = new JButton("Empty Rect");
button2.addActionListener(this);
JButton button3 = new JButton("Filled oval");
button3.addActionListener(this);
JButton button4 = new JButton("Filled Rect");
button4.addActionListener(this);
JButton button5 = new JButton("Empty oval");
button5.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
JRadioButton thin = new JRadioButton("Thin Line");
thin.addActionListener(this);
JRadioButton medium = new JRadioButton("Medium Line");
medium.addActionListener(this);
JRadioButton thick = new JRadioButton("Thick Line");
thick.addActionListener(this);
ButtonGroup lineOption = new ButtonGroup();
lineOption.add(thin);
lineOption.add(medium);
lineOption.add(thick);
this.add(button1);
this.add(color);
this.add(erase);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(button5);
this.add(button6);
this.add(thin);
this.add(medium);
this.add(thick);
addMouseListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (grid == null)
{
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage) (this.createImage(w, h));
gc = grid.createGraphics();
gc.setColor(Color.BLUE);
}
g2.drawImage(grid, null, 0, 0);
check();
}
BufferedImage grid;
Graphics2D gc;
public void draw()
{
Graphics2D g = (Graphics2D) getGraphics();
int w = xX2 - xX1;
if (w < 0)
w = w * (-1);
int h = yY2 - yY1;
if (h < 0)
h = h * (-1);
switch (choice)
{
case 1:
check();
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
if (stroke == 0)
gc.setStroke(new BasicStroke(1));
if (stroke == 1)
gc.setStroke(new BasicStroke(3));
if (stroke == 2)
gc.setStroke(new BasicStroke(6));
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
repaint();
Color temp = gc.getColor();
/**
* CHANGE BY S AQEEL : Use constant instead of hardcoding
*/
gc.setColor(BACKGROUND_COLOR);
gc.fillRect(0, 0, getWidth(), getHeight());
gc.setColor(temp);
repaint();
break;
case 7:
if (eraser == 1)
{
gc.clearRect(xX1, yY1, w, h);
}
else
{
}
break;
}
}
public void check()
{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 = z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}
public void actionPerformed(ActionEvent e)
{
/**
* CHANGE BY S AQEEL : Remove mousemotionlistener(which is added when eraser is selected) So that if another control is pressed, the user does
* not accidentally erases
*/
super.removeMouseMotionListener(this);
if (e.getActionCommand().equals("Color"))
{
Color bgColor = JColorChooser.showDialog(this, "Choose Background Color", getBackground());
if (bgColor != null)
gc.setColor(bgColor);
}
if (e.getActionCommand().equals("About"))
{
System.out.println("About Has Been Pressed");
JFrame about = new JFrame("About");
about.setSize(300, 300);
JButton picture = new JButton(new ImageIcon("C:/Users/TehRobot/Desktop/Logo.png"));
about.add(picture);
about.setVisible(true);
}
if (e.getActionCommand().equals("Empty Rect"))
{
System.out.println("Empty Rectangle Has Been Selected~");
choice = 1;
}
if (e.getActionCommand().equals("Empty oval"))
{
System.out.println("Empty Oval Has Been Selected!");
choice = 2;
}
if (e.getActionCommand().equals("Filled Rect"))
{
System.out.println("Filled Rectangle Has Been Selected");
choice = 3;
}
if (e.getActionCommand().equals("Filled oval"))
{
System.out.println("Filled Oval Has Been Selected");
choice = 4;
}
if (e.getActionCommand().equals("Line"))
{
System.out.println("Draw Line Has Been Selected");
choice = 5;
}
if (e.getActionCommand().equals("Thin Line"))
{
stroke = 0;
}
if (e.getActionCommand().equals("Medium Line"))
{
stroke = 1;
}
if (e.getActionCommand().equals("Thick Line"))
{
stroke = 2;
}
if (e.getActionCommand().equals("Erase?"))
{
eraser = 1;
choice = 7;
/**
* CHANGE BY S AQEEL : Add mousemotionlistener here.
*/
super.addMouseMotionListener(this);
}
if (e.getActionCommand().equals("Clear"))
{
System.out.println("Clear All The Things!!!");
choice = 6;
draw();
}
}
public void mouseExited(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseClicked(MouseEvent evt)
{
}
public void mousePressed(MouseEvent evt)
{
xX1 = evt.getX();
yY1 = evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
xX2 = evt.getX();
yY2 = evt.getY();
draw();
eraser = 0;
}
/**
* CHANGE BY S AQEEL : MouseMotionListener functions implemented. Note this listener is only registered when eraser is selected
*/
public void mouseDragged(MouseEvent me)
{
Color c = gc.getColor();
gc.setColor(BACKGROUND_COLOR);
gc.drawRect(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.fillRect(me.getX(), me.getY(), eraserWidth, eraserHeight);
gc.setColor(c);
repaint();
}
public void mouseMoved(MouseEvent arg0)
{
}
}
Now that your problem is solved, you should try to add little but usable quality features, like: Using different cursors for drawing/erasing different shapes. Allow user to change eraser size. Also in the current implementation, the user have to drag the eraser to erase, you should add a functionality so that user can erase points by just clicking (besides dragging).
A: An eraser is just like the pen, except that it sets the color to the background color. When you erase you replace the current color under the pen with the "background" color, which makes it look like the background, effectively removing the perceived color that was previously drawn on the screen.
If your application handles transparencies, then perhaps your eraser will set the color to transparent; but it's the same idea, as "transparency" is just one of the color components, like red, green, and blue.
In the event that you want a button to erase the entire drawing, then simply draw a rectangle as large as the screen in the background color.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Establishing month length and first day Is there a simple way of, given a month and a year, establishing:
*
*How many days there are in that month (factoring in leap years) Done
*What day of the week the first day fall upon?
A: See http://php.net/manual/en/function.cal-days-in-month.php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
and weekdays:
$weekday = date("l", mktime(0,0,0,$month,$day,$year));
$print ($weekday);
The latter is not very efficient but seems nicer than using getdate:
$my_t=getdate(date("U"));
print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]");
Output like
Wednesday, September 29, 2011
A: Take a look at the date function, particularly date('t') for the number of days in the month (ie the month given in time()) and date('t',$epoch) for the number of days of the month represented by the timestamp $epoch (which, of course, is given in epoch).
And for the day of the week, there's date('l',$epoch) (where the first argument is a lower-case 'L').
A: You may find the answer to your questions with all needed variables and calculations by going to wikipedia. http://en.wikipedia.org/wiki/Calculating_the_day_of_the_week
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Exporting an array to Excel I'm trying to export an array of arrays to excel. I have it set up to be a header variable, and a data variable that basically builds a giant string to be executed in the export. However, only the header variable is going through. Let me show some code:
This is setting the parameters:
str_replace(" ", "_", $getData['name']);
$filename = $getData['name']."_summary.xls";
header("Content-Type: application/x-msdownload");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Pragma: no-cache");
header("Expires: 0");
Which goes to a function to get the information:
foreach($tempRS as $key=>$value)
{
foreach($value as $iKey=>$iValue)
{
if($count == 6)
{
$iValue = str_replace('"', '""', $iValue);
$iValue = '"'.$iValue.'"'."\n";
$data .= trim($iValue);
$count = 0;
}
else
{
$iValue = str_replace('"', '""', $iValue);
$iValue = '"'.$iValue.'"'."\t";
$data .= trim($iValue);
$count++;
}
}
}
$header = "ROW HEADER 1\tROW HEADER 2\tROW HEADER 3\tROW HEADER 4\tROW HEADER 5\tROW HEADER 6\n";
print "$header\n$data";
I can't seem to figure out why i'm losing the $data variable on the export.
A: Why not just fputcsv() to generate that CSV data for you? Or better yet, instead of making a .csv masquerade as an Excel file, you can use PHPExcel to output a native .xls/.xlsx and actually use formatting and formulae in the generated spreadsheet.
A: first of all, use echo instead of print. Print causes loads of overhead as it does both return and echo the data.
Secondly, don't put the variables within quotes, use
echo $header ."\n".$data;
To get to your question, does the foreach loops actually loop? Have you checked the $data if it contains any data?
A better solution might be this:
$header = '';
echo $header;
foreach() loop here {
//echo the data here instead of putting it in a variable
}
Or maybe better, use http://nl.php.net/fputcsv
A: I tested your code and it seems that your trim() method is trimming your \n and \t.
If you remove it, your code should be fine.
Here's my code to export a array of product in excel.
Only one little problem with this code : Excel doesn't want to open it because of a format problem, but if you click "yes" when it promps an error message, you'll be ok...
No problem with open office though
Working on a fix...
$filename = "products_exports " . date("Y-m-d H_i_s") . ".xls";
/**
* Tell the browser to download an excel file.
*/
header("Content-Type: application/x-msdownload; charset=utf-8");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Pragma: no-cache");
header("Expires: 0");
/**
* The header of the table
* @var string
*/
$header = "";
/**
* All the data of the table in a formatted string
* @var string
*/
$data = "";
//We fill in the header
foreach ($productArray as $i => $product) {
$count = 0;
foreach ($product as $key => $value) {
if($count == count((array)new Product("")) - 1){
$header.= $key;
}
else{
$header.= $key . "\t";
$count++;
}
}
break; /*One loop is enough to get the header !*/
}
//And then the data by the product and all the categories
/*Where $productArray = This can be your custom array of object. eg.
array[0] = new YouCustomObject(your params...);
*/
foreach ($productArray as $i => $product) {
$count = 0;
foreach ($product as $key => $value) {
if($count == count((array)new Product("")) - 1){
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\n";
$data .= $value;
$count = 0;
}
else{
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
$data .= $value;
$count++;
}
}
}
echo $header ."\n". $data;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the limitations of SqlDependency? I am using a table as a message queue and "signing up" for updates by using a SqlDependency. Everywhere I read, people are saying "look out for the limitations of it" but not specifically saying what they are. From what I've gathered, you will have problems when the table has very high update frequency; fortunately, I'm only looking at 10 - 20 values per minute maximum.
What are the other limitations/impact on the SqlServer?
A: The most complete list I can find (from here) is as follows:
*
*The projected columns in the SELECT statement must be explicitly stated, and table names must be qualified with two-part names. Notice that this means that all tables referenced in the statement must be in the same database.
*The statement may not use the asterisk (*) or table_name.* syntax to specify columns.
*The statement may not use unnamed columns or duplicate column names.
*The statement must reference a base table.
*The statement must not reference tables with computed columns.
*The projected columns in the SELECT statement may not contain aggregate expressions unless the statement uses a GROUP BY expression. When a GROUP BY expression is provided, the select list may contain the aggregate functions COUNT_BIG() or SUM(). However, SUM() may not be specified for a nullable column. The statement may not specify HAVING, CUBE, or ROLLUP.
*A projected column in the SELECT statement that is used as a simple expression must not appear more than once.
*The statement must not include PIVOT or UNPIVOT operators.
*The statement must not include the UNION, INTERSECT, or EXCEPT operators.
*The statement must not reference a view.
*The statement must not contain any of the following: DISTINCT, COMPUTE or COMPUTE BY, or INTO.
*The statement must not reference server global variables (@@variable_name).
*The statement must not reference derived tables, temporary tables, or table variables.
*The statement must not reference tables or views from other databases or servers.
*The statement must not contain subqueries, outer joins, or self-joins.
*The statement must not reference the large object types: text, ntext, and image.
*The statement must not use the CONTAINS or FREETEXT full-text predicates.
*The statement must not use rowset functions, including OPENROWSET and OPENQUERY.
*The statement must not use any of the following aggregate functions: AVG, COUNT(*), MAX, MIN, STDEV, STDEVP, VAR, or VARP.
*The statement must not use any nondeterministic functions, including ranking and windowing functions.
*The statement must not contain user-defined aggregates.
*The statement must not reference system tables or views, including catalog views and dynamic management views.
*The statement must not include FOR BROWSE information.
*The statement must not reference a queue.
*The statement must not contain conditional statements that cannot change and cannot return results (for example, WHERE 1=0).
*The statement can not specify READPAST locking hint.
*The statement must not reference any Service Broker QUEUE.
*The statement must not reference synonyms.
*The statement must not have comparison or expression based on double/real data types.
*The statement must not use the TOP expression.
Additional reference:
*
*Working with Query Notifications
A: Note that you cannot use a nolock hint in the stored procedure or the dependency will remain constantly invalid and therefore any cache you make on it will permanently re-query the database.
with (NOLOCK)
This does not appear to be mentioned in the documentation (as far as I can tell).
The following SET options are required prior to the procedure script
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
Others have argued that these SET options are also required, but I don't think they are. It's a good idea to set them like this anyway though.
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET NUMERIC_ROUNDABORT OFF
SET ARITHABORT ON
A: Another big issue I have with this technology: the need for the subscriber connection to have Create Procedure permissions. The web service layer of my application at work at the moment runs as a restricted user. To get notifications setup using SQLDependency I'd have to open up that user to create procs. Sounds like a pretty good step along the path of getting owned.
A: To overcome these limitations, you can try use the SqlTableDependency.
Have a look at www.sqltabledependency.it
A: In addition to this, for anyone else thinking about using SqlDependency to receive notifications about changes, I've been using this approach in production, and I'm finding problems with it. I'm looking into it to see if the problems are related to my code, but the main issues are:
*
*If you fire multiple changes in quick succession, you don't always get the equivalent number of events coming through to the code. In my code, if 2 new records are inserted one after the other, I only get the one notification (for the last one).
*There is no way to know the record that was added. So if you add a new record, and the code fires to receive the notification, there is no way in the code to know the id of that new record, so you need to query the database for it.
A: Spent a day chasing down an issue with SQL Service Broker not working, the root cause was referencing the database in the stored procedure.
For example, this select works fine in SQL Management Studio:
select [MyColumn] from [MyDatabase].[MySchema].[MyTable]
However, this is rejected by SQL Service Broker because we are referencing the database in the select statement, and the callback from SqlDependency comes back with Invalid in SqlNotificationEventArgs e, see http://msdn.microsoft.com/en-us/library/ms189308.aspx.
Altering the SQL passed into SqlDependency to the following statement eliminated the error:
select [MyColumn] from [MySchema].[MyTable]
Update
The example above is just one of many, many limitations to the SQL statement that SQL Service Broker depends on. For a complete list of limitations, see What are the limitations of SqlDependency.
The reason? The SQL statement that SQL Service Broker uses is converted, behind the scenes, into instructions to monitor the SQL Transaction Log for changes to the database. This monitoring is performed in the core of SQL Server, which makes it extremely fast when it comes to detecting changes to table(s). However, this speed comes at a cost: you can't use just any SQL statement, you must use one that can be converted into instructions to monitor the SQL Transaction Log.
A: It uses Service Broker. Therefore it won't work on non managed SQL Azure instances. So be cautious if you're using SQL Azure or ever might.
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-features
Service Broker
Supported by single databases and elastic pools:
No
Supported by managed instances:
Yes, but only within the instance.
See Service Broker differences
So probably not a good fit unless all your environments can use it!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
}
|
Q: Convert letters to lower case I use the following with respect to letters from any language:
text = regex.sub("[^\p{alpha}\d]+"," ",text
Can I use p{alpha} to convert letters to their lower case equivalent if such an equivalency exists? How would this regex look?
A: As oxtopus suggested, you can simply convert letters to their lowercase version with text.lower() (no need for a regular expression). This works with Unicode strings too (À -> à, etc.)
A: >>> re.sub('[AEIOU]+', lambda m: m.group(0).lower(), 'SOME TEXT HERE')
'SoMe TeXT HeRe'
A: I believe you can find your answer here: http://docs.python.org/library/re.html#re.sub
You can provide a tolower function that takes a match object to the sub method which will return replacement string
A: You can change the re.findall("([A-Z]+)", text) to use whatever regex you need. This will just go through the matches, and replace each match with its lowercase equivalent:
text = 'ABCDEF_ghjiklm_OPQRSTUVWXYZ'
for f in re.findall("([A-Z]+)", text):
text = text.replace(f, f.lower())
print text
Output is:
abcdef_ghjiklm_opqrstuvwxyz
A: in languages like Perl or Js the regex engine supports \L -- python is poor that way
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Ignore Unicode Error When I run a loop over a bunch of URLs to find all links (in certain Divs) on those pages I get back this error:
Traceback (most recent call last):
File "file_location", line 38, in <module>
out.writerow(tag['href'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 0: ordinal not in range(128)
The code I have written related to this error is:
out = csv.writer(open("file_location", "ab"), delimiter=";")
for tag in soup_3.findAll('a', href=True):
out.writerow(tag['href'])
Is there a way to solve this, possibly using an if statement to ignore any URLs that have Unicode errors?
Thanks in advance for your help.
A: You can wrap the writerow method call in a try and catch the exception to ignore it:
for tag in soup_3.findAll('a', href=True):
try:
out.writerow(tag['href'])
except UnicodeEncodeError:
pass
but you almost certainly want to pick an encoding other than ASCII for your CSV file (utf-8 unless you have a very good reason to use something else), and open it with codecs.open() instead of the built-in open.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Drag with mootools on mobile Is there a way to make to work the mootools class "Drag" on Safari mobile?
Please don't link me to other frameworks.
A: I've fixed it myself. It is as easy as maping the mouse events to touch events.
So the solution is to search & replace:
mousedown -> touchstart
mouseup -> touchend
mousemove -> touchmove
A: Here was my solution to making Mootools Drag support touch events. This method didn't require me to edit the mootools more file since i used Class.refactor (This is only tested with Mootools v.1.3.1) -- it also does not break the usual click events
Class.refactor(Drag,
{
attach: function(){
this.handles.addEvent('touchstart', this.bound.start);
return this.previous.apply(this, arguments);
},
detach: function(){
this.handles.removeEvent('touchstart', this.bound.start);
return this.previous.apply(this, arguments);
},
start: function(event){
document.body.addEvents({
touchmove: this.bound.check,
touchend: this.bound.cancel
});
this.previous.apply(this, arguments);
},
check: function(event){
if (this.options.preventDefault) event.preventDefault();
var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
if (distance > this.options.snap){
this.cancel();
this.document.addEvents({
mousemove: this.bound.drag,
mouseup: this.bound.stop
});
document.body.addEvents({
touchmove: this.bound.drag,
touchend: this.bound.stop
});
this.fireEvent('start', [this.element, event]).fireEvent('snap', this.element);
}
},
cancel: function(event){
document.body.removeEvents({
touchmove: this.bound.check,
touchend: this.bound.cancel
});
return this.previous.apply(this, arguments);
},
stop: function(event){
document.body.removeEvents({
touchmove: this.bound.drag,
touchend: this.bound.stop
});
return this.previous.apply(this, arguments);
}
});
A: Could you try https://github.com/kamicane/mootools-touch ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: facebook apps settings opengraph dashboard not updating I asked a similar question earlier, but it was one of a bunch of questions, most of which I later solved. So I figured I would create a new question only about this.
In developers.facebook => $MY_APP => app settings => open graph => dashboard, you have options to manage your actions and objects. When I try to edit an action, for example by changing its name, or the object reference it points to, these changes wil ostensibly be saved, but when I refresh the page, it will not have the changes (for the object reference) or the url for the object will not change (for changing the action name).
For example,
When I change the name of action1 to action2, from "get code" the page will still be
https://graph.facebook.com/me/myapp:$action1
Furthermore, calling myapp:$action2 will not work, and when I call myapp:$action1 the action that shows up in my timeline is still $action1.
I may also wish to change the title of my object, from say title1 to title2. However, when I try to change the action so that the reference is to title2, the changes refuse to save.
Is there a solution to this, or should I just delete everything and start anew without making mistakes? I tried deleting the actions and objects and making new ones with the old names, but the moment a make an action with the old name all the old fields are filled out and I can't change them again.
Thanks.
EDIT: to change url and name stuff, those are in advanced options inside the action type edit page. Thanks Paul for pointing that out.
A: The graph api name is in the Advanced section of the ActionType edit page.
For your second question, I don't really understand why your Object Type name won't change. Do you mean the value of og:type isn't changing or the "Name" field? The second one is also in advanced.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What nodejs library is most like jQuery's deferreds? I've become a skilled user of jQuery's new and amazing Deferred module, and as I'm easing into using more of Node.js, I find myself wanting something exactly like it in much of my Node.js programming: callbacks that block until a collection of promises devolves to resolved, with the freedom to add to the array on-the-fly as the task grows in complexity-- such as when one processes a tree of data, the size of which is not known at the start of the task.
But node-fibers requires a whole new executable, Q()'s interface is just damned confusing, and node-step only seems to handle single-task synchronizations.
Has someone just ported jQuery's Deferreds to a node-ready form? It doesn't seem that unlikely, nor does it seem that Deferreds is dependent upon DOM-available features, but I haven't found a server-side equivalent.
A: I don't think you can get any closer than jQuery deferred lib for nodeJS.
A: This node library looks quite similar in functionality to jQuery's Deferred:
https://github.com/kriszyp/node-promise
A: This wasn't around when the question was asked, but according to the readme it uses (and passes) the jquery tests. It appears to be exactly identical minus the (jQuery||$). prefix.
https://github.com/jaubourg/jquery-deferred-for-node
A: If you want the same API, there's nothing stopping you from using jQuery itself under Node. Just npm install jquery, then:
var $ = require('jquery');
var deferred = $.Deferred();
A: This nodejs module is CommonJS compliant.
https://github.com/cujojs/when
A: Googling: deferred for nodejs
Gave me: https://github.com/felixge/node-deferred
Though not exactly what you are looking for, is moderately close. I find that the callback chaining is fairly natural, though deeply nested chains can be a bit difficult to keep up with.
Searching for: promise nodejs lead me down a path of more interesting results...
*
*https://github.com/willconant/flow-js
*https://github.com/creationix/conductor
Both of which are probably much closer to what you are looking for. :)
A: This node library contains jquery 1.8.2 deferred class.
https://www.npmjs.com/package/jquery-deferred
npm install jquery-deferred
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.