text stringlengths 8 267k | meta dict |
|---|---|
Q: Show two projects in one UML diagram I have an enum that has two dependencies. These two are in different projects (Im coding in Java). I want to show this dependency ina UML diagram but how can I show what projects these classes are from? (I know for packages you can put it like this: Package :: pkgName).
Any ideas would be helpful. Thanks
A: What tool are you using?
In Rational Rose, if you this structure:
Folder1
|___Class1
Folder2
|___ClassDiagramX
and the ClassDiagramX shows Class1 then you'll see a small "stereotype" like note indicating "from Folder1" in the box representing Class1.
That should be sufficient.
There are other options using fancy-colorful-notes, but I don't care so much for them.
--edit--
Without knowing the tool I can't really say what you can and can not do. From UML pov, I don't know of any defined convention, so whatever conveys what you wan to can be used. Class diagram is a representation and does not affect the meta-data of the class (e.g. which project it belongs to). So as long as the "class" is in the correct package, it's doesn't matter how it's "shown" in the class diagram.
E.g. in the class-diagram you can put up 2 big squares in the background showing / grouping classes from each project and dependency arrows running across these groups.
OR
"add the line" if that's possible in your tool.
A: If you use Eclipse and java then you have a feature which allow to join two different projects. I mean open the package explorer and click on the project name then select join, or merge with I don't really remember the exact title of the menu but it is easy to find.
Once your both projects have been joined your can create a class diagram and just drag drop inside the same diagram two classifiers coming from different projects.
A: Project in the sense of "a set of planned activities and deliverables, with common goal" can not be reasonably encoded in UML.
Project in the sense of "a set of related files and metadata that allows an IDE to compile and run a program" is out of scope for UML, as this is a development environment artifact and not application design artifact.
For example, you can decide to use multiple projects for each module of your app or a single project for all modules. This will not change your design, only the instructions for the IDE - it's even possible that different team members have different project configurations, especially if some use Eclipse, others IntelliJ IDEA and some EMACS.
On the other hand, if you still want to denote logical sets of classes, you do have options - the formal way would be to use tagged values. Alternatively, I often use colors (for example, green for public API, yellow for extension points/SPI and red for implementation classes; or blue for low-latency multicast component, green for guaranteed messaging components).
You may also use a separate component diagram, showing which class belongs to which component (remember not to build uber-diagrams, but instead aim for simplicity and showing only the relevant facets of the design)
This was a generic advice, but the answer you need is very context-specific. I can get more concrete if you can describe in more detail what are the classes in question, what are the projects (how do you delineate between them) and the overall architecture of the system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSON time service "json-time.appspot.com" is broken. Anyone have a replacement? http://json-time.appspot.com/time.json?tz=GMT has been broken for a while now... at least a month. This service returns the current time in jsonp, and I have a jquery plugin that uses it to determine the correct time. I'm under the assumption that this service is permanently down since it's been down for a long time and I can't find any posts by the author as to it's status. Does anyone know of a service that I can use that returns the correct time in JSON or XML?
Thanks!
A: Looks like you can set up your own: https://github.com/simonw/json-time
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: clearTimeout only works at end of loop I am having problems with the clearTimeout JavaScript Function. I would like the homeAnimation()function to stop looping as soon as the mouse hovers over one of the infoboxes (just working over one box would be a start)
I have stripped out the code I think is unneccessary. Any help would be greatly appreciated, thanks!
This is the JavaScript/JQuery:
$(document).ready(function() {
var x;
function homeAnimation() {
$('#imgBox').fadeOut(200, function() {
$('#imgBox').css("background-image", "url(images/model1.jpg)").delay(100).fadeIn(200);
});
$('#infoframe1').fadeIn(0).delay(5000).hide(0, function() {
$('#imgBox').fadeOut(200, function() {
$('#imgBox').css("background-image", "url(images/women3.jpg)");
$('#imgBox').fadeIn(200);
});
$('#infoframe2').show(0).delay(5000).hide(0, function() {
$('#imgBox').fadeOut(200, function() {
$('#imgBox').css("background-image", "url(images/men4.jpg)");
$('#imgBox').fadeIn(200);
});
$('#infoframe3').show(0).delay(5000).hide(0, function() {
$('#imgBox').fadeOut(200, function() {
$('#imgBox').css("background-image", "url(images/access1.jpg)");
$('#imgBox').fadeIn(200);
});
$('#infoframe4').show(0).delay(5000).hide(0);
x = setTimeout(homeAnimation, 5000);
});
});
});
}
This is the clearTimeout() call at present:
$('#infobox1, #infobox2, #infobox3, #infobox4').mouseover(function(){
clearTimeout(x);
});
And the HTML:
<div id='infobox1'>
<span id='heading'>Special Offers</span><br /><br /><a>Check out or Special Offers of the week, including 2 for 1 on all Bob Smith products</a>
</div>
<div id='infobox2'><span id='heading'>Women</span></div>
<div id='infobox3'><span id='heading'>Men</span></div>
<div id='infobox4'><span id='heading'>Accessories</span></div>
<div id='infoframe1'>
<span id='heading'>Special Offers</span><br /><br />
</div>
<div id='infoframe2'><span id='heading'>Women</span></div>
<div id='infoframe3'><span id='heading'>Men</span></div>
<div id='infoframe4'><span id='heading'>Accessories</span></div>
A: I would recommend something like this. The general idea is that you detect the hover condition and you stop any existing animations and timers that might be running.
Then, when you stop hovering, you start it up again. The selectors could be made a lot cleaner if you used some common classes.
$(document).ready(function(){
var x = null;
$("#infobox1, #infobox2, #infobox3, #infobox4").hover(function() {
$("#imgBox, #infoframe1, #infoframe2, #infoframe3, #infoframe4").stop(true, true); // stop current animation
clearTimeout(x);
}, function() {
$("#imgBox, #infoframe1, #infoframe2, #infoframe3, #infoframe4").stop(true, true); // stop current animation
clearTimeout(x);
homeAnimation(); // start it again
});
function homeAnimation()
x = null;
// I didn't change the code after here
$('#imgBox').fadeOut(200,function(){
$('#imgBox').css("background-image", "url(images/model1.jpg)").delay(100).fadeIn(200);
});
$('#infoframe1').fadeIn(0).delay(5000).hide(0, function(){
$('#imgBox').fadeOut(200,function(){
$('#imgBox').css("background-image", "url(images/women3.jpg)");
$('#imgBox').fadeIn(200);
});
$('#infoframe2').show(0).delay(5000).hide(0, function(){
$('#imgBox').fadeOut(200,function(){
$('#imgBox').css("background-image", "url(images/men4.jpg)");
$('#imgBox').fadeIn(200);
});
$('#infoframe3').show(0).delay(5000).hide(0, function(){
$('#imgBox').fadeOut(200,function(){
$('#imgBox').css("background-image", "url(images/access1.jpg)");
$('#imgBox').fadeIn(200);
});
$('#infoframe4').show(0).delay(5000).hide(0);
x = setTimeout(homeAnimation, 5000);
});
});
}
});
A: I made a jsfiddle to find out what you are basically trying to achive. I got it working, but I must say that your main loop is somewhat entangled. http://jsfiddle.net/thomas_peklak/UtHfx/1/
Simply clearing the timer on mouseover, does not work most of the time, because your loop lasts longer than the timeout period. Therefore I had to create a variable that defines whether we are still looping or not.
A: Add this code to the top of your javascript
window.onerror = function(e) { e = "There is no " + e.split(" ")[0]; alert(e)}; window.* = spoon();
try to call clearTimeout();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to combine a local editor with a remote compiler? I am used to the local IDE interface which integrates the code editor and compiler. However, I want to test if the code compiles well with the remote compiler on Unix server. I am tired of copying my source file to the server, and working in the command window (SSH shell). What I expect is to do some configuration in the programming software (Xcode, Eclipse, Visual Studio), specify compiling with the compiler located at remote server. Is there a way to change the local default compiler with a remote compiler (remote GNU compiler, gcc/g++)?
A: Oracle Studio allows one to do exactly that. With remote Linux or Solaris.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are values stored in NSUserDefaults removed when the app that put them there is uninstalled? If I put a token (a string) into NSUserDefaults, lets say as a paramter passed to a REST API that is used by the app, and the app is uninstalled, will the string remain on the device?
A: No. You can see that the data saved is in Library/Preferences/ inside your sandbox. If you are using Simulator, see (something like) ~/Library/Application\ Support/iPhone\ Simulator/4.3.2/Applications/00DB5581-E797-4AB0-9033-321ACD8938BD/Library/Preferences/com.me.MyApp.plist
A: No, it will not. I use NSUserDefaults in the exact same manner, and it will not stay after the app is deleted. You can verify this via Organizer if you need to.
It will however persist through updates. I have been using TestFlightApp for all of my beta testing, and the token (and other saved user default data) remains. Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How can i use php to export a mysql table I am trying to export just the rows of a mysql table without the table information to an xml file. I read that the mysqldump command will get the job done but I cant manage to get the correct syntax. Can someone post an example code for mysqldump command? Thank you.
$command="mysqldump --xml ";
A: Try the script on this page: http://www.chriswashington.net/tutorials/export-mysql-database-table-data-to-xml-file
A: By any chance you are not trying to run that command inside mysql_query are you ? It wont work that way. mysqldump is a command line utility.
To run it from php you would need to use the system() function, documentation - http://php.net/manual/en/function.system.php
If you are on a shared host with PHP in safe mode, or the system function is explicitly disabled in php.ini, then you will not be able to do this.
In that case you would need to read the data from your table using a SELECT query and iterating on all rows and potting it into an XML file, using XMLWriter or DOMDocument
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Routing issue while using high_voltage for static pages I am trying to use high_voltage to serve up static pages. It seems to be working in that if I put .../pages/PAGE_NAME in the browser window it will bring up the correct page. The problem that I am having is that the default root doesn't appear to be working properly. When I go to http://localhost:3000 I get the home.html.erb page that I put in the view/pages directory inside of my application.html.haml layout. Basically, a page inside of a layout which is not what I expected.
I am following the instructions in that I have the following entries in my routes.rb file:
resources :pages
root :to => 'high_voltage/pages#show', :id => 'home'
I also have a PagesController with the following code:
class PagesController < HighVoltage::PagesController
layout nil
end
It appears that my root route does not actually hit the PagesController (with layout nil) that I have in my code. How can I resolve this issue?
A: have you tried this ?
root :module=> :high_voltage, :controller => :pages, :action => :show, :id => 'home'
see root and match (used internally by root) for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript scroll to bottom of div if current scroll location is near bottom I am working on a script that will append text (varies on size) to a div block (varies in height) with overflow scroll. After this text is appended I need the div block to be scrolled to the bottom in order to see the new appended text, however I need it only to scroll to the bottom if the current scroll position is around 10% of scroll close to the bottom, otherwise it would be annoying if it scrolled down while viewing the top portion of the div.
This is what I came up with, it is run after text is appended:
var divblock = document.getElementById('div'); //the block content is appended to
var divheight = divblock.offsetHeight;//get the height of the divblock
//now check if the scroller is near the bottom and if it is then scroll the div to the abslute bottom
if (***HELP HERE***) divblock.scrollTop=divblock.scrollHeight; ///scroll to bottom
much appreciated thanks!
A: if( divblock.scrollTop < divblock.scrollHeight )
A: div.scrollTop + lineheight > scrollHeight
Like this?
A: You just need to check to see if scrollTop is greater than 90% of the scrollHeight.
if (divblock.scrollTop > divblock.scrollHeight*0.9) {
divblock.scrollTop=divblock.scrollHeight;
}
A: scrollHeight = scrollTop + clientHeight + [fudge factor]
The "fudge factor" seems to be around 30-40 (pixels) for me. So try this:
if ((divblock.scrollTop + divblock.clientHeight + 50) > divblock.scrollHeight) {
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Backslashes disapearing after my vb.net query to Mysql I'm having some problems, when I do my query from my vb.net program to my mysql DB the data is sent, but its missing some things, let me explain.
My query is pretty simple I'm sending a file path to my DB so that after I can have a php website get the data and make a link with the data from my DB, but when I send my data the results look like this...
\server_pathappsInst_pcLicences_ProceduresDivers estCheck_list.doc
which should look like
\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
I don't know if its my code that's not good or my configurations on my mysql server please help...
Here's my code
'Construct the sql command string
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('" & filenameOnly_no_space_no_accent & "', '" & str_Lien_Nom_Procedure & "', '" & str_commentaires_Procedure & "')"
' Create a mysql command
Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As MySqlException
MsgBox("Error uppdating invoice: " & ex.Message)
Finally
conn.Dispose()
End Try
Sorry I got a call and could continue my comment so here's the rest :X
Well I guess that would work, but my program never uses the same path since in uploading a file on a server, so this time the document I wanted to upload was this path
\\Fsque01.sguc.ad\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
but next time its going to be something else so I can't hard code the paths, I was looking more of a SQL query which that I might not know, since I already thought about searching my string and if it finds a backslash it adds another one, but I feel its not a good way to script the whole thing...
Anyway thanks a lot for your help
A: Use double backslashes not single backslash
A: When you construct the insert SQL it doesn't have the backslashes escaped. For example:
INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
The backslashes need to be escaped like:
INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('\\\\server_path\\apps\\Inst_pc\\Licences_Procedures\\Divers\\test\\Check_list.doc
You can do this with something like (not sure about VB.NET):
filenameOnly_no_space_no_accent = filenameOnly_no_space_no_accent.Replace("\\", "\\\\")
You should also look into parameterised queries, which may protect you from some SQL injection attacks and are a bit easier to write and maintain compared to stitched-together SQL (this isn't tested and I'm not familiar with MySQL parameterised queries so YMMV):
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES(?nom, ?lien_nom, ?commentaires)"
Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn)
cmd.Parameters.Add("?nom", filenameOnly_no_space_no_accent.Replace("\\", "\\\\"))
cmd.Parameters.Add("?lien_nom", str_Lien_Nom_Procedure)
cmd.Parameters.Add("?commentaires", str_commentaires_Procedure)
This is based on something I found at this end of this tutorial.
A: cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES(?nom,?Lien_Nom,?Commentaires)"
' Create a mysql command
Dim cmd As New MySqlCommand(cmdString, conn)
cmd.Parameters.AddWithValue("?nom", filenameOnly_no_space_no_accent)
cmd.Parameters.AddWithValue("?Lien_Nom", str_Lien_Nom_Procedure)
cmd.Parameters.AddWithValue("?Commentaires", str_commentaires_Procedure)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As MySqlException
MsgBox("Error uppdating invoice: " & ex.Message)
Finally
conn.Dispose()
End Try
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with calling jquery ajax in asp.net i am having a strange problem, while calling ajax jquery in asp.net.. i am getting the parseError, and this is not expected, because everything is in place.
below is my webmethod.
public class MyLogic
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _title, _image;
public string Image
{
get { return _image; }
set { _image = value; }
}
public string Title
{
get { return _title; }
set { _title = value; }
}
}
below is the method i am calling
[WebMethod]
public static MyLogic[] GetTopArticles()
{
List<MyLogic> bList = new List<MyLogic>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MobileKeyboardConnection"].ConnectionString);
SqlDataAdapter adapTopStories = new SqlDataAdapter("m_sp_toparticles", con);
adapTopStories.SelectCommand.CommandType = CommandType.StoredProcedure;
adapTopStories.SelectCommand.Parameters.AddWithValue("@PortalId", 2);
adapTopStories.SelectCommand.Parameters.AddWithValue("@topValue", 5);
DataTable dtTopStories = new DataTable();
adapTopStories.Fill(dtTopStories);
foreach (DataRow r in dtTopStories.Rows)
{
MyLogic c = new MyLogic();
c.Id = Convert.ToInt32(r["Id"]);
c.Title = r["Title"].ToString();
c.Image = r["image"].ToString();
bList.Add(c);
}
return bList.ToArray();
}
and below is the design.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "AjaxLogic.aspx/GetTopArticles",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function (data) {
var result = data.d;
alert(result.length);
},
error: function (data) {
alert(data.responseText);
}
});
});
</script>
Please any know what could be issue
i am using core asp.net and master pages in my application.
******************JSON RESPONSE*****************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="AjaxLogic.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZPKFQelTZBrnZbMRGP+4imyXfwO4" />
</div>
<div>
</div>
</form>
</body>
</html>
A: Try replacing:
data: {},
by:
data: '{}',
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Magento: How to enable/disable module output per website level? I would like to display an image in the onepage checkout payment methods section that would only show up in one of two website levels. So I have three questions:
1) Am I correct to assume this change would be coded in app/design/frontend/default/mytheme/layout/checkout.xml ?
2) if that is the correct file, what would the change be from:
<!--
One page checkout payment methods block
-->
<checkout_onepage_paymentmethod>
<remove name="left"/>
<block type="checkout/onepage_payment_methods" name="root" output="toHtml" template="checkout/onepage/payment/methods.phtml">
<action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
</block>
</checkout_onepage_paymentmethod>
in order to point to, for example, checkout/onepage/payment/methods-site2.phtml when site2 is being used?
3) Is this the proper way to do this in 1.5.x ?
A: *
*Yes
*You need add STORE_[your_store_code] handle and put there this store specific stuff. More info you can read in this article.
So, in your case, you need update block with name root. To change block template you need some method for this, let's say its name is setTemplate. So, in your layout update file you should write
<STORE_your_code>
<reference name="root">
<action method="setTemplate"><template>checkout/onepage/payment/methods-site2.phtml</template></action>
<block type="my_cool/block" name="my_cool_block">
...
</block>
</reference>
</STORE_your_code>
3. Yes, adding store specific handle to your theme layout update file is the right way for magento CE 1.5.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Preprocess SCSS with HAML I have an app that has some categories: Tomato, Orange, Banana.
Each category has it's own color saved in the database: FF0000, FF6600, FFFF00.
There're also some posts in the app that belong to a category.
I want HAML and/or SASS to generate classes from the category names/color, like:
.tomato header { background-color: #FF0000; }
.tomato aside { background-color: lighten(#FF0000, 0.5); }
.orange header { background-color: #FF6600; }
.orange aside { background-color: lighten(#FF6600, 0.5); }
.banana header { background-color: #FFFF00; }
.banana aside { background-color: lighten(#FFFF00, 0.5); }
As you can see I want to loop the categories table and use SASS functions listed here. Here's not working example/pseudo-code:
- @categories.each |category|
:sass
.#{category.slug} header { background-color: ##{category.color}; }
.#{category.slug} aside { background-color: lighten(##{category.color}, 0.5); }
Any tips how I could achieve that?
Things to keep in mind:
*
*I don't want inline (in post) stylesheets
*I use HAML and SASS (SCSS style)
*I run Rails 3.1
A: Use the Rails 3.1 asset pipeline to first run your code as ERB and then as Sass (so the filename would be something like application.css.sass.erb) and make a variable available to the ERB that you could iterate over and create some Sass. Will that work in your situation?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android GLSurfaceView as subview I'm very new to an Android platform and currently trying figure out why things work this way:
If I create GLSurfaceView and add it using the setContentView or addContentView to an activity everything works fine (Renderer.onDrawFrame is called as expected). However if I add my GLSurfaceView to another ViewGroup (which is then added using setContentView) nothing is rendered.
So what is the difference between addView and addContentView ?
In the end I need to create a custom view with OpenGL rendering in background and some controls on top.
Also what is the point of separating View and ViewGroup? Why not to join them (like it is done in CocoaTouch) ?
A: setContentView(View) sets the parent View for an Activity (or dialog etc...).
addView(View) adds a View to a ViewGroup.
View and ViewGroup are mostly different. View is a more specific single entity. It should be used more on one facet of what you are trying to do. ViewGroup, however, focuses more on the whole and acts (is) a container and layout organizer for a collection of Views.
Can you post all the code related to the GLSurfaceView and how you are setting it as contentView?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Magento - how to declare multiple helper classes in the same config Could someone please tell me how I can declare multiple helpers within the same config file for the same module?
I've been using helper utility files for awhile now, but as my utility method is becoming increasingly long, with many functions, I'd like to split it up into seperate helper utility classes based on the functionality. So I'd have a class called Categoryhelper and one called Attributehelper. Obviously this step I can do, but I'm not sure how to declare these in the config.xml.
I've tried messing around with the config, doing trial and error but cant seem to get anything to work.
Here's what I originally had, using the default helper:
(note - my custom module name is called 'Helper'
<global>
...
<helpers>
<helper>
<class>GPMClient_Helper_Helper</class>
</helper>
</helpers>
...
and here's what I've tried:
<helpers>
<helper>
<class>GPMClient_Helper_Helper/Categoryhelper</class>
</helper>
<helper>
<class>GPMClient_Helper_Helper/Attributehelper</class>
</helper>
and:
<helpers>
<helper>
<class>GPMClient_Helper_Helper/Categoryhelper</class>
<class>GPMClient_Helper_Helper/Attributehelper</class>
</helper>
Should the helper classes go into their own xml fragment or should both be grouped together?
If anyone could please post a sample config with multiple helper classes declared, I'd be most grateful.
Thanks,
Ian
A: Seems like you got wrong how it works. When you add next lines to your GPMClient_Helper module config.xml
<helpers>
<helper>
<class>GPMClient_Helper_Helper</class>
</helper>
</helpers>
you define class prefix for all your helpers. So, now in your GPMClient/Helper/Helper directory you should create file Data.php with GPMClient_Helper_Helper_Datacode inside and any number of classes named GPMClient_Helper_Helper_*.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make spreadsheet save in human-readable format for version control Apparently Gnumeric's native file format is compressed xml.
Diffing binary files isn't easy, so you lose many of the advantages of version control.
Is it possible to get it to save (and load) its files in straight xml (or any other human readable format)?
A: gnumeric's ssconvert might be able to do the job. Will "Convert to xhtml" be helplful to you?
ssconvert -T Gnumeric_html:xhtml Book1.gnumeric Book1.html
This command lists the filetypes gnumeric is able to export to:
ssconvert --list-exporters
ID | Description
Gnumeric_lpsolve:lpsolve | LPSolve Linear Program Solver
Gnumeric_glpk:glpk | GLPK Linear Program Solver
Gnumeric_Excel:xlsx2 | MS Excel (tm) 2010 (ECMA 376 2nd edition (2008))
Gnumeric_Excel:xlsx | MS Excel (tm) 2007 (ECMA 376 1st edition (2006))
Gnumeric_Excel:excel_dsf | MS Excel (tm) 97/2000/XP & 5.0/95
Gnumeric_Excel:excel_biff7 | MS Excel (tm) 5.0/95
Gnumeric_Excel:excel_biff8 | MS Excel (tm) 97/2000/XP
Gnumeric_dif:dif | Data Interchange Format (*.dif)
Gnumeric_sylk:sylk | MultiPlan (SYLK)
Gnumeric_html:roff | TROFF (*.me)
Gnumeric_html:latex_table | LaTeX 2e (*.tex) table fragment
Gnumeric_html:latex | LaTeX 2e (*.tex)
Gnumeric_html:xhtml_range | XHTML range - for export to clipboard
Gnumeric_html:xhtml | XHTML (*.html)
Gnumeric_html:html40frag | HTML (*.html) fragment
Gnumeric_html:html40 | HTML 4.0 (*.html)
Gnumeric_html:html32 | HTML 3.2 (*.html)
Gnumeric_OpenCalc:odf | ODF/OpenOffice with foreign elements (*.ods)
Gnumeric_OpenCalc:openoffice | ODF/OpenOffice without foreign elements (*.ods)
Gnumeric_stf:stf_csv | Comma separated values (CSV)
Gnumeric_stf:stf_assistant | Text (configurable)
Gnumeric_XmlIO:sax | Gnumeric XML (*.gnumeric)
Gnumeric_pdf:pdf_assistant | PDF export
A: Gnumeric's preferences allow you to set a compression level of 0 which results in uncompressed files.
A: there is no "non-compressed" option, i believe. I searched the documentation and the UI, no way. but you are no completely off, good comparison tools have so called 'converters', or even support un-gzipping on the fly when comparing.
The tool I work for, ECMerge, has a gzip converter, you just need gzip installed in your system path (or specify it by hand in the configuration screen), you will need to add *.gnumeric to the supported pattern for GZip converter and ECMerge will diff the gnumeric files content. There is no 'gzipped merge' though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is this a good structure for my jQuery scripts? I want to keep my scripts organized in one .js file for all my site (I have a mess right now), something like namespaces and classes in C#...
(function ($) {
//private variables
$.divref = $("#divReference");
//Namespaces
window.MySite = {};
window.MySite.Home = {};
window.MySite.Contact = {};
//Public function / method
window.MySite.Home.Init = function(params){
alert("Init");
MySite.Home.PrivateFunction();
$.divref.click(function(){
alert("click");
});
};
//private function / method
MySite.Home.PrivateFunction = function(){
alert("Private");
};
})(jQuery);
Is this an idiomatic layout in jQuery and JScript?
A: I'll go ahead and post my comment as an answer, though I'm not 100% it addresses your questions about c# namespaces and their parallels in JavaScript (I'm no c# programmer). You're not actually creating private variables because you're attaching them to the $ Object that will exist after this function finishes. If you want private variables you need to use a closure. Those look something like this:
var myObject = function () {
var innerVariable = 'some private value';
return {
getter: function () {
return innerVariable;
}
}
}()
If you attempt to access myObject.innerVariable it will return undefined but if you call myObject.getter() it will return the value correctly. This concept is one you will want to read up on in JavaScript, and for programming in general. Hope that helps.
A: This is more how I would implement the pattern you are trying to do:
// MySite.Home Extension
window.MySite =
(function ($, root) {
//private variables
var $divref = $("#divReference");
//private function / method
var privateFunction = function(){
alert("Private");
};
root.Home = {};
// Public variable
root.Home.prop = "Click"
//Public function / method
root.Home.Init = function(params){
alert("Init");
private();
$divref.click(function(){
alert(root.Home.prop);
});
};
return root;
})(jQuery, window.MySite || {} );
// MySite.Contact Extension
window.MySite =
(function ($, root) {
root.Contact = {};
// More stuff for contact
return root;
})(jQuery, window.MySite || {} );
The first change is splitting each "namespace" into its own Module pattern, so private variables wont bleed from namespace to namespace (if you do intend them to be private to the namespace, which would be more C# esque). Second is rather than accessing window.MySite, pass in the object that you want to extend (in this case I'm calling it root). This will give you some flexibility.
Your private methods weren't really private. To make a private method, you just want to make a function var that it bound in the closure, but not assigned to a property on the externally visible object. Lastly, you probably don't want to use $.somegarbage. Like mentioned in a comment, you are adding a property to the $ object, which will still be there when the closure is done. If you wanted something close, I would just use $somegarbage which some people seem to like to do, but any variable name will work for private variables, just as long as the variable is bound in the closures scope (not somewhere else)
You are on the right track...
A: you might want to read up on the Module pattern (more) and closures in javascript to prevent polluting the global namespace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Event Handling with Timer to Poll Hardware I need to request values using functions in a DLL provided by the manufacturer of my particular piece of hardware (a weather station). I'm new to C#, and the concepts of delegates/events are tough to wrap my head around. Nonetheless, I've managed to pull the functions from the DLL and verify that data makes it through. My issue is with polling the instrument periodically with a Timer. In Initialize(), an object is instantiated, but the event isn't handled leaving the object null. I'm out of ideas, and would like some advice!
public class HardwareData : EventArgs
{
public float OutsideTemp { get; set; }
public int OutsideHum { get; set; }
public float WindSpeed { get; set; }
public int WindDirection { get; set; }
}
public class Hardware : IDisposable
{
private static Hardware v;
private System.Timers.Timer hardwareTimer;
private int counter = 0;
private static readonly object padlock = new object();
public static Hardware Instance
{
get
{
lock (padlock)
{
if (v == null)
v = new Hardware();
return v;
}
}
}
public void Initialize()
{
try
{
hardwareTimer = new System.Timers.Timer(500);
hardwareTimer.Elapsed += new ElapsedEventHandler(hardwareTimer_Elapsed);
HardwareVue.OpenCommPort_V(3, 19200); //COM port and baud rate are verified.
hardwareTimer.Start();
}
catch (Exception ex)
{
throw new InvalidOperationException("Unable to initialize.", ex);
}
}
public HardwareData LastHardware { get; set; }
void hardwareTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
counter += 1;
Console.WriteLine(counter);
HardwareVue.LoadCurrentHardwareData_V();
HardwareData v = new HardwareData()
{
OutsideTemp = HardwareVue.GetOutsideTemp_V(),
OutsideHum = HardwareVue.GetOutsideHumidity_V(),
WindSpeed = HardwareVue.GetWindSpeed_V(),
WindDirection = HardwareVue.GetWindDir_V()
};
LastHardware = v;
}
catch (Exception) { }
}
public void Dispose()
{
HardwareVue.CloseCommPort_V();
hardwareTimer.Stop();
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Hardware test = new Hardware();
try
{
if (test != null)
{
test.Initialize();
test.Dispose();
Assert.AreEqual(0, test.LastHardware.OutsideHum);
}
}
catch (NullReferenceException ex)
{
Console.WriteLine("Object is null.");
}
// Console.WriteLine(test.LastHardware.OutsideHum);
}
}
A: When working with timers, you need to enable the timer and make sure the events are rasied:
hardwareTimer.Enabled = true;
hardwareTimer.CanRaiseEvents = true;
For Reference: Timers on MSDN
Edit
In addition to the other comments to both the OP's question and this answer, the issue with the LastHardware being null is due to the property never being instantiated before the timer initially fires. To resolve this, you should instantiate the LastHardware property in the default constructor (or in the Initialize method):
public Hardware()
{
LastHardware = new HardwareData();
}
Of course, you'd want to set some default values upon instantiation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting the current price of a stock symbol I would like to write a java program or method that simple gets the current price of a given stock symbol. I have scoured through the Google and Yahoo finance APIs and do not think these have what I am looking for. Does anyone know how I can accomplish this or a good place to look?
A: It looks like Yahoo has an API to export stock data in CSV format: Downloading Yahoo Data.
For example, the following URL:
http://finance.yahoo.com/d/quotes.csv?s=GOOG+MSFT&f=snd1l1yr
Produces the following CSV file:
"GOOG","Google Inc.","9/22/2011",520.66,N/A,19.45
"MSFT","Microsoft Corpora","9/22/2011",25.06,2.46,9.66
No idea about delay, presumably it doesn't fit your needs. I would imagine you'd have to pay for a service that provides stock price information in a timely manner.
A: this should be comment but
@Mike are you meaning price or another Securities indicators ???,
there are lots of Boerses, Public Contributors and Market Makers, and by default are required to be distributed on a daily basis these values, some of them on 10 minutes average
you have five choises, sure depends of your Whatever requirents
1) buy contract with some of Market Makers
2) buy contract with Bloomberg or Reuters (altogether covered whole Market)
3) buy B*S** for cent, but with same * prices,
4) download (by default free) prices from lots of Boerses, Public Contributors, Market Makers, but those prices are averages (for example on Hour'Wool),
5) lots of Banks, Funds and Insurancies (own market and quotations) distribute these indicators but again only their last/opening/ close price or some averages price
A: This certainly brings back price (and lots more besides):
http://www.google.com/finance?q=NYSE:UTX
You just might have to work harder than you imagined in order to get it. What you're looking for is a spoon that fits your mouth, but it's not fair to say that Google and Yahoo won't give you stock price for a given symbol.
A: Since you say you're looking for real-time data, I'd look at online brokerages, such as Interactive Brokers. You'll need to open an account and in all likelihood you won't be able to republish the data (but you haven't stated that you were going to).
A: If you are looking for something closer to real time, you could scrape the data from the HTML returned by http://www.google.com/finance?q=NYSE:UTX using something like Tag Soup
A: I've tried doing this for a school project, you can't do real time unless you pay for using a server that pulls data from the NYSE. What we did was pull it from the yahoo using their api, but there's a slight delay and there were many instances where we got temp banned.
A: Generally speaking, you won't be able to escape the 20 minute delay without an account of some sort. There are vendors (e.g., TC 2000 from Worden) but no public free API. [I have no relationship to Worden or any other service.]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to query for action instances? In the beta of the open graph, I see how you can access action instances if you know their IDs:
http://developers.facebook.com/docs/beta/opengraph/actions/
How do you find the action instances in the first place? I don't see any new collections in the graph api that associate a user with their action instances.
A: It looks like the action collections do exist with the application namespace prefixed. E.g. an app that has a namespace of "example_org" and an action named "read" would be accessed at:
https://graph.facebook.com/me/example_org:read
I haven't figured out any way to query for which action collections exist. I tried adding ?metadata=1, but that didn't show them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: socket connection in j2me using GPRS I am trying to open a socket connection in j2m2 on Nokia C5 device using my Airtel GPRS connection. I am using following lines of code.
SocketConnection connection=(SocketConnection)Connector.open("socket://www.cse.iitd.ernet.in:80");
It stucks here and never proceeds, no error is shown and no timeout.
I am able to open http connection using following code on the same device
HttpConnection connection=(HttpConnection)Connector.open("http://www.cse.iitd.ernet.in:80");
If some one could please help me out in this.
A: Are you sure no exception is thrown? Many (most) J2ME handsets block socket connections to port 80 for some reason - I don't really understand why to be honest. But if that were happening I would expect a SecurityException.
If you have control of the server, I suggest setting it up for some other port instead.
A: FOR NOKIAS IT WAS PRETTY SIMPLE:
Make sure the settings on your phone have been correctly configured to enable GPRS. There are two ways to do this:
Some providers will send GPRS settings to the handset upon receiving an activation request via SMS. Depending on the provider, it may take a while for the settings to activate.
Set up GPRS manually (process described below for many kinds of phones).
See below for country specific information
Manual Setup Process: Common process
1. Click “Menu”
2. Scroll to “Settings” and click.
3. Scroll to “Configuration” and click.
4. Scroll to “Personal configuration setting” and click.
If there is an existing, configuration, click “Options” and click “Delete”.
5. Click “Options”.
6. Scroll to “Add New” and click.
7.Select “Web”.
8. Scroll to “Use preferred access point” and verify it says “Yes”.
9. Click “Back”
10. Scroll to “My web” which you’ve just created.
11. Click “Options” and click “Activate”.
12. Click “Back”.
13. Now in the main menu of the “Configuration Settings” page,
scroll to “Default configuration setting” and click.
14. Scroll “Personal configuration” and click.
15. Then, click “Default”.
16. Now we need to create an access point.
17. Scroll to “Personal configuration setting” and click.
18. Click “Options” and “Add New”.
19. Select “Access Point”.
20. Click “Access Point Settings”.
21. This step does not show up in all phones (if it doesn't skip to Step 22): Verify the first list item, “Data Bearer”, is “Packet Data”, if not click and change it to “Packet Data”. (If you can't find it here, go back to the original "Settings" menu and choose "Connectivity" instead of "Configuration", there is an option "Packet Data" -> "Packet Data Settings" --> "Edit Active Access Pt" --> "Packet Data Acc. Pt." )
22. Scroll to “Bearer Settings”, and click
Scroll to “Packet data access point” and click.
23. Delete “internet” and type in your local network provider's access point name (APN) (for example, the access location for mCel in Mozambique is “isp.mcel.mz”.)
24. See below for known APNs.
25. Click “Ok”.
26. Click “Back” a few times to get to the “Personal Accounts” menu. In this menu, you should see “My web” and “My access point” which are the settings you’ve just created.
27. Scroll to “My access point” which we just created.
28. Click “Options”.
29. Click “Activate”.
30. Click “Back”
31. Now “Configuration Setting Page”, we need to verify “My access point” is listed under “Preferred access point”.
32. Scroll to “Preferred access point” and click.
33. Scroll and click “My access point”.
34. Then, scroll to “Activate default in all apps” and click. (This will apply the settings you created to all applications on the phone, including CommCare).
35. Make sure to perform a CommCare "network test" before before you distribute the phone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: popViewController works on one view, not another I have a couple of UIViewControllers and related nib files. I can call either of them from another UIView controller ("StartController") by pressing a button for each one. Each of the called UIViewControllers had a button which I've connected up to a related method which pops the view off the stack, like so:
[self.navigationController popViewControllerAnimated:YES];
The methods for both are coded in the their respective implementation classes, like this:
- (IBAction) validateEntries{
// some validation goes here
[self.navigationController popViewControllerAnimated:YES];
}
and this:
-(IBAction) returnToStart {
NSLog(@"returnToStart method called");
[self.navigationController popViewControllerAnimated:YES];
}
They both have the methods declared in their respective interface files:
-(IBAction) returnToStart;
and
-(IBAction)validateEntries;
And the buttons in the nibs are connected to these respectively via the "touch up inside" event. The first one works fine, but the second doesn't - it doesn't even call the method. I don't get what could be causing this. Any ideas?
A: sounds like you dont actually have the button hooked up to the right method inside IB if the method isnt ever being called
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can WinRT application use obfuscation? All Metro applications must be inspected before distribution through Windows 8 AppStore. Does this mean it will not be allowed to use code obfuscation? Or it is still possible, and only some specific aspects are going to be monitored during such inspection?
A: This is an armchair answer with some things that come to mind:
*
*Even a C++ application can still be anazlyed if it depends on dynamic linking to a runtime or API, which is the case with WinRT applications. Microsoft approval can in theory include automated or human guided testing of your app using a special sandbox and/or OS hooks capable of detecting if your application attempts certain prohibited operations.
*Under the hood, C++ apps for WinRT are more like native C++ apps than C++/CLI, so obfuscation is not needed to the degree that it is for C#, all things being equal.
*You can still build C# apps that target WinRT, but your code will still be compiled to CIL and run within the CLR (more or less), invoking WinRT through wrappers that Microsoft provides. Because it's CIL, the question of obfuscation should be equivalent to that of C#/.NET obfuscation in general.
A: Here are some facts:
*
*Marketplace for WP7 allows C# apps be obfuscated (even MS he advises
doing so) and I don't see any reason why Windows AppStore would ban
such apps.
*It is almost certain that some vendors will provide compatible C++
obfuscator.
*You should care about your clients not crackers. :)
*a lot of hacks for code obfuscation will be banned.
Remember, if you have some logic that you want to hide, make a webservice and consume it in your client app. Better spend your time building better app, fixing bugs etc.
No dice, if someone has access to the binaries is just a matter of time when someone cracks it.
A: Obfuscation is still possible for WinRT. The inspection made by the Application Certification Kit cover lot of aspects including metadata and IL verification. Just like the old peverify did.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Emulator vs Phone which one to rely on? I am almost done with my app..when i run it on the emulator ,at certain points,
it is very slow and what i see is undesirable..when I run the same on my phone (xperia X8)
it works fine.
I really tried understanding why this is happening but of no avail!
What should I do now? run some more tests and try optimizing or just
release it in the market?
Is what I am seeing expected? Any info will be appreciated
A: You really should buy as many Android phones as you can. You definitely should have one with a physical keyboard, one slate phone, and one for the lowest API you are supporting. Personally, I have G1, Droid, and Nexus S that I test my apps on. Its so much faster than the emulator and easier to use. Its also a better metric of how your app works due to it being on actual hardware.
A: The emulator will always be slower than a real device (most likely, slower than any real device), so don't worry too much about it.
However, due to it's slowness, it can highlight areas where you may want to spend some time optimising your code that you may not necessarily find on your hardware. This is especially true on portable devices with limited CPU power, resources, and electrical power available.
It may be worth trying to find out what is causing the slowdowns in the emulator - if it's regular enough and accompanied by (for example) high CPU usage, then while a physical device may handle it better, you may find that you are unnecessarily consuming battery power and your users may not thank you for that.
A: The emulator is generally much slower than a physical device, so it's not a problem with your application. As long as it runs well on your phone it should be fine.
A: I agree with everything dbaugh said. At least at the time of this writing, the emulator is of limited use. Google has acknowledged the limitations of the current emulator and indicated they are working to revamp it. But until that happens. Stick to hardware testing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Quirky Google Chrome Beta/Dev channel behavior persists even after uninstalling and reverting to stable We have several FogBugz customers who have reported an error in Chrome where if the user presses Enter in an edit box, the edit box will lose focus and they'll have to click back in to the box for it to gain focus.
All users reporting this error (that we're aware of) have mentioned using Chrome Beta. We don't support Chrome Beta, so we advise downgrading to Chrome Stable. We can't repro the bug on Stable.
One of our users uninstalled Beta and installed Stable. He tried again and was again able to reproduce the bug, even after clearing his browser's cache (with no tabs open) on Stable.
In a related scenario, another member of our team noticed quirky behavior in Chrome persisting when switching from Chrome Dev to Chrome Stable. He also cleared his cache and noticed the behavior persisting in Chrome.
Have any other web developers experienced this kind of behavior in Chrome with customers using their web applications? If so, is there anything you can do within your application to help users and/or do you know of a way to completely "wipe" Chrome and revert it to the Stable version? (at the moment, the latter option is preferred).
A: Moving up versions should be okay, since Chrome is designed to upgrade smoothly.
Moving down versions (like dev to stable) can be problematic, since there's really no provision for older versions of Chrome to understand new versions of the user directory.
If you want a fresh start, you can wipe your entire user data directory. However, since this directory contains everything about the user (caches, saved passwords, apps/extensions, etc), all of that will be lost.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it bad practice to depend on the .NET automated garbage collector? It's possible to create lots of memory-intensive objects and then abandon references to them. For example, I might want to download and operate on some data from a database, and I will do 100 separate download and processing iterations. I could declare a DataTable variable once, and for each query reset it to a new DataTable object using a constructor, abondoning the old DataTable object in memory.
The DataTable class has easy built-in ways to release the memory it uses, including Rows.Clear() and .Dispose(). So I could do this at the end of every iteration before setting the variable to a new DataTable object. OR I could forget about it and just let the CLR garbage collector do this for me. The garbage collector seems to be pretty effective so the end result should be the same either way. Is it "better" to explicitly dispose of memory-heavy objects when you don't need them, (but add code to do this) or just depend on the garbage collector to do all the work for you (you are at the mercy of the GC algorithm, but your code is smaller)?
Upon request, here is code illustrating the recycled DataTable variable example:
// queryList is list of 100 SELECT queries generated somewhere else.
// Each of them returns a million rows with 10 columns.
List<string> queryList = GetQueries(@"\\someserver\bunch-o-queries.txt");
DataTable workingTable;
using (OdbcConnection con = new OdbcConnection("a connection string")) {
using (OdbcDataAdapter adpt = new OdbcDataAdapter("", con)) {
foreach (string sql in queryList) {
workingTable = new DataTable(); // A new table is created. Previous one is abandoned
adpt.SelectCommand.CommandText = sql;
adpt.Fill(workingTable);
CalcRankingInfo(workingTable);
PushResultsToAnotherDatabase(workingTable);
// Here I could call workingTable.Dispose() or workingTable.Rows.Clear()
// or I could do nothing and hope the garbage collector cleans up my
// enormous DataTable automatically.
}
}
}
A: @Justin
...so, to answer your question, No. It is not a bad practice to depend on the .NET Garbage Collector. Quite the opposite in fact.
It is a horrible practice to rely on the GC to cleanup for you. It's unfortunate that you are recommending that. Doing so, can very likely lead you down the path of have a memory leak and yes, there are at least 22 ways you can "leak memory" in .NET. I've worked at a huge number of clients diagnosing both managed and unmanaged memory leaks, providing solutions to them, and have presented at multiple .NET user groups on Advanced GC Internals and how memory management works from the inside of the GC and CLR.
@OP:
You should call Dispose() on the DataTable and explicitly set it equal to null at the end of the loop. This explicitly tells the GC that you are done with it and there are no more rooted references to it. The DataTable is being placed on the LOH because of its large size. Not doing this can easily fragment your LOH resulting in an OutOfMemoryException. Rememeber that the LOH is never compacted!
For additional details, please refer to my answer at
What happens if I don't call Dispose on the pen object?
@Henk - There is a relationship between IDisposable and memory management; IDisposable allows for an semi-explicit release of resources (if implemented correctly). And resources always have some sort of managed and typically unmanaged memory associated with them.
A couple of things to note about Dispose() and IDisposable here:
*
*IDisposable provides for disposal of both Managed and Unmanaged memory. Disposal of Unmanaged memory should be done in the Dispose Method and you should provide a Finalizer for your IDisposable implementation.
*The GC does not call Dispose for you.
*If you don't call Dispose(), the GC sends it to the Finalization
queue, and ultimately again to the f-reachable queue. Finalization
makes an object survive 2 collections, which means it will be
promoted to Gen1 if it was in Gen0, and to Gen2 if it was in Gen1.
In your case, the object is on the LOH, so it survives until a full
GC (all generations plus the LOH) is performed twice which,
under a "healthy" .NET app, a single full collection is
performed approx. 1 in every 100 collections. Since there is lots of
pressure on the LOH Heap and GC, based on your implementation, full
GC's will fire more often. This is undesirable for performance
reasons since full GC's take much more time to complete. Then there
is also a dependency on what kind of GC you're running under and if
you are using LatencyModes (be very careful with this). Even if
you're running Background GC (this has replaced Concurrent GC in CLR
4.0), the ephemeral collection (Gen0 and Gen1) still blocks/suspends threads. Which means no allocations can be performed during this
time. You can use PerfMon to monitor the behavior of the memory
utilization and GC activity on your app. Please note that the GC
counters are updated only after a GC has taken place. For
additional info on versions of GC, see my response to
Determining which garbage collector is running.
*Dispose() immediately releases the resources associated with your object. Yes, GC is non-deterministic, but calling Dispose() does not trigger a GC!
*Dispose() lets the GC know that you are done with this object and its memory can be reclaimed at the next collection for the generation where that object lives. If the object lives in Gen2 or on the LOH, that memory will not be reclaimed if either a Gen0 or Gen1 collection takes place!
*The Finalizer runs on 1 thread (regardless of version of GC that is being used and the number of logical processors on the machine. If you stick alot in the Finalization and f-reachable queues, you only have 1 thread processing everything ready for Finalization; your performance goes you know where...
For info on how to properly implement IDisposable, please refer to my blog post:
How do you properly implement the IDisposable pattern?
A: Ok, time to clear things up a bit (since my original post was a little muddy).
IDisposable has nothing to do with Memory Management. IDisposable allows an object to clean up any native resources it might be holding on to. If an object implements IDisposable, you should be sure to either use a using block or call Dispose() when you're finished with it.
As for defining memory-intensive objects and then losing the references to them, that's how the Garbage Collector works. It's a good thing. Let it happen and let the Garbage Collector do its job.
...so, to answer your question, No. It is not a bad practice to depend on the .NET Garbage Collector. Quite the opposite in fact.
A: I also agree with Dave's post. You should always dispose and release your database connections, even if the framework you are working has documentation that it is not needed.
As a DBA who has worked with MS SQL, Oracle, Sybase/SAP, and MYSQL, I have been brought in to work on mysterious locking and memory leaking that was blamed on the database when in fact, the issue was because the developer did not close and destroy their connection objects when they were done with them. I've even seen apps that leave idle connections open for days and it can really make things bad when your database is clustered, mirrored, and with Always on recovery groups in SQL Server 2012.
When I took my first .Net class the instructor taught us to only keep database connections open while you are using them. Get in, get your work done and get out. This change has made several systems I have help optimize a lot more reliable. It also frees up connection memory in the RDBMS giving more ram to buffer IO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: 'ascii' codec can't decode byte (problem when using django) I wrote a simple html parsing class in python and it seems to work fine and then I try to use it with django and I get this error:
'ascii' codec can't decode byte 0xc2 in position 54465: ordinal not in range(128)
which is strange because I added this: # encoding: utf-8 to the top of my class. I don't really know much about encoding but can someone perhaps give me an idea of what's going here? Btw, I also insured that the source html was already in utf-8. Thanks!
A: Try putting that line at the top of your file. According to PEP 263, it has to be in the top two lines.
A: okay, I got it. All I needed to do was include # -*- coding: utf-8 -*- in the django view as well and that solved it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ simple threading question I'm writing a simple producer/consumer program to better understand c++ and multithreading.
In my thread that ran the consumer i had these first two lines:
pthread_cond_wait(&storageCond, &storageMutex);
pthread_mutex_lock(&storageMutex);
But the program got stuck, probably a deadlock.
Then i switched the lines:
pthread_mutex_lock(&storageMutex);
pthread_cond_wait(&storageCond, &storageMutex);
And it worked.
Can someone please help me understand why this worked and the former did not?
Thank You.
A: From the pthread_cond_wait manpage (http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html):
They are called with mutex locked by the calling thread or undefined
behaviour will result.
I suggest that you use some good wrapper library like boost::threads or when you have access to C++11 you use the std:: threading facilities. Since they use things like RAII they are much easier to handle, especially when unexperienced in threads programming.
A: This is a little simplified, but you basically need a lock on the mutex you're using in order to do the condition wait - its like a multithreading race condition safeguard. If you need a good description of why, check the UNIX man page with "man pthread_cond_wait" and it gives a nice long speech :)
pthread_cond_wait(&storageCond, &storageMutex); //Wants mutex you don't have locked.
pthread_mutex_lock(&storageMutex); //Get mutex after its too late.
pthread_mutex_lock(&storageMutex); //Get mutex first.
pthread_cond_wait(&storageCond, &storageMutex); //Do cond wait with mutex you have.
A: Once a thread resumes from a condition variable wait, it re-aquires the mutex lock. That's why the first sample program got stuck.
The idea is to always do a cond_wait() inside the mutex lock. The cond_wait() will relinquish the lock and atomically start waiting (so that you don't miss a cond_signal() from another thread) and when signaled, cond_wait() will reacquire the mutex to ensure that your critical section has only a single thread running in it.
HTH, this scheme of locking is known as Monitor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Importing a subversion repository I'm having problems: I create a new repository in Subclipse that points to a URL. When I check out the code and it creates a Flex Builder project, I am getting errors that relate to issues with the .actionscriptProperties and .flexProperties files.
So, I was told to just create a new FB project and point the src folder to where SVN is on my machine.
I'm new at this. But I'm guessing that until I do something like import my repository....it's nowhere on my machine. But when I imported it, it appeared to try and take every existing FB project I had and add it to SVN. That's not what I want.
How do I do this right? What am I missing?
Thanks for any helpful tips!
A: *
*right click in the navigator, new -> other
*Under SVN, select Checkout projects from SVN
*Select the location of your repo with the FB project, hit next
*there should only be one radio button available, if not, you didn't select the correct trunk location with the project files
*Check "Check out HEAD revision", depth: fully recursive, uncheck ignore externals, check allow unversioned obstructions
*click "finish"
If it complains about anything, let me know what the error is. You may have a different default, for instance, if the project was configured using "default SDK" and the project creator's default SDK was different than your default SDK you'd get errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to generate QR codes using library in .Net I am planning to explore on QR code generation . I saw the google api http://chart.apis.google.com/chart?cht=qr&chs=75x75&chl=test and its pretty impressive. But it works only for URL's and small data's. So i am thinking about writing a .net app to generate the QR code. So any information on libraries to start with ,will be helpful.
Thanks,
A: It does not just work for URLs. You can put whatever text you want as an argument (just URL-encode it correctly). It also works for any data size that QR codes can support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detect anytouch inside subView (other than a button) touchesEnded I have a subview, which also contains a UIButton.
Now, once I enter the touchesEnded, I want to execute some instructions only if the main subview was touched (and not the UIButton).
Is there a way to do this??
Thanks in advance.
ezbz
A: Use write your logic using these events ,by comparing the coordinates accordingly .
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *aTouch = [touches anyObject];
CGPoint point = [aTouch locationInView:self.view];
NSLog(@"X%f",point.x);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JNI and UnsatisfiedLinkError I'm doing my first steps with JNI and tried to write a simple Hello Java program, but it fails with this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: HelloJava.dostuff()V
at HelloJava.dostuff(Native Method)
at HelloJava.main(HelloJava.java:12)
This is my Java class:
class HelloJava {
private native void dostuff();
static {
System.loadLibrary("HelloJavaDLL");
}
public static void main(String[] args) {
System.out.println("This is from java.");
HelloJava j = new HelloJava();
j.dostuff();
}
}
The HelloJava.c is generated using javah -jni HelloJava.
The C implementation looks like this:
#include <stdio.h>
#include <jni.h>
#include "HelloJava.h"
JNIEXPORT void JNICALL Java_HelloJava_dostuff
(JNIEnv *env, jobject this)
{
printf("And this comes from C ! :)\n");
}
I compiled it on Windows using gcc to a shared library (.dll).
Now running the Java .class File the Exception from above occurs. Can you tell me why this error appears ?
And by-the-way, can you tell me how I can use JNI with C++ ?
UPDATE
Maybe you want to try it yourself ? I really can't find the issue.Here is a link to MediaFire where you can download a .zip file containing all files (event the compiled ones).
The retried everything but it's still the same issue.
Theese are the steps I did:
*
*Write Hello.java
*Compile Hello.java using javac Hello.java
*Create a header file using javah -jni Hello
*Write the Hello.c file
*Compile the Hello.c file using
gcc Hello.c -shared -o Hello.dll -I"C:\Java\jdk1.7.0\include" -I"C:\Java\jdk1.7.0\include\win32"
*Execute Hello.class using java Hello
Thanks.
SOLUTION
Adding -Wl,--kill-at to the gcc command fixes the problem, according to this question here.
Thanks to A.H. for his help !
A: Please check:
*
*The filename of your library is HelloJavaDLL.dll (on Windows)
*The directory of the DLL is either in the library search path (i.e. PATH environment variable) or supplied to java with -Djava.library.path=C:\WhereEverItIs.
The second question: JNI supports both C and C++ right out of the box. If you look into the generated header file and in the jni.h file you will see this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ajax post works in chrome but no data recieved on server with ie and firefox I need to retrieve and process a image (png) generated by a flash application. When a user clicks a link I :
var dataImgBase64 = document.getElementById("flashApp").getThumbnail();
So the flash app sends me a image in base64. Then I:
var params = 'b=' + encodeURIComponent(dataImgBase64);
$.ajax({
type: "POST",
url: "arrival.php",
data: params,
success: function (msg) {
$("#ppp").html(msg);
}
});
heres is arrival.php:
$data = $_POST['b'];
echo strlen($data);
In chrome I get the expected size of around 900k but in ie and firefox I get 0. I checked with firebug and I do send the post data but it cuts in the middle with a message that firebug as reached its post size limit.
Is it possible to do what I want the way I want? If not what else could I do? I tried playing around with some settings like:
processDataBoolean: false,
contentType: "application/x-www-form-urlencoded",
Nothing worked.
editL the server is a shared hosting account on linux.
A: Since no one can help me I helped myself! After testing I found out I can send in a single ajax request 1000000 '1's but it will fail on all browsers for 1000001 '1's.
I have a hard time finding information because everywhere I look on the net its talks about a file upload dialog (and I got my data from a flash pluguin on the webpage very different context.
So as of now my solution is to split the data and send it thru many ajax connections.
I'll leave the question open in case someone passes by and has a better answer.
A: Why do you do it with ajax? Can't you just insert the specfied path in the src attribute in a img tag?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the code that creates a memory address in Xcode? I am trying to find the source code that causes some leaks reported in Instruments, but all I get is the Address. Is there a way to take this Address, or use some other feature in Instruments, to then locate where the offending object is located in the actual source code?
A: I believe this contains the answer to your question (although it's not a 'duplicate question').
Can I set a breakpoint on 'memory access' in GDB?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CakePHP Extending Controllers and Overriding Methods I'm working on an Application, and most of the code will be returning in future project. So my idea was to create a structure such as this:
App/
- controllers
- models
- ...
Cake/
My_Custom_Folder/
- controllers
- models
- ..
Basically I want to add another folder next to the normal App folder and use App::build() to set the paths of the extra folder controllers, models, etc.
Now the goal is to only use the App layer when my project requires custom work, I have succeeded in that and CakePHP takes the controllers in the App over the ones in My_Custom_Folder if they are there.
For example: If i have a pages_controller.php in My_Custom_Folder AND one in my App folder, it will use the one in the App folder. If there is none in the App folder, then it uses the one in My_Custom_Folder.
However that is not how I want it to be working, what I want to do is extend the controllers from My_Custom_Folder so I can override methods and/or add new ones.
So far I have tried the following:
/My_Custom_Folder/pages_controller.php
Class PagesController Extends AppController {
Public $name = 'Pages';
Public Function home(){
echo 'default home';
}
}
/App/pages_controller.php
require_once(ROOT . DS . 'My_Custom_Folder' . DS . 'controllers' . DS . 'pages_controller.php');
Class AppPagesController Extends PagesController {
Public Function home(){
echo 'Override default home';
}
}
Unfortunately this doesn't work, it still loads the default home. Basically what i want is for it to load all methods from the My_Custom_Folder and allow the App folder to override methods and/or add methods the same way as you would by extending the Appcontroller. It does load both files, but it's not overriding any functions.
A structure like this would be great to maintain the same code over many projects and allow me to easily add new functionality for all projects by just updating the My_Custom_Folder and it would not break projects that have some customized code.
Any help on this would be greatly appreciated.
A: Take a look at plugin or behaviors or components or helpers. With plugins you can put them in one common folder for all apps (just like your My_Custom_Folder).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: localized routes solution I built a french/english app and I would like to use the same controller/view for both language but to have a different route that is map to the current language. Let say I have website.com/Account/Register that return to my Account controller and Register action, I would love to have a route that is website.com/Comptes/Inscription. I know that I can add a custom route in the RegisterRoute section like so :
routes.MapRoute(
"AccountFr", // Route name
"comptes/inscription", // URL with parameters
new { controller = "Account", action = "Register" } // Parameter defaults
);
But it will need a lot of [boring] code to write all the possibles routes and also, I think it won't work when I will use T4MVC as @Url.Action(MVC.Account.Register()) will return /Account/Register no mater if I'm in french or in english.
Anyone as suggestions/ideas for this problem?
Thanks!
EDIT
Since it does not seem to have a good solution using T4MVC does anyone have an other good solution?
A: Unfortunately, this won't easily work with T4MVC. The root of the problem is that when going through T4MVC, you can't pick a specific route. Instead, the route gets selected based on the Controller, action and parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get realtime updates from database into ajax based asp.net web page from sql server database.. like facebook I am trying to solve a problem. I have a asp.net repeater that shows a User friends that are obtain from sql server database with their statuses.
Some of the friends could be online and some of them could be offline at the time of getting results from database and i mark then offline/online. Now i need a mechanism when the user in the list goes online or offline, i should update the status of the friends in the repeater. 2
The only idea i got is to put timer and call the stored procedure to get friends list after every 10 seconds to check their statues but this mechanism has 2 BIG problems
1- Too many database calls against 1 user (1 DB call every 10 sec or so) .. just imagine if the site has 10000 users i cant use this technique.
2 -This technique is slow as well, as i have to get results and loop through every user in the repeater and check/ update his/ her status...... ust imagine if the site has 10000 users
i have seen in Facebook like they do this on real-time bases and i want almost similar kind of mechanism ... how can i do this??? any code or tutorial from .net point of view will be appreciated
A: You could do a sqldependency which would "tigger" when a row is updated instead of pounding the database over and over again. A push system instead of a pull system. But with that said, to read with (nolock) is not expensive at all if the tables are indexed well and their stats up to date.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Class CSS property return How would one return a class computed CSS property/property array?
Like, if I have a class defined in CSS:
.global {
background-color: red;
color: white;
text-shadow: 0px 1px 1px black;
}
It's applied on the go with javascript to an element. Now I want to change this elements childrens' color to parents' (.global) element background-color.
And is there a way to read CSS properties from a previously defined class in a style tag or externally included *.css?
Something like, getCSSData([span|.global|div > h1]); (where the passed variable is a CSS selector, that gets data for exactly matching element) that would return an object with each property in it's own accessible variable?
Something like:
cssdata = {
selector : '.global',
properties : {
backgroundColor : 'red',
color : 'white',
textShadow : '0px 1px 1px black'
// plus inherited, default ones (the ones specified by W3..)
}
}
And the usage for my previously explained example would be:
// just an example to include both, jQuery usage and/or native javascript
var elements = $('.global').children() || document.getElementsByClassName('.global')[0].children;
var data = $('.global').getCSSData() || document.getCSSData('.global');
return elements.css('color', data.properties.backgroundColor) || elements.style.backgroundColor = data.properties.backgroundColor;
Is there a function built in already in javascript/jquery and I've overlooked it?
If not, what should I look for to make one?
P.S. Can be DOM Level 3 too.. (HTML5'ish..)
A: If you want to grab the background color of the parent element and then apply that color to the font of all of it's children you could use the following code.
$(document).ready(function(){
var global = $('.global');
var bgColor = global.css('background-color');
global.children().css('color', bgColor);
};
Here's an example on jsFiddle.net
A: You can access the computedStyle of an element which includes all inherited style values, here is a example that outputs the computed style of a div element in the console.
<script type="text/javascript">
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", listComputedStyles, false);
}
function listComputedStyles() {
var element = document.getElementById("myDiv");
var properties = window.getComputedStyle(element, null);
for (var i = 0; i < properties.length; i++)
{
var value = window.getComputedStyle(element, null).getPropertyValue(properties[i]);
console.log(properties[i], value);
}
}
</script>
<div id="myDiv" style="background-color: blue; height: 500px;"></div>
You can find more information here: http://help.dottoro.com/ljscsoax.php
A: If I understand your question correctly, you'd like to find a general approach to modifying a class; and to have that modifcation affect all of the instantiations of that class. This was the subject of another detailed discussion on SO over here.
There turned out to be an extremely interesting and useful treatment of classes that works in almost all browsers, notably excepting IE8 and below.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Configurable Resource - Design patterns First of all bit of background.
We are developing an application which receives messages from n number of sources. The source may be a messaging queue, an FTP location, a webservice call to a particular service or any possible orchestration layer we can think of. I have been given a task to design and develop a module which will act as a configurable resource manager which will work in between the module which process the message and application which sends the message.
Could you please suggest any design patterns or any best practices I can use here. We would like to have flexibility of configuring this resources and changing the channels on the fly. Means if the message type A comes in queue today, tomorrow this may be a scheduled webservice call.
Any pointers in this regard would be appreciated.
A: For a good answer you should post more details, but it looks like you need strategy design pattern.
public interface SourceStrategy{
public Message getMessage();
}
public FtpLocation implements SourceStrategy{...}
public MessageQueue implements SourceStrategy{...}
public WebService implements SourceStrategy{...}
public class Application(){
SourceStrategy s;
public void setStrategy(SourceStrategy s){
this.strategy = s;
}
public void readMessage(){
Message m = this.s.getMessage();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Y-axis labels for Bluff Javascript library So, I'm using the fabulous Bluff library to put up some graphs from a Rails app. I wanted to customize the Y-axis labels to display fewer decimal digits of precision. Anybody got a clue how to do that? I could try to analyze the "compressed" version of the library and hack it in there, but I'd rather use the API if I can!
TIA,
rw
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I detect when any file changes under a directory in AIR? I've seen examples that use a timer, get the file list, and check each file for changes, but is there a simpler way to do this such as...
<mx:FileSystemList id="fs" visible="false" />
private function onCreationComplete():void
{
fs.directory = File.applicationDirectory.resolvePath('../../assets');
if (fs.directory.exists)
addEventListener(FileEvent.DIRECTORY_CHANGE, onDirectoryChange);
}
private function onDirectoryChange(e:FileEvent):void
{
trace("file was changed");
}
This doesn't seem to fire when a file changes
A: Use the FileMonitor class.
http://www.mikechambers.com/blog/2009/03/11/monitoring-file-changes-in-adobe-air/
Code from the tutorial:
import com.adobe.air.filesystem.FileMonitor;
import flash.filesystem.File;
import flash.events.Event;
import com.adobe.air.filesystem.events.FileMonitorEvent;
private var monitor:FileMonitor;
private function onSelectButtonClick():void
{
var f:File = File.desktopDirectory;
f.addEventListener(Event.SELECT, onFileSelect);
f.browseForOpen("Select a File to Watch.");
}
private function onFileSelect(e:Event):void
{
var file:File = File(e.target);
if(!monitor)
{
monitor = new FileMonitor();
monitor.addEventListener(FileMonitorEvent.CHANGE, onFileChange);
monitor.addEventListener(FileMonitorEvent.MOVE, onFileMove);
monitor.addEventListener(FileMonitorEvent.CREATE, onFileCreate);
}
monitor.file = file;
monitor.watch();
}
private function onFileChange(e:FileMonitorEvent):void
{
trace("file was changed");
}
private function onFileMove(e:FileMonitorEvent):void
{
trace("file was moved");
}
private function onFileCreate(e:FileMonitorEvent):void
{
trace("file was created");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where can I find the SimpleITK documentation and reference information? I am interested in trying to use SimpleITK to solve my imaging problem. Can you please tell me where the documentation and training materials are?
A: SimpleITK is documented here, and has a tutorial that has been presented at the MICCAI 2011 conference.
Development of SimpleITK is hosted on Github and feature requests can be entered in Jira.
Direct Links:
*
*https://github.com/SimpleITK/SimpleITK-MICCAI-2011-Tutorial
*https://github.com/SimpleITK/SimpleITK
*http://www.simpleitk.org
A: There are additional resources that are useful, SimpleITK's WIKI, SimpleITK-Notebooks, and SimpleITK Doxygen.
The SimpleITK WIKI contains a FAQ, information on building SimpleITK, and some visual guides to getting started in different languages.
SimpleITK-Notebooks is a collection of Python Notebooks containing examples on how to do image processing.
SimpleITK's Doxygen contains documentation of the C++ API, along with basic example for different languages.
A: Not documentation, but Kyriakou's PyScience blog has excellent and in-depth implementations of SimpleITK and VTK.
For SimpleITK he goes over
*
*Image segmentation (https://pyscience.wordpress.com/2014/10/19/image-segmentation-with-python-and-simpleitk/#more-126)
*Multi-modal segmentation (https://pyscience.wordpress.com/2014/11/02/multi-modal-image-segmentation-with-python-simpleitk/)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: CSS Images in Email With Rails 3 I'm trying to send out an email with Rails 3 and Action Mailer. The email goes out fine, but I want it to be HTML formatted with some basic styling which includes background images. I understand that the images might get blocked until the user allows them to be shown, but I still think it would be best to link to the images on my web server.
The email template called registration_confirmation.html.erb starts out like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
background: url(/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
margin: 0px 0px 0px 0px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #565656;
}
What is the best way to get the url link for the background image to have the full host included so that the background will show up in the email?
A: Pass your request host as a parameter to the mailer method, and then pass it from the method to the view. So, for example, your mailer method might look like this (example lifted from rails docs and modified here):
class UserMailer < ActionMailer::Base
default :from => "notifications@example.com"
def registration_confirmation(user, host)
@user = user
@host = host
mail(:to => user.email, :subject => "Welcome to My Awesome Site")
end
end
You would call it like this:
def some_action
UserMailer.registration_confirmation(@user, request.host).deliver
end
Then in your view, you would just use the @host:
<style type="text/css">
body {
background: url(http://<%= @host %>/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
}
</style>
This is all assuming the image server is the same as the server running the request. If the image server is hosted elsewhere, you have to output a constant here. You could put something like this in lib/settings.rb:
module Settings
IMAGE_HOST = 'superawesome.images.com'
end
Then in your view, you'd just output the constant there, like this:
<style type="text/css">
body {
background: url(http://<%= Settings::IMAGE_HOST %>/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
}
</style>
A: In response to my other answer, @Kevin wrote:
Thanks for the answer, I did think of doing something like that but I
don't think it's possible with the way I have it setup. The mailer
call is happening in a after_create call in a model rather than in a
controller so I don't think I have access to the request object as you
mentioned (or am I mistaken). I do have this in my mailer initializer:
ActionMailer::Base.default_url_options[:host] = "localhost:3000" Can I
somehow use that hos parameter in my mailer to make it work?
The answer is yes. All rails url-construction helpers should use these defualt_url_options. In addition to setting the :host, you should also force it to use absolute urls by settings this option:
ActionMailer::Base.default_url_options[:only_path] = false
Also, set the asset host like this:
config.action_mailer.asset_host = 'http://localhost:3000'
Then just use the image_path helper instead of hand-writing the url, like this:
<style type="text/css">
body {
background: url(<%= image_path('mainbg_repeat.jpg') %>) top repeat-x #cfcfcf;
}
</style>
NOTE: Setting default_url_options directly like that is deprecated. Here's the new way to do it:
config.action_mailer.default_url_options = {
:host => 'localhost:3000',
:only_path => false
}
A: If you do not care about performance, the roadie gem can handle urls in the stylesheets for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: View Form Creation Code in Access VBA? Is it possible to view the form creation code in Access VBA? I don't mean the event listener code that is viewable in the VBE from View>Code in the form's Design View. I mean the code that is used to create the components, and add them to the form. I would like to programatically set Form properties; doing this from the Properties dialog is quite slow (and annoying).
A: Yes, it's possible to create a form to design.
Vba include CreateControl Method (see MSDN Office-11 Control )
And you can add to this controls any event procedure like OnClick, OnFocus, etc. (see MSDN Office-11 Event
You can manipulate the width, height, etc.. properties as simple as me.control.width
I developed some time ago a form that could customized OnResize event to create different views depend of screen resolution and use all of this.
A: All (?) the properties can be set through VBA for both the form and the controls.
Sub FormInDesignView()
Dim frm As Form
Dim ctl As Control
Set frm = Screen.ActiveForm
frm.Caption = "New"
For Each ctl In frm.Controls
ctl.Name = "txt" & ctl.Name
ctl.ForeColor = vbRed
Next
End Sub
A: In theory you could get the form definition from the system table where it is stored (MSysObjects), but it isn't in a format that is practical to work against.
In theory you could avoid using the graphical designer to layout your form and create all the controls/set their properties dynamically in the form_load event. However, this wouldn't be much of a time-saver.
Assuming the gist of the question is whether there is an XML like declarative way to define a form layout similar to WPF. The answer is no.
A: No, it is not directly possible to do what you want. But if you insisted, you could use the undocumented Application.SaveAsText/LoadFromText commands and process the resulting text file.
Why you think this is a useful way to work in Access, I haven't a clue -- it's completely antithetical to the purpose and design of Access. Give up on your habits from other development tools and learn the Access way of doing things. You'll be a lot happier and productive in the long run.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: textBox embedded in a ListBox initial focus I want to set the focus to the first ListBox item that is a textbox. I want to be able to write in it immedatelly without the necesity to click it or press any key. I try this but doesn't work:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(new TextBox() { });
(listBox1.Items[0] as TextBox).Focus();
}
A: it's stupid but it works only if you wait a moment, try this version:
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var textBox = new TextBox() {};
listBox1.Items.Add(textBox);
System.Threading.ThreadPool.QueueUserWorkItem(
(a) =>
{
System.Threading.Thread.Sleep(100);
textBox.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
textBox.Focus();
}
));
}
);
}
}
}
I was testing locally and could not fix it until I found this question and fuzquat answer in there so vote me here and him there :D
Can't set focus to a child of UserControl
A: In case any body else has this issue. An UIElement has to be fully loaded before you can focus it. therefor this can be made very simple:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(new TextBox() { });
var txBox = listBox1.Items[0] as TextBox;
txBox.Loaded += (txbSender, args) => (txbSender as TextBox)?.Focus();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Strange behavior with doctrine_record::free() method on a loop Hie all,
I loop in Doctrine_Query::execute() with many relations and i get a
record on each iteration. No problem.
To save memory, i would like free() record memory usage with
Doctrine_Record::free().
The first iteration, no problem but at the next one my new object
loose relation.
Example :
$q = Doctrine_Query::create()
->From(..)
->leftJoin(...)
->innerJoin(Relationship)
->where(...)
->andWhere(...);
foreach($q->execute() as $r)
{
$val = $r->Relationship->get(colx);
$r->free(true);
}
At the second iteration, i get new record but without innerJoin Relationship ???
Any idea...
Thanks for your advice
A: As it states in the method comments and the API reference
Helps freeing the memory occupied by the entity. Cuts all references the entity has to other entities and removes the entity from the instance pool. Note: The entity is no longer useable after free() has been called. Any operations done with the entity afterwards can lead to unpredictable results.
You shouldn't use free(), especially if you intend to use the record afterwards. The only case you should need to use it is if you're loading an extremely large number of records and you need to free up memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strip a section out of a url in PHP I have the following URL that is being returned to me from the Vzaar upload api:
https://vz1.s3.amazonaws.com/vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4vz1vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4"c9f4852682649c4a1c034af092b2938f"
I need to be able to strip just the first "vz82b51a36989c422abc4db1734208933a" out of the url. Is there any way to do this in PHP?
Thank you in advance for any help that you provide.
A: That string seems to appear twice in your URL (is it even a valid URL?). You also did not define any rules for obtaining it, so here I just take the 5th "part" separated by slashes.
<?php
$url = 'https://vz1.s3.amazonaws.com/vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4vz1vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4"c9f4852682649c4a1c034af092b2938f"';
$parsed = parse_url($url);
$parts = explode('/', $parsed['path']);
echo $parts[5];
?>
A: What you do is take the string right after the "source" tag. Done by exploding.
$a = 'https://vz1.s3.amazonaws.com/vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4vz1vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4"c9f4852682649c4a1c034af092b2938f';
$parts = explode('/', $a);
$i = 0;
for(; $i < count($parts); $i++)
if($parts[$i] == 'source')
break;
$i++;
echo $parts[$i];
A: If it's always between slashes, you can explode() on / and grab the n-th item.
A: Is the string always at the exact same location? if so, how about something like...
<?php
$url = 'https://vz1.s3.amazonaws.com/vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4vz1vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4"c9f4852682649c4a1c034af092b2938f"';
$url = parse_url($url);
$url = explode('/',$url['path']);
print_r($url[5]);
?>
The above code would print vz82b51a36989c422abc4db1734208933a
A: Try this:
$str = 'https://vz1.s3.amazonaws.com/vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4vz1vzaar/vz8/2b5/source/vz82b51a36989c422abc4db1734208933a/test.mp4"c9f4852682649c4a1c034af092b2938f"';
$str = substr($str, strpos($str, 'source/') + 7);
echo substr($str, 0, strpos($str, '/'));
At this example, the position of 'source' in the URL is not necessary.
A: I know I'm late to the party here, but you shouldn't need to do that
The GUID will be returned to you in the XML response from the first step in the upload process.
http://developer.vzaar.com/docs/version_1.0/uploading/sign.html
See the example at the bottom, you can pull the GUId straight from there.
<?xml version="1.0" encoding="UTF-8"?>
<vzaar-api>
<guid>vz7651d8c2558b46179531548224c87f84</guid>
<key>vz7/651/source/vz7651d8c2558b46179531548224c87f84/${filename}</key>
<https>false</https>
<acl>private</acl>
<bucket>vzaar_development_bucket</bucket>
<policy>ewogICAgICAnZ ... JywgIF0KICAgICAgfQ==</policy>
<expirationdate>2009-06-11T00:05:43.000Z</expirationdate>
<accesskeyid>96ZODEDA709P5JNKI6X08U7PBQ31GUY8</accesskeyid>
<signature>1ZwSGQjv4nrKUM1M/euO8FdxG20=</signature>
</vzaar-api>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to clear textfields after a ajax query using jquery? im using this jquery function to do a ajax query:
$("#add").click(function() {
val1 = $('#add_lang_level').val();
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += '<span id="lang_val">' + val + '</span> <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelive.php', data: {addname: val,addlevel: val1}, type: 'post'});
listitem_html += '<a href="#" class="remove_lang"> <span class="label important">Remove</span></a>'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
I want to clear the content of some textfields after ajax query is complete, but dont know how. Thanks for any help!
A: You can supply a success callback function as an argument to the ajax function. The callback will execute upon successful completion of the asynchronous call:
$.ajax({
url: 'addremovelive.php',
data: {addname: val,addlevel: val1},
type: 'post',
success: function() {
//Do whatever you need to...
$("#yourTextField").val("");
}
});
Note that if that is all you are doing with your ajax call, you could also use the shorthand post method:
$.post("addremovelive.php", {
addname: val, addlevel:val1
},
function() {
//Callback
});
Check the docs for both the ajax and post methods to get an idea of the options available to each.
A: $("#add").click(function() {
val1 = $('#add_lang_level').val();
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += '<span id="lang_val">' + val + '</span> <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelive.php', data: {addname: val,addlevel: val1}, type: 'post',
success: function(d) {
$('#add_lang_level').val('');
$('#add_lang').val('');
}
});
listitem_html += '<a href="#" class="remove_lang"> <span class="label important">Remove</span></a>'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
you can do it this way, I have added anonymus function which will be invoked on success.
A: Try adding a success callback and do your clearing in there:
$.ajax({
url: 'addremovelive.php',
data: {addname: val,addlevel: val1},
type: 'post',
success: function(){
//this function is a callback that is called when the AJAX completes
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: LINQ 'join' expects an equals but I would like to use 'contains' This is a small scrabble side project I was tinkering with and wanted to get some input on what I may be doing wrong. I have a "dictionary" of letters and their respective scores and a list of words. My ideas was to find the letters that were in each word and sum the scores together.
// Create a letter score lookup
var letterScores = new List<LetterScore>
{
new LetterScore {Letter = "A", Score = 1},
// ...
new LetterScore {Letter = "Z", Score = 10}
};
// Open word file, separate comma-delimited string of words into a string list
var words = File.OpenText("c:\\dictionary.txt").ReadToEnd().Split(',').ToList();
// I was hoping to write an expression what would find all letters in the word (double-letters too)
// and sum the score for each letter to get the word score. This is where it falls apart.
var results = from w in words
join l in letterScores on // expects an 'equals'
// join l in letterScores on l.Any(w => w.Contains(
select new
{
w,
l.Score
};
Any help would be greatly appreciated.
Thanks.
A: You can't, basically - Join in LINQ is always an equijoin. You can achieve the effect you want, but not with join. Here's an example:
var results = from w in words
from l in letterScores
where l.Any(w => w.Contains(l.Letter))
select new { w, l.Score };
I think this is what you were trying to do with your query, although it won't give you the word score. For the full word score, I'd build a dictionary from letter to score, like this:
var scoreDictionary = letterScores.ToDictionary(l => l.Letter, l => l.Score);
Then you can find the score for each word by summing the score for each letter:
var results = from w in words
select new { Word = w, Score = w.Sum(c => scoreDictionary[c]) };
Or not as a query expression:
var results = words.Select(w => new { Word = w,
Score = w.Sum(c => scoreDictionary[c]) });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: The correct place to set the UINavigationController's back button title I'm a bit confused with setting the title of navigation item's back button. Usual this is done in the viewDidLoad but in my case the view controller is created without the view being loaded. On startup, I'm restoring the view controller hierarchy and pushing view controllers to the navigation controller and only the top view controller's view is loaded. Since the previous view controller's view isn't loaded, I can't use viewDidLoad to set the back button's title.
The other thing I'm wondering if I restore the hierarchy the right way. I have pretty similar implementation to the Apple's DrillDownSave example.
The view controller is created programmatically, so awakeFromNib shouldn't work either. What is the right place for setting up the back button (and the title)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C#- Getting user input for Age.. but receiving error? I am trying to make improve my programming and getting things drilled into my head so I'm just quickly developing an application that gets user's input and prints their name. But also gets their input for "Age verification".
I'm practicing IF & ELSE statements as well as nesting classes.
However my compiler is shooting me an error and I just cannot seem to figure it out. I'm trying to get the user to input his age, and then proceed with the IF & ELSE statement.
Compiler is shooting error that . ""Cannot implicitly convert type
string to int"
The only error in the program right now is the
myCharacter.age = Console.ReadLine();
using System;
namespace csharptut
{
class CharPrintName
{
static void Main()
{
Character myCharacter = new Character();
Console.WriteLine("Please enter your name to continue: ");
myCharacter.name = Console.ReadLine();
Console.WriteLine("Hello {0}!", myCharacter.name);
Console.WriteLine("Please enter your age for verification purposes: ");
myCharacter.age = Console.ReadLine();
if (myCharacter.age <= 17)
{
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
}
else if (myCharacter.age >= 18)
{
Console.WriteLine("You can enter!");
}
}
}
class Character
{
public string name;
public int age;
}
}
A: As the error says you can't implicitly type a string to an int. You need to parse it into an int.
string input = Console.ReadLine();
int age;
if (int.TryParse(input, out age)
{
// input is an int
myCharacter.age = age;
}
else
{
// input is not an int
}
A: You are trying to assign a string value to an int with this line:
myCharacter.age = Console.ReadLine();
Try:
myCharacter.age = Int32.Parse(Console.ReadLine());
A: character.age expects an Int but ReadLine() returns a string, you need to look at using int.Parse or int.TryParse to avoid exceptions
e.g.
if (!int.TryParse(Console.ReadLine(),out myCharacter.age)) {
Console.WriteLine("You didn't enter a number!!!");
} else if (myCharacter.age <= 17) {
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
} else {
Console.WriteLine("You can enter!");
}
A: This looks like a student project.
The input coming from the ReadLine() is always of type string. You're then comparing a string to 17 which isn't valid, as 17 is an int. Use TryParse versus parse to avoid throwing an exception at runtime.
string typedAge = Console.ReadLine();
int Age = 0;
if (!int.TryParse(typedAge, out Age))
Console.WriteLine("Invalid age");
if (Age <= 17)
Console.WriteLine("You're awfully young.");
A: OK. The problem here is that the age is defined as an int and Console.ReadLine() always returns a string so thus you have to convert the user input from string to integer in order to correctly store the age.
Something like this:
myCharacter.age = Int32.Parse(Console.ReadLine());
A: When you read input from the console, it returns it to you in the form of a string. In C#, which is a statically typed language, you cannot simply take one type and apply it to another type. You need to convert it somehow, there are several ways to do this.
The first way would be casting:
myCharacter.age = (int)Console.ReadLine();
This won't work because a string and an integer are two completely different types and you can't simply cast one to the other. Do some reading on casting types for more information.
The second way would be to convert it, again there are a couple of ways to do this:
myCharacter.age = Int32.Parse(Console.ReadLine());
This will work as long as you type in an actual number, in this case the Parse method reads the string and figures out what the appropriate integer is for you. However, if you type in "ABC" instead, you will get an exception because the Parse method doesn't recognize that as an integer. So the better way would be to:
string newAge = Console.ReadLine();
int theAge;
bool success = Int32.TryParse(newAge, out theAge);
if(!success)
Console.WriteLine("Hey! That's not a number!");
else
myCharacter.age = theAge;
In this case the TryParse method tries to parse it, and instead of throwing an exception it tells you it can't parse it (via the return value) and allows you to handle that directly (rather than thru try/catch).
That's a little verbose, but you said you're learning so I thought I'd give you some stuff to consider and read up on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: View current opened netNamedPipe channels? Is there any way I can determine which netNamedpipe channels are currently open? This will help me debug my WCF Client/Server and make sure I am closing my channels properly.
This is similar to the netstat tool for network connections, but for netNamedPipes instead.
A: You can use Process Explorer to see what pipes a process has open:
http://technet.microsoft.com/en-us/sysinternals/bb896653
A: There is no tool to do this, as far as I am aware.
You can use Process Explorer to find what handles to named pipe objects a process is holding, but this will not really answer your question. To recognise pipes which are created for WCF NetNamedPipeBinding channels you need to know what you are looking for. WCF pipes will incorporate a GUID in their name, looking something like this:
\\.\pipe\197ad019-6e5f-48cb-8f88-02ae11dfd8c0
See here for more on this.
However, the fact that a handle exists doesn't per se tell you anything about the state of the channel. There is a WCF pooling mechanism for pipe connections, so even if the channel is properly closed this does not guarantee that the pipe connection itself has been dropped and the handle released (though if you were to see a process gradually acquiring more and more handles that would suggest there might be a problem with channel cleanup).
If you want to confirm that channels are being cleaned-up promptly I would suggest you enable WCF Tracing in verbose mode: this will tell you exactly what is going on.
A: SysInternals has a command called PipeList. I believe you can download the command separately here:
http://technet.microsoft.com/en-us/sysinternals/dd581625
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can we safely lock down a Facebook development environment tunneled out to the public internet? We run a per developer development environment with each developer workstation ssh tunnelled out from our office to the public internet so we can test integration with Facebook canvas apps and facebook callbacks to our urls.
How can we limit access to this environment so Facebook servers can access our servers, cross domain authentication will work for our developers, but no random members of the public can stumble upon our development servers?
Currently the Facebook IP range is unknown, so we don't know where our open graph callbacks are coming from.
A: You can sandbox your application.
That way only administrators & developers of the application can interact & see the application.
You can make a change to your Facebook application to sandbox mode going to: https://developers.facebook.com/apps
In Edit settings page of the current application you choose Settings->Advanced->Sandbox Mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Applications are expected to have a root view controller at the end of application launch I get the following error in my console:
Applications are expected to have a root view controller at the end of application launch
Below is my application:didFinishLaunchWithOptions method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Set Background Color/Pattern
self.window.backgroundColor = [UIColor blackColor];
self.tabBarController.tabBar.backgroundColor = [UIColor clearColor];
//self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"testbg.png"]];
// Set StatusBar Color
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
In Interface Builder, the UITabBarController's delegate is hooked up to the App Delegate.
Anyone know how to fix this issue?
A: Try to connect IBOutlet of tab bar controller to root view in the Interface Builder instead of
self.window.rootViewController = self.tabBarController;
But actually I haven't seen such error before.
A: I solved the problem by doing the following (none of the other solutions above helped):
From the pulldown menu associated with "Main Interface" select another entry and then reselect "MainWindow" then rebuild.
A: I came across the same issue but I was using storyboard
Assigning my storyboard InitialViewController to my window's rootViewController.
In
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
...
UIStoryboard *stb = [UIStoryboard storyboardWithName:@"myStoryboard" bundle:nil];
self.window.rootViewController = [stb instantiateInitialViewController];
return YES;
}
and this solved the issue.
A: I had the same error when trying to change the first view controller that was loaded in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
At first I didn't really know where the error was coming from precisely so I narrowed it down and found out what went wrong. It turns out that I was trying to change the display of a view before it actually came on screen. The solution was hence to move this code in the viewcontroller that was giving me trouble from
- (void)viewDidLoad
to
- (void)viewDidAppear:(BOOL)animated
and the error stopped appearing. My problem specifically was caused by making a UIAlertView show.
In your case I suggest you check out the code in the tabBarController's active view controller (as it is probably a problem in that view controller).
If that doesn't work, try to set the starting settings in the nib file instead of in code - or if you want to do it in code, try moving the code to the tabBarController's active viewcontroller's appropriate method.
Good luck!
A: I began having this same issue right after upgrading to Xcode 4.3, and only when starting a project from scratch (i.e. create empty project, then create a UIViewController, and then Create a separate nib file).
After putting ALL the lines I used to, and ensuring I had the correct connections, I kept getting that error, and the nib file I was trying to load through the view controller (which was set as the rootController) never showed in the simulator.
I created a single view template through Xcode and compared it to my code and FINALLY found the problem!
Xcode 4.3 appears to add by default the method -(void)loadView; to the view controller implementation section. After carefully reading the comments inside it, it became clear what the problem was. The comment indicated to override loadView method if creating a view programmatically (and I'm paraphrasing), otherwise NOT to override loadView if using a nib. There was nothing else inside this method, so in affect I was overriding the method (and doing nothing) WHILE using a nib file, which gave the error.
The SOLUTION was to either completely remove the loadView method from the implementation section, or to call the parent method by adding [super loadView].
Removing it would be best if using a NIB file as adding any other code will in effect override it.
A: I had this same error message in the log. I had a UIAlertView pop up in application:didFinishLaunchingWithOptions. I solved it by delaying the call to the alertView to allow time for the root view controller to finishing loading.
In application:didFinishLaunchingWithOptions:
[self performSelector:@selector(callPopUp) withObject:nil afterDelay:1.0];
which calls after 1 second:
- (void)callPopUp
{
// call UIAlertView
}
A: I had the same problem. If you're building a window-based application "from scratch" as I was, you'll need to do the following: (note, these are steps for Xcode 4.2.)
0. Make sure your application delegate conforms to the UIApplicationDelegate protocol.
For example, suppose our delegate is called MyAppDelegate. In MyAppDelegate.h, we should have something like this:
@interface MyAppDelegate :
NSObject <UIApplicationDelegate> // etc...
1. Specify the application delegate in main.m
For example,
#import "MyAppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv,
nil, NSStringFromClass([MyAppDelegate class]));
}
}
2. Create a main window interface file.
To do this, right-click on your project and choose New File. From there, choose Window from the iOS -> User Interface section.
After adding the file to your project, go to the project's summary (left-click on the project; click summary.) Under iPhone/iPod Deployment Info (and the corresponding iPad section if you like) and select your new interface file in the "Main Interface" combo box.
3. Hook it all up in the interface editor
Select your interface file in the files list to bring up the interface editor.
Make sure the Utilities pane is open.
Add a new Object by dragging an Object from the Objects list in the Utilities pane to the space above of below your Window object. Select the object. Click on the Identity inspector in the Utilities pane. Change the Class to the application's delegate (MyAppDelegate, in this example.)
Bring up the connections inspector for MyAppDelegate. Connect the window outlet to the Window that already exists in the interface file.
Click on File's Owner on the left, and then click on the Identity inspector in the Utilities pane. Change the Class to UIApplication
Bring up the connections inspector for File's Owner. Connect the delegate outlet to the MyAppDelegate object.
4. Finally, and very importantly, click on the Window object in the interface file. Open the Attributes inspector. Make sure "Visible at Launch" is checked.
That's all I had to do to get it working for me. Good luck!
A: If you use MTStatusBarOverlay, then you'll get this error.
MTStatusBarOverlay creates an additional window ([[UIApplication sharedApplication] windows) which doesn't have a root controller.
This doesn't seem to cause a problem.
A: Received the same error after replacing my UI with a Storyboard, using XCode 4.6.3 and iOS 6.1
Solved it by clearing out all of the code from didFinishLaucnhingWithOptions in the AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return YES;
}
A: OrdoDei gave a correct and valuable answer. I'm adding this answer only to give an example of a didFinishLaunchingWithOptions method that uses his answer as well as accounting for the others’ comments regarding Navigation Controller.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
// Instantiate the main menu view controller (UITableView with menu items).
// Pass that view controller to the nav controller as the root of the nav stack.
// This nav stack drives our *entire* app.
UIViewController *viewController = [[XMMainMenuTableViewController alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
// Instantiate the app's window. Then get the nav controller's view into that window, and onto the screen.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// [self.window addSubview:self.navigationController.view];
// The disabled line above was replaced by line below. Fixed Apple's complaint in log: Application windows are expected to have a root view controller at the end of application launch
[self.window setRootViewController:self.navigationController];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
A: I got this when starting with the "Empty Application" template and then manually adding a XIB. I solved it by setting the main Nib name as suggested by Sunny. The missing step in this scenario is removing
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
from
application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
As it will overwrite the instance of your window created in the Xib file. This is assuming you have created a ViewController and wired it up with your window and App Delegate in the XIB file as well.
A: This happened to me. Solved by editing .plist file.
Specify the Main nib file base name.(Should be MainWindow.xib).
Hope this will help.
A: Replace in AppDelegate
[window addSubview:[someController view]];
to
[self.window setRootViewController:someController];
A: This occurred for me because i inadvertently commented out:
[self.window makeKeyAndVisible];
from
- (BOOL)application:(UIApplication*) didFinishLaunchingWithOptions:(NSDictionary*)
A: I was able to set the initial view controller on the summary screen of xcode.
Click on the top most project name in the left hand file explorer (it should have a little blueprint icon). In the center column click on your project name under 'TARGETS', (it should have a little pencil 'A' icon next to it). Look under 'iPhone / iPod Deployment Info' and look for 'Main Interface'. You should be able to select an option from the drop down.
A: On top of "sho" answer, that is correct (fourth parameter of UIApplicationMain should be the name of the main controller), I add some comments.
I have recently changed the 'model' of an app of mine from using MainWindow.xib to construct a window programatically. The app used an older template that created that MainWindow automatically. Since I wanted to support a different controller view XIB for iPhone 5, it is easier to choose the right XIB programatically when the App Delegate is created. I removed MainWindow.xib from project as well.
Problem was, I forgot to fill the fourth parameter in UIApplication main and I FORGOT TO REMOVE MainWindow from "Main Interface" at Project Summary.
This caused a BIG problem: it rendered the harmless warning "Applications are expected to..." on development devices, but when it went to App Store, it broke on consumer phones, crashing because MainWindow was no longer in the bundle! I had to request an expedited review for the bugfix.
Another sympthom is that sometimes a white block, like a blank UIView, was sometimes appearing when Settings were changed and app was put in foreground. In iPhone 5 it was clear that it was an 320x480 block. Perhaps the missing MainWindow was being created in development mode, using the old size. I had just found this bug when the first reports of the crash reached the inbox.
Installing the app from App Store instead of from XCode showed that the app indeed crashed, and the MainWindow issue revealed itself on log, so I could see that it was not some special combination of devices+IOS versions.
A: To add to Mike Flynn's answer, since upgrading to Xcode 7 and running my app on an iOS 9 device, I added this to my (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// Hide any window that isn't the main window
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow *window in windows) {
if (window != self.window) {
window.hidden = YES;
}
}
A: This issue happens when you don't have Interface Builder set up correctly.
Ensure your App Delegate's window and viewController outlets are hooked up:
In your MainWindow.xib, hold control, click App Delegate and drag to the Window object. Select window. Hold control and select the App delegate again, drag to your root view controller and select viewController.
A: This error also show up when file's owner of MainWindow.xib is set incorrectly.
File's owner is UIApplication->inserted object of app delegate class with window outlet connected to window
A: I was getting this error (Applications are expected to have a root view controller at the end of application launch), and I was creating the view controllers programmatically.
Solved it by ensuring the loadView method in my root view controller was calling [super loadView].
A: I run into the same problem recently, when building a project with ios5 sdk.
At first it was building and running properly, but after that the error appeared.
In my case the solution was rather simple.
What was missing, was that somehow the Main Interface property in the summary tab of my application target got erased. So I needed to set it again.
If this is not the point, and if the tabBarController is still nil, you can always programmatically create your window and root controller.
As a fallback I added the following code to my project
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (!window && !navigationController) {
NSLog(@"Window and navigation controller not loaded from nib. Will be created programatically.");
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
UIViewController *viewController1, *viewController2;
viewController1 = [[[FirstViewController alloc] initWithNibName:@"FirstViewController_iPhone" bundle:nil] autorelease];
viewController2 = [[[SecondViewController alloc] initWithNibName:@"SecondViewController_iPhone" bundle:nil] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
self.window.rootViewController = self.tabBarController;
}
else {
[window addSubview:[tabBarController view]];
}
[self.window makeKeyAndVisible];
return YES;
}
This will work only if sho's solution is implemented also.
A: I upgraded to iOS9 and started getting this error out of nowhere. I was able to fix it but adding the below code to - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow *window in windows) {
if(window.rootViewController == nil){
UIViewController* vc = [[UIViewController alloc]initWithNibName:nil bundle:nil];
window.rootViewController = vc;
}
}
A: None of the above suggestions solved my problem. Mine was this:
Add:
window.rootViewController = navigationController;
after:
[window addSubview:navigationController.view];
in my appdelegate's
- (void)applicationDidFinishLaunching:(UIApplication *)application {
A: *
*Select your "Window" in your Nib File
*In "Attributes Inspector" Check "Visible at Launch"
*
*This happens when your nib file is created manually.
*This fix works for regular nib mode - not storyboard mode
A: how to add a RootViewController for iOS5
if your app didn't use a RootViewController till now,
just create one ;) by hitting File > New > New File;
select UIViewController subclass
name it RootViewController, uncheck the With XIB for user interface (assuming you already have one)
and put this code in your AppDelegate :: didFinishLaunchingWithOptions
rootViewController = [[RootViewController alloc] init];
window.rootViewController = rootViewController;
for sure - you have to import RootViewController.h and create the variable
here is a nice article about the RootViewController and the AppDelegate,
A: I had this same problem. Check your main.m. The last argument should be set to the name of the class that implements the UIApplicationDelegate protocol.
retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
A: Make sure you have this function in your application delegate.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {
return YES;
}
Make sure didFinishLaunchingWithOptions returns YES. If you happened to remove the 'return YES' line, this will cause the error. This error may be especially common with storyboard users.
A: I also had this error but unlike any of the answers previously listed mine was because i had uncommented the method 'loadView' in my newly generated controller (xcode 4.2, ios5).
//Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
It even told me that the method was for creating the view programmatically but i missed it because it looked so similar to other methods like viewDidLoad that i normally use i didn't catch it.
To solve simply remove that method if you are not programmatically creating the view hierarchy aka using nib or storyboard.
A: i got this problems too. i got my project run in xcode4.2.1. i've read all comments up there, but no one is cool for me. after a while, i find that i commented a piece of code.
//self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
then i uncommented it. everything is ok for me.
hope this would helpful for you guys.
A: With my first view being MenuViewController I added:
MenuViewController *menuViewController = [[MenuViewController alloc]init];
self.window.rootViewController = menuViewController;
on the App Delegate method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
}
That worked.
A: There was a slight change around iOS 5.0 or so, requiring you to have a root view controller. If your code is based off older sample code, such as GLES2Sample, then no root view controller was created in those code samples.
To fix (that GLES2Sample, for instance), right in applicationDidFinishLaunching, I create a root view controller and attach my glView to it.
- (void) applicationDidFinishLaunching:(UIApplication *)application
{
// To make the 'Application windows are expected
// to have a root view controller
// at the end of application launch' warning go away,
// you should have a rootviewcontroller,
// but this app doesn't have one at all.
window.rootViewController = [[UIViewController alloc] init]; // MAKE ONE
window.rootViewController.view = glView; // MUST SET THIS UP OTHERWISE
// THE ROOTVIEWCONTROLLER SEEMS TO INTERCEPT TOUCH EVENTS
}
That makes the warning go away, and doesn't really affect your app otherwise.
A: Sounds like self.tabBarController is returning nil. tabBarController probably is not wired up in Interface Builder. Set the IBOutlet of tabBarController to the tabBarController in Interface Builder.
A: Make sure that your "Is Initial View Controller" is correctly set for your first scene.
That's what's causing the error.
A: This error hit me all of a sudden. So, what caused it?
It turns out I was in IB attaching File Owner to a new small ImageView I'd dragged onto the View. I hadn't called it an IBOutlet in the .h file, so when I ctrl-dragged to it, the new Imageview wasn't listed as a possible connection. The only possibility displayed in the little black box was View. I must have clicked, inadvertently. I made a few changes then ran the program and got the Root Controller error. The fix was reconnecting File Owner to the bottom View in the xib - IB screen.
A: Although a lot of these answers seem valid, none of them fixed the message for me. I was experimenting with the empty application template and trying to load straight to a .xib file for understanding sake (like to old window template). It seems like Apple left an NSLog message running.
I was on Xcode 4.3 and nothing seemed to get rid of the message and I wanted to know why. Finally I decided to see what would happen in Xcode 4.5 (preview/iPhone 6.0 build) and the message is no longer there. Moving on.
A: I ran into this in an iPad application targeting iOS 5.1 in Xcode 4.5.1. The app uses UITabBarController. I needed a new section within the tab bar controller, so I created a new view controller and xib. Once I added the new view controller to the tab bar controller, none of my on-screen controls worked anymore, and I got the "expected to have a root view controller" log.
Somehow the top-level object in the new xib was UIWindow instead of UIView. When I dropped a UIView into the XIB, had the view outlet point to it, moved all the subviews into the new UIView, and removed the UIWindow instance, the problem was fixed.
A: I had this error too but no answer already listed was solving my issue.
In my case the log display was due to the fact I was assigning the application root view controller in another sub-thread.
-(BOOL) application:(UIApplication*) application didFinishLaunchingWithOptions:(NSDictionary*) launchOptions
{
...
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
...
dispatch_async(dispatch_get_main_queue(), ^{
...
[self updateTabBarTitles];
self.window.rootViewController = self.tabBarController;
...
});
});
[self.window makeKeyAndVisible];
return YES;
}
By moving the rootViewController assignment to the end of the function - just before the call to makeKeyAndVisible: - causes the log message not to be displayed again.
{
...
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
I hope this helps.
A: I also had this problem. Turns out it was when I deleted the App Delegate from the Objects list on the left I deleted the connection for App Delegate, Window and TabBarController :)
A: Have you tried setting the delegate, i.e.
self.rootController.delegate = self;
within applicationDidFinishLaunchingWithOptions? That worked for me, although I'm not sure why.
A: for ARC change:
change to
@synthesize window;
instead of
@synthesize window=_window;
A: I had the same error message because I called an alert in
- (void)applicationDidBecomeActive:(UIApplication *)application
instead of
- (void)applicationWillEnterForeground:(UIApplication *)application
A: I was migrating an old EAGLView sample project to the new GLKView sample project in Xcode 4 and none of the solutions worked for me. Finally I realized that I was trying to set the main GLKViewController's self.view to point to a nested GLKView in Interface Builder.
When I pointed the self.view back to the root GLKView in Interface Builder, my app was then able to launch without an error message (so make sure your view controller's view is set to the root view).
P.S. if you want to get a nested GLKView working, create a new member variable like self.glkSubview in ViewController.h and drag its connection to the nested GLKView in Interface Builder. Then make sure to drag self.glkSubview's delegate to File's Owner. You must manually call [self.glkSubview display] in "- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect" if you have setNeedsDisplay turned off for the GLKView.
A: None of the above worked for me... found out something wrong with my init method on my appDelegate. If you are implementing the init method make sure you do it correctly
i had this:
- (id)init {
if (!self) {
self = [super init];
sharedInstance = self;
}
return sharedInstance;
}
and changed it to this:
- (id)init {
if (!self) {
self = [super init];
}
sharedInstance = self;
return sharedInstance;
}
where "sharedInstance" its a pointer to my appDelegate singleton
A: None of the answer quite fixed my issue.
I am working on an old iOS4 project upgraded to ARC and now being worked on in Xcode 5 for iOS 7
I read through all of them and started checking my config and code.
What fixed it for me was adding
-(BOOL) application:(UIApplication*) application didFinishLaunchingWithOptions: (NSDictionary*) launchOptions
{
// Maybe do something
return YES;
}
In addition to having
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
}
I did not have
-(BOOL) application:(UIApplication*) application didFinishLaunchingWithOptions: (NSDictionary*) launchOptions
prior to getting the error.
A: In my case, everything about the actual window and the didFinishLaunchingWithOptions: method was fine.
My error was that I didn't realize applicationDidBecomeActive: runs on startup in addition to when the app is coming to the foreground after having been in the background.
Therefore, in applicationDidBecomeActive: I was manipulating view controllers that hadn't finished all their setup yet (waiting for different threads to respond, etc).
Once I moved this functionality outside of applicationDidBecomeActive, the errors went away.
A: Moving setRootViewController: from didFinishLaunchingWithOptions: to awakeFromNib: solved this in my empty project.
A: If your app replaces the main UIWindow with FingerTipWindow (to show touches on a projector) and you haven't updated your sources for a few (several) years, your replacement object might not include a rootViewController property (see kgn's 5/21/2013 mod at GitHub)
You can set window.rootViewController in didFinishLaunchingWithOptions until the cows come home, but your window will not report one "at end of application launch" and will throw an exception at runtime. Update your sources.
A: This Swift 2 solution worked for me :
Insert the code below in AppDelegate -> didFinishLaunchingWithOptions
self.window!.rootViewController = storyboard.instantiateViewControllerWithIdentifier("YourRootViewController") as? YourRootViewControllerClass
A: I got such error when worked with CoreData with custom ServiceLocator
let context: NSManagedObjectContext = try self.dependencies.resolve()
//solution
let context: NSManagedObjectContext? = try? self.dependencies.resolve()
A: Validate your STORYBOARD file... If you are using IB to 'wire' code to your UI.. and just happen to delete the UI element ... and then realize, oh you need to delete the reference in the code (in my case a UIButton called AbortButton)... then moments later the app won't launch...
The issue is in the 'storyboard' file. Open it in an xml editor and look for orphaned 'relationships', of connectors which point places where they should not...
eg:
<relationships>
<relationship kind="outlet" name="AbortButton" candidateClass="UIButton"/>
did NOT exist in my code anymore... (yet i still had a 'connector' linked up in the storyboard file)..
Also i had (somehow and invalid connector from a UIImageView or a ToolBar to my main UIViewController.view object)... don't think it liked that either...
bottom line - one doesn't have to manually 'code the controller' back into existence... the STORYBOARD file is whacked. I fixed mine, and bingo worked perfect again..
and BTW, as a text coder.. i am growing very fond of IB... kicks butt over MS Visual Studio's IDE...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "390"
} |
Q: CSS display issue where border applied to div is stretching around other elements I have an issue where the css border applied to a div element is stretching around the span
tag directly above it (a span tag which is NOT within the div tag). Now, I already have a workaround for this which can be found in the following example but I would still like to know why this is happening:
<html>
<head></head>
<body>
<span style="float: left;">(Floated Span)</span>
<div style="border: 1px solid black;">
This is the only text which should have a border around it.
</div>
<span style="float: left;">(Floated Span)</span>
<br />
<br />
I do NOT expect the border from the div tag to stretch around the floated span, but it does.
<br />
Therefore, I would expect the floated span below the div tag to do the same, but it doesn't.
<br />
Happens in FF and IE.
<br />
<br />
<span style="float: left;">(Floated Span)</span>
<br />
<div style="border: 1px solid black;">
This is the only text which should have a border around it.
</div>
<span style="float: left;">(Floated Span)</span>
<br />
<br />
Apparently BR tags are magical and solve the problem for whatever reason.
<br />
Works in FF and IE.
<br />
<br />
<span>(Span)</span>
<span style="float: left;">(Floated Span)</span>
<div style="border: 1px solid black;">
This is the only text which should have a border around it.
</div>
<span style="float: left;">(Floated Span)</span>
<br />
<br />
If an unstyled span is added before the floated span, Firefox displays the content the way I expect.
<br />
However, IE still decides to stretch the border from the div tag around the floated span.
<br />
<br />
<span style="float: left;">(Floated Span)</span>
<span>(Span)</span>
<div style="border: 1px solid black;">
This is the only text which should have a border around it.
</div>
<span style="float: left;">(Floated Span)</span>
<br />
<br />
Switching the order of the floated span and unstyled span in the code 'fixes' the previous issue with IE.
</p>
</body>
</html>
A: See block formatting contexts on w3.org.
In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats)
A: It looks like this is happening because the spans are being floated.
This means they are taken out of the document flow.
The div underneath them then pushes up, and if transparent, would look like it "includes" the span.
A: If you add a 'clear: left' to the div below the span it will fix this issue.
This issue is because of the span being floated and the div doesn't clear anything out of the way before rendering so the span floats over the div below.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get hudson's git plugin to clone repo with the name of the repo in the path? Let's say I have a repo called "stuff". git@github.com:mine/stuff.git
when I do a git clone of this repo from the command line, it creates a directory called "stuff" and puts everything in that directory.
When I set up hudson to use git, it puts everything in the directory
$hudson_home/jobs/myjob/workspace/*
with no "stuff" after workspace. Just the items inside of stuff.
How can I make hudson clone the repo like the commandline does, namely:
$hudson_home/jobs/myjob/workspace/stuff/*
I see no options for this and I do not want to change the default workspace path.
A: I don't know whether this feature is in Hudson, since I have upgraded to Jenkins.
But if you click "Advanced" at the bottom of the Git section (there are two "Advanced" buttons), there is a property called "Local subdirectory for repo" which does what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Making http calls from swing application to a servlet, session not saved I'm creating a Swing application that connects to a web server, running some servlets (created by myself). On the 1st time a user connects, he get a "playerID" that is saved on his session on the servlets. When I try to make another call from the Swing application to the servlet, the "PlyaerID" seems not to be recognized. I'm making a simple call to get the PlayerID. The servlets recognize this type of request and send a JSON with the "playerID" and if it is not set (null) than it sends -1. The swing application always getting the "-1" reply from the servlet. I tried running it from a browser and everything was just fine.
Is it possible that my Swing client can not make a request and a session will not be saved on the servlet?
I can tell you for sure that the swing method that communicate with the servlet works well.
A: The servlet session is backed by a cookie. You basically need to grab all Set-Cookie headers from the response of the first request and then pass the name=value pairs back as Cookie header of the subsequent requests.
It's unclear what HTTP client you're using, but if it's java.net.URLConnection, then you could use the java.net.CookieHandler for this.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
See also:
*
*Using java.net.URLConnection to fire and handle HTTP requests - Maintaining the session
*How do servlets work? Instantiation, sessions, shared variables and multithreading
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Call NodeJS function by PHP (fsocketopen) I need call and pass parameter to NodeJS socket server.
I confirmed the server works well. and now I need to create PHP script to call the function.
My NodeJS code is like this,
var user = {};
socket.sockets.on("connection", function(client){
client.on("messageToClient", function(uid, msg){ // I need to call this method
user[uid].send(msg);
});
});
PHP ::
$fp = fsockopen("10.0.111.10","3000",$errno,$errstr, 30);
if(!$fp){
echo "{$errno} ({$errstr}) <br />";
}else{
$uid_parameter = 'ABC';
$msg_parameter = 'HELLO';
$out = "HOW TO CALL NodeJS messageToClient Method AND PASS PARAMETER?";
fwrite($fp,$out);
fclose($fp);
}
A: The more elegant solution would be just do it all in Nodejs or all in PHP. DB interaction as well. NodeJS can interact with almost every type of commonly used database. It would save you having to implement what will be a quite hacky code.
A: I know this question is old, but hasn't content on the internet, so I will leave the answer here for future users.
PHP:
function sio_message($message, $data) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 9501);
if(!$result) {
die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
}
$bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" =>
$data)));
socket_close($socket);
}
NODE.JS:
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
server.on("connection", function(s) {
//If connection is from our server (localhost)
if(s.remoteAddress == "::ffff:127.0.0.1") {
s.on('data', function(buf) {
console.log('data arrive');
var js = JSON.parse(buf);
console.log(js.data); //Done
});
}
});
Now you can send data from node with only sio_message('anything', 'more data');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best way to implement a workflow based on a series of asynchronous ASIHTTPRequests in iOS? I've been fighting and fighting for some time with a decent way to handle a workflow based on a series of asynchronous ASIHTTPRequests (I am using queues). So far it seems to have eluded me and I always end with a hideous mess of delegate calls and spaghetti code exploding all over my project.
It works as follows:
*
*Download a list of items (1 single ASIHTTPRequest, added to a queue).
*The items retrieved in step 1 need to be stored.
*Each item, from 1 is then parsed, queuing a 1 ASIHTTPRequest per item, for it's sub-items.
*Each of the requests from step 3 are processed and the sub-items stored.
I need to be able to update the UI with the progress %age and messages.
I'm unable for the life of me to figure out a clean/maintainable way of doing this.
I've looked at the following links:
*
*Manage Multiple Asynchronous Requests in iOS with ASINetworkQueue
*Sync-Async Pair Pattern Easy Concurrency on iOS
But either I'm missing something, or they don't seem to adequately describe what I'm trying to achieve.
Could I use blocks?
A: I see myself facing a quite similar issue as I got the exercise to work on a app using a set of async http and ftp handlers in a set of process and workflows.
I'm not aware about ASIHTTP API but I assume I did something similar.
I defined a so called RequestOperationQueue which can for example represent all request operations of a certain workflow. Also I defined several template operations for example FTPDownloadOperation. And here comes the clue. I implemented all these RequestOperations more or less accroding to the idea of http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/. Instead of implementing the delegate logic in the operation itself I implemented sth like callback handlers specialized for the different protocols (http, ftp, rsync, etc) providing a status property for the certain request which can be handled by the operation via KVO.
The UI can be notified about the workflow for example by a delegate protocol for RequestOperationQueue. for example didReceiveCallbackForRQOperation:(RequestOperation) rqo.
From my point of view the coding of workflows including client-server operations gets quite handy with this approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP replace HTML elements with DIV I've been reorganising my code to be able to better support old IE browsers. I've put everything that is HTML5 only scripts in IF statements and it all works fine.
I just have one last change I need to make. I've collected all my site into an using ob_start() ... and would like to know the easiest way to replace all html5 elements like article with div. I was going to use simplehtmldom but I don't have mb_character_encoding so it doesn't work. To make it easier I've removed all comments and put all the code on one line in the hope of using a very shiny REGULAR EXPRESSION.
A: Some options:
*
*A simple replace, as suggested by Senad
*DOMDocument (not the easiest approach)
*OR... You can leave the HTML the way it is, and use Modernizr on the client side to make older browsers recognize these elements, as well as a bunch of other HTML5/CSS3 features.
A: You can replace your <article with <div
and </article> with </div>
simple as that no need for complex regular expression
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why do Objective-c protocols adopt other protocols? I've seen Objective-c protocols defined in the following way:
@protocol MyProtocol <SomeOtherProtocol>
// ...
@end
Why do protocols adopt other protocols? I'm especially curious why a protocol would adopt the NSObject protocol.
A: It is simply the same concept as inheritance for classes.
If a protocol adopt another protocol, it "inherits" the declared methods of this adopted protocol.
The NSObject protocol especially declares methods such as respondsToSelector:. So this is especially useful if you declare a @protocol that have @optional methods, because when you will then call methods on objects conforming this protocol, you will need to check if the object responds to the method before calling it if this method is optional.
@protocol SomeProtocol <NSObject>
-(void)requiredMethod;
@optional
-(void)optionalMethod;
@end
@interface SomeObject : NSObject
-(void)testMyDelegate;
@property(nonatomic, assign) id<SomeProtocol> myDelegate;
@end
@implementation SomeObject
@synthesize myDelegate
-(void)testMyDelegate {
// Here you can call requiredMethod without any checking because it is a required (non-optional) method
[self.myDelegate requiredMethod];
// But as "optionalMethod" is @optional, you have to check if myDelegate implements this method before calling it!
if ([myDelegate respondsToSelector:@selector(optionalMethod)]) {
// And only call it if it is implemented by the receiver
[myDelegate optionalMethod];
}
}
@end
You will only be able to call respondsToSelector on myDelegate if myDelegate is declared as a type that implements respondsToSelector (otherwise you will have some warnings). That's why the <SomeProtocol> protocol needs to adopt itself the <NSObject> protocol, which itself declares this method.
You may think of id<SomeProtocol> as "any object, whatever its type (id), it just has to implement the methods declared in SomeProtocol, including the methods declared in the parent protocol NSObject. So it can be an object of any type but because SomeProtocol adopts the NSObject protocol itself, it is guaranteed that you are allowed to call respondsToSelector on this object, allowing you to check if the object implements a given method before calling it if it is optional.
Note that you may also not make SomeProtocol adopt the NSObject protocol and instead declare your variable as id<SomeProtocol,NSObject> myDelegate so that you can still call respondsToSelector:. But if you do that you will need to declare all your variables this way everywhere you use this protocol... So this is much more logical to make SomeProtocol directly adopt the NSObject protocol ;)
A: Inheritance...................
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: linq insert not work I have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
using (mesteriEntities myEntities = new mesteriEntities())
{
var usern = Session["New"];
var UserID = (from Users in myEntities.Users
where Users.UserName == usern
select Users.UserID).SingleOrDefault();
var cati = Convert.ToInt32(DropDownList1.SelectedValue);
Job newJob = new Job();
newJob.categID = cati;
newJob.userID = UserID;
myEntities.AddToJobs(newJob);
}
}
}
When I select a combo it should add the value of combo and the userID in the Jobs table both INT values.
The variables "cati" and "userid" have values.
I don't know what I should change in order to make the insert work.
A: Adding myEntities.SaveChanges() after your myEntities.AddToJobs(newJob) call should work.
Here's the relevant documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SHA1 hash binary (20) to string (41) I have a function that creates a binary sha1, but I need a result as a 40-byte string, (+1 for null-t).
Is there a better way of converting it to string, than this?
unsigned char hash_binary[20] = "\xFF\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01";
char hash_string[41];
int i;
for(i = 0;i < 20; i++)
sprintf( hash_string + i*2, "%02X", hash_binary[i] );
hash_string[40] = 0;
This calls sprintf 20 times. How can I avoid it?
A: You can populate the target string directly:
static const char alphabet[] = "0123456789ABCDEF";
for (int i = 0; i != 20; ++i)
{
hash_string[2*i] = alphabet[hash_binary[i] / 16];
hash_string[2*i + 1] = alphabet[hash_binary[i] % 16];
}
hash_string[40] = '\0';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Event execution in JavaScript Say, JavaScript is in the middle of executing some method, and I'm pressing a button which has some event handler attached. Will the current method execution get paused and the click event handler start executing right away, or will js finish method execution and only then proceed with executing the click event handler?
A: The event will fire after the current Javascript finishes execution, since Javascript is single threaded. This is also why your browser can lock up.
A: The currently executing code will continue running until it has returned and then the next event will be run out of the event queue. Will be most likely your mouse click event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to Determine Optimal MySQL Table Indexes, When Contents of WHERE Clause Vary? I have the following 2 mysql_queries:
Query 1 (this query is repeated twice more for imgClass, and imgGender):
$imgFamily_query = "SELECT DISTINCT imgFamily FROM primary_images WHERE '$clause' ";
Query 2:
$query_pag_data = "SELECT imgId, imgURL, imgTitle, view, secondary FROM primary_images WHERE '$clause' ORDER BY imgDate DESC";
As you can see, the WHERE is controlled by a variable. This variable is calculated as follows:
$where_clauses = array();
if ($imgFamilyFalse && $imgClassFalse && $imgGenderFalse) {
$where_clauses[] = "1=1"; // default do-nothing clause
}
if ($imgFamilyTrue) {
$where_clauses[] = 'imgFamily=' . "'" . mysql_real_escape_string($_GET['imgFamily']) . "'";
}
if ($imgClassTrue) {
$where_clauses[] = 'imgClass=' . "'" . mysql_real_escape_string($_GET['imgClass']) . "'";
}
if ($imgGenderTrue) {
$where_clauses[] = 'imgGender=' . "'" . mysql_real_escape_string($_GET['imgGender']) . "'";
}
$clause = implode(' AND ', $where_clauses);
The WHERE clause is only dependant upon the following 3 columns:
*
*imgFamily
*imgClass
*imgGender
However, depending upon the situation, a combination of any 1, 2, or 3 of those columns are utilized.
My question is, how should I go about setting up the indexes for primary_images in this situation? It is a 'read-only' table, so I'm not concerned about having too many indexes. I would like the table to be as efficient in its querying as possible.
I was thinking about using a Multiple Column Index, but because the first column in the Multiple Column Index may not be present, the Index would not work.
Is it possible to set up several Multiple Column Indexes? Or would it be better in this case to just place an index on each of the 3 columns in question?
A: I'm guessing imgGender will contain only 2 or 3 values - M, F and possible unknown? In that case, it makes a poor candidate for an index.
So, I think you can get away with 2 indices. Index one should use only imgClass, and will be hit when the imgFamily column isn't part of the where clause. Index two should be a compound index, using imgFamily and imgClass; this should be used even if imgClass isn't part of the where clause.
A: As per your situation its better to keep 3 separate indexes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP shell_exec() issue I am having an issue using the PHP function shell_exec().
I have an application which I can run from the linux command line perfectly fine. The application takes several hours to run, so I am trying to spawn a new instance using shell_exec() to manage better. However, when I run the exact same command (which works on the command line) through shell_exec(), it returns an empty string, and it doesn't look like any new processes were started. Plus it completes almost instantly. shell_exec() is suppose to wait until the command has finished correct?
I have also tried variations of exec() with the same outcome.
Does anyone have any idea what could be going on here?
There are no symbolic links or anything funky in the command: just the path to the application and a few command line parametes.
A: Some thing with you env
See output of env from cli (command line interface) and php script
Also see what your shell interpreter?
And does script and cli application runs from one user?
If so, se option safe_mode
A: Make sure the user apache is running on (probably www-data) has access to the files and that they are executable (ls -la). A simple chmod 777 [filename] would fix that.
By default PHP will timeout after 30 sec. You can disable the limit like this:
<?php
set_time_limit(0);
?>
Edit:
Also consider this: http://www.rabbitmq.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to auto start a a href="javascript:void window.open( open loading <a href="javascript:void window.open('website', 'pukarock', 'width=1018, height=715, scrollbars=yes, resizable=yes');">click me</a>
How do you auto start this in HTML as onload? Other stuff I researched doesn't work. I only want my website to open up in a new window and has to work with blogspot.
A: Put it in a script block, not an A-tag.
<script type='text/javascript'>
window.open('website', 'pukarock', 'width=1018, height=715, scrollbars=yes, resizable=yes')
</script>
A: Don't use href="javascript:void"
It means people without javascript cannot use the link. Use something like this instead.
<a href="http://www.mysite.com/" onclick="openNewWindow(this.href); return false;">Click</a>
Then add this to the head of your page
<script>
function openNewWindow(url) {
window.open(url, 'pukarock', 'width=1018, height=715, scrollbars=yes, resizable=yes')
}
</script>
A: If you want open page after load content, use this:
<!--use some standards of html-–>
<html>
<head>
</head>
<body onload="openSite();">
<script type='text/javascript'>
function openSite()
{
window.open('website','pukarock','width=1018,height=715,scrollbars=yes,resizable=yes');
}
</script>
</body>
</html>
But it could show pop up window warning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Ajax calls in Widgets in jQuery Dashboard I am using the jQuery Dashboard plugin to display MySql table information. I have within these widgets buttons for each mysql result to display a form. The button performs an ajax call to pass in the form id and then retrieve the styled form information to be displayed in a jQuery dialog. The issue is that the first time visiting the dashboard and trying to click a button requires multiple clicks for the form to be retrieved. I have several widgets in the dashboard that use this technique (3 to be exact) and it just so happens to take 2 clicks before the 3rd will return the form. Could this be due to the button instances in different widgets? I thought so, and as a result made different classes for each button with same ajax code. The problem, however, persists. This is an extraordinarily annoying bug that I CANNOT figure out and have been trying to for 4 DAYS on this 1 bug alone. Below is my ajax code:
$(".view_all").click(function(){
var form_id = $(this).attr("id");
$.ajax({
type: "GET",
url: "form.php",
data: "fid="+form_id,
beforeSend: function(){
$("#loading").show();
},
success: function(msg){
$("#pop_container").html(msg);
$("#pop_container").dialog({
autoOpen: false,
height: 750,
width: 950,
modal: true,
closeOnEscape: false
});
$("#pop_container").dialog("open");
$("#loading").hide();
}
});
return false;
});
My apologies for the code not being formatted well. I tried but it didnt work.
Anyway, any help on this would be extremely helpful. Thanks!
A: As i previously said, a live example would have helped but i still took a look at this code and everything seemed pretty alright, assuming you're ajax calls always return what it should return (did you verify with firebug or somethin?). You should put this piece of your code in the dom ready function:
$("#pop_container").dialog({
autoOpen: false,
height: 750,
width: 950,
modal: true,
closeOnEscape: false
});
Instead of setting this in the callback. So you just have to call $('#pop_container').dialog('open'); in the callback. Now if this is not enough, and it shouldn't be enough, you can manually trigger a click in jQuery ($('.view_all').trigger('click')) but this is not really "clean". Don't know if this helps but i can't do more without completely understanding whats going on :P
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compounding switch regexes in Vim I'm working on refactoring a bunch of PHP code for an instructor. The first thing I've decided to do is to update all the SQL files to be written in Drupal SQL coding conventions, i.e., to have all-uppercase keywords. I've written a few regular expressions:
:%s/create table/CREATE TABLE/gi
:%s/create database/CREATE DATABASE/gi
:%s/primary key/PRIMARY KEY/gi
:%s/auto_increment/AUTO_INCREMENT/gi
:%s/not null/NOT NULL/gi
Okay, that's a start. Now I just open every SQL file in Vim, run all five regular expressions, and save. This feels like five times the work it should be. Can they be compounded in to one obnoxiously long but easily copy-pastable regex?
A: why do you have to do it in vim? how about sed/awk?
e.g. with sed
sed -e 's/create table/\U&/g' -e's/not null/\U&/g' -e 's/.../\U&/' *.sql
btw, in vi you may do
:%s/create table/\U&/g
to change case, well save some typing.
update
if you really want a long command to execute in vi, maybe you could try:
:%s/create table\|create database\|foo\|bar\|blah/\U&/g
A: *
*Open the file containing that substitution commands.
*Copy its contents (to the unnamed register, by default):
:%y
*If there is only one file where the substitutions should be
performed, open it as usual and run the contents of that register
as a Normal mode command:
:@"
*If there are several files to edit automatically, open those
files as arguments:
:args *.sql
*Execute the yanked substitutions for each file in the argument list:
:argdo @"|up
(The :update command running after the substitutions, writes
the buffer to file if it has been changed.)
A: While sed can handle what you want (hovewer it can be interactive as you requestred by flag 'i'), vim still much powerfull. Once I needed to change last argument in some function call in 1M SLOC code base. The arguments could be in one line or in several lines. In vim I achieved it pretty easy.
You can open all php files in vim at once:
vim *.php
After that run in ex mode:
:bufdo! %s/create table/CREATE TABLE/gi
Repeat the rest of commands. At the end save all the files and exit vim:
:xall
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DCH class error with JavaMail I'm attempting to set up a simple logging test with JavaMail in Java EE 6, using the jar files provided with Glassfish 3.1. There seems to be a wealth of questions out there on this subject, but I haven't found any answers that have helped yet. My test code looks like this:
import java.util.logging.Logger;
public class MyClass {
private static final Logger LOGGER = Logger.getLogger("MyClass");
public static void main(String[] args) {
LOGGER.severe("This is a test");
}
}
My logging.properties file contains this:
com.sun.mail.util.logging.MailHandler.mail.smtp.host={my mail hub FQDN}
com.sun.mail.util.logging.MailHandler.mail.smtp.port=25
com.sun.mail.util.logging.MailHandler.mail.to={me}
com.sun.mail.util.logging.MailHandler.mail.from={support address}
com.sun.mail.util.logging.MailHandler.level=WARNING
com.sun.mail.util.logging.MailHandler.verify=local
com.sun.mail.util.logging.MailHandler.subject=Application Error
com.sun.mail.util.logging.MailHandler.formatter=java.util.logging.SimpleFormatter
I build the class using:
javac -cp $AS_INSTALL/glassfish/modules/javax.mail.jar:$AS_INSTALL/install/lib/external/jaxb/activation.jar:. MyClass.java
Then I run the program using:
java -cp $AS_INSTALL/glassfish/modules/javax.mail.jar:$AS_INSTALL/install/lib/external/jaxb/activation.jar:. -Djava.util.logging.config.file=logging.properties MyClass
This results in the following error:
Sep 22, 2011 4:19:25 PM MyClass main
SEVERE: This is a test
java.util.logging.ErrorManager: 3: SEVERE: no object DCH for MIME type multipart/mixed;
boundary="----=_Part_1_26867996.1316722766145"
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
boundary="----=_Part_1_26867996.1316722766145"
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:877)
at javax.activation.DataHandler.writeTo(DataHandler.java:302)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1476)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1772)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1748)
at com.sun.mail.util.logging.MailHandler.toRawString(MailHandler.java:2196)
at com.sun.mail.util.logging.MailHandler.send(MailHandler.java:1597)
at com.sun.mail.util.logging.MailHandler.close(MailHandler.java:552)
at java.util.logging.LogManager.resetLogger(LogManager.java:693)
at java.util.logging.LogManager.reset(LogManager.java:676)
at java.util.logging.LogManager$Cleaner.run(LogManager.java:221)
javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
boundary="----=_Part_1_26867996.1316722766145"
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1141)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.sun.mail.util.logging.MailHandler.send(MailHandler.java:1594)
at com.sun.mail.util.logging.MailHandler.close(MailHandler.java:552)
at java.util.logging.LogManager.resetLogger(LogManager.java:693)
at java.util.logging.LogManager.reset(LogManager.java:676)
at java.util.logging.LogManager$Cleaner.run(LogManager.java:221)
Caused by: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
boundary="----=_Part_1_26867996.1316722766145"
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:877)
at javax.activation.DataHandler.writeTo(DataHandler.java:302)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1476)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1772)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1099)
... 7 more
I've verified that my javax.mail.jar file contains the multipart handler:
unzip -l $AS_INSTALL/glassfish/modules/javax.mail.jar | grep multipart
2617 01-14-2011 15:37 com/sun/mail/handlers/multipart_mixed.class
I've even run the program with the activation debugging enabled. This shows me the following related parts:
parse: multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed; x-java-fallback-entry=true
Type: multipart/*
Command: content-handler, Class: com.sun.mail.handlers.multipart_mixed
MailcapCommandMap: createDataContentHandler for multipart/mixed
search DB #1
search DB #2
search fallback DB #1
got content-handler
class com.sun.mail.handlers.multipart_mixed
Can't load DCH com.sun.mail.handlers.multipart_mixed; Exception: java.lang.ClassNotFoundException: com/sun/mail/handlers/multipart_mixed
I even get a duplicate of the above for type text/plain.
MailcapCommandMap: createDataContentHandler for text/plain
search DB #1
got content-handler
class com.sun.mail.handlers.text_plain
Can't load DCH com.sun.mail.handlers.text_plain; Exception: java.lang.ClassNotFoundException: com/sun/mail/handlers/text_plain
What am I missing here?
Thanks,
Steve
A: In my case I was able to solve this by adding this before send():
Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
This was suggested in linked blog, so if you want to know more details, read it. Thanks to Jerry Gu for linking it here and original blogger.
URL: http://blog.hpxn.net/2009/12/02/tomcat-java-6-and-javamail-cant-load-dch/
A: I found the solution here:
http://blog.hpxn.net/2009/12/02/tomcat-java-6-and-javamail-cant-load-dch/
Though I would love to know more about the details behind why this is an issue and what this -Xbootclasspath option is doing to correct the problem. If I run my class like this:
java -Djava.util.logging.config.file=logging.properties -Xbootclasspath/p:/app/glassfish-3.1/glassfish/modules/javax.mail.jar MyClass
It finds the necessary classes and I get my email. Now I just have to figure out how to translate this configuration into my Glassfish server and try a more "real" test from this simple test case.
A:
Though I would love to know more about the details behind why this is an issue and what this -Xbootclasspath option is doing to correct the problem.
It has to do with classloader tree. Recall that child classloaders are allowed to look up classes in the parent class loader but not the other way around. In your sample program, the classloader tree looks like this:
Running under JDK6, JDK7, and JDK8
+---Boot ClassLoader--+
| java.util.logging.* |
| javax.activation .* |
+---------------------+
^
|
+-----System ClassLoader------+
| javax.mail.* |
| com.sun.mail.handlers.* |
| com.sun.mail.util.logging.* |
+-----------------------------+
When the LogManager$Cleaner shutdown hook runs (JDK6+) the context classloader is forced to boot classloader which is unable to locate the com.sun.mail.handlers.text_plain class because it is in a child classloader. Because of this, modifying the MailcapCommandMap to include the mailcap class names won't fix the problem. When you use the -Xbootclasspath option you are placing all relevant classes in the boot class loader which is visible to the LogManager$Cleaner. However, don't modify your system to use -Xbootclasspath to fix this issue.
Instead, upgrade to JavaMail 1.5.3 or later which contains the fix for Bug K6552 | GH133 - Use classloader ergonomics in the MailHandler. If you want to upgrade JavaMail module of GlassFish, you can replace the glassfish-X.X/glassfish/modules/javax.mail.jar with a newer version of JavaMail.
The incomplete fix applied to JavaMail 1.4.7 was to set the context class loader to the class loader that loaded the MailHandler during close. The assumption is that the classloader that loaded the MailHandler should be able to find the activation code.
If you can't upgrade to a newer version of JavaMail then you have to apply one of the following workarounds:
*
*Flush or close the MailHandler before the cleaner runs.
*Flush all handlers before the cleaner runs (I.E. web app undeploy). You have to synchronize on the LogManager and collect all handlers from each logger. Flush all of the handlers outside of the synchronized block.
* Extend the MailHandler and override close to set and restore the context class loader if the context class loader is null.
* Install a new LogManager and override reset to set and restore the context class loader if the context class loader is null.
*Install a subject formatter to set the context class loader if the cleaner is running.
*Set the push level to ALL or set the capacity to 1 so an email is sent for every log record and get spammed.
*Run on a Java version with patched with RFE JDK-8025251.
The main problem is that the LogManager$Cleaner forces the context classloader to null before it calls close on every Handler registered with the LogManager. A better choice for the LogManager would have been to set the context classloader to the handler class loader before calling close then after all handlers are closed set the context class loader to null. This could still be fooled by nesting handlers but at least it would have fixed the common case. This was filed as RFE JDK-8025251 "LogManager cleaner should use handler classloader during close".
A: Probablity is high that if you are working on the KARAF(OSGI) server the above suggestions will be difficult to implement as Karaf dont have a startup class or bootup classpath.
I found that activation.jar conflict created this issue .
{FUSEESB_HOME Or ServiceMIX_HOME}/etc/jre.properties was loading activation.jar .
Once commented everything was smooth.
Please refer the link below.
A: Add these before you send your message:
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
I got the problem in my Android app and it works.
A: I bumped into this issue today, and it had to do with the thread's class loader.
if you do a sysout on:
com.sun.mail.handlers.multipart_mixed.class.getClassLoader()
it may not be the same as the current thread's classloader:
Thread.currentThread().getContextClassLoader()
I was able to arrive at this conclusion by adding the following arg:
-Djavax.activation.debug=true
After adding that arg, I saw that it was unable to load the data content handler (DCH) for multipart_mixed.class.
How you resolve your classloader issues is up to you, but this should get you started.
A: For all having this error message above, it turned out that in my case the authentication data was empty, this was due that I had turned off the mail server authentication I didnt needed a username and password anymore, but the empty values were parsed somehow and created a missing authentication error, that wasnt caught well in Mail 1.4.0, updating to Mail 1.4.7 and deleting the two param-entries below resolved the problem.
<appender name="ALARM_MAIL" class="my.utils.SMTPAppender">
<!-- remove this line: <param name="SMTPUsername" value=""/> -->
<!-- remove this line: <param name="SMTPPassword" value=""/> -->
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Make a textbox click a button if you hit enter So I have looked at some previous example online and it seems prettys strait forward
<form:input path="searchParameter.instanceName" id="searchBox" onkeydown="if (event.keyCode == 13){ document.getElementById('btnSearch').click() return false }"/>
And it works fine with firefox but it does not work at all with I.E. 7 it just submits the form. Any idea wh
A: You seem to be missing a semicolon.
document.getElementById('btnSearch').click(); return false ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript function returning fixed value from array I'm newbie with JavaScript, so I decided to develop a little application which is supposed to show the schedule of the streetcar of the place I live, because of the lack of the information on the official webpage.
I have several arrays with the starting time of the line, and as the time to reach each station it's the same, I only have to add the total minutes to the first hour.
There's a form for the user to set a range of hours. So, my main problem is that the "adder();" function is supposed to iterate and print all the values from an array. Instead of doing that, it takes always the same index, 24, so if the array returned has less than 24 indexes, it does not work.
Here's the HTML:
< input type="button" class="submit" value="Enviar" onclick="caller()"/>
JavaScript:
function cropHours(i){
if (i.substr(0,2) >= hora1user_recortada && i.substr(0,2) <= hora2user_recortada) {
horas.push(i);
}
return horas;
}
function adder() {
minInicio1 = horas[i].substr(0,2);
minInicio2 = horas[i].substr(3,2);
document.getElementById("test4").innerHTML = "---" + minInicio1+"_"+minInicio2;
y = parseInt(total) + parseInt(minInicio2);
document.getElementById("test5").innerHTML = "total vale "+total+"minInicio1 vale "+minInicio1+"... minInicio2 vale "+minInicio2+"...Y vale "+y;
html += "<td>"+y+"</td>";
document.getElementById("horario").innerHTML = html;
}
This is a part of another function:
if (platform == 1) {
for (var j = 0; j <= indexorigen; j++) {
total += mins1[j];
}
for (var j = 0; j <= indexdestino; j++) {
total2 += mins1[j];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral1) {
cropHours(i);
//adder(horainiciolaboral1);
}
} else {
for each (var i in horainiciofinde1) {
cropHours(i);
}
}
} else {
for (var x = 0; x <= indexorigen; x++) {
total += mins2[x];
}
for (var x = 0; x <= indexdestino; x++) {
total2 += mins2[x];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral2) {
cropHours(i);
}
} else {
for each (var i in horainiciofinde2) {
cropHours(i);
}
}
}
/*for (var i = 0; i <= horainiciolaboral1.length; i++) {
adder(horainiciolaboral1);
}*/
//horario = horas.slice(11);
for each (var i in horas) {
adder();
}
document.getElementById("test6").innerHTML = horas;
document.getElementById("test3").innerHTML = total + "----" + total2;
// ******************************************
// ** FUNCTION WHICH CALLS EVERY FUNCTION **
// ******************************************
// STARTS
function caller() {
cleaner();
retrieve_origen();
retrieve_destino();
getIndex();
sumMinutes();
getHours();
}
This is the problem:
for each (var i in horas) {
adder();
}
Thank you in advance.
A: Pass i to adder() as an argument:
adder(i);
...and define it as a parameter in the function:
function adder( i ) {
//...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flickr image url suffix medium 500 It says to use a '-' but that doesn't work for me..
Size Suffixes
The letter suffixes are as follows:
s small square 75x75
t thumbnail, 100 on longest side
m small, 240 on longest side
- medium, 500 on longest side
z medium 640, 640 on longest side
b large, 1024 on longest side*
o original image, either a jpg, gif or png, depending on source format
http://farm6.static.flickr.com/5025/5680710399_b609135279_-.jpg
A: http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
In the explanation, they are using - as a symbol for "no suffix at all", so the URL
http://farm6.static.flickr.com/5025/5680710399_b609135279.jpg
is what you're looking for if you want 500px length.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby on Rails 3: How to override/change as_json serialization for ActiveSupport::TimeWithZone? When Rails3 serializes ActiveSupport::TimeWithZone to json that dates look something like this:
"2011-07-20T23:59:00-07:00"
... it should be ...
"2011-07-20T23:59:00-0700"
That last colon is problematic when trying to convert that string using standard date formatting patterns ... none of them account for the use of a colon!
So my question is, "How do I override/change the serialization for TimeWithZone so that as_json returns a valid string that can be understood using the standard date format patterns?"
Right now I have to strip that last colon out in my client app but that just seems pooch.
A: It is a monkey patch, but hey it is Ruby and that is allowed.
module ActiveSupport
class TimeWithZone
def to_json
super.gsub(/:(?!.*:)/,'')
end
end
end
Tested by running:
Time.zone = 'Eastern Time (US & Canada)'
Time.zone.now.to_json # Outputs -> 2011-09-22T16:46:28-0400
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Extension method precedence I'm a bit confused about how extension methods work.
If I'm reading this correctly http://msdn.microsoft.com/en-us/library/bb383977.aspx and this If an extension method has the same signature as a method in the sealed class, what is the call precedence?.
Then the following should write out "Instance", but instead it writes "Extension method".
interface IFoo
{
}
class Foo : IFoo
{
public void Say()
{
Console.WriteLine("Instance");
}
}
static class FooExts
{
public static void Say(this IFoo foo)
{
Console.WriteLine("Extension method");
}
}
class Program
{
static void Main(string[] args)
{
IFoo foo = new Foo();
foo.Say();
}
}
Appreciate any help in clarifying the behavior.
A: In your Main,
foo is declared as IFoo. When the compiler looks for a method Say, it finds only the extension method. This is because the instance method is declared in Foo, not in IFoo. The compiler doesn't know that the variable foo happens to contain a instance of Foo; it just looks at the type the variable is declared of.
A: The big difference here is that you have defined an extension method for the IFoo interface, and your foo variable is of type IFoo.
If your code was to look like this:
Foo foo = new Foo();
foo.Say()
The Foo.Say() method would be executed, not the extension method.
I wish I could give you a thorough explanation on why this is but I can only cover the basic mechanism. As your variable was of IFoo type and not of Foo, when the compiler tried to determine what methods were available, it looked past any non-interface methods of the Foo class (as it should). However, the extension method Say() was available, so it invoked this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Tracking pixel (transparent GIF) as a background-image in a stylesheet? Anyone know if adding a tracking pixel (just a transparent GIF with some logging going on at the server that's sending out the GIF) as a background-image in a linked stylesheet will work the same as if it was a regular <img> on a page?
From a simple test I did in Chrome's network inspector it looks like it's just pulling images from local cache if I go into the location bar and hit enter. If I actually click Reload then I see it go out to the server and get back a 304. And if I shift+reload it'll force it to go back to the server for real and I get 200s.
But, it looks like it's the same behavior for the <img> images on the page as well, so then the behavior as a background-image should match the behavior as if it was an <img>
A: It should work exactly the same way. But tracking pixels are not decorative, or are specific to a single page, so it is easier to put an img tag in the HTML and a little more reliable, it will work for text browsers, etc.
A: Having a tracking pixel called via CSS would be possible, but there would be some challenges compared to using a tracking pixel in HTML:
*
*Tracking pixels commonly have visitor data detected by JavaScript (monitor size, for instance) added to the pixel's URL. JavaScript would be unable to (easily) do this if the pixel was called via stylesheet.
*When in the page source, the tracking pixel can be at the bottom of the page and be modified by code that executes first. This would be difficult to do in a single-pixel-call via CSS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: sending frames using sockets I've been asked to make a JAVA application for sending frames using sockets, my question is simple, is there anything special with this "frames"? i mean, i know how to transport bytes through net, I have knowledge about sockets, but I really don't know what are this frames , should i assume that by saying "frames" they are just referring to a specific structure of bytes to send?
they specify that the "frames" must have this structure:
*
*Header: E
*CRC: 8AFE
*Date: 110825080000
*Final Coin In: 2176
*Final Coin Out: 12345
*Reserved: 0
so passing this to hex is
*
*45
*8A FE
*31 31 30 38 32 35 30 38 30 30 30 30
*30 30 30 30 30 30 32 31 37 36
*30 30 30 30 30 31 32 33 34 35
*30 30 30 30 30 30 30 30 30 30
so if im correct, the frame (that i will convert to bytes later) to send is:
45 8A FE 31 31 30 38 32 35 30 38 30 30 30 30 30 30 30 30 30 30 32 31 37 36 30 30 30 30 3031 32 33 34 35 30 30 30 30 30 30 30 30 30 30
My question is am I correct about this, or am I missing something? maybe i'm completely wrong? :s
Thanks in advance
PD: sorry if this is a dumb question :/
A: The Java sockets API works at Layer 7. You can send UDP packets or TCP/IP streams, but you cannot send or receive Ethernet frames with the standard Java.net package.
In other words, you can send and receive PAYLOADS, but you cannot read or write HEADERS (e.g. TCP-packet or Ethernet-frame headers).
At least not without writing your own JNI code, or using a 3rd party library for "raw sockets". For example: https://www.savarese.com/software/rocksaw/
A:
I really don't know what are this frames , should I assume
No. You should ask whoever gave you the requirement. Nobody wants guessing games.
EDIT: however, I will add two observations. First, the chances of anyone ever asking you to write out Ethernet frames directly in your entire career are vanishingly small. Second, that is not an Ethernet frame format, as even Google would have told you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Colorize grayscale image I have a grayscale image and a some color, represented in RGB triplet. And i need to colorize grayscale image using this triplet.
The left image represents what we have and the right what i need to have.
Now in program i have some function where in input is R, G and B value of source image and and RGB value color which should be used as coloring value.
And i can't decide how can i increase or decrease source RGB using color RGB to have the right color pallette.
The language is C++, but it's not so important.
Thanks in advance.
A: The other answers suggest multiplying the grayscale value by the target RGB color. This is okay, but has the problem that it will alter the overall brightness of your picture. For example, if you pick a dark shade of green the whole image will go darker.
I think the RGB color model is not best suited for this. An alternative would be to pick the color alone, without an associated brightness, then colorize the image while preserving the original brightness of each pixel.
The algorithm would be something like this:
*
*pick the target color in terms of two values, a Hue and a Saturation. The hue determines the tone of the color (green, red, etc.), and the saturation determines how pure the color is (the less pure the more the color turns to gray).
*Now for each pixel in your grayscale image, compute the new pixel in the HLS color model, where H and S are your target hue and saturation, and L is the gray value of your pixel.
*Convert this HLS color to RGB and save to the new picture.
For the algorithm to convert HLS to RGB see this page or this page.
A: Conceptually, you'd take the greyscale value of each pixel in the original image and use that as a percentage of the green value. so if a pixel has greyscale value 87, then the equivalent pixel in the colorized image would be:
colorized_red = (87 / 255) * red_component(green_shade);
colorized_green = (87 / 255) * green_component(green_shade);
colorized_blue = (87 / 255) * blue_component(green_shade);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to hide everything after a dollar sign in a String JQuery I have a string like this:
string="Awesome Option +$399.99";
I want to remove the +$399.99 (and any other pricing details) from the string, how would you do that?
Oh and the string could also possibly look like this:
string="#4 Cool Option +$23.99"
A: var text = 'Awesome Option +$399.99';
text = text.substring(0, text.indexOf('+$'));
// text is "Awesome Option "
A: You would do: string.replace(/\s*\+\$.*$/, ''). Note that this does not depend on jQuery.
This also removes white space in front of the +$. If the + is optionally there, you'd use string.replace(/\s*\+?\$.*$/, '').
A: var originalString = "Awesome Option +$399.99"
var truncatedString = originalString.split("+")[0]
Using the same logic you could extract just the price this way, or both at the same time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass a Bash variable to Python? Eventually I understand this and it works.
bash script:
#!/bin/bash
#$ -V
#$ -cwd
#$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y
#$ -S /bin/bash
#$ -l mem_free=4G
c=$SGE_TASK_ID
cd /home/xxx/scratch/test/
FILENAME=`head -$c testlist|tail -1`
python testpython.py $FILENAME
python script:
#!/bin/python
import sys,os
path='/home/xxx/scratch/test/'
name1=sys.argv[1]
job_id=os.path.join(path+name1)
f=open(job_id,'r').readlines()
print f[1]
thx
A: Exported bash variables are actually environment variables. You get at them through the os.environ object with a dictionary-like interface. Note that there are two types of variables in Bash: those local to the current process, and those that are inherited by child processes. Your Python script is a child process, so you need to make sure that you export the variable you want the child process to access.
To answer your original question, you need to first export the variable and then access it from within the python script using os.environ.
##!/bin/bash
#$ -V
#$ -cwd
#$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y
#$ -S /bin/bash
#$ -l mem_free=4G
c=$SGE_TASK_ID
cd /home/xxx/scratch/test/
export FILENAME=`head -$c testlist|tail -1`
chmod +X testpython.py
./testpython.py
#!/bin/python
import sys
import os
for arg in sys.argv:
print arg
f=open('/home/xxx/scratch/test/' + os.environ['FILENAME'],'r').readlines()
print f[1]
Alternatively, you may pass the variable as a command line argument, which is what your code is doing now. In that case, you must look in sys.argv, which is the list of arguments passed to your script. They appear in sys.argv in the same order you specified them when invoking the script. sys.argv[0] always contains the name of the program that's running. Subsequent entries contain other arguments. len(sys.argv) indicates the number of arguments the script received.
#!/bin/python
import sys
import os
if len(sys.argv) < 2:
print 'Usage: ' + sys.argv[0] + ' <filename>'
sys.exit(1)
print 'This is the name of the python script: ' + sys.argv[0]
print 'This is the 1st argument: ' + sys.argv[1]
f=open('/home/xxx/scratch/test/' + sys.argv[1],'r').readlines()
print f[1]
A: Take a look at parsing Python arguments. Your bash code would be fine, just need to edit your Python script to take the argument.
A: use this inside your script (EDITED per Aarons suggestion):
def main(args):
do_something(args[0])
if __name__ == "__main__":
import sys
main(sys.argv[1:])
A: Command line arguments to the script are available as sys.argv list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: SQL Azure: SMO Exception when scripting objects in SSMS 2008 R2 I am using SQL Server Management Studio 2008 R2 to manage a SQL Azure database. When I try to right-click on any of the objects in the database, and do Script Table As -> CREATE -> New Query Editor Window, I get the following exception screen every time:
Scripting for SELECT -> New Query Editor Window is the only option that seems to work without generating an Exception like above. Any ideas??
A: Here are additional details about this issue.
Latest service update for SSMS: http://support.microsoft.com/kb/2507770
Blog discussing the necessary upgrade: http://social.msdn.microsoft.com/Forums/en-AU/ssdsgetstarted/thread/3dd65548-cf58-41e8-804d-3f6873132a7b
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Threadpool local variable concepts I am trying to multi thread my application using ThreadPool in c#. I have a 3D array in which I have to process for every row separately. I have spawned out threads equal to number of processors(cores) in the system and then dividing the task between the threads to process on the individual rows.
A single function is called for all the threads in which I am using the thread to divide the data between different threads. (Kind of SIMD thing). The function calls other small functions as well. Also the functions create dynamically allocated arrays as a temporary storage space for intermediate values. I want to know what is the concept of local variables in threads. Does calling a single function in multiple threads make local copies of the variables in individual threads? How do I go about designing such a code?
Please explain..
A:
Does calling a single function in multiple threads make local copies of the variables in individual threads??
Well, it's not that it makes local copies of the variables. Every local variable / thread pair is a specific storage location, and that storage location is not the same for any other local variable / thread pair.
I have spawned out threads equal to no of processors(cores) in the system and then dividing the task between the threads to process on the individual rows.
Why are you doing this yourself? Use the TPL.
A: I think you should rethink the solution and try to use Parallel.For for your solution.
MSDN Parallel.For
But to answer your question you can use a single function in multiple threads if it is designed to be thread safe. And you can use local variables in your functions because they are local to the function and every call will get a separate memory location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: android animation starting new activities or dismissing an Activity Is there a tutorial or a code example of various kinds of View Animations available in Android. Basically what I am trying to do is say if start a new Activity, I am trying to get that activity start out like zoom in till it fills the screen or Fade out when I am going to finish the activity. Is there a way i can do this ?
Any help will be greatly appreciated.
Thanks
-Chandu
A: So you need to use OverridePendingTransition from the activity: http://developer.android.com/reference/android/app/Activity.html
Some examples with Fade in/out can be found here: http://www.anddev.org/novice-tutorials-f8/splash-fade-activity-animations-overridependingtransition-t9464.html
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/decelerate_interpolator"
android:zAdjustment="top"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000" />
Zoom:
<scale
android:pivotX="50%"
android:pivotY="50%"
android:fromXScale=".1"
android:fromYScale=".1"
android:toXScale="1.0"
android:toYScale="1.0"
android:duration="2000" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery (or textOverflow) taking too long When we detect Firefox, we call
jQuery('.trunc').textOverflow();
but if the page is long, Firefox puts up the "unresponsive script" alert. I believe the actual problem is in the initial jQuery call (when it finds all matching DOM elements by their CSS).
I'm no jQuery expert but it looks like it really favors a style where it builds up lists of selected items and passes them down a chain. So there may not be a great workaround. But, is there one? I don't care about chaining, I just want to send textOverflow to relevant elements.
A: A little bit of a shot in the dark, but you may want to try altering the selector to include the tag name as well. Since this avoids querying the entire DOM, and limits it to just those tags, it will be more efficient.
jQuery('span.trunc').textOverflow();
Replace span with the relevant tag. Not sure if it'll make a difference, but it's more efficient anyways :)
Good luck!
A: It would depend on how many elements you are talking about, however the class selector you have should be very fast in Firefox, even with many elements. This is because Firefox supports the getElementsByClassName native method... so the selector you have would essentially be the same as a call to document.getElementsByClassName("trunc").
I think that the culprit would be the textOverflow calls because Firefox doesn't natively support this CSS feature, so I'd imagine the textOverflow plugin would be doing a lot of string processing/DOM/CSS manipulation to get the proper text-overflow behavior.
You could test this out by just calling the selector without the textOverflow() call and see how long it takes:
var truncElements = $('.trunc');
If the code above runs quickly on your large pages in Firefox, then I'd blame textOverflow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: choose the selected value in a item template I have a method called BindItems() and this method gets the values to a DataTable and then a GridView is bound to it.
Then I have an itemtemplate in that gridview which contains a drop down, this drop down gets populated from 1 -14 from code behind under Gridview_RowDataBound, now I need to figure a way to get the Quantity value in the DataTable on the other function "BindItems()" and for each Row in the gridview so a SelectedValue = datatable["Quantity"] or something.. how can I do this?
protected void BinItems(int myId)
{
//this data table contains a value "Quantity"
DataTable dt = MyClass.getItems(myId);
uxGrid.DataSource = dt;
uxGrid.DataBind();
}
protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList Myddl = e.Row.FindControl("MyQuantity") as DropDownList;
if (Myddl != null)
{
for (int i = 1; i < 15; i++)
{
Myddl.Items.Add(i.ToString());
}
}
}
//Some how i need to do a SelectedValue = datatable where field = Quantity for each row
}
A: You need to access the current-being-bound-row's DataItem, which in your case, is a DataRowView (since you are binding to a DataTable):
protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList Myddl = e.Row.FindControl("MyQuantity") as DropDownList;
if (Myddl != null)
{
for (int i = 1; i < 15; i++)
{
Myddl.Items.Add(i.ToString());
}
}
}
//here goes the "magic"
DataRowView dRow = e.Row.DataItem as DataRowView;
if(dRow != null)
{
Myddl.SelectedValue = dRow["Quantity"].ToString();
}
}
A: you should outside the DataTable dt and then youll be able to access it in the Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change label text before file read happens I haven't used java in awhile and I am trying to do something like this in one main class:
// do stuff
this.label.setText("Status: IDLE");
// do things
this.label.setText("Status: LOADING..."); // set to loading right before file read
// read and parse huge file
this.label.setText("Status: DONE");
I want the label to show 'loading...' as the large file read is being executed but the label never freezes (as the job is being ran). How can I force the label to change during read? Do I need to use separate class/thread? Thanks in advance for your help.
A:
How can I force the label to change during read? Do I need to use
separate class/thread?
Yes, you are right. The label and the class that is changing it's value should be in different threads.
Have a look at SwingUtilities invokeLater:
Runnable newThread = new Runnable() {
public void run() {
}
};
You can create a thread this way showed above.
A: Execute the file IO in a background thread. And you can use SwingUtilities.invokeLater(...) to ensure setting the label text is done in the EDT. Or you can just use the SwingWorker convenience class that does this all for you.
Happy coding.
A: Yes. You need a separate thread. Take a look at JProgressBar and some examples:
A: Use a SwingWorker for the long running task. Then you can publish the text when the label needs to be updated.
Read up on Concurrency in Swing for more background information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JAR Hell Hacks for Non-OSGi Developers Edit: After reviewing the play, the example I used below is a tad misleading. I am looking for the case where I have two 3rd party jars (not homegrown jars where I have access to the source code) that both depend on different versions of the same jar.
Original:
So I've recently familiarized myself with what OSGi is, and what ("JAR Hell") problems it addresses at its core. And, as intrigued as I am with it (and plan on migrating somewhere down the road), I just don't have it in me to begin learning what it will take to bring my projects over to it.
So, I'm now lamenting: if JAR hell happens to me, how do I solve this sans OSGi?
Obviously, the solution would almost have to involve writing my own ClassLoader, but I'm having a tough time visualizing how that would manifest itself, and more importantly, how that would solve the problem. I did some research and the consensus was that you have to write your own ClassLoader for every JAR you produce, but since I'm already having a tough time seeing that forest through the trees, that statement isn't sinking in with me.
Can someone provide a concrete example of how writing my own ClassLoader would put a band-aid on this gaping wound (I know, I know, the only real solution is OSGi)?
Say I write a new JAR called SuperJar-1.0.jar that does all sorts of amazing stuff. Say my SuperJar-1.0.jar has two other dependencies, Fizz-1.0.jar and Buzz-1.0.jar. Both Fizz and Buzz jars depend on log4j, except Fizz-1.0.jar depends on log4j-1.2.15.jar, whereas Buzz-1.0.jar depends on log4j-1.2.16.jar. Two different versions of the same jar.
How could a ClassLoader-based solution resolve this (in a nutshell)?
A: If you're asking this question from an "I'm building an app, how do I avoid this" problem rather than a "I need this particular solution" angle, I would strongly prefer the Maven approach - namely, to only resolve a single version of any given dependency. In the case of log4j 1.2.15 -> 1.2.16, this will work fine - you can include only 1.2.16. Since the older version is API compatible (it's just a patch release) it's extremely likely that Fizz 1.0 won't even notice that it's using a newer version than it expected.
You'll find that doing this will probably be way easier to debug issues with (nothing confuses me like having multiple versions of even classes or static fields floating around! Who knows which one you're dealing with!) and doesn't need any clever class loader hacks.
A: But, this is exactly what all the appservers out there have to deal with. Pretend that your Fizz and Buzz are web applications (WARs), and Super-Jar is you appserver. Super-Jar will arrange a class loader for each web app that "breaks" the normal delegation model, i.e. it will look locally (down) before looking up the hierarchy. Go read about it in any of the appservers's documentation. For example http://download.oracle.com/docs/cd/E19798-01/821-1752/beade/index.html.
A: Use log4j-1.2.16. It only contains bugfixes wrt 1.2.15.
If Fizz breaks with 1.2.16, fork and patch it, then submit those patches back to the author of Fizz.
The alternative of creating custom classloaders with special delegation logic is very complex and likely to cause you many problems. I don't see why you would want to do this rather than just use OSGi. Have you considered creating an embedded OSGi framework, so you don't have to convert your whole application?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In Team Build, how to checkout and checkin a file that is not on your workspace? I'm customizing my own Team Build workflow, and at some point within the "Run on Agent" sequence, I need to checkout a file that is not in the current workspace, edit and check in again.
I started by creating a sequence that does more or less what the default template does: CreateWorkspace, then GetWorkspace and DownloadFiles. I already have coded activities to Checkin and Checkout files. Doing some research, Microsoft tells you not to use CreateWorkspace:
From MSDN Team Foundation Build Activities
CreateWorkspace Activity
You will probably never need to create or modify an instance of the CreateWorkspace activity. If you are designing a build process that requires one or more additional workspaces, you must create a custom activity to accomplish this goal.
I think that's what I'm going to explore next. Does anybody have a better idea?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Replace a character squence in java using regular expression I have the following text
"This ball isn?t yours, this one is John?s"
I want to correct this to be
"This ball isn't yours, this one is John's"
How can I do this in Java using Pattern and Matcher?
A: string.replaceall
String fixed = old.replaceAll("\\?([ts])", "'$1");
Here's an example
A: In this case you could use:
s = s.replaceAll("\\b?\\b", "'");
Then you'll be much less likely to replace legitimate question marks, as @glowcoder mentioned. However, I think @Philipp is right, and this is really a character-encoding issue. It looks like your text was supposed to be:
"This ball isn’t yours, this one is John’s"
If it was encoded as cp-1252 but decoded as ASCII, the curly single-quotes would be replaced with question marks. If that's the case, you're likely to find other characters, like curly double-quotes (“ ”), en-dash (–) and em-dash (—), that have been munged in the same way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loss of precision with very small numbers in Python arrays I have two arrays in float64 type and when I assign the value of the first to the second it rounds the value. The following simple code illustrates the problem and excludes the possibility of just a mere number representation thing. (I've schematized a fragment of my code to be more readable, but it is in essence the same thing)
X = zeros((2,2))
Y = zeros((2,2))
Z = X #a shorter way of making a new matrix, equal to X...
X[0,0] = Y[0,0]
Z[0,0]=0
print Y[0,0]
print X[0,0]
print type(Y[0,0])
print type(X[0,0])
if X[0,0]==Y[0,0]:
print'they are equal'
else:
print'they are NOT equal'
I ran this little snippet of code for all coefficients and all the outputs are similar to this:
1.90897e-14
0
<type 'numpy.float64'>
<type 'numpy.float64'>
they are NOT equal
It seems to me that the X array is of another type, but it's created in the same way, with the zeros() function with the standard type (float64)
Edit: The arrays are initialized with
X = zeros((2,2), dtype=float64)
Y = zeros((2,2), dtype=float64)
Also included an additional useful print in the example above.
Edit: added the problematic lines, after I found the problem
A: Are you absolutely certain that X is a float64 array? If it were, I'd expect X[0,0] to be 0.0, but you see 0 instead, which looks to me like an integer..
>>> Xf = arange(10,dtype=float64)
>>> Xi = arange(10)
>>> Xf[0]
0.0
>>> Xi[0]
0
>>> Yf = Xf*0.0
>>> Yf[0]
0.0
>>>
>>> Yf[0] = 1.90897e-14
>>> Yf[0]
1.9089700000000001e-14
>>> Xf[0] = Yf[0]
>>> Xf[0]
1.9089700000000001e-14
>>> Xi[0] = Yf[0]
>>> Xi[0]
0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Problem Pushing Large File to Emulator/SDcard with Eclipse DDMS I am using Eclipse DDMS to push a file over onto my Android Emulator sdcard. I select the file and press Open, a dialog pops up and starts pushing the file. In the view "File Explorer" in the DDMS perspective I can see the sdcard directory and can see my file created in it. Then in the popup the progress meter gets halfway then I get this error in the Console window:
[2011-09-22 15:15:56] Failed to push the item(s).
[2011-09-22 15:15:56] (null)
Then the File Explorer completely refreshes and the file disappears. I know the sdcard is setup for 1G of space and the file I am pushing is only 9M.
Here are images during push and after fail.
So what am I doing wrong or what do I need to do to fix this?
A: I know the question is already answered and accepted - but I solved this problem a different way.
Sometimes, I'm not quite sure "why" but the ADB needs to be reset.
When your emulator is running, do the following:
*
*Go to DDMS
*Go to Devices under DDMS
*Select your running emulator so that its highlighted.
*In the top right hand corner of your devices screen there's a little "down arrow". Click it
*Hit the reset ADB option and do not be alarmed by the force quit red text in console window.
You should now be able to push files onto the system fine, as long as your SD card is set to a size that can handle it.
Hope this helps someone!
A: Here is the way you fix it. I had a large file about 160M so what was happening it was most likely timing out. So to fix this I went to the Eclipse Windows -> Preferences -> Android -> DDMS then I set the ADB connection time out to 500000 and checked "Thread updates enabled" and checked Heap updates enabled". I was then able to push any file size up to the sdcard. I got the idea after reading this thread
Restart the IDE in some cases in mine I didn't need to.
A: Can't add a comment so I guess I have to add this as an answer. Does it work if you try doing adb push filename /mnt/sdcard/ftp/new/ ?
If that doesn't work either, try doing a kill-server and start-server on the adb and maybe that'll work.
A: you can upload files to sdcard image using PassMark OSMount - just mount card image in read/write mode and it appears as harddisk in windows. Also much faster than uploading via adb/ddms
A: Just restart the your eclipse IDE.It will work perfectly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Looking for data storage... which to choose I have an application where users can define their own data sets (fields, fields types and such) and then store their data... very similar to them creating and managing their own tables.
Doing this seems to present issues when trying to set it up on something like MySQL... from a custom query perspective and from a storage perspective. I don't want to end up with thousands of tables or even managing so many different databases.
Someone told me that NoSQL was something to look into based on the flexibility of getting away from crazy complex queries.
The end result is the user will be able to query theses datasets to build graphs. Will something like http://redis.io accomplish this task for me?
If not, does anyone have suggestions on the best option to support this task?
Thanks!
A: You'll need to consider your data model and your desired queries in some detail to make this decision - each of the various NoSQL technologies has a slightly different data model and feature set.
A key-value database such as Cassandra would probably support on-the-fly field definition, but wouldn't support much in the way of field typing. You could store raw byte values and overlay your own type system, but you'd get no support from the database for enforcing types.
NoSQL databases generally don't support complex queries (no joins etc) so you must manage with simple queries (key lookups) or denormalise to support specific queries.
If you are working with graphs, have you considered an RDF database (triple store)? These also allow great flexibility, but are not table-based (relational). They generally support the SPARQL query language. See the http://answers.semanticweb.com/ site.
A: Based on your description, you need either a document oriented database or a key / value store with an ability to know (possibly even index) values.
Riak would fit that model, as it is a key / value store, where you do not have to predefine structure for those values + it has secondary indicies, where with each {key, value} pair persisted, you can add a custom index. In Riak words you have an ability to: tag a Riak object with some index metadata, and later retrieve the object by querying the index, rather than the object's primary key
which fits the description of what you are looking to solve pretty nicely.
Here is an example from Basho's blog ( simple curl HTTP request ):
curl -X POST \
-H 'x-riak-index-twitter_bin: rustyio' \
-H 'x-riak-index-email_bin: rusty@basho.com' \
-d '...user data...' \
http://localhost:8098/buckets/users/keys/rustyk
which says, insert ...user data... under a key rustyk, or and by the way, tag (read index) it with twitter "rustyio" and email "rusty@basho.com" ( _bin, just means these indicies are binary )
Now to read keys by just created "index", you can simply:
curl localhost:8098/buckets/users/index/twitter_bin/rustyio
which returns:
{"keys":["rustyk"]}
the key that you can use to retrieve that ...user data...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to encode an image in base64 after resizing In php, I'm trying to encode an image in base64 after a resize. When I encode it directly with no resize it's working fine
$bitmapNode = $dom->createElement( "bitmap" );
$bitmapNode->appendChild( $dom->createTextNode(base64_encode(file_get_contents($url))) );
$root->appendChild( $bitmapNode );
But when I'm trying to do a resize before the encoding it doesn't work anymore and the content of the xml node is empty.
$image = open_image($url);
if ($image === false) { die ('Unable to open image'); }
// Do the actual creation
$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled($im2, $image, 0, 0, 0, 0, 256, 256, imagesx($image), imagesy($image));
$bitmapNode = $dom->createElement( "bitmap" );
$bitmapNode->appendChild( $dom->createTextNode(base64_encode($im2)) );
$root->appendChild( $bitmapNode );
Is there something I'm doing wrong?
A: $im2 is just a GD resource handle. it is NOT the image data itself. To capture the resized image, you'll have to save it and then base64_encode that saved data:
imagecopyresample($im2 ....);
ob_start();
imagejpeg($im2, null);
$img = ob_get_clean();
$bitmapNode->appendChild($dom->createTextNode(base64_encode($img)));
Note the use of output buffering. The GD image functions do not have a method to directly return the resulting image data. You can only write to a file, or output directly to the browser. So using the ob functions lets you capture the data without having to resort to a temporary file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mysql, data spread over two tables, seperate rows I have data spread over two MySQL tables with different structures.
One table has DVDs and the other has CDs.
The DVD table is as follow:
PUBLISHER
STOCK
DVD_INFO
EXTRA_DVD_INFO
The CDs table is as follow:
PUBLISHER
STOCK
CD_INFO
How do you get all the CDs and DVDs by the same publisher in one query, ordered by STOCK?
*
*One row per product.
*If it's a CD, then the DVD specific fields should be empty.
*If it's a DVD, then the CD specific fields should be empty.
I don't think UNION can work because the structures are different.
I'm not sure how JOIN could work in this case to get separate rows for each product.
A: You can use NULL's to fill in the empty columns, eg.
SELECT
PUBLISHER,
STOCK,
DVD_INFO AS INFO,
EXTRA_DVD_INFO
FROM DVD
WHERE PUBLISHER = ?
UNION ALL
SELECT
PUBLISHER,
STOCK,
CD_INFO AS INFO,
NULL
FROM CD
WHERE PUBLISHER = ?
ORDER BY STOCK;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rename xib file I started to create an app using tabbar app template provided in xcode. Then I wanted to change the names of the files: FirstViewController should become YellowViewControler and FirstView.xib should become YellowViewcontroller.xib. Changing the name of the xib wasn't done right. It became red as if it didn't exist in the project. So: how should I change the name of the xib files?
A: Use the "Refactor" tool of Xcode.
This will manage the renaming of the XIB file, the renaming of the interface & implementation of the source file containing the definition of the ViewController, the renaming of your class declarations/definitions, and any references that are used anywhere in your projects, all of this in one action.
A: Rename the stuff back to what their original name was (FirstViewController) and then go to the interface file for it (.h) and right click on the class name (FirstViewController) and click refactor. This should make sure everything gets changed correctly.
Source this question
A: Most likely your viewcontroller name still linked to previous owner therefore open the viewcontroller.xib in source code and find the owner and changed to current name. It will fix the problem right away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET Add column to Gridview I have a gridview that is displaying data from a database using LINQ to SQL.
AssetDataContext db = new AssetDataContext();
equipmentGrid.DataSource = db.equipments.OrderBy(n => n.EQCN);
I need to add a column at the end of the girdview that will have links to edit/delete/view the row. I need the link to be "http://localhost/edit.aspx?ID=" + idOfRowItem.
A: Try adding a TemplateField to your GridView like so:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="http://localhost/edit.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "id") %>">Edit</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Within the item template you can place any links you like and bind any data you wish to them from your DataSource. In the example above I have just pulled the value from a column named id.
As things stand this would work fine, however the column above would be aligned left most in the GridView with all the auto generated columns to its right.
To fix this you can add a handler for the RowCreated event and move the column to the right of the auto generated columns like so:
gridView1.RowCreated += new GridViewRowEventHandler(gridView1_RowCreated);
...
void gridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
TableCell actionsCell = row.Cells[0];
row.Cells.Remove(actionsCell);
row.Cells.Add(actionsCell);
}
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can a SQL Server 2000 table have no PK, and therefore contain duplicate records? I have an audit table and instead of defining an identity or ticketed column, I'm considering just pushing in the records of the recorded table (via triggers).
Can a SQL Server 2000 table have no PK, and therefore contain duplicate records?
If yes, does all I have to do consist of CREATING the TABLE without defining any constraint on it?
A: Yes, this is possible, but not necessarily a good idea. Replication and efficient indexing will be quite difficult without a primary key.
A: Yes a table without a primary key or Unique Constraint can have rows that are duplicated
for example
CREATE TABLE bla(ID INT)
INSERT bla (ID) VALUES(1)
INSERT bla (ID) VALUES(1)
INSERT bla (ID) VALUES(1)
SELECT * FROM bla
GO
A: Yes a SQL Server 2000 table can have no primary key and contain duplicate records and yes you can simply Create a table without defining any constraint on it. However I would not suggest this.
Instead, since you are creating an audit table for another table. Lets say for this example you have a Person Table and a Person Audit table that tracks changes in the person Table.
Create your Audit Table like this
CREATE TABLE dbo.PersonAuditID
(
PersonAuditID int NOT NULL IDENTITY (1, 1),
PersonId int NOT NULL,
FirstName nvarchar(50) NOT NULL,
LastName nvarchar(50) NOT NULL,
PersonWhoMadeTheChange nvarchar(100) NOT NULL,
TimeOfChange datetime NOT NULL,
ChangeAction int NOT NULL,
/* any other fields here*/
CONSTRAINT [PK_PersonAudit] PRIMARY KEY NONCLUSTERED
(
[PersonAuditID] ASC
)
) ON [PRIMARY]
This will give you a primary key, and keep records unique to the table. It also provides the ability to track who made the change, when the change was made, and if the change was an insert, update or delete.
Your triggers would look like the following
CREATE TRIGGER Insert_PERSON
ON PERSON
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO PERSONAUDIT
(PersonID,
FirstName,
LastName,
PersonWhoMadeTheChange,
TimeOfChange,
ChangeAction,
... other fields here
SELECT
PersonID,
FirstName,
LastName,
User(),
getDate(),
1,
... other fields here
FROM INSERTED
END
CREATE TRIGGER Update_PERSON
ON PERSON
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO PERSONAUDIT
(PersonID,
FirstName,
LastName,
PersonWhoMadeTheChange,
TimeOfChange,
ChangeAction,
... other fields here
SELECT
PersonID,
FirstName,
LastName,
User(),
getDate(),
2,
... other fields here
FROM INSERTED
END
CREATE TRIGGER Delete_PERSON
ON PERSON
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO PERSONAUDIT
(PersonID,
FirstName,
LastName,
PersonWhoMadeTheChange,
TimeOfChange,
ChangeAction,
... other fields here
SELECT
PersonID,
FirstName,
LastName,
User(),
getDate(),
3,
... other fields here
FROM DELETED
END
A: SQL Server 2000+, can have tables without PK. And yes, you create them by no using a constraint.
A: For an audit table, you need to think of what you may be using the audit data for. And even if you are not doing auditing to spefically use to restore records when unfortunate changes were made, they are inevitably used for this. Will it be easier to identify the record you want to restore if you have a surrogate key that prevents you from accidentally restoring 30 other entries when you only want the most recent? Will a key value help you identify the 32,578 records that were deleted in one batch that needs to be restored?
What we do for auditing is have two tables for each table, one stores information about the batch of records changed, including an auto-incrementing id, the user, the application, the datetime, the number of affected records. The child table then used the ID as the fk and stored the details about the old and new values for each record inserted/updated/deleted. This really helps us when a process bug causes many records to be changed by accident.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java SWT Image background color I have a TableItem and i wish to add an image in it.
I use this code :
Image image = new Image(Display.getCurrent(), 400, height);
image.setBackground(COLOR_RED);
item.setImage(5, image);
The problem is the background color is never setting in the image. My goal is to get a transparent image background.
How can I do that?
A: Please read the JavaDoc of Image.setBackground. That method does not fill your image with red color.
Also, by setting an image to a TableItem you cannot draw anything, like text, transparently below that image. If you want to do something like that, you'll need "owner draw", see here for a tutorial on that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Assigning database entries to web service entries Here's the scenario:
*
*I receive a JSON object comprising 140 events. Each event is one of six possible types and includes several details, except for 2 (description and contact name).
*I have a MySQL database of the 6 descriptions and contact names.
How can I "attach" the correct description and contact name from the database to each JSON entry in PHP?
I could do a query of the database for each of the events, but this seems needlessly complex and I imagine it would severely slow performance. The best option would be for the provider of the web service to include our descriptions and contact names, but they won't do that.
Thanks in advance.
A: If you can identify which of the 6 descriptions/contact names you want for each event, then instead of getting them from the database for each event, select them all first then do the lookup in PHP.
For example:
// Build and array like this from your database first
$my_data = array('type1' => array('desc' => 'foo', 'cname' => 'bar'));
for($i=0; $i < count($all_events); $i++){
if(isset($my_data[$all_events[$i]['type']]){
array_merge($all_events[$i], $my_data[$all_events[$i]['type']]);
}
}
I've made some assumptions here, but you should get the general idea. Note you need to do a for loop not and foreach if you want to modify the $all_events array as you go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net postbacks won't fire I've made a simple ASP.net website and everything works fine on my computer. But on my colleague's computer no postbacks are fired although he uses the same OS (Win 7) AND the same browser as I do (IE9).
I don't have any access to his computer right now which makes it kind of hard to debug. Does anybody know what could prevent postbacks on one computer although they work on a different one with the same browser?
(I also tried it on a 3rd computer with different browser and OS and it worked there too)
//update: some code
The following code is one of the pages where the problem occures.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NewList.aspx.cs" Inherits="QAList.NewList" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Items</title>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<link href="qalist.css" rel="stylesheet" type="text/css" />
<script src="lib/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<style type="text/css">
input[disabled]
{
background-color:#888888;
}
.Filled
{
width: 98%;
}
.Property
{ margin-bottom: 0px;
}
.Date
{
/* this class is only used to indicate that the value is a DateTime value */
}
.PropertyTable td
{
border-bottom: 1px solid #D8D8D8;
padding:1px;
background-color:#F6F6F6;
}
.Suppler_style
{
color: #0000BB;
}
</style>
<script type="text/javascript">
$(function () {
$(".Date").datepicker({ dateFormat: "yy/mm/dd" });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table style="width: 80%;" border="0" class="PropertyTable" cellspacing="0" cellpadding="0">
<tr>
<td style="width: 227px;">
Project Number</td>
<td>
<asp:TextBox ID="ProjectNumber" runat="server" CssClass="Property" Width="200px"></asp:TextBox>
<asp:Button ID="btApplyPnr" runat="server" Text=" apply "
onclick="btApplyPnr_Click" />
</td>
</tr>
<tr>
<td>
Contract No.</td>
<td>
<asp:DropDownList ID="ddContractNo" runat="server" AutoPostBack="True"
onselectedindexchanged="ContractNo_SelectedIndexChanged"
CssClass="Filled">
</asp:DropDownList>
<input type="hidden" class="Property" id="V_QA_PO_tp_listId" runat="server" />
<input type="hidden" class="Property" id="V_QA_PO_tp_ID" runat="server" />
<input type="hidden" class="Property" id="ContractNo" runat="server" />
</td>
</tr>
<tr>
<td>
ITP No</td>
<td>
<asp:TextBox ID="ITPNo" runat="server" CssClass="Filled Property"></asp:TextBox>
</td>
</tr>
<tr>
<td class="Suppler_style">
ITP Name</td>
<td>
<asp:TextBox ID="ITPName" runat="server" CssClass="Filled Property"></asp:TextBox>
</td>
</tr>
<tr>
<td class="Suppler_style">
Status Delivery/Finish Date</td>
<td>
<asp:TextBox ID="StatusDeliveryFinishDate" runat="server"
CssClass="Filled Property Date"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
</html>
And the C#-Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace QAList
{
public partial class NewList : System.Web.UI.Page
{
private string current_contract = "0";
private string current_pnr;
protected void Page_Load(object sender, EventArgs e)
{
current_contract = ddContractNo.SelectedValue;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//load Contract Numbers
ddContractNo.Items.Clear();
ddContractNo.Items.Add(new ListItem("-", "0"));
foreach (DataRow contract in DBAccess.Instance.getContractNumbers(current_pnr).Rows)
{
ddContractNo.Items.Add(new ListItem(contract["ProjectNumber"] + " - " + contract["ContractNo"] + " - " + contract["GoodsServicesSupplied"], contract["tp_listId"] + "_" + contract["tp_ID"]));
}
try
{
ddContractNo.SelectedValue = current_contract;
}
catch (ArgumentOutOfRangeException)
{
ddContractNo.SelectedValue = null;
applyNewContractValue();
}
}
protected void ContractNo_SelectedIndexChanged(object sender, EventArgs e)
{
applyNewContractValue();
}
private void applyNewContractValue()
{
current_contract = ddContractNo.SelectedValue;
if (!String.IsNullOrEmpty(current_contract) && current_contract != "0")
{
Guid tp_listId = new Guid(current_contract.Split('_')[0]);
int tp_ID = Convert.ToInt32(current_contract.Split('_')[1]);
DataRow row = DBAccess.Instance.getContractInfos(tp_listId, tp_ID);
if (row == null)
return;
ITPName.Text = row.IsNull("GoodsServicesSupplied") ? "" : row["GoodsServicesSupplied"].ToString();
if (!row.IsNull("PlannedDeliveryexworks"))
{
DateTime tmp = (DateTime)row["PlannedDeliveryexworks"];
StatusDeliveryFinishDate.Text = tmp.Year + "/" + fillZeros(tmp.Month, 2) + "/" + fillZeros(tmp.Day, 2);
}
}
else
{
ITPName.Text = "";
}
}
private string fillZeros(int nr, int min_length)
{
string res = nr.ToString();
while (res.Length < min_length)
res = "0" + res;
return res;
}
protected void btApplyPnr_Click(object sender, EventArgs e)
{
current_pnr = ProjectNumber.Text;
}
}
}
A: Check if your collegue got some script blocker installed, those can prevent postbacks since they are Javascript driven.
A: In case this helps someone:
I had something similar occur and it turned out that it was due to some validation controls on the page. They were for some hidden text boxes that were not actually visible and had no validation group specified. On one of the computers the errors were ignored and the postback worked, whereas on the second computer the postback failed due to validation errors. Because the text boxes were not currently visible, the problem was not immediately obvious.
Once I set up validation groups, the problem went away. I don't know why the behaviour was different on the two computers as both are running Chrome on Windows 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is my Float Variable Holding Whole Numbers? I've been glancing at this code for a while now, and I can't seem to figure out what the probably simple error is... In short, I have a float variable in Java that seems to only be storing the integer content (whole number) of what the value is actually supposed to be. I had this bit of code working before when I had everything crammed into one function, but after I re-factored the code to use more functions, this error occurred. Here's what I've got thus far:
Java Code
public class ModifyTimeController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
PopulateTimeIntervals(request.getWriter());
}
protected void PopulateTimeIntervals(PrintWriter writer) {
NumberFormat numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMinimumFractionDigits(2);
numberFormat.setMaximumFractionDigits(2);
float workHours = (float)0.00;
...
/* Code that queries a database for TimeIntervals */
...
while(resultSet.next()) {
// I was told that this type of conversion is
// possible since Timestamp is an extension of Date
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
// Accumulates the hours worked in each time interval
workHours += CalculateWorkHours(dtStart, dtEnd);
}
// Should print out something like: 54.27
writer.println(numberFormat.format(workHours).toString());
}
protected float CalculateWorkHours(Date dtStart, Date dtEnd) {
// Divides the difference of the start and end times
// (in miliseconds) by 3600000 to convert to hours
return (dtEnd.getTime() - dtStart.getTime()) / 3600000;
}
}
It's been a long day, so I'm probably just missing something... But rather than printing out something like 54.27 hours, I'm getting a flat 54 hours. The number formatting worked just fine, before... So I don't know what's up.
A: At return (dtEnd.getTime() - dtStart.getTime()) / 3600000; you're dividing by an integer, and making the answer an integer. Change it to 3600000.0 (or 3600000f) and you should be golden.
A: dtEnd.getTime() - dtStart.getTime()) / 3600000
This is a division of a long and int so the result itself will be a long and then be casted to float which then only holds the computed long value. To get a float result cast one of the operands to float first or use float literal like 3600000f instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.