text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to integrate l7-filter option with linux iptables in Debian Squeeze? I did :
mkdir /usr/local/iptables_l7
cd /usr/local/iptables_l7
Download following packages from Debian source:
linux-2.6-2.6.32-amd64
netfilter-layer7-v2.22
l7-protocols-2009-05-28
iptables-1.4.8
Now i patch up kernel linux-2.6-2.6.32-amd64 with netfilter-layer7-v2.22/kernel-2.6.25-2.6.28-layer7-2.22.patch by the command
patch -p1 < netfilter-layer7-v2.22/kernel-2.6.25-2.6.28-layer7-2.22.patch
Now copy netfilter-layer7-v2.22/iptables-1.4.3forward-for-kernel-2.6.20forward/libxt_layer7.c and netfilter-layer7-v2.22/iptables-1.4.3forward-for-kernel-2.6.20forward/libxt_layer7.man to iptables-1.4.8/extensions/
Then i compiled the kernel to activate layer7 and string match modules
cd linux-2.6-2.6.32
make menuconfig
i Check those options
Networking-->
Networking options -->
Network Packet Filtering framework (Netfilter) -->
Core Netfilter Configuration -->
under Core Netfilter Configuration option i can't found layer7 match suport option.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Other Open Graph og:type not being parsed correctly by Facebook linter As per Open Graph's documentation at http://developers.facebook.com/docs/opengraph , we can specify our own og:types.
If your object does not fit into one of the types above, you can
specify your own type. This will be represented as type other on
Facebook. We will monitor the most commonly used types and graduate
them to fully supported og:types. If you are specifying your own type
we recommend that you use your own namespace.
Running the linter on a page on my website
http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fznood.com%2Fachkar_tools returns the following errors:
Object at URL 'http://znood.com/places/dcGPdl0Psuc' is invalid because
the configured 'og:type' of 'znoodcom:store' is invalid
On my other page wich og:type is "city", if you check the linter up top, the og:type is set to "website" (which is bad!)
http://developers.facebook.com/tools/debug/og/object?q=znood.com%2Fcities%2FbIYWj4uRhCc
Can someone clarify how to set up custom types that Open Graph can pick? Also, why is the "city" type being replaced with "website" on my page?
A: Try visiting the Open Graph tool inside your app and declare your Object Type.
https://developers.facebook.com/docs/beta/opengraph/define-objects/
A: Are you passing in your namespace links in your head tag? Like:
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# yourns: http://ogp.me/ns/fb/yourns#`">
where yourns is your namespace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to close popup and redirect a page My site using php and i create an online quiz and the quiz show in pop up mode.
Currently when i want to redirect my page using the script below. it goes to my homepage BUT it still at the pop up mode. I want it to close the pop up and go to homepage after I click finish.
How can I do that?
<script type="text/javascript">
window.parent.location = "../../../"
</script>
A: You can try this code (used on an HTML button):
<input type="button" onclick="parent.window.opener.location='http://homepage.com'; window.close();">
And have a look at some similar threads like this one: Javascript: Close Popup, Open New Window & Redirect
[EDIT] See this article too
A: this way you can do it ..
<script type="text/javascript">
function close_window(){
window.opener.location = 'pop_up.php';
window.close();
}
</script>
html code..
<body>
<form method="post" name="frm_2" id="frm_2">
<input type="submit" name="btn_close" id="btn_close" onclick="return close_window();" />
</form>
</body>
A: You can access the window that opened a popup with the window.opener property on the popup. So, something like this should work:
window.opener.location.replace(redirectUrl);
window.close;
If you wanted to put that behavior in the onclick event on a submit button you're building like this:
echo "<input type=\"submit\"
name=\"finishattempt\"
value=\"".get_string("finishattempt", "quiz")."\"
onclick=\"$onclick\" />\n";
You'd need to assign the String window.opener.location.href='someUrl';window.close(); to the variable $onclick before echoing the submit button out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: LINQ to remove elements from one collection that don't match elements in another collection based on a field I have 2 Lists of different objects eg List and List. I want to remove all objects in first list whos value of a field doesn't match on a value of a field in the second list.
Eg I want to remove all Type1 objects from the first list whos Type1.name (string) member doesnt match a Type2.id (string) member in the second list.
Is this possible with LINQ ?
A: LINQ isn't about modifying existing collections - it's about running queries. If you need to change a list in place, you might want something like:
HashSet<string> ids = new HashSet<string>(list2.Select(x => x.Id));
list1.RemoveAll(x => !ids.Contains(x.Name));
In "normal" LINQ you could do this with:
// I'm assuming no duplicate IDs in list2
var query = (from x in list1
join y in list2 on x.Name equals y.Id
select x).ToList();
A: You can also use lambda:
var query = (list1.Join(list2, x => x.Name, y => y.Id, (x, y) => x)).ToList();
or
var query = (Enumerable.Join(list1, list2, x => x.Name, y => y.Id, (x, y) => x)).ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Retrieving All Payments From Sage Line 50 Database I'm trying to retrieve a list of all payments received/entered into a Sage Line 50 database. The company I work for are members of the Sage developer program, so I have access to the SDK, help files and the like but I have been unable to find any specific information regarding payments.
Some of the .dta files contain references to payments (SPLITS.DTA & HEADER.DTA) alongside Invoice rows.
Does anyone know whether or not there is a separate file which contains only payment information, and if so what is it? Alternatively, will I have to pull the full list of rows from the SPLITS/HEADER files and filter them by type?
Many thanks in advance
A: I pulled data from the Header and Split files for a test customer this afternoon, and they contain (as near as I can tell) all customer activity - Invoices, Invoice payments and Credits are all reflected in both data files (the split data file containing more in depth data) and can be filtered by bank_code and transaction type.
To get the data - first create a reference to a customer object and from there link to all of the header (assuming you have an existing connection and workspace).
dynamic workspace = this._workspaces[workspaceName];
dynamic customer = workspace.CreateObject("SalesRecord");
bool added = customer.AddNew();
customer.MoveFirst(); //find first customer
dynamic headerObject = customer.Link;
bool headerFound = headerObject.MoveFirst(); //use .MoveNext() to cycle headers
You can then pull data from the header object using :
string AccountRef = headerObject.Fields.Item("ACCOUNT_REF").Value;
Where ACCOUNT_REF is a field in the HeaderData object.
Use the following code to get split data
dynamic splitObject = headerObject.Link;
bool splitFound = splitObject.MoveFirst() //and so on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ssl certificate for several domains, one IP AFAIK, SSL is assigned to a single domain name (maybe several subdomains via wildcard).
On the other hand i heard that the webserver does not see the domain before it serves the ssl?
If I have multiple domains running as vhosts on one IP address:
Q1: Can the webserver serve the appropriate respective SSL to the sites?
Q2: Is there a way to have only one multi-domain SSL serving two domains on one IP?
Illuminate me out of confusion brought upon me by this seemingly self-contradictory quote:
Regular SSL Certificates are issued for a single FQDN (Fully Qualified
Domain Name). The domain using the certificate has to have its own
unique external IP address from which to be served. In practice, this
means that if you have multiple domains on a single IP address/server,
then you had to install a separate certificate on each domain you
wanted to secure.
The reason for this is the use of 'Host-Headers'. They allow a
web server to use a single IP address to serve many separate sites
with different FQDNs. They do this by identifying the incoming request
for a webpage, and routing it to the correct site accordingly.
When an SSL connection is initiated, the server must send a
certificate to the client - before it knows the host-header of the
request. The only identifying piece of data it has is the requested IP
address. As such, two or more sites on one IP address cannot use
different SSL certificates....
A: Q1> the web server doesn't need to know the domains embedded in an SSL cert. only the browser does since it's the one making sure the domain in the certificate matches the domain in the address bar. The web server just serves up the cert bound to the ip address, regardless of what domain is in the certificate.
Q2> what you describe is a SAN or UC certificate. They are designed to do what you stated, namely allow multiple domains to share one cert on one ip address. Check out this link on Subject alternative names for more info
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Jquery mobile orientation change returns opposite value I am currently working on a mobile website using jquery mobile and I encountered problem in detecting orientation change. My mobile website detects the orientation as "landscape" when in portrait mode and vice versa when testing on my Samsung Galaxy. However, working properly on iphone n HTC Desire. I did find in some forums that described that as Android bug and someone used setTimeOut to tackle it. But I can't solve the problem using that. Not sure if it's my syntax error or not. Can someone kindly enlighten me? Thanks in advance.
Sample code will be much appreciated.
Here is my current code:
$(document).ready(function() {
$(window).bind("orientationchange", function (event) {
setTimeout(detectOri(event),100);
});
function detectOri(event)
{
alert(event.orientation);
if(event.orientation == 'portrait')
{
//load portrait mode page
}
else if(event.orientation == 'landscape')
{
//load landscape mode page
}
}
});
A: you shouldn't be using DOM ready
use pageinit
A: change setTimeout(detectOri(event),100); for this:
setTimeout(detectOri,1000);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a way to use command line for load testing a web URL (single web page) using jmeter without creating test plan Is there a way to use command line for load testing a web URL (single web page) using jmeter without creating test plan file. (i.e. *.jmx)
Thanks,
Yugal
A: Yes, it is called Apache Benchmark tool.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add to Timeline's button mode broken? Though I've embedded the Add to Timeline social plugin in button mode:
<div class="fb-add-to-timeline" data-show-faces="false" data-mode="button"></div>
it keeps showing up as the full plugin including a preview of how Timeline items will look like. Is this a known issue?
I grabbed the embed code from here: https://developers.facebook.com/docs/reference/plugins/add-to-timeline/#.
A: I had the same issue, and just remove the "timeline" permission from my app settings, and then it showed up.
A: Since the button is really just a permission trigger you can build around it with your actual access request. This is logical if you are doing an SDK call of all sort using javascript, php or other versions.
Of course as timeline is not enabled outside of dev, one would suspect this will be addressed soon as so far I'm seeing the box in just about any type of testing I do. Odds are Facebook wants to show the box when someone calls timeline specifically to build adoption understanding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to view email source in Yahoo! mail I'm getting CSS rendering issues in Yahoo! mail in IE8. How can I view the email source? I've tried installing the IE dev toolbar but the message body is within an iframe which doesn't provide any useful information.
In case it's a common issue, has anyone else had problems with inline CSS classes not being used in IE with Yahoo? In Firefox it looks fine, but the same email in IE has all font formatting ignored (aside from the basics like "bold" or "italic").
A: The IE developer tools are rubbish, even in IE9. Any web inspector tools other than IE9 ones will help you (view the source).
*
*Opera Dragonfly
*Firefox Firebug addon
*Webkit Inspector
In future refer to the Email Standards Project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can I get pay with tweet button in dutch language? I am going to use pay with tweet button in wordpress site,but my site is in Dutch Language,
So if anyone know can I get pay with tweet button in Dutch Language please tell.
Thanks
A: From http://www.paywithatweet.com/faq.html as of time of this writing
Q: Can I choose another language than english?
A: Not yet. But we are working on it.
You could modify the alt attribute of the button via JavaScript after the button was included or add a title attribute to it so when visitors hover over it they get "Pay with a Tweet" in Dutch in a tooltip.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: problem in fetching values,JSF-data table I'm using JSF 2.0 and trying to display a list of data using a datatable. After my data is fetched I have button in each row, on this button it has to take some of the fields as input parameters and then save it.
<h:dataTable id="dt1" value="#{vendorApp.editQtnList}" var="qList" >
<h:column>
<f:facet name="header">
<h:outputText style=""value="RFQ Number" />
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Vendor Number"/>
</f:facet>
<h:outputText value="#{qList.vendorNumber}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="RFQ Date"/>
</f:facet>
<h:outputText value="#{qList.rfqDate}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:inputText id="adComment" value="#{qList.adminComment}"></h:inputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:form>
<h:commandButton id="rejectBtn" value="Reject" action="#{vendorApp.rejectEditQuotation}">
<f:param name="vendorNum" value="#{qList.vendorNumber}" />
<f:param name="rfqNum" value="#{qList.rfqNumber}" />
<f:param name="adComment" value="#{qList.adminComment}" />
</h:commandButton></h:form> </h:column> </h:dataTable>
In my above code, editQtnList is the getter method for list which gives a list fetched from database.Now user can click on reject by proving a comment in the text box provided, I have tried this as shown but the value of the comment is not feteched..Need suggestions on this....
A: All input fields of interest must be placed inside the same form as the submit button.
Rewrite your view as follows:
<h:form>
<h:dataTable value="#{vendorApp.quotations}" var="quotation">
...
<h:column>
<h:inputText value="#{quotation.adminComment}" />
</h:column>
<h:column>
<h:commandButton value="Reject" action="#{vendorApp.rejectEditQuotation(quotation)}" />
</h:column>
</h:dataTable>
</h:form>
with
public void rejectEditQuotation(Quotation quotation) {
// ...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to update global variable in titanium? i'm having some problem in updating my array which is global by the way.
here is my code:
Ti.App.dinercolor=["#FF5A00","#007EFF","#dccdc0","#C2FF95","#A700FD","#dccdc0","#dccdc0","#5F9EA0","#dccdc0","#dccdc0","#22A000","#DCCDC0","#dccdc0","#FF003C","#dccdc0","#FF003C","#dccdc0","#22A000","#dccdc0","#FFF191"];
thats my global array which i can access data from it from anywhere in the application.
the problem comes when i want to update the array like:
for(var q=0; q<Ti.App.dinercolor.length; q++){Ti.App.dinercolor[q] = '#dccdc0';}
so, the array i was expecting after the operation thats done is something like this:
Ti.App.dinercolor=["#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0"];
but somehow i'm getting the same array with out updating,
Ti.App.dinercolor=["#FF5A00","#007EFF","#dccdc0","#C2FF95","#A700FD","#dccdc0","#dccdc0","#5F9EA0","#dccdc0","#dccdc0","#22A000","#DCCDC0","#dccdc0","#FF003C","#dccdc0","#FF003C","#dccdc0","#22A000","#dccdc0","#FFF191"];
please help me out, i have no idea what i'm doing wrong here,
Thank you,,
A: Your code is correct, but you shouldn't extend the Ti object as unexpected things like this will happen. Create your own object and it will work.
myObj = {};
myObj.dinercolor = [];
And so on.
It is recommended you keep your app in a single context so you will be able to access the object from anywhere. Check out the forging titanium video series for some best practices.
A: I agree with Jeff, however if you want the above approach to work you will need to update the whole array, you cannot just update elements.
So read the array out into a new variable, update the specific elements and then set the property again
A: In App.js:
Ti.App.my_variable = 0;
In some_other_page.js:
Ti.App.my_variable = 101;
In yet_another_page.js:
alert( Ti.App.my_variable );
This will alert 101 !!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django: following the reverse direction of the one-to-one relationship I have a question about the way Django models the one-to-one-relationship.
Suppose we have 2 models: A and B:
class B(models.Model):
bAtt = models.CharField()
class A(models.Model):
b = models.OneToOneField(B)
In the created table A, there is a field "b_id" but in the table B created by Django there is no such field as "a_id".
So, given an A object, it's certainly fast to retrieve the corresponding B object, simply through the column "b_id" of the A's row.
But how does Django retrieve the A object given the B object?
The worst case is to scan through the A table to search for the B.id in the column "b_id". If so, is it advisable that we manually introduce an extra field "a_id" in the B model and table?
Thanks in advance!
A: Django retrieves the field through a JOIN in SQL, effectively fusing the rows of the two tables together where the b_id matches B.id.
Say you have the following tables:
# Table B
| id | bAtt |
----------------
| 1 | oh, hi! |
| 2 | hello |
# Table A
| id | b_id |
-------------
| 3 | 1 |
| 4 | 2 |
Then a join on B.id = b_id will create the following tuples:
| B.id | B.bAtt | A.id |
------------------------
| 1 | oh, hi! | 3 |
| 2 | hello | 4 |
Django does this no matter which side you enter the relation from, and is thus equally effective :) How the database actually does the join depends on the database implementation, but in one way or another it has to go through every element in each table and compare the join attributes.
A: Storing the id in one of the tables is enough.
In case 1, (a.b) the SQL generated would be
SELECT * from B where b.id = a.b_id
and in case 2, the SQL would be:
SELECT * from A where a.b_id = b.id
You can see that the SQLs generated either way are similar and depend respectively on their sizes.
In almost all cases, indexing should suffice and performance would be good with just 1 id.
A:
Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don't Repeat Yourself) principle, so Django only requires you to define the relationship on one end.
Always take a look at the doc ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to convert an ERD to Code First classes? I have the following ERD and want to convert it EF 4.1 Code First classes. For the sake of simplicity, I will concentrate on the first two Entities only.
Author > Quote.
Which is the correct way of having my code for the Entities, this:
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public int AuthorId { get; set; }
public int LanguageId { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
Where I have given each Quote a property of type Integer signifying the IDs of the Author and Language or this:
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public Author Author { get; set; }
public Language Language { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
Where each Quote has a property of Type Author and one of type Language.
A: The first example is rare. You are exposing foreign properties without using navigation properties = you are exposing database specific features but not using object oriented features.
The second example is common and there is even third possible way where your Quote entity will have both FKs and navigation properties. That will make difference between independent and foreign key associations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Resizing the NSTableView programmatically How to implement the feature of resizing NSTableView created programmatically ? Interface builder should not be used. It should be like click and drag to change the size of the NSTableView. Is it possible? If yes, please help. . . .
A: I am afraid you need to write a bit of code to make it working. This is how I would do it.
Make a special Resize View that will track the mouse events and call delegate methods providing how the tracking position changes.
- (void)mouseDown:(NSEvent *)theEvent
{
_startPoint = [theEvent locationInWindow];
[_delegate resizingDidStart];
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint hitPoint = [theEvent locationInWindow];
[_delegate resizeWithDeltaX:(hitPoint.x - _startPoint.x) deltaY:(hitPoint.y - _startPoint.y)];
}
Put this view in the right bottom corner of the Base View. Set the autoresizing mask so this view always stays in the right bottom corner.
Put the table view along with its scroll view on to the Base View. Set autoresizing mask of the scroll view so its size and width are sizeable.
In the delegate of the Resize View process changes in the mouse position and set the frame of the Base View.
- (void)resizingDidStart
{
_initialRect = [_baseView frame];
}
- (void)resizeWithDeltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY
{
[_baseView setFrame:NSMakeRect(_initialRect.origin.x, _initialRect.origin.y + deltaY, _initialRect.size.width + deltaX, _initialRect.size.height - deltaY)];
}
Of course the scroll view should be under the resize view. You can draw some ind of a handle on the resize view, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do i need to delete dom fragments or will the garbage collector remove them? This maybe a bit of a silly question. I'm assuming that the garbage collector disposes of any dangling variables after a function ends execution, but I was wondering if this also applies to DOM fragments.
If I create a DOM fragment or any unattached node for that matter, will the garbage collector delete it after the function has finished execution?
//would this create a memory leak?
setInterval(function exampleScope() {
var unusedDiv = document.createElement('div');
}, 10);
I know this example is useless but its the simplest form of the pattern I'm worried about. I just want to know I'm doing the right thing. I've been hard at work building a very high performance JavaScript game engine, Red Locomotive. I don't want to add any memory leaks.
A: There is an IE 7 memory leak with DOM elements in event handlers: jQuery leaks solved, but why?
With other browser you should be fine. See Freeing memory used by unattached DOM nodes in Javascript.
If you worry much about memory leaks and care for your tech illiterate IE users, you should read this: Understanding and Solving Internet Explorer Leak Patterns
A: Well, it's not 100% conclusive but I made a quick JSFiddle to experiment with this. This is a tight loop that runs your code above 100000000 times. Using the Chrome Task Manager memory usage jumped from 47.9MB to 130MB and stayed fairly constant until completed, where it dropped down to 60MB ish.
http://jsfiddle.net/u7yPM/
This suggests that the DOM nodes are definitely being garbage collected, else the memory usage would continue increasing for the whole run of the test.
EDIT: I ran this on Chrome 14.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to translate a NSString object to NSDate quickly? I try to get NSDate objects from NSString which I get from sqlite, but there is a time problem. I takes me 130ms every time. And it's insufferable for i have two hundred objects to deal with. So can somebody tell me what i should do. Thanks.
A: Assuming you're using NSDateFormatter, you should attend to Apple's recommendation, caching formatters for efficiency. Instead of creating a NSDateFormatter each time you want to convert a date, you should keep a single instance of your NSDateFormatter. From Data Formatting guide:
Cache Formatters for Efficiency
Creating a date formatter is not a cheap operation. If you are likely
to use a formatter frequently, it is typically more efficient to cache
a single instance than to create and dispose of multiple instances.
One approach is to use a static variable.
A: NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss:SSS"];
NSDate *currentdate=[formatter dateFromString:currentdateStr];
//it returns DateObject If String in Specified Format otherwise Returns nil;
A: I think this code block will help you :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<Add Your Date Format>"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponent = [calendar components:NSYearCalendarUnit
|NSMonthCalendarUnit
|NSDayCalendarUnit
fromDate:[dateFormatter dateFromString: <Add Your Date String> ]];
[dateComponent setHour:24];
[dateComponent setMinute:00];
[dateComponent setSecond:00];
<Your NSDate Object> = [calendar dateFromComponents:dateComponent];
It might require to change dateComponent values for Hour, Minute, Seconds - according to your calendar time.
Let me know if you face any problem in this..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What would it take to create a C# compilation error, when you use custom methods where Expression is expected? What would it take to create a C# compilation error, when you use custom methods where Expression is expected?
Its true that Lambda expressions that contain invocations to custom methods are also, technically, well, expressions. But since the consumer of the expressions like LINQ to SQL, LINQ to JSON etc dont expect it, they throw runtime errors.
What can be done to let the compiler know what a framework like LINQ to SQL etc expects, and what aren't allowed.
A: Nothing can be done, because of the following reasons:
*
*A lambda expression (!) that contains a method call is still an expression
*Not all method calls are illegal. Some methods are understood and correctly translated. So, even if you would find a way to only allow lambda expressions that don't call methods, you would disallow all method calls, even the valid ones.
A: This is not possible. It would be similar to requiring that a variable of type string can not contain certain characters. The compiler is not able to check this, since the actual content of the variable is only known at runtime.
That said, the transformation from a lambda expression to an Expression instance is done by the compiler, so theoretically/technically, one could imagine a 'LINQ compiler service' that would integrate with the compiler, and provide information about the supported constructs at compile time.
It would obviously require a lot of work both in the compiler and in the LINQ providers (LINQ provider writers should in this scenario also implement this 'linq compiler interface' to integrate with this compiler service).
I wouldn't count on this to be available in the near future. Maybe the whole 'compiler as a service' (aka Roslyn) could enable this scenario?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Getting ComboBox variable to store in MySQL I have an html page that gets data from 'hs_hr_employee' table and lays the info in a table on a web page. Then I have another table 'rights' which gets info from 4 columns from the 'hs_hr_employee' table and stores them in columns. In addition to those 4, the 'rights' table has an extra column 'Permissions'.
Now, I have a combobox with 4 options. When I click the 'Save' button I want to store the value select in the combobox and save it in the 'rights' table in relation to the user.
(Each user has a combobox next to it).
Updated code:
<?php
$connection = mysql_connect('localhost','admin','root');
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_permissions'] ) && is_array( $_POST['cb_permissions'] ))
{
foreach( $_POST['cb_permissions'] as $emp_number => $permission)
{
$sql = "UPDATE `your_permission_table` SET permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
<p style="text-align: center;">
<span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p>
<p style="text-align: center;">
</p>
<head>
<style type="text/css">
table, td, th
{
border:1px solid #666;
font-style:Calibri;
}
th
{
background-color:#666;
color:white;
font-style:Calibri;
}
</style>
</head>
<form method="post" action="admin.php">
<?php
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
$result = mysql_query("SELECT emp_number, employee_id, emp_lastname, emp_firstname FROM hs_hr_employee");
echo "<center>";
echo "<table >
<tr>
<th>Employee Number</th>
<th>Employee ID</th>
<th>Surname</th>
<th>Name</th>
<th>Permissions</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['emp_number'] . "</td>";
echo "<td>" . $row['employee_id'] . "</td>";
echo "<td>" . $row['emp_lastname'] . "</td>";
echo "<td>" . $row['emp_firstname'] . "</td>";
echo "<td> <select name='cb_permissions['".$row['emp_number']."'><option value='all'>All</option> <option value='remote'>Remote Gaming</option> <option value='landbased'>Landbased Gaming</option> <option value='general'>General Gaming</option> </select> </td>";
echo "</tr>" ;
}
echo "</table>";
echo "</center>";
echo mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee');
$_POST['cb_permissions'];
mysql_close($connection);
?>
<p style="text-align: center;">
</p>
<p style="text-align: center;">
</p>
<p style="text-align: right;">
<input name="Save_Btn" type="button" value="Save" />
</p>
</form>
Any help on how I can do it?
Screenshot to get a basic idea of what I'm doing:
A: First of all, you should move connection code at the very top of your documents:
$connection = mysql_connect('localhost','admin','root');
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
Next, you have to wrap your table inside tag:
<form method="post" action="target_url.php>
<table>
...
</table>
<input type="submit" name="submit" value="Save"/>
</form>
After that, you would store employee_id or emp_number (depending on what table key you will use for setting permission) somewhere on your form:
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['emp_number']; ?></td>
<td><?php echo $row['employee_id']; ?></td>
<td><?php echo $row['emp_lastname']; ?></td>
<td><?php echo $row['emp_firstname']; ?></td>
<td><select name="cb_permissions['<?php echo $row['emp_number']; ?>']">
<option value='all'>All</option>
<option value='remote'>Remote Gaming</option>
<option value='landbased'>Landbased Gaming</option>
<option value='general'>General Gaming</option>
</select></td>
</tr>
<?php
}
Then, on your target_url.php, you will have to do:
If target_url.php is the same as your form, then code below should be placed at the very top of your document.
<?php
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_permissions'] ) && is_array( $_POST['cb_permissions'] ))
{
foreach( $_POST['cb_permissions'] as $emp_number => $permission)
{
$sql = "UPDATE `your_permission_table` SET permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
That's it.
A: i suggest:
*
*Use require_once( "db_connect.php" ) <- in this file make connection
*Use smarty & html_options to show this drop down.
1 time your will learn this, next - using. Code will start be organized ...
Maybe to complex for starter. But this is right Way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trouble initializing NSViewController - UI Objects not retained I'm having some issues with understanding how to work with NSViewControllers on Mac. I'm trying to create custom table cells for NSTableView. In one of the delegates of the NSTableView, it can return a view, instead of a cell.
I have a subclass of NSViewController, and in the .xib everything is linked up correctly, but when I initialize the NSViewController, its UI components is not initialized... not even the default view that comes with it. I have tried it with a clean, stock, untouched implementation of NSViewController, just to make sure that the issue is not with something I'm doing. It is probably. I am initializing the NSViewController as follows:
testview *tmpChannel = [[testview alloc] initWithNibName:@"testview" bundle:nil];
The .xib does exist, and all the outlets are linked up correctly. Could anyone explain what is happening here? I'm using xCode 4.1 with Lion OS
Thanks.
A: Check your initialization with
NSLog(@"%@", [tmpChannel description]);
From your code I would assume, that you do get an object address here. That means the error is probably in the code that is supposed to display it.
BTW, I recommend using capitalized class names, such as TestView.
EDIT:
Additional Information for loading xibs: The name of the xib file has to be the exact same as the class name. In this case you can actually completely omit the initWithNibName:bundle: part:
// xib file is "ViewController.xib"
// Class is defined as "ViewController"
ViewController *newController = [[ViewController alloc] init]; // this is enough
A: The IB (xib) Objects are initialized only after the view is actually loaded. And not during the initWithNibName:bundle:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: synchronize sharepoint documents with another system Is it possible for the documents (inside the sharepoint document library)
to be accessible from another system library (implemented in J2ee), and both
should be synchronized together ?
Is this possible using "Microsoft Sync Framework for SharePoint" , then
using "webservices" to connect to the java API ?
May anyone give me brief descriptions how this can be achieved?
Thanks in advance.
A: You can access the documents inside a document library using the Server/Client Object Model or WebServices.
*
*Download a file using the Server Object Model
*Upload a file using the Client Object Model
*Get ListItemChanges WebService
Please explain what you want to achieve (architecture) so it will be easier for us to understand and give you hints in the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to properly format unusual date string using Java SimpleDateFormat? I've got date in following format:
Pon Cze 07, 2011 9:42 pm
It's Polish equivalent of English date:
Mon Jun 07, 2011 9:42 pm
I'm using following SimpleDateFormat matcher:
SimpleDateFormat("EEE MMM dd, yyyy H:mm a", new Locale("pl", "PL"))
But date cannot be parsed because of AssertionFailedError. I've try some other solution, but no one works for me. Do you got any ideas what I do wrong?
A: There are two problems:
*
*The day is wt, and not Pon, in the pl locale
*The AM/PM indicator is not taken into account because you used H (which means hour from 0 to 23) instead of h.
I would just parse from the first character after the first white space (to avoid parsing "Pon"), adn replace H by h. in the pattern:
DateFormat df = new SimpleDateFormat("MMM dd, yyyy h:mm a", new Locale("pl", "PL"));
Date d = df.parse(s.substring(s.indexOf(' ') + 1));
A: It seems, that the day of the week is only represented by two Letters, whatever the reason for this might be.
Try this Code and check the Output
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd, yyyy H:mm a", new Locale("pl", "PL"));
GregorianCalendar gc = new GregorianCalendar(new Locale("pl", "PL"));
gc.setTime(new Date(System.currentTimeMillis()));
System.out.println(sdf.format(gc.getTime()));
My Output is: "Wt wrz 27, 2011 11:05 AM"
So maybe if you try two lettered weekdays, it could work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Changing schemas in mongoDB/mongoose I am getting started with mongoDB and mongoose. I was wondering how people manage evolving schemas. For example if i started with a schema like this:
user_ID : 123,
user_firstName : 'bob',
user_lastName : 'smith'
And evolved it to something like this:
user_ID: 123,
user_name: [first:'bob', last:'smith']
How could I update or manage old records that were established using the old schema design?
A: One approach to migrating document schemas involving simple data transformations would be to use $exists to find documents that are missing the new fields and migrate them.
For example, transforming firstName and lastName into a new user_name field:
db.mycollection.find( { user_name : { $exists : false } } ).forEach(
function (doc) {
doc.user_name = {'first': doc.user_firstName, 'last': doc.user_lastName};
// Remove old properties
delete doc.user_firstName;
delete doc.user_lastName;
// Save the updated document
db.mycollection.save(doc);
}
)
For more complex migrations some tools that could be helpful are:
*
*schema.js or variety for analyzing the current schema of a collection
*JSV: JSON Schema Validator for validating documents
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: PHP Memory Error(No File Name specified) I am getting php error like this:
PHP Fatal error: Allowed memory size of 33554432 bytes exhausted
(tried to allocate 7077994 bytes) in Unknown on line 0, referer:REFERER
I have checked my code there is no infinite loop or code which will take such high memory.
I concern is why it is not showing the error line where it has happened.What is the meaning of Unknown in this case..
Thanks in Advance..
A: Do you have xdebug installed?
I would try to increment memory_limit and profile your script with xdebug. It produces a human-readable text file. So you can read where and how much memory is used.
A: memory_limit = 128M
increase it in your php.ini file.
Or visit the link below
memory limit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A PHP platform to post messages on specific date I am planning to write my first PHP server side code. It includes a scheduler that will email a message to a user on a specific date. The front end of the application is fairly simple.
PHP produces an HTML page where you can select a date in the future to post the message to a an email address.
The question is how would you create an event manager in PHP to handle this? What database would you use? MYSQL or PostgreSQL and why!?
A: It makes no difference MySQL and PostgreSQL can both handle this fine, they are called databases for a reason.
MySQL is more common as a LAMP stack and you will probably find a lot more information on using PHP with MySQL so I'd stick with that.
A: In regards with the scheduling, you can utilize a cron job if you are using Linux. Windows has a similar service as well.
A: To run schedule tasks on server use cron. With cron you can run php file that will read data from database and send email.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Silverlight ProgressBar with custom image Bricks I need a progressbar style which uses an image as each of its progress bricks.
Any idea?
A: EDIT: my answer is for a Slider control, it could be adapted quite easily to a ProgressBar control, using as said in the original post either DataBinding or ElementBinding + a Converter.
Not the perfect solution, but I've used a Binding + a custom Converter to achieve that, for a volume bar. My volume bar is made of eight bricks, in my case using rectangles which have two colors, one for inactive, one for active. You could replace that by images and a converter which toggle the visibilities.
<Grid>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding Volume, ConverterParameter=0.0, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.125, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.25, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.375, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.5, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.625, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.75, Converter={StaticResource VolumeToColor}}" />
<Rectangle Fill="{Binding Volume, ConverterParameter=0.875, Converter={StaticResource VolumeToColor}}" />
</StackPanel>
<Slider Maximum="1" LargeChange="0.25" SmallChange="0.1" Value="{Binding Volume, Mode=TwoWay}" Opacity="0" Height="10" />
</Grid>
I'm sure you could do much better using Blend, copying the default Slider template and using TemplateBinding on the slider's Value.
BTW, If you don't use data binding for the Slider's value, you can use ElementBinding to grab its value for the elements of the bar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASPxComboBox 'specified cast is not valid' error when data binding I have a Dev Express ASPxComboBox:
<dx:ASPxComboBox runat="server" ID="DropDownListTemplates"
DataSourceID="SqlDataSourceTemplates" ValueField="template_id" TextField="name"
ValueType="System.Int32" Enabled="false" Width="100%" SelectedIndex='<%#
Eval("subs_template") %>'/>
Which throws a "Specified cast is not valid error" at runtime. It's something to do with the
SelectedIndex='<%# Eval("subs_template") %>'
Expression, however, subs_template is guaranteed to be a number:
<asp:SqlDataSource ID="SqlDataSourceClientDetail" runat="server"
ConnectionString="<%$ code: AutoNat.ConnectionManager.AutoNatConnectionString %>"
SelectCommand="SELECT *, isnull(subs_template_id, 0) subs_template FROM [person] p WHERE [person_id]=@person_id">
<SelectParameters>
<asp:SessionParameter Name="person_id" SessionField="personID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSourceTemplates" runat="server" ConnectionString="<%$ code: AutoNat.ConnectionManager.AutoNatConnectionString %>"
SelectCommand="SELECT * FROM
(SELECT t.template_id, name FROM subs_template t UNION SELECT 0, 'Custom...') s
ORDER BY template_id">
</asp:SqlDataSource>
Why does this keep failing?
I have tried
SelectedIndex='<%# 0 %>'
Which works fine!
A: Have you tried casting it o an integer like this? Convert.ToInt32(Eval("subs_template"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SSRS 2008 reexecute report when parameters changed I have a report with many parameters, some dropdown lists some textual and some dates.
After the report viewer is loaded, user choosed parameters and pressed the 'View Report' button the report is loaded perfect.
Now user wish to change on of the many parameters enterd and watch the report....
after pressing the 'View Report' button, he get the same data in each page number wich been watched before until he press the refresh button..... (Caching of pages i guess).
I changed the report Execution property to allways run the report from most recent data.
my temporarly solution was to add a 'New Report' button above the report in order to refrash page (in that case no page is being cached), the problem is old parameters are also being flushed what make the report user put all again when he just wanted to change 1!!!!!
any creative solution will be appreciated.
Noam.
EDITED
A: Found a solution apperently the application calling the window defind the window to cach the data.
I had to change the server side configuration in order to solve this issue.
not a very halpfull post.... sorry
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I pull the facebook pages that my fans like Based on this this article, let's say that I manage FB page "A". When I'm logged into Facebook as "Page A" I'm seeing on the right sidebar under Recommended Pages, a few Pages that my fans like. Because this info is very useful, I want to pull all the pages that my fans like automatically. Any ideas on how to proceed?
A: Have them authorise an application you write and grant you the user_likes permission.
You can then access the list of pages they like from the /{user id}/likes endpoint of the Graph API
A: FB.api('/me/likes',function(response) {
console.log(response);
});
This will give you all the user's like in an array, with ids etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: predicate to many-to-many relationship core-data I have two entities in a Core Data Model like these: A <<--->> B.
Entity B has an attribute name which is a string object and a relationship AObjects to A; instead, entity A has got a relationship BObjects to B.
Now I want to get a list of all BObjects connected with A entity and then, I want to show their names in a label.
Is this possible? I know CoreData doesn't support many-to-many relationships...
Thanks!
A: I think you may not have fully described your situation, because of course Core Data absolutely does support many-to-many relationships. I suspect you may mean that an NSFetchedResultsController does not support many-to-many relationships? As far as I've been able to determine, that is correct. (Edit: It is possible to use an NSFetchedResultsController with many-to-many relationships... it is just not very obvious how to do it.)
To do this without an NSFetchedResultsController, identify/fetch the A entity you are interested in, and then traverse the relationship you are interested in. So, if you already know that you are interested in a specific A object that I will call theAObject, with the class names A and B, you can just traverse the relationship using dot syntax and fast enumeration using something like the following:
for (B *theBObject in theAObject.BObjects) {
NSLog(@"theBObject.name: %@.", theBObject.name);
// Run whatever code you want to here on theBObject.
// This code will run once for each B Object associated with theAObject
// through the BObjects relationship.
}
Alternatively, you can set up a fetch request to get a set of AObjects you are interested in, and then traverse BOjects relationship for each of them. It does not make any difference that it is a many-to-many relationship... each AObjecct will return all B objects that are in its BObjects relationship.
Later
Now, you say you want to get all the names, and display it in a label. Let's break that down for you:
NSString *myLabel = null;
// You may of course want to be declaring myLabel as a property and @synthesising
// it, but for the sake of a complete example we'll declare it here which means
// it will only have local scope.
for (B *theBObject in theAObject.BObjects) {
myLabel = [myLabel stringByAppendingString:theBObject.name];
// Add a line break in the string after each B object name.
myLabel = [myLabel stringByAppendingString:@"\n"];
}
// Do something with your myLabel string to set your desired label.
A: You could try a predicate like this:
NSPredicate* fetchPredicate = [NSPredicate predicateWithFormat: @"any AObjects = %@", [NSManagedObjectID of an A]];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i end session when user was inactive Hi all i have seen several examples regarding the session. But i would like to know whether the following work as per my requirement or not. My requirement i will have some pages that user can access. If user visits a page and if he didn't perform any operations for 5 minutes or so i would like to redirect him to the default page available. This is what i have done
<authentication mode="Forms">
<forms timeout="50"/>
</authentication>
<sessionState timeout="5" />
The script i wrote is as follows
<script language="javascript" type="text/javascript">
var maxInactiveInterval = 120;
function startCountdown() {
window.setTimeout(alertSessionTimeout, ((maxInactiveInterval - 60) * 1000));
}
function alertSessionTimeout() {
alert("You're session is going to timeout in 1 minute.");
}
</script>
and i call this script in my body as follows
body onload="startCountdown();">
I would like to know whether it works as per my requirement or not and also the best possible methods to aler user that the session is going to expire in few minutes when he was inactive
A: Why dont you relay on the IIS where you can set the seesion time out or you can make change in you Web.Config file and set the session time out perio/ minutes. rather than writing script.
Something like:
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
EDIT
I hope you have seen this article for alerting user before session time out : Alert Session Time out in ASP.NET the better way to achieve you want.
A: You can achieve this by Jquery idle time out plug in
http://philpalmieri.com/2009/09/jquery-session-auto-timeout-with-prompt/
http://www.erichynds.com/jquery/a-new-and-improved-jquery-idle-timeout-plugin/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a comprehensive description for log4j.properties options? I have Googled till my finger bleed if I could not find a comprehensive description of the option usable for log4j.properties. All I find a general overview and samples from existing projects.
Among my questions are:
*
*Which % place-holder are available log4j.appender.*.layout.ConversionPattern
*Which type of layouter are available for log4j.appender.*.layout
*Are there any % place-holder available for log4j.appender.*.file
Maybe I just used the wrong search terms so just having a link to right place would be ok.
A: See the API docs at the link below.
http://logging.apache.org/log4j/1.2/apidocs/index.html
Basically, your configuration in a properties file will look much like if you set all the configuration via code, which is why the API docs should answer all your questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there any way to show vxml content into Google Chrome? I am searching for VXML 2.1 help. I know vxml can be tested on tellme.com server. But I am searching, if there is any way to test vxml in Google Chrome. That is, can vxml content be shown on Google Chrome?
A: To view the VXML generated in a Chrome browser you just need to enter the URL that the IVR or VXML browser uses to render the page. Most IVR platforms provide logs or trace files that show what URL's the platform is using to fetch the VXML documents. Just paste the URL from the log into the address for Chrome and you should see the VXML that is generated.
If the page appears blank then right click on the page and select "View page source". Most of the time the IVR platform just uses HTTP GET requests which work fine in the browser. But if it issues a POST, like when you record user input and save the audio file back to the application, then you will not be able to use Chrome. Then you can use something like Fiddler to view the VXML as described in this post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: JiBX Code-Gen Error: Duplicate name on format element at I am trying to generate code (with customizations applied) for OTA schema available at [OTA2003B] ( http://www.opentravel.org/Specifications/SchemaIndex.aspx?FolderName=2003B ) using JiBX Code Gen tool.Following is the code I have written to achieve the same.
Maven pom.xml jibx-maven-plugin configuration
<!-- JiBX Maven Plugin -->
<plugin>
<groupId>org.jibx</groupId>
<artifactId>jibx-maven-plugin</artifactId>
<version>1.2.3</version>
<configuration>
<customizations>
<customizations>src/test/resources/custom1.xml</customizations>
</customizations>
<schemaLocation>src/main/conf</schemaLocation>
<includeSchemas>
<includeSchema>FS_OTA_VehAvailRateRQ.xsd</includeSchema>
<includeSchema>FS_OTA_VehAvailRateRS.xsd</includeSchema>
</includeSchemas>
<schemaBindingDirectory>src/main/java</schemaBindingDirectory>
<includeSchemaBindings>
<includeSchemaBindings>*binding.xml</includeSchemaBindings>
</includeSchemaBindings>
</configuration>
<executions>
<execution>
<id>generate-java-code-from-schema</id>
<goals>
<goal>schema-codegen</goal>
</goals>
</execution>
<execution>
<id>compile-the-binding-</id>
<goals>
<goal>bind</goal>
</goals>
</execution>
</executions>
</plugin>
Customization XML: custom1.xml
<schema-set xmlns:xs="http://www.w3.org/2001/XMLSchema"
prefer-inline="true"
type-substitutions="xs:integer xs:int xs:decimal xs:float"
binding-per-schema="true">
<schema name="FS_OTA_VehAvailRateRQ.xsd"
includes="OTA_VehAvailRateRQ"
binding-file-name="otaVehAvailRateRQ_binding.xml"
package="com.poc.jibx.vehAvailRateRQ"/>
<schema name="FS_OTA_VehAvailRateRS.xsd"
includes="OTA_VehAvailRateRS"
binding-file-name="otaVehAvailRateRS_binding.xml"
package="com.poc.jibx.vehAvailRateRS"/>
</schema-set>
When I try to generate code from the configured schemas the code gets generated without the binding files and I get the following error:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jibx-sample 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- jibx-maven-plugin:1.2.3:schema-codegen (default-cli) @ jibx-sample ---
[INFO] Generating Java sources in src/main/java from schemas available in src/main/conf...
Loaded and validated 2 specified schema(s)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:InventoryStatusType; on format element at (source unknown)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:RatePeriodSimpleType; on format element at (source unknown)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:OffLocationServiceID_Type; on format element at (source unknown)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:VehicleTransmissionType; on format element at (source unknown)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.527s
[INFO] Finished at: Mon Sep 26 13:38:06 IST 2011
[INFO] Final Memory: 12M/84M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.jibx:jibx-maven-plugin:1.2.3:schema-codegen (default-cli) on project jibx-sample: Terminating d
ue to errors in bindings -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
However when I append generate-all="false" to <shema-set> element in custom1.xml the code generation and binding generation gets done
successfully.Please see the output below when I am using generate-all="false"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jibx-sample 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- jibx-maven-plugin:1.2.3:schema-codegen (default-cli) @ jibx-sample ---
[INFO] Generating Java sources in src/main/java from schemas available in src/main/conf...
Loaded and validated 2 specified schema(s)
Generated 11 top-level classes (plus 40 inner classes) in package com.poc.jibx.vehAvailRateRQ
Generated 24 top-level classes (plus 69 inner classes) in package com.poc.jibx.vehAvailRateRS
Total top-level classes in model: 35
Total classes (including inner classes) in model: 144
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.574s
[INFO] Finished at: Mon Sep 26 14:08:11 IST 2011
[INFO] Final Memory: 12M/84M
[INFO] ------------------------------------------------------------------------
I can see that the in both the schemas specified the elements referred to in the error shown above, for e.g. InventoryStatusType are available.And due to this the problem is occurring.But I have specified prefer-inline="true" and different packages for each schema code to be generated in my custom1.xml, which means that for both the schemas the fully qualified name of InventoryStatusType(assuming this would be created as an inner class) would be different and this should not create a duplication error like the one I am encountering.
1) What is that is causing the problem and how generate-all="false" is able to avoid this issue?
2) How to resolve the Duplicate Name error without using generate-all="false"?
Note: When using generate-all="false" binding files gets generated but on compilation of bindings I face the following error:
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:AddressType; on mapping element at (line 251, col 104, in otaVehAvai
lRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:CompanyNameType; on mapping element at (line 275, col 112, in otaVeh
AvailRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:LocationType; on mapping element at (line 324, col 106, in otaVehAva
ilRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:PersonNameType; on mapping element at (line 362, col 110, in otaVehA
vailRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:TPA_Extensions_Type; on mapping element at (line 383, col 118, in ot
aVehAvailRateRS_binding.xml)
Error: Duplicate mapping name not allowed for unmarshalling; on mapping element at (line 386, col 88, in otaVehAvailRateRS_binding
.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:TelephoneType; on mapping element at (line 394, col 108, in otaVehAv
ailRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:EffectiveExpireOptionalDateGroup-AttributeGroup; on mapping element
at (line 418, col 161, in otaVehAvailRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:PrivacyGroup-AttributeGroup; on mapping element at (line 430, col 12
1, in otaVehAvailRateRS_binding.xml)
Error: Duplicate name {http://www.opentravel.org/OTA/2003/05}:VehicleCustomerType; on mapping element at (line 470, col 120, in ot
aVehAvailRateRS_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.CompanyNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.
CompanyNameType; on structure element at (line 13, col 166, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.CompanyNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.
CompanyNameType; on structure element at (line 28, col 144, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.LocationType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Loc
ationType; on structure element at (line 43, col 159, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.LocationType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Loc
ationType; on structure element at (line 44, col 159, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.CompanyNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.
CompanyNameType; on structure element at (line 51, col 118, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.TPAExtensionsType is incompatible with binding for class com.poc.jibx.vehAvailRateR
S.TPAExtensionsType; on structure element at (line 227, col 50, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.VehicleCustomerType is incompatible with binding for class com.poc.jibx.vehAvailRat
eRS.VehicleCustomerType; on structure element at (line 106, col 117, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.AddressType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Addr
essType; on structure element at (line 128, col 111, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PersonNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.P
ersonNameType; on structure element at (line 130, col 140, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.TelephoneType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Te
lephoneType; on structure element at (line 131, col 136, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.LocationType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Loc
ationType; on structure element at (line 136, col 151, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.CompanyNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.
CompanyNameType; on structure element at (line 137, col 157, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.CompanyNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.
CompanyNameType; on structure element at (line 138, col 157, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.CompanyNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.
CompanyNameType; on structure element at (line 144, col 145, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PrivacyGroup is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Pri
vacyGroup; on structure element at (line 187, col 133, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PrivacyGroup is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Pri
vacyGroup; on structure element at (line 220, col 133, in otaVehAvailRateRQ_binding.xml)
Error: References to structure object must have compatible types: com.poc.jibx.vehAvailRateRQ.TPAExtensionsType cannot be used as
com.poc.jibx.vehAvailRateRS.TPAExtensionsType; on structure element at (line 227, col 50, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PrivacyGroup is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Pri
vacyGroup; on structure element at (line 230, col 133, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PersonNameType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.P
ersonNameType; on structure element at (line 253, col 134, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.TelephoneType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Te
lephoneType; on structure element at (line 256, col 125, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PrivacyGroup is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Pri
vacyGroup; on structure element at (line 264, col 137, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.AddressType is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Addr
essType; on structure element at (line 271, col 119, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PrivacyGroup is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Pri
vacyGroup; on structure element at (line 288, col 137, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.EffectiveExpireOptionalDateGroup is incompatible with binding for class com.poc.jib
x.vehAvailRateRS.EffectiveExpireOptionalDateGroup; on structure element at (line 295, col 197, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.PrivacyGroup is incompatible with binding for class com.poc.jibx.vehAvailRateRS.Pri
vacyGroup; on structure element at (line 300, col 137, in otaVehAvailRateRQ_binding.xml)
Error: Object type com.poc.jibx.vehAvailRateRQ.EffectiveExpireOptionalDateGroup is incompatible with binding for class com.poc.jib
x.vehAvailRateRS.EffectiveExpireOptionalDateGroup; on structure element at (line 307, col 197, in otaVehAvailRateRQ_binding.xml)
Updates on this after receving Don's reply
After posting the issue I viewed the OTA schemas online ( http://www.opentravel.org/Specifications/SchemaIndex.aspx?FolderName=2003B ) I was trying to generate code from and I found that the one available at the above link and the one I had was different.So I thought the flattened version of schema
I had might be causing the issue.So I downloaded the online version of schemas which is properly structured in the sense that it includes the
common schemas i.e.
<xs:include schemaLocation="OTA_VehicleCommonTypes.xsd"/>
<xs:include schemaLocation="OTA_SimpleTypes.xsd"/>
<xs:include schemaLocation="OTA_CommonTypes.xsd"/>
<xs:include schemaLocation="OTA_CommonPrefs.xsd"/>
<xs:include schemaLocation="OTA_AirCommonTypes.xsd"/>
Note: I am not using the OTA_AirCommonTypes.xsd in my code as some errors were occuring related to schema elements in this schema definition.
So I thought now the modular generation technique mentioned about (http://jibx.sourceforge.net/fromschema/example-modular.html ) can help.
I proceeded with the same and following is the code I have written:
jibx-maven-plugin configuration
<!-- For applying custom_a.xml customization -->
<!--
<configuration>
<customizations>
<customization>src/test/resources/custom_a.xml</customization>
</customizations>
<schemaLocation>src/main/conf/OTA_Schemas</schemaLocation>
<includeSchemas>
<includeSchema>Common/*.xsd</includeSchema>
</includeSchemas>
<schemaBindingDirectory>src/main/java</schemaBindingDirectory>
<includeSchemaBindings>
<includeSchemaBindings>*binding.xml</includeSchemaBindings>
</includeSchemaBindings>
<options>
<u>http://www.opentravel.org/OTA/2003/05</u>
</options>
</configuration>
-->
<!-- For applying custom_b.xml customization -->
<configuration>
<customizations>
<customization>src/test/resources/custom_b.xml</customization>
</customizations>
<schemaLocation>src/main/conf/OTA_Schemas</schemaLocation>
<includeSchemas>
<includeSchema>vehAvailRate/*.xsd</includeSchema>
</includeSchemas>
<schemaBindingDirectory>src/main/java</schemaBindingDirectory>
<includeSchemaBindings>
<includeSchemaBindings>*binding.xml</includeSchemaBindings>
</includeSchemaBindings>
<options>
<i>src/main/java/base-binding.xml</i>
</options>
</configuration>
My Customization XMLs
custom_a.xml
<schema-set prefer-inline="true" package="com.poc.jibx.ota.common"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
type-substitutions="xs:integer xs:int xs:decimal xs:float"
binding-file-name="base-binding.xml">
<schema name="OTA_CommonPrefs.xsd" />
<schema name="OTA_CommonTypes.xsd" />
<schema name="OTA_SimpleTypes.xsd" />
<schema name="OTA_VehicleCommonTypes.xsd">
<complexType name="VehicleProfileRentalPrefType">
<element path="**" name="VendorPref" ignore="true"/>
</complexType>
</schema>
</schema-set>
custom_b.xml
<schema-set prefer-inline="true"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
type-substitutions="xs:integer xs:int xs:decimal xs:float" >
<name-converter strip-prefixes="OTA_"
strip-suffixes="Type AttributeGroup Group Attributes"/>
<schema name="OTA_VehAvailRateRQ.xsd"
includes="OTA_VehAvailRateRQ" binding-file-name="otaVehAvailRateRQ_binding.xml"
package="com.poc.jibx.ota.vehAvailRateRQ" />
<schema name="OTA_VehAvailRateRS.xsd"
includes="OTA_VehAvailRateRS" binding-file-name="otaVehAvailRateRS_binding.xml"
package="com.poc.jibx.ota.vehAvailRateRS" />
</schema-set>
First I applied custom_a.xml which generated the code and ran the jibx:bind goal which compiled the bindings(base-binding.xml) successfully.
Then I commented the configuration section for applying custom_a.xml and enabled the configuration section for applying custom_b.xml
which generated the code successfully but running the binding compiler produced following errors:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jibx-sample 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- jibx-maven-plugin:1.2.3:bind (default-cli) @ jibx-sample ---
[INFO] Running JiBX binding compiler (single-module mode) on 4 binding file(s)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.693s
[INFO] Finished at: Mon Sep 26 20:57:56 IST 2011
[INFO] Final Memory: 12M/69M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.jibx:jibx-maven-plugin:1.2.3:bind (default-cli) on project jibx-sample: Internal error - cannot
modify class com.poc.jibx.ota.common.ActionType loaded from /media/data/Practice/SpringRoo/jibx-sample/target/classes -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
So now what is it that I am missing or going wrong at and how to fix this?
Also is the code I have written in line with the best practice JiBX users should follow or there are improvements I can make?
Note:
Generated Code Packages and Hierarchy
src/main/java
com.poc.jibx.ota.common (Java Package)
com.poc.jibx.ota.vehAvailRateRQ (Java Package)
com.poc.jibx.ota.vehAvailRateRS (Java Package)
base-binding.xml
binding.xml
otaVehAvailRateRQ_binding.xml
otaVehAvailRateRS_binding.xml
binding.xml contents:
<binding name="binding" package="com.poc.jibx.ota" trim-whitespace="true">
<include path="/myproject/jibx-sample/src/main/java/base-binding.xml" precompiled="true"/>
<include path="otaVehAvailRateRS_binding.xml"/>
<include path="otaVehAvailRateRQ_binding.xml"/>
</binding>
Thanks,
Jignesh
A: Jignesh,
When you are using flat schema (schema prefixed with FS_) it is best not to compile more than one schema at a time, since all the included schemas will be duplicated in each top level schema.
Since you want different package names anyway, split this into two projects, one that includes:
<includeSchemas>
<includeSchema>FS_OTA_VehAvailRateRQ.xsd</includeSchema>
</includeSchemas>
and another that includes this:
<includeSchemas>
<includeSchema>FS_OTA_VehAvailRateRS.xsd</includeSchema>
</includeSchemas>
This is the easiest way to resolve the Duplicate Name error without using generate-all="false".
Don
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails notification system I need to create a facebook-like notification system for an app I am working on. I was wondering what suggestions any of you have for how to go about doing this? If possible, I would like to avoid using the database for the notifications, if this is feasible I'd love to know how.
Thanks in advance
A: It wasn't clear in the question if notices needed to persist across sessions or user-to-user (who may not be online at the same time); however, I had a similar need on a Rails app and implemented it through a Notice ActiveRecord model. It's used for broadcasting downtime and other pending events coming up across every page on the site. Notices will show ahead and during their scheduled times.
class Notice < ActiveRecord::Base
validates_presence_of :header
validates_presence_of :body
validates_presence_of :severity
validates_presence_of :start_time
validates_presence_of :end_time
validates_inclusion_of :severity, :in => %( low normal high )
end
Since it needed to be displayed everywhere, a helper method was added to ApplicationHelper for displaying it consistently:
module ApplicationHelper
def show_notifications
now = DateTime.now.utc
noticeids = Notice.find(:all, :select=>"id", :conditions=>['start_time >= ? or (start_time <= ? and end_time >= ?)', now, now, now])
return "" if noticeids.count == 0 # quick exit if there's nothing to display
# ...skipping code..
# basically find and return html to display each notice
end
end
Lastly, in the application layout there's a tiny bit of code to use the ApplicationHelper#show_notifications method.
A: Rails has a default notification system - the flash. You could pass on your own messages around in the flash and then display them in any way you want on the front-end with some CSS and JS. Do google around for some plugins to see if they suit your requirements, though it should not be very hard to implement on on your own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails3:how to register scss template handler I'm interested how can I register a .scss template handler in Rails 3.1 . I know that I already can use .scss files in the app/assets directory, however I need to have access to the application environment and instance variables.
I'm trying to do something like this (the end goal is to have dynamic scss files):
file: app/views/css/layout.css.scss.erb
$site_width = <%= @site.width %>px;
.container { width: $site_width; }
The "problem" with the assets directory is that we don't have access to the application environment there.
I tried to achieve it this way, however it isn't the correct way :)
file: initializers/scss_template_handler.rb
ActionView::Template.register_template_handler :scss, Sass::Rails::ScssTemplate.new
Thanks for any help or ideas in advance!
A: I found a solution for this.
By following this gist: https://gist.github.com/827572 you can easily register a :scss template handler!
However here comes another showstopper :) - processing a file by multiple template handlers. I'll open a new questions for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: securityinspector for org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean Can anybody help me out wheather Spring provide security inspector for org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean (purpose i have RPC/ENCODED secure webService)
A: Spring Does not support RPC style. Its only support document style.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generate sequence with step value I have following inputs:
double zmin;
double zmax;
int count;
int N; //Total number of element in result array
I want to generate a sequence of double array with zmin as first and zmax as last value. But from second value until last but one it should be steзped by (zmax-zmin)/count.
Example:
zmin = 1;
zmax = 10;
count = 3
Expected result:
double[] result = { 1, 4, 7, 10}
My try:
double[] result = Enumerable.Repeat(zmin, N).Select(iv => (iv +(zmax-zmin)/count)).ToArray();
A:
This is an improvement on existing answer from Muhammad Hasan Khan.
The solution works fine but as the decimal error accumulates over time , it produces lot of error in decimal places over time.
First improvement on the existing solution is to get away with the accumulation of error like,
public static IEnumerable<double> Range(double min, double max, double step)
{
double result = min;
for (int i = 0; result<max; i++)
{
result = min + (step * i);
yield return result;
}
}
This solves the problem almost but if you are even pedantic to get rid of the dirt sometimes sticking around the decimal place, you can go a step further like,
public static IEnumerable<double> Range(double min, double max, double step)
{
double result = min;
int decPlaces = BitConverter.GetBytes(decimal.GetBits((decimal)step)[3])[2];
for (int i = 0; result<max; i++)
{
result = min + (step * i);
yield return Math.Round(result,decPlaces);
}
}
And for the way how to call the above methods,
just as an example,
double[] Myarray = classname.Range(0, 50, 0.01).ToArray();
will get you a double array with the mentioned parameters.
A: public static IEnumerable<double> Range(double min, double max, double step)
{
double i;
for (i=min; i<=max; i+=step)
yield return i;
if (i != max+step) // added only because you want max to be returned as last item
yield return max;
}
A: This one is good not only for numbers, but for more complex types as date/time.
The second method allows to provide result selector - useful in some cases.
public static IEnumerable<TItem> Range<TItem>(
TItem itemFrom, TItem itemTo, Func<TItem, TItem> itemSelector
) where TItem : IComparable
{
// Call to the below method
return Range(itemFrom, itemTo, itemSelector, o => o);
}
public static IEnumerable<TItem> Range<TItem, TResult>(
TItem itemFrom, TItem itemTo, Func<TItem, TItem> itemSelector, Func<TItem, TResult> resultSelector
) where TItem : IComparable
{
while (true)
{
yield return resultSelector(itemFrom);
if ((itemFrom = itemSelector(itemFrom)).CompareTo(itemTo) > 0)
break;
}
}
Usage:
Range(1, 10, o => o + 3);
1
4
7
10
Range(
DateTime.Now,
DateTime.Now.AddYears(1),
o => o.AddMonths(1),
o => o.ToString("MMMM"));
January
February
March
April
May
June
July
August
September
October
November
December
January
A: A bit cleaner than existing answers (as of 2020-01-22):
static IEnumerable<double> GetSteppedSequence(double from, double to, int numberOfSteps)
{
if (numberOfSteps < 1)
{
throw new ArgumentOutOfRangeException(nameof(numberOfSteps), "Number of steps must be greater than zero.");
}
var stepSize = (to - from) / numberOfSteps;
return Enumerable.Range(0, numberOfSteps + 1).Select(stepIndex => from + stepIndex * stepSize);
}
This uses multiplication instead of repeated addition, so that rounding errors are avoided.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Autoconf subdirectories with subpackages depending on each other? I've got a large project on my hand (master) that is split into several components (liba, b, c, d) to ease building and maintenance. When building the whole package, all of the subcomponents must be built in sequence, and some of these packages depend upon each other.
In more explicit terms, liba is a prerequisite for b, c and d, and the presence of liba is checked by the configure script. This check is definitely necessary to give user-friendly error messages when building the b distribution on its own. However, when building the master package and all its subpackages, liba is built as a subtarget. Therefore, when configure runs on the master suite, liba is not installed yet and the check for liba in b fails.
I could rectify this issue by passing a --with-liba=internal or similar flag to the configure script of b; however, I haven't found any documentation on such flag-passing for autoconf. For the time being, I have a long, long custom Makefile in master that does just the same as autoconf/automake with subdirectories, but reorders dependencies a bit so that instead of (configure liba) => (configure b) => (build liba) => (build b), the order is (configure liba) => (build liba) => (install liba) => (configure b) => (build b).
Any idea how I could refactor this with standard autoconf/automake subdirectories?
A: This mail might help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to list all the elements found in a long listing format? I use often ls -l to list files in a long listing format, and find -name ... to find elements...
Does anyone know how to list the return of find -name ... in a long listing format?
Thank you!
A: Sure - just use the -ls option:
$ find . -name ... -ls
See: man find
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Problem loading MORE than one custom font blackberry I tried to load a custom font, which works. Now I have got the problem Iam not able to use more than one custom font in an application. If i add three labelFields each with a different font, only the last custom font is used for all labels.
If i delete the last setFont for the last label the second font is used. Is there some kind of mechanism which uses only the last font?
Here is the code which add the LabelFields and sets the fonts
LabelField TestLabel1 = new LabelField("Test Label 1");
Font fo1 = loadCustomFonts("FirstFont.ttf", "FirstFont", 0, 30);
TestLabel1.setFont(fo1);
add(TestLabel1);
LabelField TestLabel2 = new LabelField("Test Label 2");
Font fo2 = loadCustomFonts("SecondFont.ttf", "SecondFont", 0, 30);
TestLabel2.setFont(fo2);
add(TestLabel2);
LabelField TestLabel3 = new LabelField("Test Label 3");
Font fo3 =loadCustomFonts("ThirdFont.TTF", "ThirdFont", 0, 30);
TestLabel3.setFont(fo3);
add(TestLabel3);
Here is my "loadCustomFonts" Method, which loads the custom Font and returns a font object.
public Font loadCustomFonts (String path, String fontname,int fontStyle, int fontSize){
InputStream stream = this.getClass().getResourceAsStream(path);
if (FontManager.getInstance().load(stream, fontname, FontManager.APPLICATION_FONT) == FontManager.SUCCESS){
try{
FontFamily family;
add(new LabelField("A"));
family = FontFamily.forName(fontname);
Font myFont = family.getFont(fontStyle,fontSize);
return myFont;
}
catch (ClassNotFoundException e){System.out.println(e.getMessage());}
}
else {
try{
FontFamily family;
add(new LabelField("B"));
family = FontFamily.forName(fontname);
Font myFont = family.getFont(fontStyle,fontSize);
return myFont;
}
catch (ClassNotFoundException e){System.out.println(e.getMessage());}
}
return null;
}
A: I found the reason. It was the maximum size of 60kb per custom font and if the font was allready loaded.
So I changed the loader method.
public Font loadCustomFonts (String path, String fontname,int fontStyle, int fontSize){
//Loads custom Fonts
InputStream stream = this.getClass().getResourceAsStream(path);
System.out.println("fontname"+fontname);
//System.out.println("fontname"+fontname +"FontManager Return "+FontManager.getInstance().load(path, fontname, FontManager.EXCEEDS_LIMIT));
if (FontManager.getInstance().load(stream, fontname, FontManager.APPLICATION_FONT) == FontManager.EXCEEDS_LIMIT)
System.out.println("FontManager.EXCEEDS_LIMIT => true");
else
System.out.println("FontManager.EXCEEDS_LIMIT => false");
System.out.println (FontManager.DUPLICATE_DATA);
if (FontManager.getInstance().load(path, fontname, FontManager.APPLICATION_FONT) == FontManager.APPLICATION_FONT)
{
//if (FontManager.getInstance().load(stream, fontname, FontManager.APPLICATION_FONT) == FontManager.SUCCESS){
System.out.println("A getInstanc => true");
try{
System.out.println("A Try");
FontFamily family;
family = FontFamily.forName(fontname);
Font myFont = family.getFont(fontStyle,fontSize);
System.out.println("A return myFont"+myFont);
return myFont;
}
catch (ClassNotFoundException e){System.out.println(e.getMessage());}
System.out.println("A Catch");
}
else {
//font could not be loaded
System.out.println("B getInstanc => false");
System.out.println("FontManager.getInstance().load(path, fontname, FontManager.APPLICATION_FONT"+FontManager.getInstance().load(path, fontname, FontManager.APPLICATION_FONT));
if (FontManager.getInstance().load(path, fontname, FontManager.APPLICATION_FONT) == FontManager.DUPLICATE_NAME)
//check if font already is loaded
try{
System.out.println("B Try");
FontFamily family;
family = FontFamily.forName(fontname);
Font myFont = family.getFont(fontStyle,fontSize);
System.out.println("B return myFont"+myFont);
return myFont;
}
catch (ClassNotFoundException e){System.out.println(e.getMessage());}
else
System.out.println("FontManager.getInstance().load(path, fontname, FontManager.APPLICATION_FONT"+FontManager.getInstance().load(path, fontname, FontManager.APPLICATION_FONT));
}
return null;
}
Does someone know a solution to load fonts which are bigger than 60kb ? I already tried to use a input stream but it did not work.
(the limit "FontManager.EXCEEDS_LIMIT if font data exceeds 60k in size. " - http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/ui/FontManager.html#load%28java.io.InputStream,%20java.lang.String,%20int%29)
A: try to override the paint() of the each labelfield and apply setFont inside it.
A: LabelField lf1 = new LabelField("This is font 1"){
protected void paint(Graphics graphics)
{
setFont( getFont().derive(Font.STYLE_BOLD,15));
graphics.drawText(getText(), 1, 1);
super.paint(graphics);
}
};
LabelField lf2 = new LabelField("This is font 2"){
protected void paint(Graphics graphics)
{
setFont( getFont().derive(Font.STYLE_ITALIC,18));
graphics.drawText(getText(), 1, 1);
super.paint(graphics);
}
};
LabelField lf3 = new LabelField("This is font 3"){
protected void paint(Graphics graphics)
{
setFont( getFont().derive(Font.STYLE_UNDERLINED,20));
graphics.drawText(getText(), 1, 1);
super.paint(graphics);
}
};
add(lf1);
add(lf2);
add(lf3);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Output row in text file with max value in specified column to new file I have a fairly simple task I need to automate for an analysis. I have found similar questions on this forum but not applied to a plain text file, and as I am a python newbie I am not sure how to convert these solutions directly to my needs. So I'd appreciate any help.
I have a series of files in this format:
11 5012 1000 10036040.000000 1.089555 4.529811 0.150000
11 5013 1000 10038040.000000 1.089783 4.340549 0.150000
11 5014 1000 10039040.000000 1.090000 4.733367 0.150000
11 5015 1000 10044040.000000 1.090217 4.601943 0.150000
11 5016 1000 10044040.000000 1.090435 5.048237 0.150000
11 5017 1000 10046040.000000 1.090652 1.280908 0.050000
each file is named "data1-1", "data1-2", "data1-3" etc
The data is separated by single spaces and there is no header
I would like a script to go into each file, find the row with the max value in column 5 (eg value 5.048237 above) and to print that row into a new output file.
In the end I need one output file that contains the rows with the max value in column 5 from each of the input files. So if there were 5 input files the output file would have 5 rows.
I hope this is clear, any help is really appreciated!
A: import glob, operator
fpout = open("result.dat","w")
for path in glob.glob("data?-?"):
with open(path, "r") as fp:
fields = [ line.split(" ") for line in fp ]
maxline = " ".join(max(fields, key = lambda row: float(row[5]))
print >> fpout, maxline
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: FancyBox navigation on certain links Hi there good people of StackOverfow, i need help with visibility of the FancyBox navigation arrows. I need them to be always visible (not only on hover) on image groups, but invisible on videos that open in FancyBox window.
the code that I have for images is:
$("a[rel=images]").fancybox({
'transitionIn' : 'none',
'transitionOut' : 'none',
'showNavArrows' : 'true',
'titlePosition' : 'over',
'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
return '<span id="fancybox-title-over">Image <strong>'
+ (currentIndex + 1)
+ ' </strong>/ '
+ currentArray.length
+ (title.length ? ' ' + title : '')
+ '</span>';
}
});
and I've added two lines of CSS to make the arrows always visible on the images:
#fancybox-left-ico {left: 20px;}
#fancybox-right-ico {right: 20px;}
The code for opening videos in FancyBox window is:
$(".video").click(function() {
$.fancybox({
'padding' : 0,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'title' : this.title,
'width' : 700,
'height' : 450,
'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'showNavArrows' : 'false',
'allowfullscreen' : 'true'
}
});
//$('.fancy-ico').hide();
return false;
});
When i click on video link the fancybox window shows both of the navigation arrows, which is understandable since that is what my 2 added lines of CSS are there for. When I add a line of code that is something like:
$('.fancy-ico').hide();
the video window opens up without any arrows which is still good. The problem is when I click on the images again, the arrows don't show up, because I've hidden the arrows with the last jquery line.
Now my question is how can I make this work? Where can i insert a piece of code that looks like:
$('.fancy-ico').show();
Is there some smarter way of doing something like this?
Thank you all for any help
A: You can use to your images code the onStart function:
so that, each time the images fancybox loads, it will display the arrows as well.
$("a[rel=images]").fancybox({
'transitionIn' : 'none',
'transitionOut' : 'none',
'showNavArrows' : 'true',
'titlePosition' : 'over',
'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
return '<span id="fancybox-title-over">Image <strong>' + (currentIndex + 1) + ' </strong>/ ' + currentArray.length + (title.length ? ' ' + title : '') + '</span>';
}
// onStart: "Will be called right before attempting to load the content"
'onStart' : function() {$('.fancy-ico').show();}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Transaction and Rollback in Spring with JPA Hi friends of StackOverflow,
I do not understand how to roll back I read the documentation of Spring, but I still do not understand. Basically I'm going to persist an object in the db (with primary key manually) all the way here all right, the object is inserted into the db. But when you persist the object again with the same primary key I have caused an exception, and rightly so, a violation of restriction of uniqueness. In this case I would get a Transaction rollback and warn you that there was the problem and continue running the program
This is my class:
public class ServiceDaoImpl{
@PersistenceContext (unitName="fb-persistence")
protected EntityManager em;
public void setEntityManager(EntityManager entityManager) {
this.em = entityManager;
}
@Transactional(readOnly=false)
public void write(Service entity){
try {
em.persist(entity);
em.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
}
/*
* .. other method
*/
}
And this is the stack of error:
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:798)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy27.flush(Unknown Source)
at it.synclab.fb.jpa.dao.impl.GenericDaoImpl.write(GenericDaoImpl.java:236)
at it.synclab.fb.jpa.dao.impl.EnteDaoImpl.write(EnteDaoImpl.java:1)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy34.write(Unknown Source)
at it.synclab.fb.jpa.test.ConfigTest.insertEnte(ConfigTest.java:47)
at it.synclab.fb.jpa.test.ConfigTest.main(ConfigTest.java:32)
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:795)
... 21 more
Caused by: java.sql.BatchUpdateException: ORA-00001: violata restrizione di unicità (FLUSSIBATCH.SYS_C008896)
and my configuration files are (persistence.xml and applicationContext.xml):
This is the applicationContext.xml:
...
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="fb-persistence" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean name="serviceDaoImpl" class="it.synclab.fb.jpa.dao.impl.ServiceDaoImpl" />
...
This is the persistence.xml:
<persistence>
<persistence-unit name="fb-persistence" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>META-INF/orm.xml</mapping-file>
<class>it.entity.Service</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.username" value="############"/>
<property name="hibernate.connection.password" value="############"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
</properties>
</persistence-unit>
</persistence>
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:629)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:9467)
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:211)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 27 more
Exception in thread "main" org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:476)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy34.write(Unknown Source)
at it.synclab.fb.jpa.test.ConfigTest.insertEnte(ConfigTest.java:47)
at it.synclab.fb.jpa.test.ConfigTest.main(ConfigTest.java:32)
Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:73)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467)
... 9 more
Why have to be complicated? I just do not understand ... I hope some of you have had the same problem and solved
A: I don't know if I understand your question correctly, but your problem might be with ServiceDaoImpl exception handling:
try {
em.persist(entity);
em.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
This is a really bad practice (tm). Don't catch the exception but let it pop up from your method. This way:
*
*Transaction demarcation mechanism will intercept the exception and mark transaction as rollback only
*You won't ignore the exception (yes, catching and logging is almost as bad as swallowing)
*Very likely the exception will be caught at some higher level and logged properly (using SLF4J or similar) and you won't have this boilerplate.
So to cut long story short:
public class ServiceDaoImpl{
@PersistenceContext (unitName="fb-persistence")
private EntityManager em;
@Transactional(readOnly=false)
public void write(Service entity){
em.persist(entity);
em.flush();
}
}
Note that you don't need setter for EntityManager and the field can be private.
A: Add a try catch block in your write method and throw an exception in case of error.
Put a rollbackFor or rollbackForClassname attribute in your @Transactional annotation for the exception that you rise, if you want to controll rollback events.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Help with a SQL querying speed and performance issue I've got a classified listing website for cars which I'm in the process of developing built in PHP. The user enters the details of the car they are looking for using drop down option boxes on the homepage. When they click submit they are taken through to the results page, and this is where I'm having problems.
The way it is set-up at the moment is:
*
*The database is queried for any results matching the car they are looking for. The query returns the ID of the car and the Postcode of the advert;
*Each advert is then checked for the distance between the users postcode and the postcode of the advert. This itself requires a database query to find the coordinates for individual postcodes of each advert and is quite time consuming for what can be in excess of 350 results at times;
*An if statement is then used to determine if the distance is less than or equal to the distance the user entered on the homepage
*If the advert is within the allowed distance it's ID is added to an array;
*The total number of adverts in the array is then calculated and used to determine a variable dependant on the number of adverts and the number of adverts to be displayed on the page;
*A second query of the advert table is then executed using a WHERE statement and the ID's in the array. e.g. SELECT * FROM adverts WHERE ID=1 AND ID=4 AND ID=23 ........ The total number of ID's used in the query depend on the variable mentioned in point 5. When the user then clicks next page the query is re-run from the position in the array that it was left at and the query is then re-created and executed.
The problem I'm having is that it is taking ages to complete and I was looking for a more resource and time concious way of completing it.
It originally was designed that a query would execute with WHERE clauses for each of the users specific requirements for the car, and then before being output to the page the distance was being checked using an if statement. This caused problems with the page numbering because it was impossible to determine the number of adverts that would match the distance requirements from the adverts returned in the query- hence it is done this way with the distance conditions being satisfied before the full adverts are collected so an exact number of adverts to be displayed is calculated.
Sorry its a little long - hope it makes sense. I haven't included any code because it would make it longer, and its a problem with the logic as opposed to the actual code.
Thanks for any suggestions you are able to make.
Someone has requested the table layout and SQL. Here goes.....
Advert Table
ID, Make, Model, Colour, Mileage, Engine, Year, Postcode
Postcode Table
ID, Postcode, GridN, GridE, Longitude, Latitude
SQL for first query to get the ID and Postcode
SELECT ID, Postcode FROM adverts WHERE Make = '$subMake' AND Model = '$subModel' etc
SQL for the second query to get the advert details using the ID's that match the distance requirements:
SELECT Make, Model, Year, Engine, Colour FROM adverts WHERE ID IN(1,2,6,90,112,898)
(Sorry if its not syntactically correct, it does work, that SQL is just a rough outline of the many lines of the query strings.)
A: Amend the query so that it includes the distance between the postcodes and is restricted to those adverts within the specified distance range.
A: The biggest optimization would be query the postcode table and store the Grid references in the adverts table -- when you are inserting the advert row.
This would drastically reduce the number of accesses to the post code table.
You could also reduce the number of calculations by some simple filtering on the advert table as follows.
Get the Users GridN and GridE values from the post code table.
Calculate minN as GridN - maxDistance , maxN as GridN + maxDistance, minE as GridE - maxDistance, and maxE as GridE + Maxdistance.
You can then query on the advert table like so:
SELECT * FROM ADVERTS WHERE GridN between (minN,maxN) and GridE Between(minE,maxE);
To further speed this up you can add indexes to GridN and GridE.
Once you have selected the rows you can calculate the "real" distance and reject the few rows that fall outside the limit.
A: You should change your distance function into a view with all possible combinations of postcodes, then you can join on that within your queries rather than hitting the function, or you can calculate the latitudes and longitudes that are 50km from your user's post code
Further to that if you provide fixed options (most of these websites offer 5, 10, 25, 50, 100 as the distance options only) then you can pre-compute these distance calculations and to go even further you could do the extra check and map each postcode to all the ones nearby if you really wanted, you would only need to calculate it 5 times (5 distances) for each post code, and you could exclude the results from the previous value, such that you exclude 5km from the 10km query because you just look for distance <= 10km.
A: Depending on your database maybe use something like PostGIS?
Setup a column in the Adverts table for a LonLat datatype and then run the built-in functions such as ST_DWithin to find all adverts with a LonLat within a specified distance from the target record.
Just to point out another issue that I find with using a static postcode database is that they quickly go out of date (especially for new builds). You might also want to use something like Mapstraction to return a geocoded result from Google / Yahoo etc and save that LonLat instead - although you might have to have more error checking on the postcode input and restrict your returned results to exact matches.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring MVC invalid Date Format error message not showing I'm having trouble regarding Date validation in Spring MVC 3
ClientForm.java
public class ClientForm
{
private Date bday = new Date();
//Getters and setters
}
In my Controller
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@Valid ClientForm form, BindingResult result)
{
if(result.hasErrors())
{
return "client.form";
}
return "redirect:search";
}
messages.properties
client.search.notnumber=Search value must be a number
typeMismatch.java.util.Date = Invalid date
jsp
<form:form action="save.html" method="post" commandName="clientForm">
<form:input path="bday" cssClass="date-pick dp-applied" />
<form:errors path="bday" element="label" cssClass="error"/>
</form:form>
Other validation messages in 'messages.properties' works fine
but when i intentionally typed an invalid date (i.e. 111/12/2011)
i got this error message
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'clientForm' on field 'bday': rejected value [21/05e/2011]; codes [typeMismatch.clientForm.bday,typeMismatch.bday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [clientForm.bday,bday]; arguments []; default message [bday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'bday'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "21/05e/2011" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException: Invalid format: "21/05e/2011" is malformed at "e/2011"]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:359)
org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:275)
org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:344)
org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:272)
org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
root cause
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'clientForm' on field 'bday': rejected value [21/05e/2011]; codes [typeMismatch.clientForm.bday,typeMismatch.bday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [clientForm.bday,bday]; arguments []; default message [bday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'bday'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "21/05e/2011" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException: Invalid format: "21/05e/2011" is malformed at "e/2011"]
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:810)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:153)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:359)
org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:275)
org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:344)
org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:272)
org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
A: This is a binding exception. Have you defined a binder? If yes, have you registered an editor for dates? Perhaps you should check that editor, you may have a typo there... where is that 'e' in the date coming from? It seems like a conversion error to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Internationalization of custom validation error messages I need to have custom validation messages in my ActiveRecord models internationalized. Currently, I'm using something like this, which works:
validates_uniqueness_of :name, :message => lambda { I18n.t(:family_name_in_use) }
I know Rails has validation message translations builtin, but for reasons I can't go into here, I can't use those. Is there a nicer solution than this lambda thing? I'm using Rails 2.3.8, if that matters.
A: You can use builtin solution https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/ro.yml
And you can add translation of database attributes like this:
ro:
activerecord:
models:
user: utilizator
attributes:
profile:
name: "afişare Nume"
phone: "telefon"
A: I ultimately stuck with the lambda solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jqueryUi autocomplete combobox going up instead of down Is there a way to show the combobox ending instead of starting in the autocomplete form if the autocomplete is near the bottom of a page (pageview).
The problem with this widget is that if it's near the bottom, the combobox will not be visible; as it's going down
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you use Dijkstra's algorithm if there is a negative weight so long as there are no cycles? Update: I really botched the original question. My original title was "Why do we first do a topological sort for acyclic weighted digraph shortest path problems?" but my question content was about Dijkstra's algorithm. Hopefully since I've changed the title, the question is updated in such a way that it is useful to someone else. The answer to the updated question title is "yes".
Original question:
Why do I need to do a topological sort first? (see code here) Can't I just use Dijkstra's algorithm shown below and avoid the topological sort altogether (little messy syntax-wise but you get the idea)
MinIndexedPriorityQueue waitingEdges = new MinIndexedPriorityQueue
Graph g //some weighted directed graph
double[] distTo = new double[g.vertexCount]
Edge[] edgeTo = new Edge[g.vertexCount]
int source = //init to some value
void minPathInit()
init distTo to double.MAX_VALUE
//init first node
distTo [source] = 0
visit(source)
while waitingEdges.count>0
int vertex = waitingEdges.dequeue()
relax(vertex )
void relax(v) //note that visit has been renamed to relax
for each edge in graph.getEdgesFrom(v)
int to= edge.to
if edge.weight + distTo [edge.from]< distTo [to]
distTo[to] = edge.weight + distTo [edge.from]
edgeTo[to] = edge
if waitingEdges.contains(to)
waitingEdges.change(to, distTo[to] )
else
waitingEdges.enqueue(to, distTo[to] )
//after everything is initialized
getPathTo(v)
if not hasBeenVisited[v]
return null
Stack path = new Stack
while edgeTo[v] != source
path.push(edgeTo[v])
v = edgeTo[v].from
return path
I can understand why Dijkstra's algorithm can't handle negative cycles (because it would get stuck in an infinite loop) but if there are no negative cycles, why does it fail as shown (and require the topological sort first)
Update: Ok, I can see that I've botched up this question so I will try to fix it up a bit with an update. Thanks for taking the time to point the hole's out for me. I mistakenly thought AcyclicSP becomes Dijkstra's algorithm when removing the topological sort which is not the case.
However, my question about Dijkstra's algorithm (using the version shown above) remains. Why can't it be used even if there is a negative weight so long as there are no cycles? There is a java version of Dijkstra's algorithm here. Mine is very similar to this (since this guy's book is where I learned about it) but his example is probably easier to read for some of you.
A: You don't make any topological sort in the original algorithm. But in the case of an a-cyclic graph, then you can decrees the running time to O(V) (while the original running time is O(|V|*log(|V|)).
The reason is that you sort in O(|V|) time, and then you can use that order, and don't need any heap (or priority queue). So the over all time decreases to O(|V|).
A: Dijkstra's algorithm doesn't appear to require a topological sort. Perhaps doing so avoids a bug you have in your implementation.
Dijkstra's algorithm doesn't support negative path costs, but does handle looping cycles. It does this by stopping when it finds that there is a shorter path to a node. A looping path will not be shorter and there for stop (provided the cost is non-negative)
A: It is not possible to use Dijkstra Algo with negative weights.
Hundreds have tried, no one was successfull.
Use Bellman-Ford Algo if you have neg. Weights
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: passing correlation token to WCF service? Having a lot of similar calls, maybe in parallel, to some web services, I'm wondering what is the best way to implement a correlation token mechanism.
The idea is to have, from the client to the server, the ability to log information for a single request with an identifier that helps, later, to get a log for a specific request.
I'd like to avoid adding a parameter on each operation, because I think this is plumbing, not business.
PS: I'm controlling both client and server side in my solution. I can change whatever is needed. MY services are running with .Net V4, and I'm using log4net to create the logs. I've wrapped log4net is some utility methods I can change if required.
A: So do you want only information about request and its response? If you use message version with WS-Addressing you should have it automatically because each messages will contain its autogenerated ID (guid) and each response will contain ID of the request as well. You can access these headers through OperationContext:
Server side:
UniqueId id = OperationContext.Current.IncomingMessageHeaders.MessageId;
Client side:
using (var scope = new OperationContextScope())
{
// Do call to server and after that access headers
OperationContext context = OperationContext.Current;
UniqueId responseId = context.IncomingMessageHeaders.MessageId;
UniqueId requestId = context.IncomingMessageHeaders.RelatesTo;
}
To use WS-Addressing you must use SOAP service with WsHttpBinding or CustomBinding using correct MessageVersion in TextMessageEncodingBindingElement.
If you want to have correlation for all requests from the same client you need WCF session and use session Id (OperationContext.Current.SessionId).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Split html body in two parts Is it possible to split the body tag in my web site into two parts. For example having the first 50% (in height) in the background-color in white and the rest 50% in black?
Does anyone know how I can do that?
Thanks
A: If it's enough to work with CSS3, then the following do the trick:
body {
background: #000 url(white.png) 0 100% repeat-x;
-webkit-background-size: 0 50%;
-moz-background-size: 0 50%;
-o-background-size: 0 50%;
background-size: 0 50%;
}
Or you need a (vertically) big enough image, then:
body {
background: #000 url(white.png) 0 50% repeat-x;
}
A: You can make two DIVs for the two colors and place the content in a third div over them.
A: Not sure what you mean to 'split' the body but here is how you could do 50% 50% background
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rotate TextView without cut off text i'm trying to rotate a TextView, but my text gets cut off by the bounds. But the text is rotated.
I'm not using this for an animation or some sort. It's just static, design-wise :)
I have a RotatedTextView where i do this:
public class RotatedTextView extends TextView
@Override
public void onDraw(Canvas canvas)
{
canvas.save();
float py = this.getHeight()/2.0f;
float px = this.getWidth()/2.0f;
px = py = 0;
canvas.rotate(this.degrees, px, py);
super.onDraw(canvas);
canvas.restore();
}
Here's how it is looking now:
Orginial source
Can anyone help me solve this issue ?
Thanks !
A: Try add padding to the textview. That should make the canvas remain inside the bounds. Or you might need to put the height of the view accordingly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to extend the "New" context menu? Is it possible to add menu item in "New" context menu(package explorer)? I tried something like this, but the the menu item isn't placed in the context menu, but above it.
<extension point="org.eclipse.ui.popupMenus">
<viewerContribution
id="org.eclipse.ui.articles.action.contribution.popup.navigator"
targetID="org.eclipse.jdt.ui.PackageExplorer">
<action
id="org.eclipse.ui.articles.action.contribution.navigator.action1"
label="View Action 1"
icon="icons/red_dot.gif"
menubarPath="group.new"
class="org.eclipse.ui.articles.action.contribution.ViewAction1Delegate"
enablesFor="!">
</action>
</viewerContribution>
</extension>
A: Only by using the org.eclipse.ui.newWizards extension point. Otherwise it's probably not the right context menu to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: see if content element is a reference or not Hi I need to find out if an content element is a reference or not.
I tried to see if $this->destPointer was set but then I realized that this was set for all elements...
I cant find where the references are saved in the database either.
Someone got any idea?
A: References are saved in the "pages" table, column "tx_templavoila_flex" (XML format).
Check the current page id against the content elements' pid and then you know whether it's a reference.
if($this->cObj->data['pid'] != $GLOBALS['TSFE']->id) {
//reference
}
else {
//not a reference
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails: Find and use the id number from a diff controller I want to extract the id number of a unique record, that resides in a different controller as an integer, so I can save it as part of a new record in a new controller.
I can't seem to get the id to shed it's 'Array' attribute.
I've been using this:
class MessagesController < ApplicationController
def incoming
a = Group.where("name = ?", name).map { |n| n.id }
group_number = a.id
puts "#{group_number} is the number!"
end
output is always [2] or [3] or whatever.
adding this doesn't seem to cure it
group_as_int = group_number.to_i
Lastly, the reason I'm doing all this is to save that group number as a new record in a third controller, like this:
Subscriber.create(:group_id => group_number, :active => "1")
or
Subscriber.create(:group_id => group_as_int, :active => "1")
Of course, the create balks when I try to pass an array into the create function.
Thoughts?
A: You are trying to put business logic into the controller.
Try to refactor your methods and put them into your models instead.
Beside that you get the number in the following way:
group = Group.where("name = ?", name).first
group_number = group.id if group.present?
A: You might want to try .first to get the integer out of the array.
A: I will try to explain from your code what you did wrong.
The first line:
matching_group_ids = Group.where("name = ?", name).map { |n| n.id }
You called it a, but i prefer more verbose names. matching_group_ids now holds an array of id's. To get the first value of this array, the easiest solution is to just write
group_number = matching_group_ids[0]
or, more readable:
group_number = matching_group_ids.first
Mind you: you should test that the returned array is not empty.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can we use pom.xml into ANT I know that, we can very well use ANT and Maven together to build the project.We can run ANT scripts through Maven's POM.xml. But my question is can we run pom.xml through ANT's build.xml ?
i.e. can we create maven build from build.xml
A: Yes, using maven ant tasks.
The page lists out multiple maven tasks which can be integrated into an ant build script, thus combining the features of both. To take an example, there is the mvn task, which as documented can do a full maven build from ant.
<artifact:mvn mavenHome="/path/to/maven-3.0.x">
<arg value="install"/>
</artifact:mvn>
Besides this, there are
*
*Dependencies task
*Install and Deploy tasks
*Pom task
each described with examples.
A: Maven and ANT are very different build tools. In ANT you write all the logic yourself, whereas a standard build process is "baked in" with Maven.
The POM file contains no logic, instead it contains a series of declarations about your project.
If you understand well how Maven works, it is theoretically possible to take a POM and generate an ANT build that emulates the behaviour of the Maven build. I'm not aware of any solution which can easily convert in the other direction, mainly because ANT is missing Maven functionality, such as dependency management.
Instead of trying to convert an ANT build into Maven, I'd recommend that you keep your existing build logic and delegate the management of your classpath to the ivy or Maven ANT tasks. These tools also provide tasks to publish your build output to a Maven repository, enabling your project to share with other projects using Maven.
Finally, I'm an ivy advocate and wrote an ant2ivy script which can assist in upgrade process. It creates an initial set of configuration files for downloading your projects dependencies from the Maven central repository.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Most efficient way to clamp values in an OpenCv Mat I have an OpenCv Mat that I'm going to use for per-pixel remapping, called remap, that has CV_32FC2 elements.
Some of these elements might be outside of the allowed range for the remap. So I need to clamp them between Point2f(0, 0) and Point2f(w, h). What is the shortest, or most efficient, way of accomplishing this with OpenCv 2.x?
Here's one solution:
void clamp(Mat& mat, Point2f lowerBound, Point2f upperBound) {
vector<Mat> matc;
split(mat, matc);
min(max(matc[0], lowerBound.x), upperBound.x, matc[0]);
min(max(matc[1], lowerBound.y), upperBound.y, matc[1]);
merge(matc, mat);
}
But I'm not sure if it's the shortest, or if split/merge is efficient.
A: Try splitting, using cvThreshold and then merging. You may also get away with using cvSetImageCOI to avoid the splitting. I'm not sure if thresholding code supports the COI.
You may want to profile both versions and compare their performance. I have a feeling it will do the same thing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: JAVA :: RESTful Web Service to consume a XML file Is there any other way that we can send an XML file to a RESTful Web Service other than as a FORMPARAM?
My requirement is to develop a webservice which Consumes a XML file, stores it in my local machine and returns a statement saying that the file was downloaded/saved.
A: Here's the code to post, way easier than SOAP...
// POST the XML string as text/xml via HTTPS
public static String postRequest(String strRequest, String strURL) throws Exception {
String responseXML = null;
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
byte[] requestXML = strRequest.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf(requestXML.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Send the String that was read into postByte.
OutputStream out = httpConn.getOutputStream();
out.write(requestXML);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp;
String tempResponse = "";
//Create a string using response from web services
while ((temp = br.readLine()) != null)
tempResponse = tempResponse + temp;
responseXML = tempResponse;
br.close();
isr.close();
} catch (java.net.MalformedURLException e) {
System.out.println("Error in postRequest(): Secure Service Required");
} catch (Exception e) {
System.out.println("Error in postRequest(): " + e.getMessage());
}
return responseXML;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to show on focusable item in listview In my application i have used list view and custom cell which contain product name , image ,quantity and price now i want to implement that if use click on the product name then it should open a new quick action showing delete /edit .
But problem is that when i m touching the listview cell, complete cell is showing focused. which is not desired. So please help me to implement this.
listviewObj = (ListView) findViewById(R.id.cart_items_listview);
listAdapter = new CustomListAdapter(ShowCart.this);
listviewObj.setAdapter(listAdapter);
listviewObj.addFocusables(views, direction)
listviewObj.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Toast.makeText(ShowCart.this, "click on the position"+position, Toast.LENGTH_SHORT).show();
}
});
Any help is appreciated?
Thanks in advance.
A: You will need listviewObj.setItemsCanFocus(true); in order for items inside listview cells to gain focus.
A: you should implement listener on the cell item you want to work on as textview , Edit text or any kind of button you have in your List Item layout to show product name, image etc.
implement the Click-listener on cell items instead of whole listview item
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: where to put log4j.properties- for use in java desktop app I am trying to use log4j logging framework in a java desktop application.
When I run the code I am getting a message
log4j: log4j:WARN No appenders could be found for logger
I googled for the above error and found that it occurs when the log4j.properties file is not found by the app.
I am creating the desktop app using Eclipse. Currently log4j.properties is within the same folder that contains the source (in 'src' folder). Where should I put this file to make it work properly?
A: log4j will use a Default Initialization Procedure to find your configuration file. The documentation notes:
The preferred way to specify the default initialization file is through the log4j.configuration system property
If this property is not set - log4j will look at the classpath. In your case you have to place the file in the src directory (assumed that the content will be put in the classes path while you build the system). If you use maven place the file to the src/main/resources directory.
As you placed your file to the src directory check, that the file get transferred to the top level directory of your compiled classes.
A: Keep the properties file in the classes folder i.e. the folder that contains the classes (specially the main class).
Another reason for getting this error may be the wrong appenders or an appender without setting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: QImage definition this command line:
QImage:: QImage (uchar * data, int width, int height, int bytesPerLine, Format format)
Would use is it so?
QImage image = new QImage (buffer, 600, 400, jpg)
the bytesPerLine not they mean well, will the photo occupies kb?
thanks
A: If you do not want to use the bytesPerLine parameter, there is a
QImage::QImage ( uchar * data, int width, int height, Format format )
constructor.
However, Format is not what you might think. Theformatparameter specifies an enum value which decides over the bit depth etc. I.e. enteringjpgor"jpg"there won't work. Check Format-enum for a list of possible values.
A: I will try to answer the best I can considering the fact that your question is very unclear to me.
From the Qt documentation:
bytesPerLine specifies the number of bytes per line (stride)
Also consider that the format argument, which you specified as jpg, must be given as one of the enum values specified in here.
Best regards
A: That's how you would use this constructor:
int imageWidth = 800;
int imageHeight = 600;
int bytesPerPixel = 4; // 4 for RGBA, 3 for RGB
int format = QImage::Format_ARGB32; // this is the pixel format - check Qimage::Format enum type for more options
QImage image(yourData, imageWidth, imageHeight, imageWidth * bytesPerPixel, format);
You don't specify the image format (png, jpeg, etc.) but the pixel format (RGB, RGBA, etc.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS sprite position problem I trying to create a fixed border to the site that dynamically change size with the browser window from this sprite (it isn't perfect I know.): http://fc07.deviantart.net/fs70/f/2011/269/7/0/bordersprite_by_nakos-d4ayzne.png
DEMO on jSFiddle
My problem as you can see is the vertical wall part. As the #falJ and #falB are height:100% they include the bottom wall's end too with the space between the two wall sprites. Is there a way to force backround-position to only use vertical wall part without bottom wall's end?
Thanks in advance.
A: Solution: http://jsfiddle.net/vonkly/Ld43B/
It's not the prettiest thing in the world, but it achieves what you want. Check out the source code & direct link for the background images to see what you'll need to do. It's currently set at 299px wide; I imagine you'll be using something wider.
I'd also suggest adding some padding around your content (either with a p tag, span, another div, etc.) - the way it is currently set up isn't what I'd recommend for readability.
EDIT
The only way I can imagine achieving a fluid width + height box with the borders that you have in the way that you want is to use a second image for the west and east containing divs. This should work with your current method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# setting property/field to value of none I have what I presume must be a common problem. Lets say I have a typical Person Class and I have a Car Class, which has a field/property owner of type Person:
public class Car
{
Person owner;
}
But sometimes I want the car to have no owner. What's the recommended way of dealing with this problem. A Nullable type doesn't work as reference types are already nullable.(Edit: clarification, I meant you cant use Person? owner;)
I could add in a bool field/property: hasOwner, but that seems rather verbose, so I thought of creating a static member none of type Person in the Person class like so:
namespace ConsoleApplication2
{
public class Person
{
public static Person none;
public int age;
static Person()
{
none = new Person();
}
}
public class Car
{
public Person owner;
}
class Program
{
static void Main(string[] args)
{
Car dumped = new Car();
dumped.owner = Person.none;
Console.ReadLine();
}
}
}
This compiles and runs, although I haven't used it in a real application. Then I thought I could make a generic class with a none member as so:
namespace ConsoleApplication2
{
public class NoneMember<T> where T : new()
{
public static T none;
static NoneMember ()
{
none = new T();
}
}
public class Person: NoneMember<Person>
{
}
public class Car
{
public Person owner;
}
class Program
{
static void Main(string[] args)
{
Car dumped = new Car();
dumped.owner = Person.none;
if (dumped.owner == Person.none)
Console.Write("This car has no owner");
Console.ReadLine();
}
}
}
That compiles and runs, although there would be a problem if you wanted to inherit form the person class, with the generic and non generic versons. The thoughts of more experienced c# programmers would be appreciated.
Edit: The problem with using null to represent none is that you can't pass null as a method / constructor parameter. null means value not set, which is different from value is none.
Edit2: I thought I was getting exceptions thrown when I passed null parameters. Not sure what was going on. I don't know if I can reproduce the errors now.
A: Both are valid approaches. You'll probably find that most applications simply leave the property as null and having a special value to indicate an empty value is generally used for value types (TimeSpan.Min etc).
A: I usually leave it as it is, if Car's owner is null, that means just that - it does not have an owner. There is no need to complicate, if there is value - it has owner, otherwise it does not have (known to system) owner.
Exception from this policy is the case when you need to have journaling database, but in that case you usually can have versioned cars and owners and use the same principle.
A: Indeed, why don't null value fit for solve of our problem. If owner is null, It means that owner is not exists at all...
A: The first solution is something that is called in design patterns a null-object.
Normally it is done a little different, you create a new class inherited from Person.
public class Person
{
public int age;
}
public class NoPerson : Person
{
}
Then you can validate this with a typeof() statement
A: Yes, static properties/fields is a bit weird when you have inheritance. One framework example is the EventArgs.Empty field which IMO would be nice to have on more specialized classes.
If you expect inheritance from Person and you want to enforce the "this person is nobody" throughout the inherited classes then my recommendation is that you add this concept to the class itself.
If you make a virtual method that returns true or false whether a person is "nobody" or not, your derived classes can extend this check to meet their respective classes' needs:
public class Person
{
public Person()
{
// This constructor will create a "nobody"
}
public Person(string name)
{
// Proper initialization
this.Name = name;
_isNobody = false;
}
public string Name { get; set; }
public virtual bool IsNobody
{
get
{
return String.IsNullOrEmpty(this.Name) == false;
}
}
// TODO: Maybe override Equals/==/GetHashCode to take IsNobody into account
}
One simple example of overridden Person could be an Employee which is defined to be "Nobody" if either the base class (Person) says it is or if the employee number isn't set:
public class Employee : Person
{
public int EmployeeNumber { get; set; }
public override bool IsNobody
{
return base.IsNobody || EmployeeNumber == -1;
}
}
You could of course combine the above with static fields on your classes, so on your Person class you'd have a
public static readonly Person Nobody = new Person();
and for derived classes (notice use of the new modifier here)
new public static readonly Employee Nobody = new Employee();
I've never seen this approach (with the 'new' modifier) in the wild and would personally be quite reluctant to use it but if it makes sense in your domain it may be an alternative to look at.
A: Giving meaning to null is a valid approach, but generally I find it indeed preferable to have 'richer' support for this situation.
You can always build your own 'nullable type' for reference types. You won't have compiler support, (e.g. no Person?) but you can get something that gets pretty close.
For example, look at this article from Bart De Smet (look for Option<T>, the rest of the article is interesting but not in the scope of your question :-))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python equivalent of Perl's idiom do this or that, usually known as "or die"? IN Perl it's quite common to do things like function() || alternative(). If the first returns false it will run the second one.
How can this be easily implemented in Python?
Update
Examples (pseudocode):
x = func() or raise exeption
x = func() or print(x)
func() or print something
If possible solutions should work with Python 2.5+
Note: There is an implied assumption that you cannot modify the func() to raise exceptions, nor to write wrappers.
A: Use or: Python uses short circuit evaluation for boolean expressions:
function() or alternative()
If function returs True, the final value of this expression is determined and
alternative is not evaluated at all.
A: you can use or:
function() or alternative()
also, there is conditional expression defined in PEP 308:
x = 5 if condition() else 0
Which is sometimes useful in expressions and bit more readable.
A: function() or alternative()
The mechanism is exactly the same.
A: try with or:
>>> def bye():
return 3
>>> print bye() or 342432
3
Unfortunately, this does not work like in Perl, because in Perl, after an assignment like my $c = $d || 45; you have in $c the value 45 if $d is undefined. In Python you get an error NameError: name 'd' is not defined
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How should I try to fix java.lang.IllegalStateException in JBoss "is already registered"? I have a web application. When I try to deploy it via Netbeans, the JBoss server throws the following error:
DEPLOYMENTS IN ERROR:
Deployment "vfs:///path/to/my/Application.ear" is in error due to the following reason(s): java.lang.IllegalStateException: Container jboss.j2ee:ear=Application.ear,jar=Application-ejb.jar,name=Another,service=EJB3,VMID=583c10bfdbd326ba:71d035f1:132a4c6a8ba:-7ffd + is already registered
at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:1370) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:1316) [:2.2.0.GA]
at org.jboss.deployers.plugins.main.MainDeployerImpl.checkComplete(MainDeployerImpl.java:968) [:2.2.0.GA]
at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.checkComplete(MainDeployerPlugin.java:82) [:6.0.0.Final]
at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.checkComplete(ProfileControllerContext.java:138) [:0.2.2]
at org.jboss.profileservice.plugins.deploy.actions.DeploymentStartAction.doPrepare(DeploymentStartAction.java:104) [:0.2.2]
at org.jboss.profileservice.management.actions.AbstractTwoPhaseModificationAction.prepare(AbstractTwoPhaseModificationAction.java:101) [:0.2.2]
at org.jboss.profileservice.management.ModificationSession.prepare(ModificationSession.java:87) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.internalPerfom(AbstractActionController.java:234) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.performWrite(AbstractActionController.java:213) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.perform(AbstractActionController.java:150) [:0.2.2]
at org.jboss.profileservice.plugins.deploy.AbstractDeployHandler.startDeployments(AbstractDeployHandler.java:168) [:0.2.2]
at org.jboss.profileservice.management.upload.remoting.DeployHandlerDelegate.startDeployments(DeployHandlerDelegate.java:74) [:6.0.0.Final]
at org.jboss.profileservice.management.upload.remoting.DeployHandler.invoke(DeployHandler.java:156) [:6.0.0.Final]
at org.jboss.remoting.ServerInvoker.invoke(ServerInvoker.java:898) [:6.0.0.Final]
at org.jboss.remoting.transport.socket.ServerThread.completeInvocation(ServerThread.java:791) [:6.0.0.Final]
at org.jboss.remoting.transport.socket.ServerThread.processInvocation(ServerThread.java:744) [:6.0.0.Final]
at org.jboss.remoting.transport.socket.ServerThread.dorun(ServerThread.java:548) [:6.0.0.Final]
at org.jboss.remoting.transport.socket.ServerThread.run(ServerThread.java:234) [:6.0.0.Final]
I found many results when I google this, so this kind of error seems to appear quite often. But all results I saw were posts in forums which didn't show how to fix it in a general way.
The problem seems to be that the application is already registered in JBoss. Where can I get a list of registered JBoss applications? How can I de-register an application (if this could help).
What is a good way to try to fix this kind of problem?
A: There are chances that you may have multiple class files deployed in your .jar directory/archive one of which is places all by mistake. If you have deployed in exploded from on unix you may search the class file by below command for above raised issue as:
find . -name Another -print
there after remove the unrequired file and restart the server and the above problem should have been solved/fixed/resolved.
A: Delete Application.ear from this path: /path/to/my/Application.ear and then DELETE
EAR from "jboss-5.1.0.GA\server\default\deploy" because you might have EAR in JBOSS.
DELETE log,data,temp,work folder in jboss-5.1.0.GA\server\default.
If you are using eclipse then remove the EAR from JBOSS server and clean the server.
Start the server wihtout EAR and after server gets started directly add EAR without stoping the server and let it publish itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ASP.NET href CSS not being applied CSS isn't being applied in aspx page. It works when the css is defined in the same page (href references a.classname) but when it is put into a stylesheet it is not applied. When element is inspected, Chrome says user agent stylesheet is being applied.
It says that a:-webkit-any-link is being applied to hyperlinks (user agent stylesheet)
Any ideas why this isn't working?
I reference the class for the hyperlink using:
<div class="summaryitem"><a ID="hl" runat="server" href="" class="someclassname">Hyperlink CSS should be applied to this</a>
Here's the CSS I'm using:
a.someclassname:link {
font-weight: bold;
color: #555;
text-decoration:none;
}
a.someclassname:visited {
font-weight: bold;
color: #555;
text-decoration:none;
}
a.someclassname:hover {
font-weight: bold;
color: #555;
text-decoration:none;
}
a.someclassname:active {
font-weight: bold;
color: #555;
text-decoration:none;
}
A: I think you have not properly added your stylesheet, does it resemble something like this
<link type="text/css" href="css/mylayout.css" rel="Stylesheet" />
A: Please check the following
*
*Check the href location that you are refering is correct.
*Try to delete the offline files in your browser
*Check your class name correctly mapped..
A: If you're in a partial view, just be sure the parent view includes the CSS ref.
EDIT: wow got a similar problem a few minutes ago. I've solved testing my view with Chrome and using the network auditing feature (at the page hit F12, click on Network and then reload your page). Should tell you at least if your CSS is correctly sent to the browser. (my problem was I wasn't referencing the correct CSS).
EDIT-2:
I usually refer to CSS via:
<link href="@Url.Content("~/Content/css/fg.menu.css")" media="screen" rel="stylesheet" type="text/css" />
But I'm using MVC with Razor views, I've noticed that putting CSS out of the Content folder can be nasty on ASP.NET.
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 3.1: javascripts not served correctly from vendor/assets directory? I have organized my javascript files in a couple of directories and I have found the following strange behavior. Given the following tree:
+ app
+ assets
+ javascripts
+ common
+ public
+ common
+ home
- home.js
home.js looks like this:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_directory ../../jquery_plugins
//= require_directory ../../common
//= require_directory ../common
//= require_self
Now the trick lies in the jquery_plugins directory. I placed this inside vendor/assets/javascripts (which is included in the asset load path, when I check Rails.application.config.assets.paths). When I do this I get the error: require_tree argument must be a directory. When I move that directory to app/assets/javascripts then everything works.
Does anybody have a clue as to what I'm doing wrong? Or is this a bug?
A: You could add a manifest file to the directory you are trying to serve with something like
vendor/assets/javascripts/jquery_plugins/manifest.js
//= require_directory .
and require it in your app/assets/javascripts/application.js via
//= require jquery_plugins/manifest
Edit (even simpler way)
Thanks to @LeEnno for this
You can actually put all your single library related files in a folder named after the library for example vendor/assets/javascripts/bootstrap and in that same folder add an index.js which will act as your manifest and Rails will automatically pick it up
if in your
app/assets/javascripts/application.js
you add the line
//= require bootstrap
SO EASY!!!
Link to Rails Asset Pipeline Guide
A: I had the same problem. I'm still not sure if it's a bug or intentional behavior, but it seems that Rails.application.config.assets.paths only works for single files, i.e. require jquery and so on. Apparently the asset load paths are just used to return the best match for a single require but not for require_directoryor require_tree.
In my case, to load all files from vendor/assets/javascripts, I had to add the following to my app/assets/javascripts/application.js:
//= require_tree ../../../vendor/assets/javascripts/.
In your case something like this should work:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_directory ../../../../../vendor/assets/javascripts/jquery_plugins
//= require_directory ../../common
//= require_directory ../common
//= require_self
It seems that you always have to use the relative path from file where you're calling require_directory or require_tree.
Also, I found this discussion on the structuring of JS-assets to be helpful: Rails 3.1 asset pipeline and manually ordered Javascript requires
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Limit product quantity to 1 per customer in magento I need to limit the quantity of a product purchased by a customer to 1 per day. We are going to have something like deal and day and targeting consumers. We do not want some one to buy high quantities. Could some one guide me as to what the general approach should be to do this? Thanks.
I noticed that there is a table sales_flat_order_item which contains products_id for an order, a join of this table with sales_flat_order should give me product_id for the orders placed by the customer. How do i access this table data directly and perform the join operation the magento way? Do i need to create a new module? or modify a existing module?
A: You could just create a coupon/coupons for this. Leave the product at the original price and hand out a coupon to the targeted customers. Make sure that you set it to "only applies to 1 item" and can only be used once.
Regards,
Kenny
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the quick way to make my change of firefox plugin take affect in windows? Now I have to restart whenever I modified a single line...
Is there a way to make it refresh without restarting the firefox?
A: Yes, you use plain directories in your extension instead of a JAR file, add <em:unpack>true</em:unpack> to your install.rdf and add boolean nglayout.debug.disable_xul_cache/nglayout.debug.disable_xul_fastload preferences and set them to true. You also start Firefox with -purgecaches command line flag (for Firefox 4 and newer). Then you will be able to edit extension files directly in the profile and have these changes picked up immediately. If you have an own dialog window then closing it and opening it again will be enough. For browser window overlays you will have to open a new browser window. JavaScript modules and XPCOM component will still need a browser restart however, these are loaded only once per browser session. But at least you won't have to reinstall the extension.
More information: Setting up an extension development environment
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cobol dashes are confusing me
Possible Duplicate:
cobol difference with Picture having a dash (-) and a having a X
I'm tying to get to grips with Cobol and can't understand the dashes when formatting a number. I have this example:
--9
Am I correct with the following?
The first dash - If number is a negative put a dash otherwise don't.
the second dash - I'm confused with this. There is already a dash at the start to specify whether its negative or positive.
9 - Numeric digit (0-9)
An example would be good. :S
Thanks
A: from stackoverflow:cobol-difference-with-picture-having-a-dash-and-a-having-a-x
The dash means that if you have a negative number, a dash will be
shown beside (at the left) of the number. Only one dash will be
displayed. If the number is positive, a space will shown for every
dashes.
A: In view of your previous question, Im not sure what you are having trouble with. But lets try again...
In COBOL, numeric display fields may contain various types of "punctuation". This "punctuation" is defined in the items PICTURE clause. A few examples of the type of "punctuation" symbols you can use are: Explicit decimal points, plus/minus signs, CR/DR indicators and thousnads separators (commas in North America). There is a well defined set of rules that determine what type of "punctuation" can occur in the PICTURE clause and where. This link to PICTURE CLAUSE editing explains how to construct (or read) any given PICTURE clause.
One thing that you, and many others new to COBOL, trip up on is that a data definition in COBOL specifies two distinctly different types of information about numeric display data. One is the range of values it may hold and the other is how
that range of values may be displayed. Your example: PICTURE --9 tells me two things about the data item: 1) Values are integers in the range of -99 through to +99, and 2) Displaying this item will take 3 spaces. If the number is positive, spaces will appear before the first non zero digit. If the number is negative a minus sign will appear immediately to the left of the first non zero digit. Consider the following COBOL DISPLAY statement:
DISPLAY '>' DISP-NBR '<'
IF DISP-NBR has a PICTURE clause of: --9 this is how various values will be displayed.
0 displays as: > 0<
-1 displays as: > -1<
-11 displays as: >-11<
10 displays as: > 10<
Note that all displays take 3 character positions. At least 1 digit will always be displayed (because of the '9' in the PICTURE clause), other than that, no leading zeros are displayed. A minus sign will display only for negative values. The minus sign, if displayed will be to the immediate left of the first displayed digit.
Now to answer you specific question: The total number of character positions needed to display a numeric display data item is determined by the length of the PICTURE. You have a 3 character PICTURE so 3 character positions are needed. When
a sign is specified in the PICTURE, a space is always reserved for it. This is what limits the range of integers to those containing at most 2 digits. The second minus sign indicates 'zero supression'. Zero supression just means not printing leading zeros. Only 1 minus sign is ever printed and it will be to the immediate left of the first displayed digit.
COBOL contains a lot of flexability with respect to displaying numbers. Understanding the numeric display PICTURE clause is key to understanding how this all works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Remove plugins rss results Joomla I wonder how you can remove plugins syntax of the return results RSS joomla.
When viewing a feed section of Joomla, all items listed in that section in RSS format. If such articles contain a plugin, it displays the syntax of the plugin. I want to know is what is the way that syntax does not appear in the RSS.
Thanks for the help.
Regards.
A: Unfortunately that has to be coded into the plugin so that the code is removed. There is no default Joomla method to remove code from plugins that has not been processed in the content when the plugin does not replace it itself. Which is why I don't use the {-brackets for my plugins, but instead invent XML-tags, which are ignored by all RSS readers and browsers if the plugin is disabled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is the expression in this while loop causing an infinite loop? New to oop and was just wondering why this causes an infinite loop:
while ($row=$dbh->query("SELECT * FROM animal")->fetch(PDO::FETCH_ASSOC)){
printf("A(n) %s is a type of %s<br />", $row['name'], $row['species']);
}
However this does not cause an infinite while loop
$sth=$dbh->query("SELECT * FROM animal");
while ($row=$sth->fetch(PDO::FETCH_ASSOC)){
printf("A(n) %s is a type of %s<br />", $row['name'], $row['species']);
}
A: In the first code sample you are re-running the query repeatedly in a loop, each time fetching only the first row.
In the second code sample you first run the query once before the loop starts. Then you loop, fetching each row in the result set until there are no more rows.
A: The parenthesized statement in the while loop gets executed each time. That means that your query starts over each time, so you're always looking at the first object, and so infinite loop!
The second is way more correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do I get the message: 'module' object has no attribute 'load_source' I have function:
def load_from_file(filepath, expected_class):
mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
py_mod = imp.load_source(mod_name, filepath)
in templatetags file and it is ok.
But when i copy/paste this function to my view i get error:
'module' object has no attribute 'load_source'
My example view:
import os, imp
def get_module(request, position):
[...]
imod = load_from_file(settings.PROJECT_ROOT + '/core/manager/modules/' + mod.type.fileview + '.py', 'ModuleManager')
[...]
def load_from_file(filepath, expected_class):
[...]
Why this not working?
A: You have another module named imp.
Either rename it, move it either to a spot later in your sys.path than the standard library modules or out of sys.path completely, or rearrange your sys.path.
It's most likely in the same directory as your views; if that's the case, the easiest thing to do is probably to move it to a directory where no modules import imp or rename it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Application's package can't find in Device? I've successfully written a simple android database application, but I can't see and find my package on the device.
When, I'm using this application on my Device it doesn't show the database in my device's file manager.
What am I doing wrong? Also, what do I need to do to display my package on my device? Is there any
permission I'm missing?
A: It is very simple to open database in android device . Just copy it from data/data directory to sdcard using code and then copy from sdcard to PC manually.
A: The database that an application creates is private to the application and cannot be seen from another application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chrome interpreting jpg resource as Document Consider the following image at:
http://znood.com/images/801/130x130.jpg
I have a controller rendering this image and transferring it with image/jpeg MIME.
Chrome is throwing the warning:
Resource interpreted as Document but transferred with MIME type
image/jpeg.
Why would an image be interpreted as a document and why would Chrome throw such a warning?
A: add the proper doctype to your pages, something like
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
and then start your HTML with
<html xmlns="http://www.w3.org/1999/xhtml">
Regards,
M.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to pass intent extras to broadcast reciever? I've been trying to get an android application to install an APK on the sdcard programmatically and to delete the apk once it's installed.
This is how I'm doing it:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType("ApkFilePath...","application/vnd.android.package-archive");
intent.putExtra("apkname", apkName);
activity.start(intent);
And I have written a braodcast-reciever class so that I can handle apk deletion process there once the app is installed. But I can't get extras passed from my intent in the broadcast-reciever.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to install features depending on the value of property I have a registry key that can be equal to one of two values: special value or null. And two features.
When my registry key equals to special value the installer has to install first feature. if registry key is not found by registry search the installer has to install second feature. And if registry key has null value the installer must not install any of these two features.
What I'm doing or understanding wrong? If INSTALLLEVEL=5, SPECIALVALUE="special",MYTREAT="1" the first feature must be installed,but the installer doesn't install both of the features in this case.
<Feature Id="MyFeatures" Level="1" ConfigurableDirectory='INSTALLLOCATION' Display='expand' AllowAdvertise='no'>
<ComponentRef Id='Empty'/>
<Feature Id='First' Level='3' AllowAdvertise='no' ConfigurableDirectory='INSTALLLOCATION'>
<Condition Level="0">INSTALLLEVEL=4 OR (MYTREAT="1" AND NOT SPECIALVALUE AND NOT SPECIALVALUE="")</Condition>
<Condition Level="1">SPECIALVALUE="special" AND MYTREAT="1"</Condition>
<ComponentRef Id="first_comp"/>
</Feature>
<Feature Id="Second" Level="4" AllowAdvertise="no" ConfigurableDirectory="INSTALLLOCATION">
<Condition Level="0">INSTALLLEVEL=3 OR (MYTREAT="1" AND SPECIALVALUE)</Condition>
<ComponentRef Id="second_comp"/>
</Feature>
</Feature>
I had modified my code, but it's still not working right. Problem with conditions. There is a special value in registry key, but the installer is still skipping first feature. I had found that condition with just "MYTREAT=1" is not working. But in logs the client side is sending MYTREAT property with this value to the server.. INSTALLLEVEL is 1. MYTREAT property is initialized with pushbutton control,may be here is my trouble? Here new code:
<Feature Id="Myfeatures" Level="3"
ConfigurableDirectory='INSTALLLOCATION'
Display='expand' AllowAdvertise='no'>
<Condition Level='1'>MYTREAT="1"</Condition>
<ComponentRef Id='Empty'/>
<Feature Id='First' Level='3' AllowAdvertise='no'
ConfigurableDirectory='INSTALLLOCATION'> <!--Must be installed by default,default value of INSTALLLEVEL is 3-->
<Condition Level="1">MYTREAT="1" AND SPECIALVALUE="SPECIAL"</Condition>
<ComponentRef Id="first_comp"/>
</Feature>
<Feature Id="Second" Level="10" AllowAdvertise="no"
ConfigurableDirectory="INSTALLLOCATION"><!---->
<Condition Level="1">(MYTREAT="1" AND NOT SPECIALVALUE)</Condition>
<ComponentRef Id="second_comp"/>
</Feature>
</Feature>
............
<Dialog Id="TreatDlg" Width="260" Height="85">
<Control Id="Mytreat" Type="PushButton" X="50" Y="57" Width="56" Height="17" Property="MYTREAT">
<Publish Property="MYTREAT" Value="1">1</Publish>
<Publish Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
</Control>
P.S. I initialized MYTREAT with 1 by default and condition was evaluated correctly. Why I cannot use control's property in feature's condition? And how to resolve my problem!Please any help!
A: A common mistake is trying to control features through INSTALLLEVEL property. The install level should be static, you shouldn't change it during install.
The INSTALLLEVEL value is considered a level above which features are no longer installed. For example, if INSTALLLEVEL = 5 a feature with Level 4 will be installed and a feature with Level 6 will not be installed.
Through INSTALLLEVEL you can control the original feature state, for example:
<Feature Id="MyFeatures" Level="4" ConfigurableDirectory='INSTALLLOCATION' Display='expand' AllowAdvertise='no'>
<!-- Feature is not installed by default -->
<Feature Id='First' Level='6' AllowAdvertise='no' ConfigurableDirectory='INSTALLLOCATION'/>
<!-- Feature is installed by default -->
<Feature Id="Second" Level="4" AllowAdvertise="no" ConfigurableDirectory="INSTALLLOCATION"/>
</Feature>
For the above configuration you can then add install conditions by setting a Level lower or higher than INSTALLLEVEL:
<Feature Id="MyFeatures" Level="4" ConfigurableDirectory='INSTALLLOCATION' Display='expand' AllowAdvertise='no'>
<Feature Id='First' Level='6' AllowAdvertise='no' ConfigurableDirectory='INSTALLLOCATION'>
<Condition Level="4">(MYTREAT="1") AND (SPECIALVALUE="special")</Condition>
</Feature>
<Feature Id="Second" Level="4" AllowAdvertise="no" ConfigurableDirectory="INSTALLLOCATION">
<Condition Level="6">(INSTALLLEVEL = 3) OR (MYTREAT="1" AND SPECIALVALUE)</Condition>
</Feature>
</Feature>
As you can see, the feature Level attributes revolve around INSTALLLEVEL, not the other way around.
Edit:
Feature conditions are evaluated before any installation dialogs are shown. So you cannot condition a feature with a dialog control (for example a checkbox or a button).
A solution would be to use a custom action which modifies the feature action based on your custom property. For example you can use MsiSetFeatureState function. You can find a custom action tutorial here:
http://www.codeproject.com/KB/install/msicustomaction.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is best way to share class instance (create and share singleton)? I know 2 ways. What is better? And anything better than 2 ways?
+ (MyClass *)shared {
/*
static MyClass *sharedInstance = nil;
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
}
return sharedInstance;
*/
/*
static dispatch_once_t pred;
static MyClass *sharedInstance = nil;
dispatch_once(&pred, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
*/
}
A: Can also create a your class instance in AppDelegate and use it anywhere in your project.
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appappDelegate.<yourClassInstance>
A: Here is another way to setup you shared instance. Thread safety is handled by the runtime and the code is very straight forward. This is usually how I setup my singletons. If the singleton object uses lots of resources but may not used then the dispatch_once approach works well.
static MyClass *sharedInstance = nil;
+ (void) initialize
{
sharedInstance = [[MyClass alloc] init];
}
+ (MyClass*)sharedInstance
{
return sharedInstance;
}
A: Just use the dispatch_once version - it's reliable and clean. Besides, it will work also with ARC - unlike the approach suggested above.
A: Here's some Details
+ (YourClass *)sharedInstance
{
// structure used to test whether the block has completed or not
static dispatch_once_t p = 0;
// initialize sharedObject as nil (first call only)
__strong static id _sharedObject = nil;
// executes a block object once and only once for the lifetime of an application
dispatch_once(&p, ^{
_sharedObject = [[self alloc] init];
});
// returns the same object each time
return _sharedObject;
}
A: The second one looks better, but this is still not perfect. Check Apple's recommendation:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-97333-CJBDDIBI
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ListView onitemclick is not working I have a ListView containing a checkbox, an imageview, two textviews and a button. The problem is after adding the checkbox and the button the onitemclick event of the ListView is not responding. Will anybody suggest a work around for the problem?
A: You can set both android:focusable and android:focusableInTouchMode attributes of checkbox to false and onItemClick of the list will be called. But you'll have to call CheckBox#toggle() yourself in onItemClick.
A: Add an onlick listner to the view. or the checkbox and handle it manually.
A: When you use checkbox in your listview then it consumes your click action and your check action will be performed.
You can put click listener over textview, imageview or button. you also need to handle checkbox.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Howto avoid copying when casting a vector to a vector Is there a way to avoid copying large vectors, when a function expects a vector with (pointer to) baseclass objects as input but I only have a vector of (pointers to) derived objects?
class Base {};
class Derived : public Base {};
void doStuff(vector<Base*> &vec)
{
//do stuff with vec objects
}
int main()
{
vector<Derived*> fooDerived(1000000);
vector<Base*> fooBase(fooDerived.begin(), fooDerived.end()); // how to avoid copying here?
doStuff(fooBase);
}
A: If you could use a vector<Derived*> as if it where a vector<Base*>, you could add a pointer to a class OtherDerived : public Base to that vector. This would be dangerous.
A: You can't cast the vectors. However, you shouldn't really need to either.
If you really want, you could use Boost Iterator (documentation)
static Derived* ToDerived(Base* b)
{
return dynamic_cast<Derived*>(b); // return null for incompatible subtypes
}
static void DoSomething(Derived* d)
{
if (!d)
return; // incompatible type or null entry
// do work
}
// somewhere:
{
std::vector<Base*> bases;
std::for_each(
boost::make_transform_iterator(bases.begin(), &ToDerived),
boost::make_transform_iterator(bases.end(), &ToDerived),
DoSomething);
}
Note: a particularly handy effect of using dynamic_cast<Derived*> is that if the runtime type of the object cannot be casted to Derived* (e.g. because it is actually an OtherDerived*, it will simply return a null pointer.
A: If your definition of doStuff() is absolutely mandatory, then you won't get around the copy. Containers of pointers aren't "covariant" with respect to the pointee's class hierarchy, for a whole host of reasons. (For example, if you could treat vector<Derived*> like a vector<Base*>, you could insert Base-pointers into it which wouldn't behave like Derived-pointers. In any event, the parameter type of a container is fixed and part of the container's type.)
If you do have some leeway with the function, you could restructure the code a bit: You could make it a template parametrized on the container, or a template on an iterator range, and/or you could split the actual workload into a separate function. For example:
void doStuffImpl(Base *);
template <typename Iter>
void doStuff(Iter begin, Iter end)
{
for (Iter it = begin; it != end; ++it)
{
doStuffImpl(*it); // conversion happens here
}
}
A: Since your template for the vector is a pointer, your fooBase local variable is going to be using reference. Maybe the question is not very clear, if you could specify clearly we may try to address the problem!
A: One way is to store only pointers to the base class like this:
vector<Base*> v(100);
v.push_back(new Derived());
doStuff(v);
A: I found this topic interesting where they mention you can safely cast Derived* to Base* (but not the other side) while this is not possible from vector<Derived*> to vector<Base*> but you kind of should be able to... (Ok, the address of the vector changes, thus needing a copy)
One dirty solution they mention is using reinterpret_cast<vector<Base*> >(vector<Derived*>) but not sure if it's better then using the copy constructor... probably the same thing happens.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Empty excel cell using java "getNamedRange("SOME_VARIABLE")" I am project i have to modify the excel file using java codings.
My requirement is to empty the cell completely which has the string value "SOME_VARIABLE".
book.getNamedRange("SOME_VARIABLE").remove();
Is the above code a right one. I tried with this but it is not working. So I tried to write a code to check Am I deleting it in a right WORKBOOK, like if the workbook does not contain "SOME_VARIABLE" then it should inform me . That code is as follows:
if(book.getNamedRange("SOME_VARIABLE")== null)
{record("the"+SOME_VARIABLE+" is not found");}
else{
book.getNamedRange("SOME_VARIABLE").remove();}
Am I going in a right path ? As i am new to handle this excelEngine I am strugling. Kindly help me friends.
A: The code you provided will delete the cells of the Named Range (ref) SOME_VARIABLE.
If you want to check the value of the cell, you need to find (ref) the cells that contains SOME_VARIABLE.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first This is my code:
Frame.gameController.test();
setContentView(Frame.world.getScreen());
Frame.world.setRunning(true);
On the second line I am getting the following error:
ERROR/AndroidRuntime(15229): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Can anyone help me solve it? Previously it was working just fine, the problem starts when I take it in another activity.
I'm using android 2.2.
A: Maybe you are trying to set content from objects that already have parent. It looks like you set some views in one activity, for example:
TextView tv = new TextView();
layout.adView(tv);
layout2.adView(tv);
and that error appears when you try to add that tv to different layout. In your situation it's because Layout from one activity is trying to be set as a child in the other activity.
You have to release child from other parent first.
A: You can't use the same view in multiple activities. Instead you should create a new instance of the view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: CGContextConcatCTM vs CALayer affineTransform I'm trying to change the affine transform of a CALayer so what's drawn in it gets deformed.
First I was doing this without CALayers, just redrawing with a different CGAffineTransform passed to CGContextConcactCTM.
That worked, but it wasn't fast enough, so I decided to do it with CALayer so it won't get redrawn every time. It just get transformed.
The problem is that setting myLayer.affineTransform = myTransform; doesn't seem to have the same effect as redrawing with CGContextConcatCTM(myTransform);
I'm new to Objective-C and pretty lame at math, so I'm sure I'm doing something wrong. But I can't see what.
Thanks.
A: Ok, nevermind, I found out.
Turns out myLayer.affineTransform does the transform relative to the center of the layer where as CGContextContactCTM does it relative to the origin.
So I just concatenated 2 other transforms:
CGPoint center;
center.x = capa.bounds.origin.x + capa.bounds.size.width/2;
center.y = capa.bounds.origin.y + capa.bounds.size.height/2;
CGAffineTransform trf1 = CGAffineTransformMakeTranslation(center.x, center.y);
CGAffineTransform trf2 = CGAffineTransformMakeTranslation(-center.x, -center.y);
capa.affineTransform = CGAffineTransformConcat(trf1, CGAffineTransformConcat(mat, trf2));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java: How to reproduce Legen...dary ClassNotFoundException in Singleton? On my last interview I was asked a standard question about all Singleton implementations in java. And how bad they all are.
And I was told that even the static initialization is bad because of the probability of unchecked exception in constructor:
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
private Singleton() {
throw new RuntimeException("Wow... Exception in Singleton constructor...");
}
}
And they also told me that the Exception is gonna be "ClassNotFoundException" so it would be extremely hard to find the problem in real app.
I tried to get that Exception:
public static void main(String[] args) {
new Thread(new Runnable(){
public void run() {
Singleton.getInstance();
}
}).start();
}
But the onlything I get is ExceptionInInitializerError...
I googled about that exception and everywhere I found - they all talked about the same problem I was told on my interview. Nothing about the "implementation"=)
Thanks for your attention.
A: Sometimes you get strange questions in interviews, you should always expect the unexpected. ;)
Any technique you use has positives and minuses. You have to know when is a good time to use them and what the problem might be and how to work around them.
The important thing to remember that almost every problem has a solution or a work around.
On my last interview I was asked a standard question about all Singleton implementations in java. And how bad they all are.
Sounds less like a question, more like a religious debate.
And I was told that even the static initialization is bad because of the probability of unchecked exception in constructor:
Siderman IV: Spider man vs Singleton and the Static Initialiser. (the bad guys ;)
throw new RuntimeException("Wow... Exception in Singleton constructor...");
That is a bad idea, so don't do that. In fact it won't even compile. The compiler in Java 6 reports.
initializer must be able to complete normally
And they also told me that the Exception is gonna be "ClassNotFoundException" so it would be extremely hard to find the problem in real app.
You get a ExceptionInInitializerError with a cause of the exception which caused the problem. Apart from having to read the nested exception its not that tricky.
static class Inner {
static {
Integer.parseInt(null);
}
}
public static void main(String... args) {
try {
new Inner();
} catch (Throwable e) {
e.printStackTrace();
}
new Inner();
}
prints
Exception in thread "main" java.lang.ExceptionInInitializerError
at Main.main(Main.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Integer.parseInt(Integer.java:499)
at Main$Inner.<clinit>(Main.java:8)
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class Main$Inner
at Main.main(Main.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
This happens the first time, after that you get NoClassDefFoundError if you try to use the class again.
It used to be that when you tried to access a class using reflections, and it failed you got a ClassNotFoundException (with no details as to what really happens) However this is no longer the case.
A: Imo, I don't think you'll ever get a ClassNotFoundException out of a construction like that. The classloader will not fail to load that class, but will fail to initialize it. The ExceptionInInitializerError is correct, according to Javadoc:
ExceptionInInitializerError "signals that an unexpected exception has
occurred in a static initializer. An ExceptionInInitializerError is
thrown to indicate that an exception occurred during evaluation of a
static initializer or the initializer for a static variable.", which
is exactly your case.
Side note: the most purist way of implementing a singleton in Java is, according to Joshua Bloch (author of part of the Java API and the book "Effective Java") the Singleton Enum Pattern (http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java).
In any case, unchecked exceptions can potentially happen in the constructor of any class, so in my opinion this possibility is not a reason enough to not use the Static Initialization Singleton Pattern in Java.
A: If you saying that on account of a RuntimeException being thrown from the ctr of the Singleton class , a ClassNotFoundException will be throw - then that is not correct - CNFEx is a results of the runtime failing to locate the class to load - the fact that the ctr code is called at the first place is evidence enough to rule out CNFEx.
A: It is very simple. Your constructor should call some third party library. For example log4j. Compile it with log4j.jar in classpath and then run without. You will get ClassDefNotFoundError. If you really need ClassNotFoundException initiate some class using dynamic class loading: Class.forName("MyNotExistingClass")
Anyway, I think that your interviewer is wrong. The problem with static initialization is not possible RunTimeExceptions: you will see them on STDERR of your application. The problem is that they run before the real objects are needed while lazy initialization of classic singleton is running only when the instance is really going to be used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Example of chained exceptions stack I do not know much about these technologies, and was not very successful at finding how an exception stack is displayed.
Therefore, several basic questions:
*
*how are 2 independent successive exceptions shown?
*how are several chained exceptions displayed?
*is the root cause displayed at the top or the bottom of the stack?
A: It's pretty easy to try this for yourself. For example:
using System;
class Test
{
static void Main(string[] args)
{
try
{
Top();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
static void Top()
{
try
{
Middle();
}
catch (Exception e)
{
throw new Exception("Exception from top", e);
}
}
static void Middle()
{
try
{
Bottom();
}
catch (Exception e)
{
throw new Exception("Exception from middle", e);
}
}
static void Bottom()
{
throw new Exception("Exception from bottom");
}
}
Results (the first two lines would be on one line if it were long enough):
System.Exception: Exception from top ---> System.Exception: Exception from middle
---> System.Exception: Exception from bottom
at Test.Bottom() in c:\Users\Jon\Test\Test.cs:line 43
at Test.Middle() in c:\Users\Jon\Test\Test.cs:line 33
--- End of inner exception stack trace ---
at Test.Middle() in c:\Users\Jon\Test\Test.cs:line 37
at Test.Top() in c:\Users\Jon\Test\Test.cs:line 21
--- End of inner exception stack trace ---
at Test.Top() in c:\Users\Jon\Test\Test.cs:line 25
at Test.Main(String[] args) in c:\Users\Jon\Test\Test.cs:line 9
A: When two independent successive exceptions are thrown, the first one will interrupt the normal execution of the program, until it is handled. Then, the second exception will be thrown in the same way, if the program was not terminated by the first one.
As for chained exceptions, you will see the last thrown exception, but that last exception was thrown when handling another exception and so forth. For example:
void Foo()
{
throw new FooException("foo");
}
void Bar()
{
try
{
Foo();
}
catch(FooException ex)
{
throw new BarException("bar", /* innerException = */ ex);
}
}
So at the top of the stack you will see BarException and at the bottom, the FooException. Hope I did not miss anything.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sending a file via POST using raw HTTP (PuTTY) If I set up an HTML page with the following form:
<html>
<body>
<form action="upload_file.php"
method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
I can upload a file to upload_file.php where I can handle it using a PHP script.
For testing purposes, I need to do the same using raw HTTP via a PuTTY session.
I can do a normal POST (just sending text data) this way:
POST /test_post.php HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
name=myname
How can I send a file this way?
A: Open a port with netcat and save the incoming request:
nc -l -p 1090 > income-http.txt
Then modify your form to send the data to the netcat:
<form action="http://localhost:1090/upload_file.php"
method="post" enctype="multipart/form-data">
Submit the form from your browser. You can find the full raw request with the contents of the file in the income-http.txt file.
Saving the income-http.txt is an one-time activity. Later you can send the saved request out any times. Please note that you should edit the Host: header in the saved txt.
A: You have to use multipart content-type and encode the file data into hex/binary
Try the following in telnet:
POST /the_url HTTP/1.1
User-Agent: Mozilla
Host: www.example.com
Content-Length: xxxx
Content-Type: multipart/form-data; boundary=--------------------31063722920652
------------------------------31063722920652
Content-Disposition: form-data; name="a"
value_for_a
------------------------------31063722920652
Content-Disposition: form-data; name="b"
value_for_b
------------------------------31063722920652
Content-Disposition: form-data; name="c"; filename="myfile.txt"
Content-Type: text/plain
This is a test
and more
-----------------------------31063722920652
Content-Disposition: form-data; name="submit"
Submit
-----------------------------31063722920652--
Remember that an extra newline is necessary between field name and its data. Also, update the Content-Length value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: File Download using HTML 5 , Javascript and File API Can we integrate the FileAccess API of HTML with normal download of Files using javascript.
We typically download a file by the below way:
var fileUrl='../File.doc';
window.open(fileUrl,'Downloading');
Now I believe that the file would be downloaded to tempFolder and the folder designated by us for download.
But is it possible for us to download the file to a sandboxed location as mentioned in WWC draft on HTML 5 File API.
If this is possible, I believe "need for a way to delete downloaded files" of my previous question would be solved.
A: There's a new download attribute you can add to links that tells the browser to download the resource rather than navigating to it. That downloads the file to whatever "Downloads" folder the browser uses by default. You cannot programmatically delete files that are downloaded. That would be a security risk.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is accessing volatile local variables not accessed from outside the function observable behavior in C++? In C++03 Standard observable behavior (1.9/6) includes reading and writing volatile data. Now I have this code:
int main()
{
const volatile int value = 0;
if( value ) {
}
return 0;
}
which formally initializes a volatile variable and then reads it. Visual C++ 10 emits machine code that makes room on the stack by pushing a dword there, then writes zero into that stack location, then reads that location.
To me it makes no sense - no other code or hardware could possibly know where the local variable is located (since it's in automatic storage) and so it's unreasonable to expect that the variable could have been read/written by any other party and so it can be eliminated in this case.
Is eliminating this variable access allowed? Is accessing a volatile local which address is not known to any other party observable behavior?
A: The thread's entire stack might be located on a protected memory page, with a handler that logs all reads and writes (and allows them to complete, of course).
However, I don't think MSVC really cares whether or how the memory access might be detected. It understands volatile to mean, among other things, "do not bother applying optimizations to this object". So it doesn't. It doesn't have to make sense, because MSVC is not interested in speeding up this kind of use of volatile.
Since it's implementation-dependent whether and how observable behavior can actually be observed, I think you're right that an implementation can "cheat" if it knows, because of details of the hardware, that the access cannot possibly be detected. Observable behavior that has no physically-detectable effect can be skipped: no matter what the standard says, the means to detect non-conforming behavior are limited to what's physically possible.
If an implementation fails to conform to the standard in a forest, and nobody notices, does it make a sound? Kind of thing.
A: That's the whole point of declaring a variable volatile: you tell the implementation that that variable may change or be read by means unknown to the implementation itself and that the implementation should refrain from performing optimizations that might impact such access.
When a variable is declared both volatile and const your program may not change it, but it may still be changed from outside. This implies that not only the variable itself but also all read operations on it cannot be optimized away.
A:
no other code or hardware could possibly know
You can look a the assembly (you just did!), figure out the address of the variable, and map it to some hardware for the duration of the call. volatile means the implementation is obliged to account for such things too.
A: Volatile also applies to your own code.
volatile int x;
spawn_thread(&x);
x = 0;
while (x == 0){};
This will be an endless loop if x is not volatile.
As for the const. I'm unsure whether the compiler can use that to decide.
A:
To me it makes no sense - no other code or hardware could possibly
know where the local variable is located (since it's in automatic
storage)
Really? So if I write an x86 emulator and run your code on it, then that emulator won't know about that local variable?
The implementation can never actually know for sure that the behaviour is unobservable.
A: My answer is a bit late. Anyway, this statement
To me it makes no sense - no other code or hardware could possibly
know where the local variable is located (since it's in automatic
storage)
is wrong. The difference between volatile or not is actually very observable in VC++2010. For instance, in Release build, you cannot add a break point to a local variable declaration that was eliminated by optimization. Hence, if you need to set a break point to a variable declaration or even just to watch its value in the Debugger, we have to use Debug build. To debug a specific local variable in Release build, we could make use of the volatile keyword:
int _tmain(int argc, _TCHAR* argv[])
{
int a;
//int volatile a;
a=1; //break point here is not possible in Release build, unless volatile used
printf("%d\n",a);
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Java: How to view icon overlapping each other JLabel l1 = new JLabel( new ImageIcon( ... ) ) ;
JLabel l2 = new JLabel( new ImageIcon( ... ) ) ;
l1.setBounds( 0, 0, 50, 50 ) ;
l2.setBounds( 10, 10, 50, 50 ) ;
That occupy some of the place of l1. If I want to view all the l1 ignoring l2, what should I write ?
A: Any of:
*
*A JLayeredPane. See How to Use Layered Panes.
*A custom layout. See Creating a Custom Layout Manager.
*Custom painting. See Performing Custom Painting.
Could fulfill the requirement.
Here is a screenshot from the tutorial on layered panes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a ready made roles/membership framework for ASP.NET Web Forms? There were few questions related to this but none answered the question in my head. Suggestions included Asp.net Membership system, a search on codeplex foundation or role out your own. Rolling out my own would be last resort as it would involve testing and design time involved. All i want role provider to perform is restrict users permissions over a action. Below you can find a scenario for understanding it,
Think you are admin of a Forum/Discussion board of some sort and during installation of the software it created two membership for you something like
*
*Gold member
*Silver member
Here are some imaginary roles for these memberships,
Gold member:
Can edit Posts by others
Can create Polls
Silver Member:
Can report Posts to admin
Can ban members of lower membership value
all these above roles are bit fields for ease of validation based on roles. Now my question is ,
Question
Do you know any role provider that would give me fine grain of control like above where i can edit roles for a membership, create new membership and assign roles etc which would also integrate to SignUp time integration
Specs:
.NET 2.0 & Asp.net 2.0
A: Yes there is, and it's all in the box: http://msdn.microsoft.com/en-us/library/879kf95c.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: admob ads not displaying when request.setTesting(false) When i place my pub id
AdView adView = new AdView(this, AdSize.BANNER, Publisher ID);
and
layout.addView(adView);
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
iam getting the ads but when i set it to
request.setTesting(false)
i am not getting ads how to solve this.. what is the actual prob;lem?
A: Use this in your activity:
adview = (AdView) findViewById(R.id.adView);
AdRequest re = new AdRequest();
re.addTestDevice(AdRequest.TEST_EMULATOR); // Emulator
re.addTestDevice("xxxxxxxxxxx"); // Test Android Device
adview.loadAd(re);
Use this in your XML file:
<com.google.ads.AdView
android:id="@+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxx"
ads:loadAdOnCreate="true">
</com.google.ads.AdView>
A: Add the banner in XML it is much easier !
<com.google.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxx"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
and in the activity put only
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trying to set screen brightness on android phone I am trying to set the screen brightness but when I try and get the current window with this.getWindow() I get null. Why is this? I will post all of my code in my setBrightness() method.
System.putInt(getContentResolver(), System.SCREEN_BRIGHTNESS,
brightness);
Window window = getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = brightness / (float) 255;
window.setAttributes(lp);
A: Don't use System.putInt()... You already set the screenBrightness in the lp!
The following code works:
Window window = getWindow();
float brightness = 100.0f;
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = brightness/255.0f;
window.setAttributes(lp);
A: If you are using a seekbar, try these lines,
System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = brightness / (float)255;
window.setAttributes(layoutpars);
A: If you call it from fragment add getActivity() before getWindow() like this
getActivity().getWindow().setAttributes(layoutParams);
And if use seekbar dont let your brogress be 0, cause it can make your screen goes completly dark(on android 2.3)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Write non ASCII char with PhoneGap Javascript Image Here is what I'm doing :
In javascript I ask for an image with AJAX.
The server php execute the following code :
readfile($pathfile);
Then the javascript receive the data, and with Phonegap I try to write it to a file :
var writer = new FileWriter();
writer.fileName = "./../Documents/" + nameFile;
writer.write(dataReceived);
In fact, it works with ASCII chars, but the function "write" fail with the content of the image received (png format). So I tried to encode the transferred data in Base64, in Hexadécimal and it works. But I don't want to store encoded data because I want to use it later in "img" tags (html tag). And make something like :
<img src='./../Documents/createdFile.png' />
Do you have any idea on how to write any characters in Phonegap to a file? Or what I'm doing wrong with the FileWriter of PhoneGap ? I know the way to do something like src='Image.php', but I have to store files on the device.
I've got the version 0.9x of Phonegap (included with Dreamweaver). Thanks in advance.
A: I finally found the explication. To begin I want to say that I just learned javascript ;) .So I asked the question to "macdonst" on github and he answered me :
"Sadly, you will be unable to write binary data with the FileWriter. JavaScript can't handle binary data very well and we can't pass binary data from the JavaScript side to the Native side so it is a limitation we have to live with.
However, once you've written you've gotten your base64 image data you can display it like this:
<img src="data:image/gif;base64,{this is where your base64 data goes}" />
"
Thanks to "macdonst", I posted his answer because I hope it will help beginners like me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook Javascript SDK window location reload not working on Firefox I'm building a website with Facebook Connect and therefore using the Facebook Javascript SDK.
Problem: when using Firefox, the page doesn't reload properly once logged in or logged out.
FB.Event.subscribe(
'{% if current_user %}auth.logout{% else %}auth.login{% endif %}',
function(response){
window.location.reload();
});
Obviously, it looks like a known problem (just type "window location reload not working on firefox" and you'll get a lot of results)
More precisely, Firefox doesn't seem to send the right cookie when reloading the page...
- When I click to login, once Facebook logged me in and sets a cookie, Firefox doesn't send any cookie
- When I click to logout, once Facebook has logged me out and remove the cookie, Firefox sends the cookie that was previously there.
I conclude it uses some "cache functions".
I tried to make a workaround as described here and implemented this:
redirect_url = encodeURIComponent(window.location.href);
url = window.location.href + "account/login?redirect_url=" + redirect_url;
window.location.replace(url);
But the problem remains (the cache I guess...) Can you help me out with this?
Thanks.
A: Incase there was anymore confusion over this, for Firefox, the above referenced example of setTimeout() works perfectly. Simply include your reload call, or if it's easier just replace:
document.location.reload();
with:
setTimeout('document.location.reload()',0);
Using the most recent version of Firefox released, I have tested every example above, and this is the only one that has actually worked consistently. Basically, you just need to "pause" the JavaScript just for a moment to let the rest of the script catch up. I did not test this on Chrome or IE, but it does work flawlessly on Firefox.
A: Try wrapping the window.location.reload() call in a setTimeout() with a zero delay. Apparently, Firefox fires the event before setting the cookie. The wrapping should place the reload call in the event queue and allow the cookies to be set correctly.
A: We are using the work-around with
window.location.href = url;
instead of
window.location.replace(url);
Works fine in Firefox, too.
A: For anyone using Rails and Koala, you can just check for the cookies and redirect to the same action if they are not present:
def fb_authenticate
@fb_cookies ||= Koala::Facebook::OAuth.new.get_user_info_from_cookie(cookies)
if @fb_cookies
#login user or create new user
else
redirect_to :controller => 'account', :action => 'fb_authenticate'
end
end
A: Try redirect to a different URL each time:
top.location.href = 'https://apps.facebook.com/YOUR_APP_NAME/?t=' + <?php echo time(); ?>;
, I use PHP but you can replace with JS ( Math.round(+new Date()/1000) I guess ).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: sugarcrm report In Sugarcrm Reports , How to Show opportunity amount in the user entered /actual currency, rather user preference currency. Struggling to find solution, any hint or help would be great helpful
A: Please tell whether you are using Sugarcrm Edition Or Professional. and if You are using edition then which report module you are using?
In Case Of Professional Edition , there is option to select the opportunity amount in the side bar and we can easily use them and their amount
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: COleDateTime alternative for linux Good Day.
I have to make a C++ project Linux compatible. In the existing Project some old MFC functions were used. I am searching for a substitute for the COleDateTime wrapper. Does a alternative object exist for Linux or do I have to implement my own wrapper? (examples would be appreciated)
A: Boost DateTime library: http://www.boost.org/doc/libs/1_47_0/doc/html/date_time.html
Using Boost, you can make many other things portable: file system, multithreading, interprocess communications, sockets etc.
More about Boost Datetime here: http://en.highscore.de/cpp/boost/ Chapter 10: Date and Time
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Press and release a key with Linux I'm trying to make a little program that types for a user, using c++. I've found the method keybd_press(...) but it seems as though that only works with the Windows header. Any way to achieve this in Linux? Basically what I want it to do is emulate a key being pressed for me, an auto-typer if you will. I'd like it to be ran from the terminal, read the input from the user, and then type it until the number of times it should be typed is reached. I can do all of that stuff, I just can't figure out how to emulate a key being pressed and released.
I don't think code is really necessary but this is what I'm working with:
#include <iostream>
#include <string>
using namespace std;
int main () {
string mystr;
cout << "What key would you like me to press? ";
getline (cin, mystr);
pressKey(mystr);
return 0;
}
void pressKey(string str) {
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
keybd_event(VkKeyScan(str), 0x45, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VkKeyScan(str), 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
Note: I wouldn't mind using Shell for this if it is better, if it is an example would be highly appreciated!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to connect Database Thanks for previous replies
How to connect mysql to zend framework. i created table in mysql. i used
$config = array(host' => 'localhost',username' => 'userName','password' => 'sqlpass',
'dbname' => 'databasename',$db = Zend_Db::factory('PDO_MYSQL', $config);
print_r($db->fetchAll("SELECT * FROM tablename")); this command to connect with database, but whenever i tried this, nothing is displayed. Is there any tutorials to connect database with zend framework. i am new to this topic. pls guide me.
A: try this:
$config = array('host' => 'localhost',
'username' => 'userName',
'password' => 'sqlpass',
'dbname' => 'databasename');
$ResourceDb = Zend_Db::factory('PDO_MYSQL',$config);
Zend_Db_Table_Abstract::setDefaultAdapter($ResourceDb);
and now try with fetchAll().
which error do you receive?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kohana 2 ORM: ->with() for has_many relations We have a table for articles, and a table for locale data for articles.
class Article_Model extends ORM {
protected $has_many = array('article_translations');
[...]
class Article_Translation_Model extends ORM {
[...]
'articles_translations' table contain 'article_id', 'locale_id', 'heading', 'body', etc. columns.
Is it possible to do
SELECT article.id, article_translations.heading, article_translations.body
FROM articles
JOIN articles_translations ON (articles_translations.article_id = article.id)
WHERE articles_translations.locale_id = 'en_US.UTF-8'
using Kohana 2 ORM?
The ->with() construction works only for has_one relations. The articles_translations.article_id and articles_translations.locale_id is UNIQUE, of course.
A: You could go the other way though:
$article_translation = ORM::factory('article_translation')
->where('locale_id', 'en_US.UTF-8')
->find();
Then you can reference the article columns as:
$article_translation->body;
$article_translation->heading;
$article_translation->article->id;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553063",
"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.