text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Zipping commands and directory (Windows) Troubles The problem is 'I want a program which creates a backup of all my important files'.
This lesson is located at: http://www.ibiblio.org/g2swap/byteofpython/read/problem-solving.html
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
I'm using Windows.
For # 2, where is this and does it apply to Windows?
For # 5, I can't find the commands to zip a file for the default windows zipping program.
This would be easy if the lesson explained how to use this with Windows and the zipping commands. Any assistance is appreciated. This is homework reading but It's not helpful when all the applicable tools are not defined.
A: You can get a zip program from http://info-zip.org/Zip.html but I would recommend just using Python's zipfile module.
Also, there's no standard backup file location. You'll just have to make one up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Post with radio button check verification I have a page that uses jQuery post to submit a form and return the data within a div tag in the same page. then the form is still accessible so that multiple questions can be asked to the user and information will be elicited from the data base.
On the first time around if the user tries to submit the form without selecting a radio button they get an alert box that says they must make a selection. However after the first time through the user can submit the form without making a selection.
The radio buttons are maintaining their set value. Any ideas on how I can use this format and make sure that with each successive form submission a radio button is selected?
Here is the first page test.php
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test jQuery post</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
//<![CDATA[
jQuery.noConflict ();
jQuery(document).ready(function(){
initializeForm();
});
function initializeForm() {
jQuery("#university").validate({
debug: false,
submitHandler: function(form) {
var validationTypes = jQuery("#validationTypes");
var valid = false;
if (validationTypes.val()== 'radio')
{
for(i=0; i<university.radio.length; i++) if(university.radio[i].checked) {valid=true;}
if (valid == false)
{
alert ( "Please pick an answer before trying to Submit this form." );
return false;
}
}
jQuery.post('post.php',
jQuery("#university").serialize(),
function(data) {
jQuery('#box').html(data);
initializeForm();
});
}
});
}
// ]]>
</script>
</head>
<body>
<div id="box"><? include('post.php') ?></div>
</body>
</html>
Here is the second page post.php
<?
$radio = (isset($_POST['radio'])? $_POST['radio']: 0);
switch ($radio)
{
default:
echo 'pick a number<br /><br />';
break;
case '1':
echo 'you pick one<br /><br />Pick Again<br /><br />';
break;
case '2':
echo 'you pick two<br /><br />Pick Again<br /><br />';
break;
case '3':
echo 'you pick three<br /><br />Pick Again<br /><br />';
break;
}
?>
<form action="" method="POST" id="university" name="university">
<input type="radio" name="radio" value="1" /> 1
<input type="radio" name="radio" value="2" /> 2
<input type="radio" name="radio" value="3" /> 3
<input type="hidden" name="validationTypes" id="validationTypes" value="radio">
<input type="submit" name="submit" value="submit" /></form>
A: I think your event handler for the validation (jQuery("#university").validate) is still attached to the HTML that you just replaced after you submit the form (jQuery('#box').html(data)).
So in this case I can think in 2 options which I think will solve your issue:
*
*Easy solution: Move this part of your javascript inside the post.php page (so it's executed each time you load the form):
jQuery(document).ready(function(){
initializeForm();
});
*Performant solution: Move your HTML in the post.php page to below closing the "box" div in the test.php page. And then use something to clean the values like:
$('input[name=radio]').val([]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get dictionary key of view being panned and add it to an array I have a bunch of UIImageViews in an NSMutableDictionary.
My imageview creation method:
for (int i = 1; i <= 5; i++)
{
char a = 'a';
NSString *key = [NSString stringWithFormat:@"%c%d", a, i];
alphabetVowelA = [[UIImageView alloc] initWithFrame:CGRectMake(39, 104, 70, 70)];
[alphabetVowelA setImage:[UIImage imageNamed:@"a.png"]];
alphabetVowelA.tag = i;
[alphabetVowelA setUserInteractionEnabled:YES];
[self addGestureRecognizersToPiece:alphabetVowelA];
[letterDictionary setObject:alphabetVowelA forKey:key]; //Adds the letter a UIImageView to dictionary with key: a1, a2, a3, a4, a5.
[self.view addSubview:alphabetVowelA];
[alphabetVowelA release];
}
Here is my pan gesture method.
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];
[self.view bringSubviewToFront:piece];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:[piece superview]];
CGRect startingPointFrame = CGRectMake(245, 428, 31, 20);
[startingPoint setFrame:startingPointFrame];
[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}
if ([gestureRecognizer state] == UIGestureRecognizerStateEnded)
{
pannedPieces = [[NSMutableArray alloc] init];
[pannedPieces addObject:piece];
NSEnumerator *enumerator = [pannedPieces objectEnumerator];
id element;
NSUInteger arrayCount = [pannedPieces count];
while(element = [enumerator nextObject])
{
NSUInteger i = [pannedPieces indexOfObject:element];
NSLog(@"%@ \n @index %i \n Array Count: %i",element, i, arrayCount);
}
}
I'm trying to add the views that were panned and dropped to an NSMutableArray so that I can work with those views independently of all my other views. When doing it with my above code, it seems that every piece that is panned doesn't add itself to the end of the array, it only places it at index 0 every time. So my @index prints 0, and Array Count prints 1 no matter how many of the views I've panned.
Instead of just adding the "piece" that was panned, how can I get the dictionary key of the UIImageView being panned, so that I can add it to the array by key?
I hope this question makes sense.
A: This line:
pannedPieces = [[NSMutableArray alloc] init];
overwrites pannedPieces with a new array every time you enter that branch (and probably also leaks). If you want to collect more pieces, don't use a new array and just add to the existing one.
To get the key(s) for an object from a dictionary use -allKeysForObject:.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CakePHP Acessing full User Information I am very new to CakePHP and I was just wondering if someone could help me with a couple of things.
I have a User class and an Image class.
In my users_controller.php I have the following functions
function beforeFilter(){
$this->userOb = $this->User->find();
}
function beforeRender(){
$this->set('userOb', $this->userOb);
}
This works fine and I can view the object in my view, with all the correct relations to the Image class.
But doing this overwrites the beforeFilter() and beforeRender() functions in my app_controller.php, so I try and move this functionality to my app_controller.php but I get an error (Undefined property: PagesController::$User)
Also,
$this->Auth->user();
doesn't seem to have the full object map that
$this->User->find();
returns.
So, I guess my question is how can I create a variable that is acessable in all my views, i.e it's defined in app_controller.php, that contains the current logged in Users Object and it's relations.
Thanks.
A: If the issue is your parent methods are being overwritten by child methods, simply call the parent method in the child, see below:
function beforeFilter(){
parent::beforeFilter();
$this->userOb = $this->User->find();
}
function beforeRender(){
parent::beforeRender();
$this->set('userOb', $this->userOb);
}
A: put your find result in SessionComponent so you don't have to perform a query for each request (and set variable in beforeRender). In the view you can access it with SessionHelper. $this->Auth->user(); only have the User record.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: make duplicate levels unique in r I have to extract data for each individual from one large file based on a date/time window from another file. I have ID, Start, End date as my window file and a huge file (FULLDATA) with all sorts of other data in it, but we shall just simplify it and say it has only ID, Date, X, Y, Z.
Eg., Dates window Data file
ID Start End Date
c1 03/03/03 01:02 03/15/03 12:00
a2 03/03/03 04:35 03/10/03 13:00
f3 02/03/03 11:02 05/15/03 15:00
c1 01/03/04 13:02 02/15/05 17:00
a2 04/23/04 04:02 05/14/05 10:00
There are duplicate ID's but unique windows of time I need to get data from.
In my code I need to set the levels
IDNames = levels(dates$ID)
but in doing this it will make the ID levels unique and only use the window from the 1st time that level showed. So, in my example c1 and a2 will only be used 1 time and extract the information from their first appearance.
I have tried
levels(make.unique(IDNames))
But this then will turn the ID "c1" into "c1.1" which will not match up with the FULLDATA file in the rest of my commands.
for (n in 1:(length(IDNames))) {
IndivData = FULLDATA[FULLDATA$ID==IDNames[n],]
Dateswindow = dates[dates$ID==IDNames[n],]
}
A: If I'm understanding you correctly, it sounds like you want to produce a single column that identifies a unique combination of ID, Start and End Date, that in some sense preserves each piece so that you can refer to them using another data frame.
Why not simply coerce everything to characters and paste them together with a useful separating character? So something like:
IDNames <- paste(as.character(dates$ID),as.character(...),as.character(...),sep = "-")
Then you'll have a unique value for each ID-Start-End combination, and you can easily pull each piece out again to use to merge back with your other data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will this copy the object or add a reference to it? Let's say I have the following object:
var lol = {
section: {},
other: {foo: 'bar', foob: 'baz'}
};
Now if I do the following:
lol.section.other = lol.other;
will a reference be made linking section.other to other or will the entire other object be copied and placed in section?
A: You're creating two references to the same object.
Javascript objects are never implicitly copied.
A: Like quite a few other OO languages, JavaScript also passes and assigns the object by reference therefore, you are only creating a new reference to an existing object.
Where JavaScript breaks away from other OO languages is in inheritance and in encapsulation. So be cautious in those areas.
A: As SLaks said, javascript assigns objects as a reference (without copying). It's easy to test or see yourself:
var lol = {
section: {},
other: {foo: 'bar', foob: 'baz'}
};
lol.section.other = lol.other;
lol.other.foo = 'test';
console.log(lol.section.other.foo); // will be 'test', not 'bar'
You can see it here: http://jsfiddle.net/jfriend00/r73LH/.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Old version of applet still running in the background in eclipse Sometime I forget to close my previous applet before I re-compile a new version. So I end up with multiple versions of my old applets hanging around in my dock.
Is there a way to tell Eclipse to close these old version before launching the new one?
A: No, there isn't such a feature on Eclipse. I've always have to stop the current running instance before starting a new one. Depending on the environment thought, sometimes saving the code files and refreshing the running instance will do the trick (like for example when running a GAE application) but i always better to start with a complete fresh execution to avoid inconsistencies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a fillable PDF that POST's it's data then returns a flattened PDF with the data in it the user can save I have a pdf that currently people fill in, print out, hand to a receptionist who scans the paper form into a pdf, enters the form fields into a web form, attaches the scan to the web form and submits that. This is dumb.
What I want is a PDF form that once filled out the user can press a submit button. That submit button sends a post request to a web server with the form fields and the completed form. So far I can do half of that, submit the fields to a web site where they show up in POST, and the server's response gets returned to the user as a PDF, at least in Acrobat pro it does. Reader throws an error, but I am hoping that if the server returns a PDF reader will open it.
What I need is the submit button to send the fields to the server, along with a copy of the completed form. I can catch it with PHP and do everything I need from there. Preferably I would like both in the same transaction, but if not I can work around it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IE9, focus on input text box, but pressing enter will execute the first input button. I need it to stop I have a web app, where people can search for stuff. In IE9 the focus is on the search input element but the first button is highlighted so when someone press enter it would always execute the first button.
I don't want people to be able to press enter and execute the first button.
The reason is because some people tends to press enter after typing in the search's input text box even though it's base on keyup event.
I've try refocusing it to the search input element. I've also try blurring the button. It doesn't seem to work.
Does anyone know a solution to this?
Thank you for your time.
edit:
I don't want to highjack the enter button because what if someone actually tab the focus on to the first button and press enter? Maybe I can check for that? Or maybe there's a better solution?
Edit 2: Found a similar problem here:
Stopping IE from highlighting the first submit-button in a form
But the solution is for that question is ASP.
edit 3:
A code example:
<div >
<label>ETTRN:<input type="text" id="search" maxlength="16" /></label>
<input type="submit" value="Generate CSV" id="generate_csv" />
</div>
A: Put the search box inside a <form> all on its own.
<form action="javascript:void(null);" method="post">
<input type="text" id="searchbox" />
</form>
This will (or at least, should) prevent IE (or any browser) from treating the first button as the action for the Enter key.
A: I figure out a solution.
jQuery('*:focus').live('keydown', function(event) {
if (event.keyCode == 13) {
switch(jQuery(this).attr('id')) {
case 'search' :
case 'date-start':
case 'date-end':
event.preventDefault();
return false;
}
}
});
I only care about when the focus is on the text input elements, that are used for searching (namely search, date-start, and date-end). So if one these three text input elements is in focus while a key is press, check if it's the Enter key (13), if it is then disable the default.
Thank you all for helping.
A: The problem is similar to what a document has described here: https://github.com/aleen42/PersonalWiki/issues/32#issuecomment-489966824
If you want to solve the problem, you can use keypress or keydown event instead:
$('input.input-wrapper').on('keydown', e => { console.log(e.keyCode); });
Or wrap the input element with a empty form:
<form action="javascript: void(0);">
<input type="text" class="input-wrapper" value="" />
</form>
<button>test</button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convert DataInput to DataInputStream? How can I convert DataInput to DataInputStream in java?
I need to know the size of the DataInput.
A: Since a stream, by definition, really has no begining or end and thus no fool proof way of knowing how much is available, you just have to read from the stream in fixed sized chunks. It almost sounds like you'd be better off with plain old .read() rather than readFully():
DataInputStream dis = new DataInputStream(...);
byte[] buf = new byte[1024];
int lastRead = 0;
do {
lastRead = dis.read(buf);
//do something with 'buf' here
} while (lastRead > 0);
A: You'll encounter difficulty when you want know how many bytes to be read. Simplest solution is to cast it to a ByteArrayInputStream and use it's available() method to get to know how many bytes are available for reading.
Following example worked for me
DataInput in = (...);
ByteArrayInputStream bis = (ByteArrayInputStream) in;
byte[] buffer = new byte[bis.available()];
in.readFully(buffer);
//use buffer as your wish
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Links published to my page wall with graph do not show up in user feeds I have a php script that posts links to my facebook page wall using the php sdk that works fantastic except for one minor annoyance. When my links are posted programatically via the api they do not appear in the feeds of people who like the page. When the links are posted manually they show up. My question is: is there any special considerations I need to take into account to make those automatic posts show up or is this just how facebook's algorithm works when choosing content for the feed? I suspect this is more of policy issue than a technical one but facebook has been changing things around so I don't want to jump to conclusions. Any insight would be appreciated.
A: So I discovered that facebook intentionally penalizes you for auto-posting through the api. Read here: http://sproutsocial.com/insights/2011/04/facebook-penalizes-you-for-automating-your-page-updates/
Bastards. Oh well. Question answered.
A: Try using the latest version of the API. Maybe they've resolved a previous bug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: receive microphone sound without hearing it This captures microphone sound and changes the alpha of 'foo' according to the sound level. However, I hear the microphones input. I want the visuals to work without hearing any sound. How would I do that?
m = Microphone.get();
_root.attachAudio(m);
m.setVolume(0); //i can still hear sound. does not mute mic.
onEnterFrame = function () {
foo._alpha = m.activityLevel+33;
};
EDIT: ANSWER / SOLUTION
series8217's trick with setLoopBack did not work, but that led me to the answer online:
m = Microphone.get();
var myAudio:Sound=new Sound(attachAudio(m));
myAudio.setVolume(0);
thanks for your time
EDIT: OTHER SOLUTION
my trick may interfere with sound. using this, mutes the mic but flash still receives input:
m = Microphone.get();
m.setSilenceLevel(100);
A: Switching the loopback mode on the microphone object should do the trick.
m.setLoopBack(false);
However, if that doesn't do it, perhaps your OS sound settings have monitor or loopback mode turned on. I'd say look into that before trying setLoopback().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In JavaScript, how can serializer part of the DOM to XHTML? I would like to serialize part of the DOM to XHTML (valid XML). Let's assume I have just one element inside <body>, and that this is the element I want to serialize:
<div>
<hr>
<img src="/foo.png">
</div>
With this, document.innerHTML gives me almost what I want, except it returns HTML, not XHTML (i.e. the <hr> and <img> won't be properly closed). Since innerHTML doesn't do the trick, how can I serialize part of the DOM to XHTML?
A: I am not sure if using another language (on top of the JavaScript engine) is an option. If this is of any help, this would be the XQuery (XQIB) way of doing it:
<script type="application/xquery">
serialize(b:dom()//div)
</script>
For example, in the following page, the serialized XHTML is written as text on the page instead of the script tag, after the div tag:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Serializing part of the DOM</title>
<meta charset="UTF-8"/>
<script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
</head>
<body>
<div>
<hr>
<img src="/foo.png">
</div>
<script type="application/xquery">
serialize(b:dom()//div)
</script>
</body>
</html>
The HTML DOM is mapped to the XQuery data model (a data model on top of XML). b:dom() returns the document node of the page, and //div navigates to all descendant div tags. The serialize function then serializes this to a string.
However, this will work for IE9+ (not 6+) and recent versions of Chrome, Firefox, Safari, Opera.
A: this is not tested code, but I would scan recursively children of the parent element and build XHTML like this:
var parent;
var parse = function(el) {
var res = "";
for(var i=0; i < el.childNodes.length; i++) {
var child = el.childNodes[i];
res += "<"+child.tagName;
// scan through attributes
for(var k=0; k < child.attributes.length; k++) {
var attr = child.attributes[k];
res += " "+attr.name+"='"+attr.value+"'";
}
res += ">";
res += parse(child);
res += "</"+child.tagName+">";
}
return res;
}
var xhtml = parse(parent);
A: Sarissa, the cross-browser Javascript compatibility library has an XMLSerializer implementation for browsers that lack one:
http://dev.abiss.gr/sarissa/jsdoc/symbols/XMLSerializer.htm
They also have an example of how to use it, which is just:
var xmlString = new XMLSerializer().serializeToString(someXmlDomNode);
According to them, the browser support for their library is good:
Supported browsers are Mozilla - Firefox and family, Internet Explorer with MSXML3.0 and up, Konqueror (KDE 3.3+ for sure), Safari and Opera.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Custom Textarea/texbox and scroll I need to customize an HTML textarea (put round corners) and costumize his respective horizontal scrollbar. Ive search for a js/jquery plugin but the closest that I have found was this:
http://jscrollpane.kelvinluck.com/
but this one does not work on textareas, only in Div elements.
A: Looks like it's a bug of it maybe.
But there is a work-around.
Workaround
If it works on a <div>, then why don't you use a <div> as a <textarea>?
<div id="textarea_1" contentEditable="true"><p>Blah</p></div>
<script>
var ele=$("div#textarea_1")[0]; //Make it a textarea-like when it is a <div>
if('contentEditable' in ele){
ele.contentEditable=true; //Turn it on
}else if('designMode' in ele){
ele.designMode="on"; //For older Firefox versions
}
var value=$("div#textarea_1>p").html();
console.log(value) //The value is here
//please look at the demo below for more...
</script>
See it for yourself: Working demo 1 (includes round corners, works on all popular browsers)
Better plugin?
Personally, I think this one also works good at customizing scroll bars.
It lets you to apply CSS style on it.
See it for yourself: demo 2
CSS3 Maybe?
Maybe it's the time to use CSS3.
Read more here.
--> Demo
Hope this helps you out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ windows pause timer I'm using SetTimer to create a timer in my application with an interval of 50ms, this timer is going to be used to draw an object, and move it around.
Now I don't want the object to move when the window is out of focus, but I still need it to be painted.
And having it paint every 50ms, seems unnecessary. And performance is extremely important in this project.
So I need a way to pause the timer, but still draw the object, but preferably only when needed.
A: When you get WM_ACTIVATE, decide whether to call KillTimer or SetTimer.
A: Just a note aside to you initial problem.
I would not rely on Windows Timer with such low resolution. It's a low priority message and if you have lots of heavy duty things going on in you program, the timer might be invoked at higher intervals that you expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting started with SQLite and C++? For an online game I'm making, I need to be able to add users and their stats to a database, an example table:
Username, Password, Email, Wins, Loses
The username will be the unique key, and from there I need to retrieve the other information.
I also need to do other things such as find all the usernames with a given e-mail.
I have been searching for a few hours for an SQLite tutorial that shows C or C++ on how to do these sorts of simple tasks.
Could anyone recommend a tutorial like this or possibly some insight on performing some of the above tasks with the SQLite library?
Thanks
A: The SQLite documentation is quite good:
*
*Documentation main page
*Quickstart
*C/C++ API intro
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is this html code using php inside it without the signs? <a href="?page={$smarty.section.page.index}&{$per_pages_vars}">{$smarty.section.page.index}</a>
{/if}
{/section}
{if $pagesArray.is_next_page eq 'Y'}
<span class="resultsnext">
<a href="?page={$pagesArray.next_page_is}{if $id}&id={$id}{/if}&{$per_pages_vars}">></a>
</span>
{/if}
I have written simple php based websites before but this is the first time I am getting involved in a complex php website that another person has already finished to a large extent. This is also the first time I'm seeing this type of code in a html template section of the website.
Basically, what I'm curious is, what are all the code in the {} curly brackets? Is it some sort of php code? Another php file refers this .html file that is containing the above code.
There is a lot of content being dynamically generated, but I've never seen '{}' curly brackets being used in a .html file while having it being used as part of a template so I was wondering if some of you guys could enlighten me.
thanks.
A: That is a PHP templating language, specifically, Smarty.
Smarty parses the file for its own syntax and replaces their placeholders with variables, etc that are bound to the smarty view.
Smarty Documentation.
A: That's smarty:
http://www.smarty.net/
A: You're looking at Smarty tags. Here's a link to the current documentation.
A: It's smarty :)
Actually you're looking at sections.
http://www.smarty.net/docsv2/en/language.function.section.tpl
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Javascript regular expression for punctuation (international)? I need a regular expression to match against all punctuation marks, such as the standard [,!@#$%^&*()], but including international marks like the upside-down Spanish question mark, Chinese periods, etc. My google-fu is coming up short. Does anyone have such a regular expression on hand that's compatible with Javascript?
A: Adding to @stema's answer (https://stackoverflow.com/a/7578937/114140)... here is the regex as a string (so you don't need to bloat your project with XRegExp).
!-#%-\x2A,-/:;\x3F@\x5B-\x5D_\x7B}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E3B\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65
I used this in my own project with some additions...
// any kind of punctuation character (including international e.g. Chinese and Spanish punctuation)
// author: http://www.regular-expressions.info/unicode.html
// source: https://github.com/slevithan/xregexp/blob/41f4cd3fc0a8540c3c71969a0f81d1f00e9056a9/src/addons/unicode/unicode-categories.js#L142
// note: XRegExp unicode output taken from http://jsbin.com/uFiNeDOn/3/edit?js,console (see chrome console.log), then converted back to JS escaped unicode here http://rishida.net/tools/conversion/, then tested on http://regexpal.com/
// suggested by: https://stackoverflow.com/a/7578937
// added: extra characters like "$", "\uFFE5" [yen symbol], "^", "+", "=" which are not consider punctuation in the XRegExp regex (they are currency or mathmatical characters)
// added: \u3000-\u303F Chinese Punctuation for good measure
var regex_characters_to_remove = /[\$\uFFE5\^\+=`~<>{}\[\]|\u3000-\u303F!-#%-\x2A,-/:;\x3F@\x5B-\x5D_\x7B}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E3B\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/g
A: If it's possible for you to use a plugin, there is a plugin for JavaScript: XRegExp Unicode plugins. That adds support for Unicode categories, scripts, and blocks (I personally have only read about it, I never used it).
With this plugin it should be possible to use Unicode categories like \p{P} as explained at regular-expressions.info.
Update:
OK, I tested it, and it seems to work fine.
You need to get the lib from XRegExp and additionally the Unicode Base and Unicode Category plugins (linked above).
<script src="xregexp.js"></script>
<script src="addons/unicode-base.js"></script>
<script src="addons/unicode-categories.js"></script>
<script>
var unicodePunctuation = XRegExp("^\\p{P}+$");
alert(unicodePunctuation.test("?.,;!¡¿。、·")); // true
</script>
The above alerts true. I included some Spanish and Chinese punctuation in my test string, "?.,;!¡¿。、·".
A: From ES 2018, Unicode property escapes are supported. You can use \p{Punctuation} or just \p{P} (the same as the XRegExp answer) to match any punctuation character (by the Unicode definition), or \P{Punctuation} to match any non-punctuation character.
If you want to match any "non-word" character, like a Unicode version of \W, you can try something like:
[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}]
(as recommended in the proposal for the feature). You might want to remove \p{Connector_Punctuation}, since that includes underscores and similar.
Don't forget to add the u flag to your regular expression to make it Unicode-aware and enable this feature.
A: Well... idk how extensive it would be, but you could use this:
[^\w\s\n\t]
A: Your regex would look something like...
/[,!@#$%^&*()\u9999]/
Where you replace each \u9999 with the Unicode codepoint for the other punctuation characters.
If you could find a bunch in a range, you could specify that with the - range operand, e.g. \u9990-\u9999.
As far as I know you can't use something like \pP in JavaScript regexes.
A: For Python this regex to remove from the start and end any type of punctuation marks:
import re
def cleanspecialcharacters(str):
regex = re.compile((
'^[/\"_\(\)&*\$¥\^\+=`~<>\{\}\[\]\|\-!#%\,\:;@¡§«¶·»¿;·՚-՟։֊؉،॥॰෴๏๚๛༄-༒༔༺-༽྅჻፠-፨᐀᙭᙮។-៖៘-៚‧‰-⁃⁅-⁑⁓-⁞⁽⁾₍₎、〃〈-【】〔-〟〰〽゠・﴾﴿︐-︙︰-﹒﹔-﹡﹣﹨﹪﹫!-#%-*,-/:;?@[-]_{}⦅-・〔〕《》]*|'
'([/\"_\(\)&*\$¥\^\+=`~<>\{\}\[\]\|\-!#%\,\:;@¡§«¶·»¿;·՚-՟։֊؉،॥॰෴๏๚๛༄-༒༔༺-༽྅჻፠-፨᐀᙭᙮។-៖៘-៚‧‰-⁃⁅-⁑⁓-⁞⁽⁾₍₎、〃〈-【】〔-〟〰〽゠・﴾﴿︐-︙︰-﹒﹔-﹡﹣﹨﹪﹫!-#%-*,-/:;?@[-]_{}⦅-・〔〕《》])*$'))
str = regex.sub('', str)
return str
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Excel 2010 index match VBA Tried everything and can't seem to get this. Trying to replace values in Row B (SiteTag) of one worksheet with the proper sitetag from an index match in another worksheet.
Worksheet(Site_Visit)
SiteTag
AL27
AS26
GBEM4
...
Worksheet(Sites)
SiteTag Project Name
203AL27 AL27
203AS26 AS26
201GBEM4 GBEM4
... ...
I need to replace the values SiteTag in Sheets("Site_Visit") with the appropriate SiteTag from Sheets("Sites").
For now I've simply tried to get the code to place the correct index value into a variable in which I'll place as the value for each cell, and run it in a loop. But for the life of me can't get it to get a value. This is what I've tried for the variable (everything has been declared).
ST_Cells2 = Application.WorksheetFunction.Index("Sites!A2:A34", Application.WorksheetFunction.Match("Site_Visit!B2", "Sites!B2:B34", 0), 0)
Where "Sites!A2:A34" is the range for the appropriate replacement value
"Sites_Visit!B2" is the lookup value
"Sites!B2:B34" is the lookup range
I'm getting a Run Time error '1004' Unable to get the Match property of the WroksheetFunction class. Anyone have any ideas?
A: The Index and Match functions are expecting Ranges, but you are sending them strings. The easiest way to turn strings into Ranges is to use Excel's Range function:
st_cells2 = Application.WorksheetFunction.Index(Range("Sites!A2:A34"), Application.WorksheetFunction.Match(Range("Site_Visit!B2"), Range("Sites!B2:B34"), 0), 0)
A: I had the same error, but it run ok when I changed to "Application" indstead of WorksheetFunction:
Cells(12, 12).Value = Application.Index("Sheet1!B1:9", 2)
Somehow running the Function from Application directly worked...
/K
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Does pointer arithmetic have uses outside of arrays? I think I understand the semantics of pointer arithmetic fairly well, but I only ever see examples when dealing with arrays. Does it have any other uses that can't be achieved by less opaque means? I'm sure you could find a way with clever casting to use it to access members of a struct, but I'm not sure why you'd bother. I'm mostly interested in C, but I'll tag with C++ because the answer probably applies there too.
Edit, based on answers received so far: I know pointers can be used in many non-array contexts. I'm specifically wondering about arithmetic on pointers, e.g. incrementing, taking a difference, etc.
A: From the top of my head I know it's used in XOR linked-lists (very nifty) and I've seen it used in very hacky recursions.
On the other hand, it's very hard to find uses since according to the standard pointer arithmic is only defined if within the bounds of an array.
A: a[n] is "just" syntactic sugar for *(a + n). For lulz, try the following
int a[2];
0[a] = 10;
1[a] = 20;
So one could argue that indexing and pointer arithmetic are merely interchangeable syntax.
A: Pointer arithmetic by definition in C happens only on arrays. However, as every object has a representation consisting of an overlaid unsigned char [sizeof object] array, it's also valid to perform pointer arithmetic on this representation. For example:
struct foo {
int a, b, c;
} bar;
/* Equivalent to: bar.c = 1; */
*(int *)((unsigned char *)&bar + offsetof(struct foo, c)) = 1;
Actually char * would work just as well.
A: If you follow the language standard to the letter, then pointer arithmetic is only defined when pointing to an array, and not in any other case.
A pointer may point to any element of an array, or one step past the end of the array.
A: Pointer arithmetic is only defined on arrays. Adding an integer to a pointer that does not point to an array element produces undefined behavior.
A: In embedded systems, pointers are used to represent addresses or locations. There may not be an array defined. (Although one could say that all of memory is one huge array.)
For example, a stack (holding variables and addresses) is manipulated by adding or subtracting values from the stack pointer. (In this case, the stack could be said to be an array based stack.)
A: Here's a case for pointer arithmetic outside of (strictly defined) arrays:
double d = 0.5;
unsigned char *bytes = (void *)&d;
for(size_t i = 0; i < sizeof d; i++)
printf("Byte %zu of d is %hhu\n", i, bytes[i]);
Why would you do this? I don't know. But if you want to look at the bitwise representation of an object (useful for things like memcpy and memcmp), you'll need to cast their addresses to unsigned char *s (or signed char *s if you like) and work with them byte-by-byte. (If your task isn't too difficult you can even write the code to work word-by-word, which most memcpy implementations will do. It's the same principle, though, just replace char with int32_t.)
Note that, in the standard, the exact values (or the number of values) that are printed are implementation-defined, but that this will always work as a way to access an object's internal bytewise representation. (It is not required to work for larger integer types, but almost always will - no processor I know of has had trap representations for integers in quite some time).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Is there a way to list the groups of a user who is a contact of the authenticated user on LinkedIn? The LinkedIn API documentation has confused me. It says that it is possible to list the groups of a user (not the logged in user, but any contact of the user) by providing the person-id.
The url shows this as an example:
To Get the Group of the Logged In User:
http://api.linkedin.com/v1/people/~/group-memberships:(group:(id,name,counts-by-category))?membership-state=member
I've tried the following
http://api.linkedin.com/v1/people/person-id=abcde/group-memberships:(group:(id,name,counts-by-category))?membership-state=member
http://api.linkedin.com/v1/people/abcde/group-memberships:(group:(id,name,counts-by-category))?membership-state=member
http://api.linkedin.com/v1/people/~/group-memberships:(group:(id,name,counts-by-category))?membership-state=member&person-id=abcde
None of them work. Where should I put the person-id? It's driving me bananas.
A: Turns out that the LinkedIn Groups API doesn't support retrieval of groups for anybody else except the logged in user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenCV hand recognition? After spending on a while on this, I finally managed to detect the hands through thresholding. The only problem is that VERY FEW pixels in the background remain, which will mess up the next step. Any suggestions on how to get rid of the few background pixels? Because I don't want to go through the whole background subtraction thing for just a few pixels. Background Subtraction is not an option for the program, so please don't suggest it
Thanks
A: It's hard to be sure without a more detailed description of your hand detection algorithm. If you have a few background pixels that are isolated from the hands you have detected, I would suggest morphological operation like opening to eliminate single pixel detections in your binary mask. In openCV, I think you need to erode and then dilate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C++ auto keyword. Why is it magic? From all the material I used to learn C++, auto has always been a weird storage duration specifier that didn't serve any purpose. But just recently, I encountered code that used it as a type name in and of itself. Out of curiosity I tried it, and it assumes the type of whatever I happen to assign to it!
Suddenly STL iterators and, well, anything at all that uses templates is 10 fold easier to write. It feels like I'm using a 'fun' language like Python.
Where has this keyword been my whole life? Will you dash my dreams by saying it's exclusive to visual studio or not portable?
A: The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.
It can be very useful when we have to use the iterator. For e.g. for below code we can simply use the "auto" instead of writing the whole iterator syntax .
int main()
{
// Initialize set
set<int> s;
s.insert(1);
s.insert(4);
s.insert(2);
s.insert(5);
s.insert(3);
// iterator pointing to
// position where 2 is
auto pos = s.find(3);
// prints the set elements
cout << "The set elements after 3 are: ";
for (auto it = pos; it != s.end(); it++)
cout << *it << " ";
return 0;
}
This is how we can use "auto" keyword
A: It's not going anywhere ... it's a new standard C++ feature in the implementation of C++11. That being said, while it's a wonderful tool for simplifying object declarations as well as cleaning up the syntax for certain call-paradigms (i.e., range-based for-loops), don't over-use/abuse it :-)
A: It's just taking a generally useless keyword and giving it a new, better functionality. It's standard in C++11, and most C++ compilers with even some C++11 support will support it.
A: For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).
Syntax
auto variable initializer (1) (since C++11)
auto function -> return type (2) (since C++11)
auto function (3) (since C++14)
decltype(auto) variable initializer (4) (since C++14)
decltype(auto) function (5) (since C++14)
auto :: (6) (concepts TS)
cv(optional) auto ref(optional) parameter (7) (since C++14)
Explanation
*
*When declaring variables in block scope, in namespace scope, in initialization statements of for loops, etc., the keyword auto may be used as the type specifier.
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). The keyword auto may be accompanied by modifiers, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u) if the function call f(expr) was compiled. Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop.
If auto is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0; is ill-formed, while the declaration auto i = 0, *p = &i; is well-formed and the auto is deduced as int.
*In a function declaration that uses the trailing return type syntax, the keyword auto does not perform automatic type detection. It only serves as a part of the syntax.
*In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.
*If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.
*If the return type of the function is declared decltype(auto), the keyword auto is replaced with the operand of its return statement, and the actual return type is deduced using the rules for decltype.
*A nested-name-specifier of the form auto:: is a placeholder that is replaced by a class or enumeration type following the rules for constrained type placeholder deduction.
*A parameter declaration in a lambda expression. (since C++14) A function parameter declaration. (concepts TS)
Notes
Until C++11, auto had the semantic of a storage duration specifier.
Mixing auto variables and functions in one declaration, as in auto f() -> int, i = 0; is not allowed.
For more info : http://en.cppreference.com/w/cpp/language/auto
A: auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used because there were only two possible conditions: either it wasn't allowed, or else it was assumed by default.
The use of auto to mean a deduced type was new with C++11.
At the same time, auto x = initializer deduces the type of x from the type of initializer the same way as template type deduction works for function templates. Consider a function template like this:
template<class T>
int whatever(T t) {
// point A
};
At point A, a type has been assigned to T based on the value passed for the parameter to whatever. When you do auto x = initializer;, the same type deduction is used to determine the type for x from the type of initializer that's used to initialize it.
This means that most of the type deduction mechanics a compiler needs to implement auto were already present and used for templates on any compiler that even sort of attempted to implement C++98/03. As such, adding support for auto was apparently fairly easy for essentially all the compiler teams--it was added quite quickly, and there seem to have been few bugs related to it either.
When this answer was originally written (in 2011, before the ink was dry on the C++ 11 standard) auto was already quite portable. Nowadays, it's thoroughly portable among all the mainstream compilers. The only obvious reasons to avoid it would be if you need to write code that's compatible with a C compiler, or you have a specific need to target some niche compiler that you know doesn't support it (e.g., a few people still write code for MS-DOS using compilers from Borland, Watcom, etc., that haven't seen significant upgrades in decades). If you're using a reasonably current version of any of the mainstream compilers, there's no reason to avoid it at all though.
More recent revisions of the standard have added a few new places that auto can be used. Starting with C++14, you can use auto for the type of a parameter to a lambda:
[](auto s) { return s + 1; }
This does essentially the same thing as the example above--even though it doesn't explicitly use template syntax, this is basically a template that deduces the type of the parameter, and instantiates the template over that type.
That was convenient and useful enough that in C++20, the same capability was added for normal functions, not just lambdas.
But, just as before all of this really comes down to using the same basic type deduction mechanism as we've had for function templates since C++98. auto allows that to be used in more places, and more conveniently, but the underlying heavy lifting remains the same.
A: This functionality hasn't been there your whole life. It's been supported in Visual Studio since the 2010 version. It's a new C++11 feature, so it's not exclusive to Visual Studio and is/will be portable. Most compilers support it already.
A: The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).
There are 3 different rules regarding the auto keyword.
First Rule
auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.
int y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)
const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)
int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)
const int a[10] = {};
auto x = a; // x is const int *. (Array to pointer conversion)
Note : When the name defined by auto is given a value with the name of a function,
the type inference will be done as a function pointer.
Second Rule
auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.
Warning : const is not ignored in this rule !!! .
int y = 10;
auto& x = y; // The type of variable x is int&.
Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.
auto& x = "hello"; // The type of variable x is const char [6].
static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier
// The type of variable x is int.
Third Rule
auto&& z = expr; ----> This is not a Rvalue reference.
Warning : If the type inference is in question and the && token is used, the names
introduced like this are called "Forwarding Reference" (also called Universal Reference).
auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression.
auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression.
A: It's Magic is it's ability to reduce having to write code for every Variable Type passed into specific functions. Consider a Python similar print() function in it's C base.
#include <iostream>
#include <string>
#include <array>
using namespace std;
void print(auto arg) {
cout<<arg<<" ";
}
int main()
{
string f = "String";//tok assigned
int x = 998;
double a = 4.785;
string b = "C++ Auto !";
//In an opt-code ASCII token stream would be iterated from tok's as:
print(a);
print(b);
print(x);
print(f);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "206"
}
|
Q: Array of numbers inside a JTextField - Java I'm trying to make a JTextField receive an array of numbers. I tryed with "for" and all the stuff needed to run an array, but without succes. Here is the piece of code.
private void cbxGeraValorActionPerformed(java.awt.event.ActionEvent evt)
{
if(cbxRandom.isSelected())
{
double[] num = new double[10];
for(int i=0; i<10; i++)
{
Random r = new Random();
num[i] = r.rnd;
txtValor.setText(String.valueOf(num[i]));
}
}
A: if(cbxRandom.isSelected())
{
double[] num = new double[10];
String newtxt = "";
for(int i=0; i<10; i++)
{
Random r = new Random();
num[i] = r.rnd;
newtxt += String.valueOf(num[i]);
}
txtValor.setText(newtxt); //do setting only after the loop ends
}
A: if(cbxRandom.isSelected())
{
double[] num = new double[10];
String newtxt = "";
for(int i=0; i<10; i++)
{
Random r = new Random();
num[i] = r.rnd;
newtxt += String.valueOf(num[i]) + " "; // Separate numbers
}
txtValor.setText(newtxt); //do setting only after the loop ends
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Getting a Python Modules Dierctory from Inside Itself I have a Python module and I'd like to get that modules directory from inside itself. I want to do this because I have some files that I'd like to reference relative to the module.
A: First you need to get a reference to the module inside itself.
mod = sys.__modules__[__name__]
Then you can use __file__ to get to the module file.
mod.__file__
Its directory is a dirname of that.
A: As you are inside the module all you need is this:
import os
path_to_this_module = os.path.dirname(__file__)
However, if the module in question is actually your programs entry point, then __file__ will only be the name of the file and you'll need to expand the path:
import os
path_to_this_module = os.path.dirname(os.path.abspath(__file__))
A: I think this is what you are looking for:
import <module>
import os
print os.path.dirname(<module>.__file__)
A: You should be using pkg_resources for this, the resource* family of functions do just about everything you need without having to muck about with the filesystem.
import pkg_resources
data = pkg_resources.resource_string(__name__, "some_file")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c double pointer giving error that doesn't make sense int p_entity(char **data){
char *pch;
pch = strtok(*data, " \n");
// printf("%s ", pch);
pch = strtok(NULL, " \n");
// (*data) = (*data) + 1; // 1. this is okay
// (*data) = pch; // 2. but doing this will cause an error
printf("%c %d \n", *pch, pch);
printf("%c %d \n", **data, *data);
}
From the above code I will get the following if I uncomment 1:
g 4927479
e 4927456
I will get the following if I uncomment 2:
g 4927479
g 4927479
3 [main] main 8172 exception::handle: Exception: STATUS_ACCESS_VIOLATION
470 [main] main 8172 open_stackdumpfile: Dumping stack trace to main.exe.stackdump
Can anyone explain why I am getting that error? I would think both assignments would be legal and incrementing (*data) would be equivalent to straight assignning the address I want it to be at.
A: Seems like even when you get the error (and uncomment 2), you still get the two printfs... seems like it is crashing much later in your code.
A: Answer really depends on how you are handling data before and after calling this function.
if you are allocating memory to *data before calling this function and tying to free it after this function returns, it could crash, as you have changed its value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Load various images at same time from the internet objective-c I'm trying to load 5 images at the same time,for them put it on the view and change the image every 5 sec(change between the current 5)
I create the current a class wich is called when the viewdidload and starts the timer,the method to load all images is this:
-(NSMutableArray *)getAllPhotos
{
NSMutableArray * photosArray = [[NSMutableArray alloc]init];
NSString * pic0 = [NSString stringWithFormat:@"http://74.53.32.202/~ltashiro/public/Servidor/Images/0.png"];
NSString * pic1 = [NSString stringWithFormat:@"http://74.53.32.202/~ltashiro/public/Servidor/Images/1.png"];
NSString * pic2 = [NSString stringWithFormat:@"http://74.53.32.202/~ltashiro/public/Servidor/Images/2.png"];
NSString * pic3 = [NSString stringWithFormat:@"http://74.53.32.202/~ltashiro/public/Servidor/Images/3.png"];
NSURL *image0 = [NSURL URLWithString:pic0];
NSURL * image1 = [NSURL URLWithString:pic1];
NSURL * image2 = [NSURL URLWithString:pic2];
NSURL * image3 = [NSURL URLWithString:pic3];
NSMutableArray * arrayURL = [[NSMutableArray alloc]init];
[arrayURL addObject:image0];
[arrayURL addObject:image1];
[arrayURL addObject:image2];
[arrayURL addObject:image3];
for (int i = 0; i<4; i++)
{
NSData * imageData = [[NSData alloc]initWithContentsOfURL:[arrayURL objectAtIndex:i]];
Photo * aPhoto = [[Photo alloc]init];
aPhoto.photoID = (i+1);
aPhoto.photo = [[UIImage alloc]initWithData:imageData];
[photosArray addObject:aPhoto];
[aPhoto release];
[imageData release];
}
return photosArray;
}
But sometimes the appcrashs on launch,theres any other solution abordation to it?
A: I was searching for the problem posted here. I found a solution here:
http://www.switchonthecode.com/tutorials/loading-images-asynchronously-on-iphone-using-nsinvocationoperation
Didn't test it yet though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to update SystemName from Get-WmiObject or update data table I need to override SystemName from Get-WmiObject:
Function Get-VolumeSpace ([string]$ServerName="localhost") {
$wql="Select SystemName, Name, Capacity, FreeSpace From Win32_Volume Where (DriveType=2 or DriveType=3) and name like '[a-z]%'"
$volSpace=Get-WmiObject -ComputerName $ServerName -Query $wql
$volSpace | Select SystemName, Name, Capacity, FreeSpace}
On a SQL cluster, SystemName contains the physical node name and not the virtual name that I passed into Get-VolumeSpace. I need it to be the name that I passed in and not the actual physical node name.
If I can override SystemName from within my Get-VolumeSpace function, that would be good. Alternatively, I can just update the data table. So I have put the output into a data table using Out-DataTable function that I found on the web:
$dataTable = Get-VolumeSpace $ServerName | Out-DataTable
Can someone either help me override SystemName with $ServerName in Get-VolumeSpace OR help me update the first column in every row to $ServerName in $dataTable?
A: If I understood what you are asking, the following should work:
$volSpace | Select @{expression ={$ServerName};label="SystemName"}, Name, Capacity, FreeSpace
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generating Unique Numeric IDs using DateTime.Now.Ticks I need to generate a unique numeric ID to attach to an incoming request. This ID is used only temporarily to track the request and will be discarded once the request has completed processing. This ID will only be used in the context of this application but will need to be assigned in a high performance multi-threaded way.
I was thinking of using DateTime.Now.Ticks for this ID but would like to know if DateTime.Now.Ticks could still generate a colliding ID if simultaneous requests are being concurrently being processed?
If anyone could suggest a better way to generate these IDs (preferably one that is not Int64 like Tick is) in a multi-threaded environment, please let me know. Something as simple as an incrementing number would suffice even, if only I didn't have to lock the number before incrementing.
A: DateTime.Now is absolutely terrible for this purpose. At best, you'll have a resolution of 1 millisecond; at worst, 17 ms on NT and 1 second (!) on CE/Compact Framework.
Consider using Interlocked.Increment method for a fast, thread-safe counter.
A: Start with a per-thread ID (if multiple threads are originating the requests), concatenated with a per-thread counter (if each thread is expected to originate more than one request).
A: Just get a strong random number or use a GUID
*
*http://www.codeproject.com/KB/security/CryptoPasswordGenerator.aspx
*http://msdn.microsoft.com/en-us/library/system.random.aspx
*http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
If high performance is the MUST have feature, allocate sequential numbers in monotonous sequence. Prevent lock contention by 'reserving' a range of (say, 20-100) ID's per thread that handles messages. That way, you'll need to lock the sequence generator only once in 20-100 iterations.
A: You just need to use a static variable that is incremented each time you want another unique value. You can make this thread safe and still very fast by using the Interlocked.Increment method...
// Declaration
private static int safeInstanceCount = 0;
// Usage
{
...
Interlocked.Increment(ref safeInstanceCount);
...
}
A: If you know how many threads you're going to have (or at least an upper bound), you can divide your ID space up between your threads, computing the ID as the value of a (thread local) counter and the thread's ID - eg, counter_value++ << 8 | thread_id. Thus, no coordination or locking between threads is required, and generating an ID requires only an increment, a bitshift, and an or.
If you use the system thread ID for this, your IDs will be slightly longer, but you don't need to manually assign IDs to your threads.
A: Can use this property but pay 1ms which is not important!
public static long UniqId {
get {
Thread.Sleep(1);
return long.Parse(DateTime.Now.ToString("yyMMddHHmmssffff"));
}
}
A: I am using a simple generation Id based on time,It might help.
private static readonly string prefixNumber = ConfigManager.Current.GetAppSetting("AppTimeIdPrefix", "");
private static readonly DateTime epoch = DateTime.SpecifyKind(DateTime.Parse(ConfigManager.Current.GetAppSetting("AppTimeIdEpoch", "1970/01/01")), DateTimeKind.Utc);
/// <summary>
/// DateTime.Now is only updated every 10-15ms.
/// </summary>
private static long lastTime = CurrentTimeMilliseconds();
private static readonly object timeLock = new object();
private static long CurrentTimeMilliseconds()
{
return (long)(DateTime.UtcNow.ToUniversalTime() - epoch).TotalMilliseconds;
}
public static long CreateId()
{
lock (timeLock)
{ // prevent concurrent access to ensure uniqueness
long original, newValue;
do
{
original = lastTime;
newValue = Math.Max(CurrentTimeMilliseconds(), original + 1);
} while (Interlocked.CompareExchange(ref lastTime, newValue, original) != original);
return long.Parse(string.Format("{0}{1}", prefixNumber, newValue));
}
}
refer to How to ensure a timestamp is always unique?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: hadoop-streaming example failed to run - Type mismatch in key from map I was running $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \
-D stream.map.output.field.separator=. \
-D stream.num.map.output.key.fields=4 \
-input myInputDirs \
-output myOutputDir \
-mapper org.apache.hadoop.mapred.lib.IdentityMapper \
-reducer org.apache.hadoop.mapred.lib.IdentityReducer
What hould be the input file when IdentityMapper is the mapper?
I was hoping to see it can sort on certain selected keys and not the entire keys. My input file is simple
"aa bb".
"cc dd"
Not sure what did I miss? I always get this error
java.lang.Exception: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, recieved org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:371)
Caused by: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, recieved org.apache.hadoop.io.LongWritable
A: This is a known bug and here is the JIRA. The bug has been identified in Hadoop 0.21.0, but I don't think it's in any of the Hadoop release version. If you are really interested to fix this, you can
*
*download the source code for Hadoop (for the release you are working)
*download the patch from JIRA and apply it
*build and test Hadoop
Here are the instructions on how to apply a patch.
Or instead of using an IdentityMapper and the IdentityReducder, use a python/perl scripts which will read the k/v pairs from STDIN and then write the same k/v pairs to the STDOUT without any processing. It's like creating your own IdentityMapper and the IdentityReducder not using Java.
A: I was trying my hands on Hadoop with my own example, but got the same error. I used KeyValueTextInputFormat to resolve the issue. You can have a look at following blog for the same.
http://sanketraut.blogspot.in/2012/06/hadoop-example-setting-up-hadoop-on.html
Hope it helps you.
Peace.
Sanket Raut
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ASP.NET grid with auto-paging,sortable,searchable... GridView? ListView? I need to build a <table> to display Products. I am not very familiar with GridView or ListView, not sure if they can do these below.
The requirements:
*
*Automatic paging. Fetch only 100 records at a time (not the whole 1000000 records when it first loads)
*Sortable. I need to be able to specify the default sort order, but user can also click on the header
*Searchable. User needs to be able to filter the data they want to see.
*I (the programmer) need to be able to easily turn off/on columns (Ideally I only need to comment out one line to hide a column)
*Data will be from SQL Server, multiple tables
Does anyone know any ASP.NET control that can do all the above? Thanks in advance!
A: Both GridView and ListView can do paging if you put a DataPager in them. ListView is a templated control - the display is completely customised so you have to roll your own "columns"; don't have much use for GridView so I don't know about that one.
As for searching and sorting, there's some sort of builtin support for it that becomes useless if you need a data source ASP.NET can't query directly - an ObjectDataSource lets you create your own data access code, but you also have to implement everything that can't be done automatically.
For searching, you can handle the ODS's Selecting event, you can pass arbitrary parameters to the query method; I believe there's also some way to automagically get control values / query string parameters etc.
For sorting, ListView lets you add Buttons where CommandName="Sort" and CommandArgument="[column to sort by]". When using a non-custom data source, I believe they will Just Work. When using an ObjectDataSource, all they do is make the ListView keep track of a "sort expression" that you can pass into your data source in the ODS.Selecting event. The format of the sort expression is specified… somewhere I can never find when I need it. When using single-column sorting, this will be either "[column name]" for an ascending sort, or "[column name] DESC" for a descending one. You can pass this directly to ObjectQuery.OrderBy; EntityFramework.Extended also provides that extension method for the new API surface. ListView (I believe) only handles single column sorting, for multiple-column sorting you have to manage the sort expression yourself anyway.
The documentation for all this is scattered, a good starting point is this tutorial, its followups, and the links for ListView you can find in the sidebar to the left.
My project also has a reasonably simple use of a ListView in combination with an ObjectDataSource – meaning, no part of it relies on magic RAD features, that follows below. I extracted it from my actual project, so it might have minor inconsistencies.
ListView+ObjectDataSource Example
The following example retrieves "messages" (think news announcements on a company portal) from a WCF service (not included).
MessagesDataSource.cs
An ObjectDataSource delegate that calls a WCF service. The data source is responsible for:
*
*filtering based on the username and type parameters
*sorting based on the sort expression in the sort parameter
*paging as specified by the skip and take parameters - named to be consistent with the LINQ operators
Because we're using an ObjectDataSource, all of this has be implemented in the delegate – this is where the service is ultimately called.
public enum MessageType
{
None = 0,
All,
General,
OfficeHoursUpdate,
// …
}
[DataObject]
public class MessagesDataSource : IDisposable
{
IMessagesService _svc = new MessagesServiceClient();
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<Message> Select(string username, MessageType type, string sort, int skip, int take)
{
return _svc.GetMessages(username, type, sort, skip, take);
}
public int SelectCount(string username, MessageType type, string sort, int skip, int take)
{
return _svc.CountMessages(username, type);
}
}
Messages.ascx
Renders a list of messages as a table with one <tbody> per message, with one row split into columns for the message "headers", and a second row with all columns merged for the message body. Points to note:
*
*When a value is selected in the dropdown list, the ListView is refreshed starting with the first page.
*All the parameters the MessageDataSource.Select() and .SelectCount() methods take should be declared in the ODS's <SelectParameters>. (Visual Studio will show an error if they don't match.)
*The TypeName attribute of the ObjectDataSource control indicates the ODS delegate that gets instantiated by the ODS. For more control over this, handle the ObjectCreating / ObjectCreated events of the ODS. (For instance, you can pass the containing control to the ODS delegate.)
*The values for the parameters named by the StartRowIndexParameterName and MaximumRowsParameterName attributes will be provided automatically by the data pager.
*I don't believe the value for the SortParameterName parameter is filled in by the ListView when using an ObjectDataSource - it might or might not be when using a GridView. I also don't think it's necessary in this case but then again it's not hurting anybody to keep it there.
*I omitted the data pager fields, they're just clutter here.
*The CommandArgument values of the sorting LinkButtons in the header don't have to match up the properties of the data objects and can in fact be completely arbitrary.
<asp:Label ID="lblType" runat="server" AssociatedControlID="ddlType" Text="Message Type:"/>
<asp:DropDownList runat="server" ID="ddlType" AutoPostBack="true"
OnSelectedIndexChanged="ddlType_SelectedIndexChanged"
OnLoad="ddlType_Load" />
<table>
<asp:ListView ID="lvMessages" runat="server" DataSourceID="dsMessages" ItemPlaceholderID="message">
<LayoutTemplate>
<thead>
<tr>
<th>
<asp:LinkButton runat="server" Text='Timestamp'
CommandName="Sort" CommandArgument="Timestamp" />
<asp:Literal ID="lvMessages__Timestamp" runat="server"
OnPreRender="UpdateSortIndicator" />
</th>
<th>
Sender
</th>
<th>
<asp:LinkButton runat="server" Text='Subject'
CommandName="Sort" CommandArgument="Subject" />
<asp:Literal ID="lvMessages__Subject" runat="server"
OnPreRender="UpdateSortIndicator" />
</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3">
<asp:DataPager ID="dpMessages" runat="server"
PageSize="10" PagedControlID="lvMessages"
OnInit="dpMessages_Init">
<Fields>
<%-- Data Pager Fields --%>
</Fields>
</asp:DataPager>
</td>
</tr>
</tfoot>
<%--
The following tag gets replaced with the rendered contents of
ItemTemplate for each data item
--%>
<tbody runat="server" id="message" />
</LayoutTemplate>
<ItemTemplate>
<tbody>
<tr>
<td>
<%# Eval("Timestamp") %>
</td>
<td>
<%# Eval("Sender") %>
</td>
<td>
<%# Eval("Subject") %>
</td>
</tr>
<tr>
<td colspan="3">
<%# Eval("Body") %>
</td>
</tr>
</tbody>
</ItemTemplate>
<EmptyDataTemplate>
No messages loaded!
</EmptyDataTemplate>
</asp:ListView>
</table>
<asp:ObjectDataSource ID="dsMessages" runat="server" TypeName="Foo.MessagesDataSource"
DataObjectTypeName="Foo.Message" SelectMethod="Select"
SelectCountMethod="SelectCount" StartRowIndexParameterName="skip" MaximumRowsParameterName="take"
OnSelecting="dsMessages_Selecting" EnablePaging="true" SortParameterName="sort">
<SelectParameters>
<asp:Parameter Name="username" />
<asp:Parameter Name="scope" />
<asp:Parameter Name="sort" />
<asp:Parameter Name="skip" />
<asp:Parameter Name="take" />
</SelectParameters>
</asp:ObjectDataSource>
Messages.ascx.cs
This class is reasonably straightforward and deals mostly with initialising the page and tangential issues like sort indicators. Most of the "interesting" bits have had comments added to them.
public partial class Messages : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Initialise the dropdown list values
var types = Enum.GetValues(typeof(MessageType));
types.Remove(MessageType.None);
foreach (var t in types)
{
ddlType.Items.Add(new ListItem(t.ToString()));
}
// Default message filter and sort
Type = MessageType.All;
lvMessages.Sort("Timestamp", SortDirection.Descending);
}
}
private MessageType _type;
public MessageType Type
{
get { return _type; }
set
{
if (!_type.Equals(value))
{
ddlType.SelectedValue = value.ToString();
_type = value;
}
}
}
private static readonly IDictionary<SortDirection, string> SortIndicators =
new Dictionary<SortDirection, string>
{
{SortDirection.Ascending, "\u25b4"}, // upwards triangle
{SortDirection.Descending, "\u25be"} // downwards triangle
};
/// This is where you can programmatically add / change the values of
/// parameters that will get passed to MessagesDataSource.Select()
protected void dsMessages_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
// Add "filter" parameters that have to be determined programmatically.
e.InputParameters["username"] = GetUsernameLoggedIn();
e.InputParameters["type"] = Type;
}
/// When the message type changes, go back to the first page
protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
{
Type = (MessageType) ddlType.SelectedValue);
var pager = (DataPager)lvMessages.FindControl("dpMessages");
if (pager == null)
{
((IPageableItemContainer)lvMessages).SetPageProperties(0, 10, true);
}
else
{
pager.SetPageProperties(0, pager.PageSize, true);
}
}
/// Reload the value from the dropdown list.
protected void ddlType_Load(object sender, EventArgs e)
{
Type = (MessageType) ddlType.SelectedValue;
}
protected void UpdateSortIndicator(object sender, EventArgs e)
{
var indicator = (Literal) sender;
if (indicator.ID.EndsWith("__"+ lvMessages.SortExpression))
{
indicator.Text = SortIndicators[lvMessages.SortDirection];
}
else
{
indicator.Text = "";
}
}
}
Disclaimer: I don't claim to be an authority on the topic and am in fact fairly new to .NET. This just happens to be something I had to deal with recently and was also confused by the scattered documentation that tended to either take shortcuts with a part of the problem (i.e. either use GridView to get a complete view automatically, or use an ADO.NET data source instead of custom data access code); or spend too much space on fluff (e.g. screenshots of what button to click in which Visual Studio wizard.)
A: It's not free but Telerik's RadGrid is incredibly full-featured and either does 100% of what you need or else it will get you pretty darn close.
Telerik RadGrid: http://demos.telerik.com/aspnet-ajax/grid/examples/overview/defaultcs.aspx
A: if your data is going to be just displayed only not edited or updated you can go with a Data Repeater control. It is a very light weight control but then you may have write all the logic for the paging and sorting.It is good in a way so that you get fine grained control over your code..
Check this link for more details.ASP.net Repeater Control
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to add a list view to a tab in android? I know that a similar question has been asked before but it doesn't really fit what I was looking for. Here it goes. I am trying to populate a tab with a list view however all the examples lead to using Intent in .setContent(), which does not fit what I am trying to do. So, here is what I did:
try {
spec = tabHost.newTabSpec("ratingSort").setIndicator("TAB 1",
res.getDrawable(R.drawable.ic_tab_sort))
.setContent((TabContentFactory) new ArrayAdapter<String>(this, R.layout.list_item, ratingSort));
tabHost.addTab(spec);
} catch (Exception err) {
Log.e(err.toString(), "an error occurred...");
}
I put in try-catch clause because it causes a runtime error. Apparently the error is in .setContent(), with the cast: ERROR/java.lang.ClassCastException: android.widget.ArrayAdapter(31530).
Here is the xml file:
<resources>
<string-array name="rating_array">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<item>Item 4</item>
<item>Item 5</item>
</string-array>
</resources>
Any ideas, help is greatly appreciated.
A: You cannot cast an ArrayAdapter to a TabContentFactory, any more than you can cast a HashMap to a Double.
If you want a ListView in a tab, either:
*
*Put the ListView as a child of the FrameLayout in the layout file, then use the version of setContent() that takes a widget ID, or
*Create an actual TabContentFactory implementation that, in createTabContent(), returns a newly-constructed ListView widget
In either case, you can call setAdapter() on your ListView to supply it with the ArrayAdapter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ada - strange error - consistent version of gcc/gnatbind i'm trying to compile an Ada project.
I installed the current 2011 GNAT GPL package from Libre AdaCore, it contains the gcc compiler too.
The strange error is the following
fatal error: file dom.ali is incorrectly formatted
make sure you are using consistent versions of gcc/gnatbind
if i type which gcc it gives me /usr/gnat/bin/gcc
if i type which gnatbind it gives me /usr/gnat/bin/gnatbind
The content of "the incorrectly formatted" file is the following
V "GNAT Lib v2011"
A -gnat05
A -gnatA
P ZX
R nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnvnnnnnnnnnnnnnnnnnnn
U dom%s dom.ads 2bd88f63 NE OO PK IU
D dom.ads 20090519080656 2bd88f63
D system.ads 20110419093140 2d1a1afa
X 1 dom.ads
44K9*DOM 46l5 46e8
Any clue?
Thank you in advance
Edit: gnatls -v shows the following (formatted for readability),
GNATLS GPL 2011 (20110419) Copyright (C) 1997-2011, Free Software Foundation, Inc.
Source Search Path: <Current_Directory>
/usr/gnat/lib/gcc/i686-pc-linux-gnu/4.5.3/adainclude/
Object Search Path: <Current_Directory>
/usr/gnat/lib/gcc/i686-pc-linux-gnu/4.5.3/adalib/
Project Search Path: <Current_Directory>
/usr/gnat/i686-pc-linux-gnu/lib/gnat
/usr/gnat/share/gpr /usr/gnat/lib/gnat
A: All compilation units have to be compiled with exactly the same GNAT version and used library versions. If you use precompiled libraries, you might have to recompile them.
See the Debian Ada Policy part about ali files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Read java special character from a string in a file I am making a program that reads code from a java file and removes all the comments, but I am having some problems with special character since I am assuming everything inside the " is part of a string
For example I have written in the file:
String my_string= " \" "
The string doesn't end when it reaches the second \, so how do I detect the \" as if it was a single character
Another issue I have is for when I have something like this
String my_string= ' " '
If I am reading the character one by one, how do I exactly I know I have reached an ' obviously something like this if(char==' ' ') doesn't work
A: Use if(char=='\'')
And to detect escaped quotes, just put in a check for a backslash. If there is a backslash, do consider the next character to be a special character and not something to be parsed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iOS In App Purchases for Subscriptions and Consumables products As I understand, Store Kit API will handle storage and retrieval of history related to "Non-Consumables" products, while for "Consumables" and "Subscriptions" you have to have your own server/backend. What are the best hosted existing solutions for that kind of server (backend)? Inexpensive (or free? :-) and reliable?
Thanks!
A: There is not any service (that I know of) that includes the needed functionality by default. There is more here than just hosting the files. You need to use the included functionality to verify the receipt that is sent from the StoreKit API to your server (to ensure that it is a valid receipt):
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/VerifyingStoreReceipts/VerifyingStoreReceipts.html
So you would need to have a web application that managed this process as well as hosting the actual consumable content (in a way that made it inaccessible from the outside). You might want to look at a Java application hosted on a solution like Elastic Beanstalk with a connection to a protected Amazon S3 account.
If this is too complex, you could also create a simple PHP application that could be run from most any web server that could also do this functionality and manage access to the S3 account's files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to modify a contact number in address book programmatically? I am currently writing an app which should enable the user to modify the contact details (mainly numbers) in the app, and then these modifications should be reflected directly to the Address Book.
I searched thoroughly on the internet, but all the examples I found were either to load the contacts or add new contact, but nothing on modifying an existing contact.
also how can I get a list of all phone numbers of a single contact, in case he has several numbers stored.
A: To allow a user to edit their details directly, see Apple's documentation on displaying and editing a person record. The initial section of that says, "Set the delegate, which must adopt the ABPersonViewControllerDelegate protocol. To allow the user to edit the record, set allowsEditing to YES."
For example:
ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
personViewController.personViewDelegate = self;
personViewController.allowsEditing = YES;
Other than setting allowsEditing, the code would be exactly the same as that required to display a person's details without editing. (This code was drawn from this answer which displays a fuller example regarding deleting a contact from the address book.)
However, I see your title refers to doing so programatically. Apple's Address Book Programing Guide for iOS says, "Remember that the Address Book database is ultimately owned by the user, so applications must be careful not to make unexpected changes to it. Generally, changes should be initiated or confirmed by the user."
However, it is possible. The following example appears on p.17 of that document:
ABRecordRef aRecord = ABPersonCreate();
CFErrorRef anError = NULL;
bool didSet;
didSet = ABRecordSetValue(aRecord, kABPersonFirstNameProperty, CFSTR("Katie"), &anError);
if (!didSet) {/* Handle error here. */}
didSet = ABRecordSetValue(aRecord, kABPersonLastNameProperty, CFSTR("Bell"), &anError);
if (!didSet) {/* Handle error here. */}
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(aRecord, kABPersonLastNameProperty);
/* ... Do something with firstName and lastName. ... */
CFRelease(aRecord);
CFRelease(firstName);
CFRelease(lastName);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript interop assignment in Clojurescript Dumb question: how do I do Javascript assignment in Clojurescript ? I'm using a Javascript lib and need to set the value of an object's field like obj.this=that; - I don't know Javascript so maybe there's a .set method ?
A: Try some thing like
(set! (.-property foo) 5)
A: Use
(aset foo "property" 5)
Be aware, that symbolic references may fail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: jQuery UI Dialog - Input textbox in the titlebar is disabled? I'm placing a textbox in the titlebar of my jQuery UI dialog.
Unfortunately, it is disabled (or otherwise unclickable) when in the titlebar.
How can I change this so that my text box is enabled?
var $dialog = $('#dlgsearch')
.dialog({
autoOpen: false,
modal: true,
resizable: false,
draggable: false,
maxWidth:600,
maxHeight: 500,
width: 600,
height: 500,
title: 'Text Search:<input type="text" id="input_search" maxlength="255">'
});
});
A: It looks like the title bar's draggable attribute (even when set to false) is causing the issue of not being able to focus on the textbox. One way around this is to simply add the textbox after the title bar area as soon as the dialog opens and then position it back to the top with absolute coordinates like so:
title: 'Text Search: ',
open: function(event, ui) {
$('.ui-dialog-titlebar').after('<input type="text" id="input_search"
maxlength="255" style="position:absolute;top:13px;left:135px;">');
},
I set up an example here: http://jsfiddle.net/nemVr/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is my Animate alone broken? Using the Raphael.js I have made a circle and a path, all I wanted to do was make the circle animate alone the path, as if the center of the circle went along the line.
http://jsfiddle.net/rEJNJ/3/
Can anyone offer some advice
window.onload = function () {
var paper = Raphael("canvas", 640, 480);
var c = paper.circle(90, 90, 40);
c.attr({fill: "blue"});
var p = paper.path("M150,380 C150,360 50,250 220,90").attr({stroke: "#ff0000"});
c.animateAlong(p, 4000, true);
};
A: The animation works if you create your circle with the same X/Y coordinates as the beginning of the path:
http://jsfiddle.net/rEJNJ/4/
window.onload = function () {
var paper = Raphael("canvas", 640, 480);
var c = paper.circle(150, 380, 40).attr({fill: "blue"});
var p = paper.path("M150,380 C150,360 50,250 220,90").attr({stroke: "#ff0000"});
c.animateAlong(p, 4000, true);
};
Take a look at this post for some insight as to why: SVG animation along path with Raphael
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I provide the ServiceURI constructor parameter when instantiating a DomainContext declaratively? I am trying to use RIA in my Silverlight app to pull down data. The twist is that The URI for server side part of the RIA connection (WCF endpoint) is not on the same web server that served up the web page with the XAP on it.
I've seen that in code I can use the constructor for the DomainContext to specify a different ServiceURI as follows:
SomeDomainContext context = new SomeDomainContext(new Uri("http://blah.com/Something.svc"));
SomeGrid.DataContext = context.SomeObjects;
But, how do I do I specify this parameter when using the declarative syntax?
<riaControls:DomainDataSource AutoLoad="True" d:DesignData="{d:DesignInstance my:Project, CreateList=true}" Height="0" LoadedData="projectDomainDataSource_LoadedData" Name="projectDomainDataSource" QueryName="GetProjectsQuery" Width="0">
<riaControls:DomainDataSource.DomainContext>
<my:SomeDomainContext />
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Identifying a Specific Face in an Image Using OpenCV's HaarDetectObjects with haarcascade_frontalface_default.xml, I've found I can detect a face fairly reliably. However, is anyone aware of any libraries or methods for identifying a face (i.e. labeling it with a name)?
A: Check out PyVision. It's part of a research project out of Colorado State University but it's fairly mature. I've had good success using it, though I've never used the face-labeling parts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to stop/interrupt a servlet handler? If I have a long-running request handler, and the user hits the browser Stop button, how do I terminate the handler so it doesn't continue working? I'm thinking something simple like raising a thread interrupt based on the client connection state as checked from another watchdog thread (who's given the connections as they come in), but perhaps there are better solutions.
A: Another, simpler approach would be to make that long-running process asynchronous, using ExecutorService from java.util.concurrent. Return immediately and give the client a way to get the response when it's ready, a la Federal Express.
Servlets should never be executing processes, synch or asynch. They're for listening for HTTP requests, binding and validating input parameters, routing to the appropriate service to fulfill the request, and marshaling the response to the appropriate view.
A: If the user hits the Stop button you will never know about it other than as a connection reset. You don't get any opportunity to raise a thread interrupt: that would imply another communication from the browser to another thread in the server, which doesn't happen.
A: one way to handle to this is to implement the long work/req/proc separately and expose status flags to give status. options. Now call it from your servlet async. When a client presses STOP, come to servlet check the running status and interrupt if required and update user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is a simple 50 item list enough to justify using a ListView? In the Google I/O 2010 talk about ListView they say you might not need to use a ListView with a bounded and reasonable number of rows. They state if you are dealing with a reasonable number of rows it is possible to just lay them out in a ScrollView.
I'm curious what people find "reasonble length" means in practice.
Would a list of 50 items with each row's views just having a few strings be reasonable to layout without using a ListView? How about 12?
I'm used to using UITableViews on iPhone for most UI so I'm inclined to use ListViews on Android but I also want to be aware it might be overkill for some scenarios and I have a really limited understanding of perf on android presently.
A: ListView is really the best option for anything over 3 items, it is a good option for even 2 or 3 items. If not you'll end up writing a bunch of code that converts indexes to individual variables instead of arrays, database rows, or other data structure.
A: It's not only about the number of items but also about whether or not your data collection will be dynamically updated. If you know you will never update the list while it's on screen and it doesn't have many items then a LinearLayout will do just fine.
A:
In the Google I/O 2010 talk about ListView they say you might not need to use a ListView with a bounded and reasonable number of rows. They state if you are dealing with a reasonable number of rows it is possible to just lay them out in a ScrollView.
Hmmm, I can understand the logic up to a point but in reality using a ListActivity, for example, as your base class makes things very simple. OK, if you have a static list of only a dozen or so lines of text (one for each list 'item') then using a ScrollView containing TextViews would be an alternative but in reality using the adapter approach to ListViews is a lot more flexible in my opinion.
Would a list of 50 items with each row's views just having a few strings be reasonable to layout without using a ListView? How about 12?
No, if each list item has a few strings to be laid out then custom list item layouts together with a ListView and a custom adapter are basically a must.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I hide all columns in a treelistitem? I'm using the HyperTreeList to display a list of items with the name in the first column, and a "Remove" button in the second column. I wrote a function to filter what is displayed in the tree by some text in a TextCtrl. To hide the TreeListItems, I'm doing this:
treelist.HideItem(branch, True)
where treelist is a HyperTreeList and branch is a TreeListItem. The first column hides just fine, but none of the buttons in the second column hide. How do I get all columns in a TreeListItem to hide?
A: According to the docs, this should work:
treelist.SetColumnShown(column_index, False)
but this will hide that column for everything. If I understand what you're saying, the row you are trying to hide doesn't actually disappear, just the value of the first column. In that case, you might have to refresh the widget with treelist.Update() to get the rest of the row to disappear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java - my paint program needs a menu bar with a submenu with an image - how to do? SO I have this program that is kind of like paint, it lets you draw shapes and lines, but my assignment is to add a menu bar with a sub menu File-> About, when Click on the about section. It should pull up a panel or a frame or a something that has a image which I have already made.
However it's not working and I have never actually dealt with images before. All I have is from a Google search and that failed. I know the method is being called from the delightful system.out.println, and a box opens up but there is no picture!~ any help would be very nice.
if (e.getActionCommand().equals("About"))
{
System.out.println("stfu");
JFrame about = new JFrame("About");
about.setSize(300, 300);
BufferedImage img = null;
try{
img = ImageIO.read(new File("C:/Users/TehRobot/Desktop/Logo.png"));
}catch (IOException e1)
{
}
A: You'll want to ...
*
*Read in the Image with ImageIO.read(...)
*Put your Image into an ImageIcon via the ImageIcon constructor
*Put the ImageIcon into a JLabel via JLabel's setIcon(...) method.
*And display that JLabel in a dialog such as a JOptionPane (super easy to do) or a modal JDialog (a little more complicated, but not much).
In all this should just take a few lines of code, that's all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is passing NSString pointer not working for me? I am having troubles passing/receiving NSString pointers through function calls. I'm hoping someone can help me see what I'm doing incorrectly.
So this is from my first class...
void addTo(int pk, NSString* nam, NSString *descrip)
{
//open the database
sqlite3 *db;
db = [Item openDB:databasePath];
printf("'%i', '%s', '%s'", pk, nam, descrip);
//create new item with key, name, description, and database
Item *Obj = [[Item alloc]initWithPrimaryKey:pk:nam:descrip:db];
.
.
.
}
And then this is the function in Item.m called as above...
- (id) initWithPrimaryKey:(NSInteger) pk :(NSString*) nam: (NSString*) descrip: (sqlite3*) db{
printf("'%i', '%s', '%s'", pk, nam, descrip);
.
.
.
return self;
}
Let's say I call addTo with inputs 1234, "Tree", "plant with leaves"
The print in the first code block outputs what I sent to addTo but the print in initWithPrimaryKey prints the following...
'1234', 'P?a', 'P?a'
Why is this? Or more.. why is it not printing what I expect?
A: When printing in the NSLog the NSString should be %@ not %s
A: %s is used for char* strings, but %@ should be used with NSStrings. printf may or may not support %@, I don't know. If not, you need to use NSString's cStringUsingEncoding or UTF8String to convert to a char* that you can use.
initWithPrimaryKey:pk:nam:descrip:db is invalid (or at least very loopy) syntax, BTW, as is initWithPrimaryKey:(NSInteger) pk :(NSString*) nam: (NSString*) descrip: (sqlite3*) db.
It's important to understand the difference between an NSString and a char* string. The NSString is a full-fledged object, with about 50 methods that it supports to do all sorts of neat/strange/(and occasionally)obscene things with string values. The two are not in any way interchangeable. And unlike with some C++ libraries, you can't substitute a char* string for an NSString on a call and have automatic conversion occur.
So using "letters" for a string will not produce something usable as an NSString -- you must use @"letters".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Work around for iFrame cross domain policy? I have an iFrame and, understandably, I can't edit the elements.
Is there a work around for this, like using some sort of proxy? I would need it to work for any website and have things like sessions and cookie data persist (for logins etc).
Is it at all possible?
A: Nup, and you can't use CORS because it is only supported by XHR.
Same Origin Policy is going to stop you, and rightfully so.
If you could proxy the site through your own domain, protocol and port, it'd work, but that is often quite difficult.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Need a jQuery randomly selected identifier from options available I want to randomly select an id or value from one of the many option items in my select tag. Also I was wandering how do I quickly count all the option tags in my select tag, and how can I randomly call an ID field efficiently so if I hit refresh, it will just pick another random id? This is for a testing environment to auto fill a form out for qa people.
Examples
<select id="selectVendor">
<option value="55" selected="selected">Company A</option>
<option value="56">Company B</option>
<option value="57">Company XYZCYK</option>
... </select>
Finally I want to put the value of my selected id into my form field... Eventually I want to use ajax to populate my entire form with the randomly selected identifier when the page first loads. thx
<input type="text" id="txtCompany" value="empty" />
A: $("#txtCompany").val(
$("#selectVendor option").eq(
Math.floor(Math.random() * $("#selectVendor option").length + 1)
).val());
Live example here: http://jsfiddle.net/rkMYB/1/
A: $('#selectVendor option').size();
Will give you the options number.
var randomOption=Math.floor(Math.random()*$('#selectVendor option').size());
$("#selectVendor option[value='"+randomOption+"']").attr('selected', 'selected');
Will select a random option.
A: Here's an easy to read jsfiddle to get you going. http://jsfiddle.net/z5aHm/15/
Takes the number of options there are, generates a random number between 0 and the number of options, and grabs the value of the option at that index.
A: var options = $("#selectVendor > option");
var random = Math.floor(options.length * (Math.random() % 1));
options.attr('selected',false)
.eq(random).attr('selected',true);
Sample at jsfiddle is here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Inline if statement escapes HTML characters So I'm playing with Mako on Pyramid and I'm trying to do inline if statements.
<li>${'<a href="#">Opinions</a></li>' if whichnav == 'opinions' else 'Opinions'}
Outputs:
<li><a href="#">Opinions</a></li>
Whereas:
% if whichnav =='opinions':
<li><a href="#">Opinions</a></li>
% else:
<li>Opinions</li>
% endif
Outputs correctly without escaping the HTML characters:
<li><a href="#">Opinions</a></li>
I want to make my code as clean as possible so inline if statements are preferable, but I don't understand why HTML characters are escaped whereas using % they are not. Thanks!
A: Looks like your HTML is being escaped. What happens if you change your inline if to this:
${'<a href="#">Opinions</a></li>' if whichnav == 'opinions' else 'Opinions' | n}
(Edit: Put the | n to disable the filtering AFTER the conditional).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: viewDidLoad runs before instance variables are given values What I have is a advertisement Class that has an instance variable that will receive the banner url:
@interface Advertisement : UIViewController {
}
@property (nonatomic, retain) NSString *image;
Now, in my app delegate I am initializing the ad class and giving the instance variable "image" a value.
//setup the ad
Advertisement *theAdView = [[Advertisement alloc] init];
theAdView.view.frame = CGRectMake(0.0, self.window.frame.size.height-120.0, 320.0, 76.0);
theAdView.view.clipsToBounds = YES;
theAdView.view.tag = AD_TAG;
NSLog(@"Added the image");
theAdView.image = theAd.banner;
theAdView.nid = theAd.nid;
[self.window addSubview:theAdView.view];
[self.window bringSubviewToFront:theAdView.view];
In the advertisement class' viewDidLoad method I want the value of the "image." However I get a null value. So it looks like the class is initializing before it gets a chance to get the instance variables.
I think I found a solution before, but I can't remember exactly what. I believe it had something to do with setting another variable that does not use (nonatomic, retain)... I'm not sure.
A: a UIViewController will load it's view (from nib or call the loadview method if you've overriden it) when you attempt to access it's 'view' property. In your case, 1 easy result would be to move the lines
theAdView.image = theAd.banner;
theAdView.nid = theAd.nid;
to before anything that accesses the view property, like
theAdView.view.frame = CGRectMake(0.0, self.window.frame.size.height-120.0, 320.0, 76.0);
or a better one would be to accept the image and nid as properties in a new initializer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bash empty array expansion with `set -u` I'm writing a bash script which has set -u, and I have a problem with empty array expansion: bash appears to treat an empty array as an unset variable during expansion:
$ set -u
$ arr=()
$ echo "foo: '${arr[@]}'"
bash: arr[@]: unbound variable
(declare -a arr doesn't help either.)
A common solution to this is to use ${arr[@]-} instead, thus substituting an empty string instead of the ("undefined") empty array. However this is not a good solution, since now you can't discern between an array with a single empty string in it and an empty array. (@-expansion is special in bash, it expands "${arr[@]}" into "${arr[0]}" "${arr[1]}" …, which makes it a perfect tool for building command lines.)
$ countArgs() { echo $#; }
$ countArgs a b c
3
$ countArgs
0
$ countArgs ""
1
$ brr=("")
$ countArgs "${brr[@]}"
1
$ countArgs "${arr[@]-}"
1
$ countArgs "${arr[@]}"
bash: arr[@]: unbound variable
$ set +u
$ countArgs "${arr[@]}"
0
So is there a way around that problem, other than checking the length of an array in an if (see code sample below), or turning off -u setting for that short piece?
if [ "${#arr[@]}" = 0 ]; then
veryLongCommandLine
else
veryLongCommandLine "${arr[@]}"
fi
Update: Removed bugs tag due to explanation by ikegami.
A: According to the documentation,
An array variable is considered set if a subscript has been assigned a value. The null string is a valid value.
No subscript has been assigned a value, so the array isn't set.
But while the documentation suggests an error is appropriate here, this is no longer the case since 4.4.
$ bash --version | head -n 1
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
$ set -u
$ arr=()
$ echo "foo: '${arr[@]}'"
foo: ''
There is a conditional you can use inline to achieve what you want in older versions: Use ${arr[@]+"${arr[@]}"} instead of "${arr[@]}".
$ function args { perl -E'say 0+@ARGV; say "$_: $ARGV[$_]" for 0..$#ARGV' -- "$@" ; }
$ set -u
$ arr=()
$ args "${arr[@]}"
-bash: arr[@]: unbound variable
$ args ${arr[@]+"${arr[@]}"}
0
$ arr=("")
$ args ${arr[@]+"${arr[@]}"}
1
0:
$ arr=(a b c)
$ args ${arr[@]+"${arr[@]}"}
3
0: a
1: b
2: c
Tested with bash 4.2.25 and 4.3.11.
A: @ikegami's answer is correct, but I consider the syntax ${arr[@]+"${arr[@]}"} dreadful. If you use long array variable names, it starts to looks spaghetti-ish quicker than usual.
Try this instead:
$ set -u
$ count() { echo $# ; } ; count x y z
3
$ count() { echo $# ; } ; arr=() ; count "${arr[@]}"
-bash: abc[@]: unbound variable
$ count() { echo $# ; } ; arr=() ; count "${arr[@]:0}"
0
$ count() { echo $# ; } ; arr=(x y z) ; count "${arr[@]:0}"
3
It looks like the Bash array slice operator is very forgiving.
So why did Bash make handling the edge case of arrays so difficult? Sigh. I cannot guarantee you version will allow such abuse of the array slice operator, but it works dandy for me.
Caveat: I am using GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Your mileage may vary.
A: The only safe idiom is ${arr[@]+"${arr[@]}"}
Unless you only care about Bash 4.4+, but you wouldn't be looking at this question if that were the case :)
This is already the recommendation in ikegami's answer, but there's a lot of misinformation and guesswork in this thread. Other patterns, such as ${arr[@]-} or ${arr[@]:0}, are not safe across all major versions of Bash.
As the table below shows, the only expansion that is reliable across all modern-ish Bash versions is ${arr[@]+"${arr[@]}"} (column +"). Of note, several other expansions fail in Bash 4.2, including (unfortunately) the shorter ${arr[@]:0} idiom, which doesn't just produce an incorrect result but actually fails. If you need to support versions prior to 4.4, and in particular 4.2, this is the only working idiom.
Unfortunately other + expansions that, at a glance, look the same do indeed emit different behavior. Using :+ instead of + (:+" in the table), for example, does not work because :-expansion treats an array with a single empty element (('')) as "null" and thus doesn't (consistently) expand to the same result.
Quoting the full expansion instead of the nested array ("${arr[@]+${arr[@]}}", "+ in the table), which I would have expected to be roughly equivalent, is similarly unsafe in 4.2.
You can see the code that generated this data along with results for several additional version of bash in this gist.
A: "Interesting" inconsistency indeed.
Furthermore,
$ set -u
$ echo $#
0
$ echo "$1"
bash: $1: unbound variable # makes sense (I didn't set any)
$ echo "$@" | cat -e
$ # blank line, no error
While I agree that the current behavior may not be a bug in the sense that @ikegami explains, IMO we could say the bug is in the definition (of "set") itself, and/or the fact that it's inconsistently applied. The preceding paragraph in the man page says
... ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing.
which is entirely consistent with what it says about the expansion of positional parameters in "$@". Not that there aren't other inconsistencies in the behaviors of arrays and positional parameters... but to me there's no hint that this detail should be inconsistent between the two.
Continuing,
$ arr=()
$ echo "${arr[@]}"
bash: arr[@]: unbound variable # as we've observed. BUT...
$ echo "${#arr[@]}"
0 # no error
$ echo "${!arr[@]}" | cat -e
$ # no error
So arr[] isn't so unbound that we can't get a count of its elements (0), or a (empty) list of its keys? To me these are sensible, and useful -- the only outlier seems to be the ${arr[@]} (and ${arr[*]}) expansion.
A: @ikegami's accepted answer is subtly wrong! The correct incantation is ${arr[@]+"${arr[@]}"}:
$ countArgs () { echo "$#"; }
$ arr=('')
$ countArgs "${arr[@]:+${arr[@]}}"
0 # WRONG
$ countArgs ${arr[@]+"${arr[@]}"}
1 # RIGHT
$ arr=()
$ countArgs ${arr[@]+"${arr[@]}"}
0 # Let's make sure it still works for the other case...
A: I am complementing on @ikegami's (accepted) and @kevinarpe's (also good) answers.
You can do "${arr[@]:+${arr[@]}}" to workaround the problem. The right-hand-side (i.e., after :+) provides an expression that will be used in case the left-hand-side is not defined/null.
The syntax is arcane. Note that the right hand side of the expression will undergo parameter expansion, so extra attention should be paid to having consistent quoting.
: example copy arr into arr_copy
arr=( "1 2" "3" )
arr_copy=( "${arr[@]:+${arr[@]}}" ) # good. same quoting.
# preserves spaces
arr_copy=( ${arr[@]:+"${arr[@]}"} ) # bad. quoting only on RHS.
# copy will have ["1","2","3"],
# instead of ["1 2", "3"]
Like @kevinarpe mentions, a less arcane syntax is to use the array slice notation ${arr[@]:0} (on Bash versions >= 4.4), which expands to all the parameters, starting from index 0. It also doesn't require as much repetition. This expansion works regardless of set -u, so you can use this at all times. The man page says (under Parameter Expansion):
*
*${parameter:offset}
*${parameter:offset:length}
...
If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one
greater than the maximum index of the specified array. It is an
expansion error if length evaluates to a number less than zero.
This is the example provided by @kevinarpe, with alternate formatting to place the output in evidence:
set -u
function count() { echo $# ; };
(
count x y z
)
: prints "3"
(
arr=()
count "${arr[@]}"
)
: prints "-bash: arr[@]: unbound variable"
(
arr=()
count "${arr[@]:0}"
)
: prints "0"
(
arr=(x y z)
count "${arr[@]:0}"
)
: prints "3"
This behaviour varies with versions of Bash. You may also have noticed that the length operator ${#arr[@]} will always evaluate to 0 for empty arrays, regardless of set -u, without causing an 'unbound variable error'.
A: Turns out array handling has been changed in recently released (2016/09/16) bash 4.4 (available in Debian stretch, for example).
$ bash --version | head -n1
bash --version | head -n1
GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)
Now empty arrays expansion does not emits warning
$ set -u
$ arr=()
$ echo "${arr[@]}"
$ # everything is fine
A: this may be another option for those who prefer not to duplicate arr[@] and are okay to have an empty string
echo "foo: '${arr[@]:-}'"
to test:
set -u
arr=()
echo a "${arr[@]:-}" b # note two spaces between a and b
for f in a "${arr[@]:-}" b; do echo $f; done # note blank line between a and b
arr=(1 2)
echo a "${arr[@]:-}" b
for f in a "${arr[@]:-}" b; do echo $f; done
A: Here are a couple of ways to do something like this, one using sentinels
and another using conditional appends:
#!/bin/bash
set -o nounset -o errexit -o pipefail
countArgs () { echo "$#"; }
arrA=( sentinel )
arrB=( sentinel "{1..5}" "./*" "with spaces" )
arrC=( sentinel '$PWD' )
cmnd=( countArgs "${arrA[@]:1}" "${arrB[@]:1}" "${arrC[@]:1}" )
echo "${cmnd[@]}"
"${cmnd[@]}"
arrA=( )
arrB=( "{1..5}" "./*" "with spaces" )
arrC=( '$PWD' )
cmnd=( countArgs )
# Checks expansion of indices.
[[ ! ${!arrA[@]} ]] || cmnd+=( "${arrA[@]}" )
[[ ! ${!arrB[@]} ]] || cmnd+=( "${arrB[@]}" )
[[ ! ${!arrC[@]} ]] || cmnd+=( "${arrC[@]}" )
echo "${cmnd[@]}"
"${cmnd[@]}"
A: Now, as technically right the "${arr[@]+"${arr[@]}"}" version is, you never want to use this syntax for appending to an array, ever!
This is, as this syntax actually expands the array and then appends.
And that means that there is a lot going on computational- and memory-wise!
To show this, I made a simple comparison:
# cat array_perftest_expansion.sh
#! /usr/bin/bash
set -e
set -u
loops=$1
arr=()
i=0
while [ $i -lt $loops ] ; do
arr=( ${arr[@]+"${arr[@]}"} "${i}" )
#arr=arr[${#arr[@]}]="${i}"
i=$(( i + 1 ))
done
exit 0
And then:
# timex ./array_perftest_expansion.sh 1000
real 1.86
user 1.84
sys 0.01
But with the second line enabled instead, just setting the last entry directly:
arr=arr[${#arr[@]}]="${i}"
# timex ./array_perftest_last.sh 1000
real 0.03
user 0.02
sys 0.00
If that is not enough, things get much worse, when you try to add more entries!
When using 4000 instead of 1000 loops:
# timex ./array_perftest_expansion.sh 4000
real 33.13
user 32.90
sys 0.22
Just setting the last entry:
# timex ./array_perftest_last.sh 4000
real 0.10
user 0.09
sys 0.00
And this gets worse and worse ... I could not wait for the expansion version to finish a loop of 10000!
With the last element instead:
# timex ./array_perftest_last.sh 10000
real 0.26
user 0.25
sys 0.01
Never use such an array expansion for any reason.
A: Interesting inconsistency; this lets you define something which is "not considered set" yet shows up in the output of declare -p
arr=()
set -o nounset
echo ${arr[@]}
=> -bash: arr[@]: unbound variable
declare -p arr
=> declare -a arr='()'
UPDATE: as others mentioned, fixed in 4.4 released after this answer was posted.
A: The most simple and compatible way seems to be:
$ set -u
$ arr=()
$ echo "foo: '${arr[@]-}'"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "134"
}
|
Q: Pass login information from Apache/PHP to Tomcat/GWT We are planning to deploy our GWT module as explained in
http://code.google.com/webtoolkit/doc/1.6/DevGuideServerCommunication.html#DevGuideRPCDeployment
under the section "Using Tomcat with Apache HTTPD and a proxy"
Basically, we configured Apache/PHP server to pass on the requests to a Tomcat/GWT server that match a part of the URL. That worked as expected.
Now we would like to pass the information of the currently logged in user from Apache/PHP to the GWT module.
My initial idea was to load the GWT module from a PHP page (by including it's nocache.js) and include a login token with it which the GWT module can read.
But I am not sure if it is safe to read a DOM value and consider that as a login token.
Any suggestions for what would be the best way to do it?
Thank you.
A: IMHO it is definitifly the best idea to use a login-token, that is passed from apache/php to your gwt project. To pass this token, you have three possibilities:
First one: You can pass your token using a cookie. Write your token into a cookie and read it again in your GWT-context:
import com.google.gwt.user.client.Cookies;
Collection<String> cookies = Cookies.getCookieNames();
An example on dealing with cookies from GWT you can find in the GWT-Showcase.
Second one: Instead of writing your token to a cookie, you can pass it with a HTTP GET and read this again within your GWT-context:
// returns whole query string
public static String getQueryString() {
return Window.Location.getQueryString();
}
// returns specific parameter
public static String getQueryString(String name) {
return Window.Location.getParameter(name);
}
This method is -IMHO- that one you should never ever choose!
Third one: Instead of a HTTP GET you can also use a HTTP POST. The HTTP POST is send to the server. So you have to handle the request on your server-side with a simple servlet. This can be implemented as singelton and so be readable from your GWT-server-context. This method is a bit complex and brings a lot of work, since you then have to pass your information back to the GWT-client-context.
Which version is the best for you, depends on the details of your project. Usually I would say, that the Cookie-Version is the best.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MatLab assigning only the first two variables in I am trying to write a MatLab function to compute Fibonacci numbers. below is what I have but it comes up with an error about F(0).
??? Attempted to access F(0); index must be a positive integer or logical.
Error in ==> fibonacci at 11
F(0) = 0;
How do I tell matlab that the first two values in the array are 0 and 1??
function F = fibonacci( n )
%A fibonacci sequence is where the next term in the series is given by the
%sum of the pervious two terms
%Only valid if n is greater than or equal to 2
if n >= 2 ;
%Make an array with n terms
F = zeros (1,n);
%run a for loop from 2 to n
for i = 2:n;
F(0) = 0;
F(1) = 1;
F(i) = F(i-1) + F(i-2)
end
end
end
A: Your formatting is a bit off, but it seems like you are assigning a value to the zero-index of an array. As far as I know MatLab uses 1 as the index of the first item in an array.
If you change your if n>=2 to if >=3 and set the 1 and 2 index items instead of the 0 and 1 items you should be well on your way.
See also Is zero based indexing available in MATLAB
A: MATLAB uses 1-based indexing, which means you should rewrite indices to reflect this shift, by replacing your n variables with n+1. This starts the fibonacci at 0, but indexed to 1, 1 at 2, 1 at 3, 2 at 4, 3 at 5, and so on to your "n"th term, now be indexed at n+1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HG: Checkout 'tipmost' tag In mercurial, is there an easy way to programmatically check out the 'latest' tag?
Meaning, if hg tags produces this:
tip
Tag3
Tag2
Tag1
Is there an easy way to checkout Tag 3 in a generic way? Meaning, not just hg checkout Tag3, but a generic way of doing so.
EDIT: If I must use scripting, I can. However, I'm stuck on windows and would like to avoid scripting if possible.
A: If you're using bash:
hg checkout $(hg tags | sed -n '2p')
Note that this degrades gracefully: if there are no tags the subcommand will return blank and you'll get a simple checkout of the tip.
A: You can do it with revsets. Probably something like this:
hg update -r 'max(tagged())'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to get the position of the preview of a draggable element when it's dropped in HTML5 DnD I'm doing a visual editor using HTML5 Drag and Drop and i need to drag an element set as draggable to a div who acts as a container.
Some browsers provides a kind of preview image that represents the element while i'm dragging it, and when i let the element in the container with the drop event, i need to get the position where the user wants to put him. The problem is that i don't know the position of the preview ghost provided by browsers, so i don't know where exactly the element should be positioned.
I used the mouse position but it's not what i wanted, because the mouse position is not ever the same as the preview's. Is there a way to get the current position of the preview of a dragging element?
A: Have you considered using jQuery UI to do your DnD? I'm not sure if you've considered that or not, but here are some resources that might help you in-case you do choose to do the jQuery UI route:
jQuery UI Draggable (also see Droppable)
jquery ui drag/drop getting position from multiple draggables
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ruby on rails to command line interaction Very new to Ruby so please try to look past my ignorance. Cause I have no idea what I am talking about currently. However I know the ability to do what I want exists. Essentially I have some JAVA server side that can be used via a command line. I am trying to figure out where and how to begin with communicating in the same notion of me typing it out in the cli without actually typing it out to the cli. Basicly I want to pass the commands like as if I was using the CLI but Im not. Does that make sense?
Its for a CLI to UI conversion. I have seen the process done RoR to JAVA in such a fashion but where to begin I couldn't tell ya to save my life.
A: First of all, I would suggest at least looking into jRuby, which can interact with java classes as though they were ruby classes.
If you still want the cli integration, the naive approach is extremely simple, all you need to do is wrap your cli command in backticks (`) and it will execute the command as if you typed it into a shell, and return the results as a string.
If you need to do this very frequently, check out https://github.com/rtomayko/posix-spawn which is a much more efficient way of doing it then the backtick approach.
A: If the Java program has a command prompt of its own, look into popen. It allows you to open a subprocess as an I/O stream allowing you to send it input and read its output. If all you need is to start the process and get its output then use backticks as suggested by Matt Briggs:
output = `the-command-to-start-the-java-program`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android onClick() tasks all happen at once I'm trying to develop a feature for my app that pulls a string of text off of the internet (sort of like twitter, but a lot more basic) and displays it on the screen in a permeanent window. The user sees a large box with a refresh button next to it, and a small space below both where I would like to have a little progress monitor (just a TextView) which displays "Refreshing..." as soon as the refresh button is clicked, and then "Refresh successful!" once the string of text has been successfully pulled from the internet and displayed. This is just to reassure the user that something is actually happening when they press the button.
After a lot of research I've come to the conclusion that the way to update the TextView is to use a handler to execute a runnable which will update the text in the TextView. So my code looks like this:
refreshbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View abc)
{
//display "Refreshing..."
refreshhandler.post(refreshingmsg);
/*Code to pull the string of text from the internet goes here (not shown)*/
//display "Refresh successul!"
successfulhandler.post(successfulmsg);
//clear the "Refresh successful" message after 2 seconds
clearhandler.postDelayed(clearmsg, 2000);
}
});
I hope that sort of makes sense. My issue is that these things all happen at once: I want the "Refreshing..." message to display, THEN for the phone to connect to the internet to find the string of text for the update, and THEN for the "Refresh Successful" message to display once the internet string has been successfully displayed. But what actually happens is that none of the commands in the onClick method actually happen until the phone has already pulled the message from the internet so the "Refreshing..." message isn't displayed at all. So what actually happens when the user clicks the button is that nothing happens for a second or two (presumably because the phone is busy pulling the string from the internet), then the string from the internet is suddenly displayed along with the message saying "Refresh Successful!".
So why is this happening? Is onClick supposed to work this way? If so, is there a workaround? I haven't posted my runnable and handler statements because I'm not sure it'll make any difference... but if it would help then I can post them!
Also, you can probably tell from this that I haven't been doing android (or indeed java) for very long, but I'm trying my best so please be gentle! Thanks :)
A: What is happening is that your code is locking on the network communication and doesn't let your app update itself with the handler value.
You should create an AsyncTask to that work for you.
On the OnPreExecute method, change your UI to show the user that you are refreshing your content. Reading your code it appears that you are updating an image, do that here.
On the doInBackground method do your actual network communication, an optional step is to use onProgressUpdate(Progress...) to update your UI to notify the user that the operation is progressing.
On the onPostExecute method you them update your UI to reflect the new content.
For more info check the documentation in AsyncTask, you can also search StackOverflow, there's a lot of good questions about it here.
As a side note, I don't recommend that you use handlers at all, AsyncTasks are easier to use and the code looks better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $.children("selector") vs $("selector", parent) vs "parent > child" selector I have the following table structure.
<table id='mytable'>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>
<table>
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
</table>
</td></tr>
</table>
What I want to do is just getting the direct TR elements from mytable. Obviously, there are 4 direct TR of mytable.
The following shows three statements. I expected they return same result. However they don't.
var mytable$ = $("#mytable");
var trcount1 = mytable$.children("tbody").children().length; // trcount1 = 4
var trcount2 = mytable$.children("tbody > tr").length; // trcount2 = 0
var trcount3 = $("tbody > tr", mytable$).length; // trcount3 = 7
Only the syntax for getting trcount1 is what I wanted.
Why are trcount2 and trcount3 not 4?
Thanks
Alex
===================================
Thanks jfriend00's reply.
That's what I want.
$("> tbody > tr", mytable$).length; // 4
mytable$.find("> tbody > tr").length; // 4
I missed ">" before tbody.
A: Inside the browser, your DOM actually looks like this (note the automatic inclusion of the <tbody> tags):
<table id='mytable'>
<tbody>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>
<table>
<tbody>
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
</tbody>
</table>
</td></tr>
</tbody>
</table>
So, given that, here's how to explain your observations:
var trcount1 = mytable$.children("tbody").children().length; // trcount1 = 4
You're asking for direct children of the table that are tbody and then the children of that. There is one direct child that is a tbody and there are four direct children of that tbody tag so you get 4.
var trcount2 = mytable$.children("tbody > tr").length; // trcount2 = 0
You're asking for direct children of the table (which is only the tbody object) that also match this selector "tbody > tr". Since we're only looking at direct children of the table, this is only the tbody object itself and the tbody object iself doesn't match "tbody > tr" the result is 0 as there are no direct children that match that criteria.
Remember .children() is direct children only. If you want to consider all children and children of children, then you use .find() or just put the tag in the main selector.
var trcount3 = $("tbody > tr", mytable$).length; // trcount3 = 7
Here's you're asking for any tr tag inside of mytable that has a direct parent that's tbody. There are seven of those since all tr tags in mytable match that criteria.
If you want just the tr tags in the first table, I would recommend:
$("#mytable > tbody > tr") // will be 4
If you want all the tr tags in both tables, I would recommend:
$("#mytable tr") // will be 7
If you want just the tr tags in the second table, I would recommend:
$("#mytable table tr") // will be 3
A: trcount1 gets all tbodys that are direct descendants of mytable$ and then gets all direct descendants of that which are your four trs.
trcount2 looks for all trs that are a direct descendant of a tbody in the children of mytable$. The children of mytable$ is only the one tbody.
trcount3 looks for all trs that are a direct descendant of a tbody in the context of mytable$. The first four trs are direct descendants of a tbody and the nested trs are also direct descendants of a tbody.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to add object to unparameterized Java List? I have a Java object OldFashioned that extends Java 1.4 List:
[Java]
class OldFashioned extends List { ... }
That is, OldFashioned doesn't take any type parameters. I need to add SomeObject to it. In Java there's no problem, since it treats List 1.4 as List<Object> 1.5 and allows to add any subclasses of Object to the collection. But Scala doesn't. So next code doesn't work:
[Scala]
val oldFashioned = new OldFashioned()
oldFashioned.add(new SomeObject) // found: SomeObject; required: E
That is, Scala compiler requires to pass type parameters to OldFashioned that actually doesn't take them:
[Scala]
var oldFashioned: OldFashioned[SomeObject] = null // OldFashioned does not take type parameters
How can I overcome it and add SomeObject to OldFashined?
A: Ok, I can't believe one of my earlier question finds a usage here (you should go upvote agilesteel's answer)
def add(oldFashioned: OldFashioned, any: Any): Boolean = oldFashioned match {
case l: java.util.List[a] => l.add(any.asInstanceOf[a])
}
val oldFashioned = new OldFashioned
// oldFashioned: OldFashioned = []
add(oldFashioned, "test")
// res0: Boolean = true
add(oldFashioned, 1)
// res1: Boolean = true
add(oldFashioned, new Object)
// res2: Boolean = true
oldFashioned
// res3: OldFashioned = [test, 1, java.lang.Object@1db8f8e]
Edit: I guess as long as I'm going to cast:
oldFashioned.asInstanceOf[java.util.List[SomeObject]].add(new SomeObject)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to get the current UTC time in seconds I have an application, which needs to compare the time in seconds.
I want to know how to get the current UTC time in seconds.
Can some one post an example of it how can we do this in Java?
A: public static long getUtcTime(long time) {
System.out.println("Time="+time);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dbefore=new Date(time);
System.out.println("Date before conversion="+format.format(dbefore));
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
TimeZone timezone = c.getTimeZone();
int offset = timezone.getRawOffset();
if(timezone.inDaylightTime(new Date())){
offset = offset + timezone.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("Date after conversion: "+format.format(c.getTime()));
System.out.println("Time converted="+c.getTime().getTime());
return c.getTime().getTime();
}
A: Joda makes everything simple
import org.joda.time.ReadableInstant;
import org.joda.time.DateTime;
import static org.joda.time.DateTimeZone.UTC;
import static org.joda.time.Seconds.secondsBetween;
...
ReadableInstant start = new DateTime("2011-01-01", UTC);
ReadableInstant end = new DateTime("2011-02-02", UTC);
int secondsDifference = secondsBetween(start, end).getSeconds();
A: You can use this to get timezone passing in timezone you want time back in
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can call whatever you want on the calendar object
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
Below example to compare two calendars in seconds
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// Set the dates for calendars
cal1.set(2011, 1, 1);
cal2.set(2011, 2, 2);
// Get the represented date in milliseconds as a long
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSecs = diff / 1000;
System.out.println("In seconds: " + diffSecs + " seconds");
A: System.currentTimeMillis()
A: Get current UTC time in seconds (since 1.5) :
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
according to Javadoc:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#currentTimeMillis
Returns:
the difference, measured in milliseconds, between the current time and
midnight, January 1, 1970 UTC.
A: To store the date as an integer instead of long, you can divide by 1000 and optionally subtract by another date, such as Jan. 1 2019:
private int getUTC()
{
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal1.set(2019, 1, 1);
long millis1 = cal1.getTimeInMillis();
//Current date in milliseconds
long millis2 = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
// Calculate difference in seconds
long diff = millis2 - millis1;
return (int)(diff / 1000);
}
A: This works:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
GregorianCalendar gregorianCalendar = new GregorianCalendar
(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND)
);
return gregorianCalendar.getTime();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: JSON Sub Level Extraction - How to? Objective-C I'm using SBJSON (and am new to JSON) and can easily extract httprequest's response data with it at its top most level. The problem is that I am quite clueless on accessing elements in a sub level.
For instance:
Level 1:
Key: id
Key: car_list
=========
car_list (Level 2)
Key: car_id
Key: car_name
Key: car_size
So like I said, I can access top level objects by using:
NSDictionary *responseDict = [responseString JSONValue];
NSString *id = [responseDict objectForKey:@"id"];
But don't know how to access the elements within the "car_list".
Thanks
A: A simple way, if you have a dictionary of dictionaries, is to use valueForKeyPath:
For example:
NSString *carName = [responseDict valueForKeyPath:@"car_list.car_name"];
All you need to do is join up your keys with periods. If any of those paths returns an array or set, then you'll receive a collection. You can additionally use set/array key-value coding paths to compute things on collections, such as @avg and @count.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: facebook opengraph not updating and other questions I'm having a problem using Facebook's OpenGraph. I'm attempting to implement timeline features into my application. However, when try changing my meta tags to change the tile of my object, the changes are not reflected. When I pass my url into the debugger tool facebook offers, it displays that my OG object is still using the old data, as opposed to the new data. However, the weird thing is the raw properties show my changes. How do I get facebook to update the OG object?
Another problem I'm having is that when I make changes to my actions, facebook isn't properly updating it. When I reopen the action, it's still referencing my old object titles. For example, if a title of one of my movie objects was "sci fi," and I reference "sci fi" in the action "see," it will still be referencing "sci fi" even if I try to change it to something else. I would save and it, but when I reopened the action the old settings where still there.
I was also wondering about dynamic generation of objects. For example, if I had an app that allowed people to list movies they've watched, could I dynamically generate the OG object so that users can have the "see a $movie" show up in their timeline no matter what movie it was? The reason I'm wondering is because right now I'm unsure whether or not I need to keep the page with the meta tags up after I use it once.
Sorry for the word blocks and if my questions seem basic to you. I'm pretty much a newbie at this.
A: Putting your URL into the Object Debugger should force Facebook to crawl it. Do you have your og:url pointing to the old URL?
I don't understand your second question. Is Facebook not crawling your page? It should recrawl every 7 days or you can force it with the scrape API.
For your third question, yes, you can do that. Just make a different URL for each movie with a different og:url. For good SEO you want to do example.com/movie/1234/The-Matrix.
A:
http://developers.facebook.com/tools/debug
Try this and put the link of the page you want facebook to clear its cache for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is myString.equals("aString"); different from "aString".equals(myString);? I heard several times that in using boolean equals(Object o) to compare Strings, it's better to put the constant on the left side of the function as in the following:
*
*Bad: myString.equals("aString");
*Good: "aString".equals(myString);
Why is this?
A: Because if myString is null you get an exception. You know "aString" will never be null, so you can avoid that problem.
Often you'll see libraries that use nullSafeEquals(myString,"aString"); everywhere to avoid exactly that (since most times you compare objects, they aren't generated by the compiler!)
A: This is a defensive technique to protect against NullPointerExceptions. If your constant is always on the left, no chance you will get a NPE on that equals call.
A: This is poor design, because you are hiding NullPointerExceptions. Instead of being alerted that string is null, you will instead get some weird program behaviour and an exception being thrown somewhere else.
But that all depends if 'null' is a valid state for your string. In general 'null's should never be considered a reasonable object state for passing around.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Check and send variables via URL without redirection i am trying from my main web page to check and in some cases send a variable via URL like this (http://192.168.0.110/CVAL.CGI?A0=1) this is to modify the status of something in my web page depending on the value seen in the url.
A: Sounds like you need Ajax.
There are many javascript libraries that can help you with this functionality such as jQuery, Prototype, or one of the many found on this page.
Hope that is what you are looking for and is helpful. Next time post more specific details so we can answer your question correctly the first time. Specific, detailed examples of what you want to do are also helpful.
UPDATED:
Here is an example using the Prototype Javascript library given your example form:
new Ajax.Request('/CVAL.CGI?A0=1', {
method: 'get',
parameters: { anotherValue: 'something' },
onSuccess: function(transport) {
alert(transport.responseText); // this is what the server returned
}
});
This would result in a request to /CVAL.CGI?A0=1&anotherValue=something. Whatever CVAL.CGI returns in response to that request, is available from transport.responseText.
This way, the user never has to leave the page or submit a form but it is all done behind the scenes. Your parameters can be any values you want to send which you can grab from form fields or other user input. You can return responses in JSON to make accessing the return data easier as well. Change method from 'get' to 'post' to do post requests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What does a table way to small for the screen create a scrollbar? Here's a DEMO
Here's my HTML:
<div>
<table>
<tbody>
<tr>
<td>A1</td>
<td>B1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
</tr>
</tbody>
</table>
</div>
and CSS:
div {
position: relative;
left: 100px;
}
table {
border: 1px solid black;
}
As you can see in the demo, it causes horizontal scrollbars. Is there any way to get rid of this, other than using javascript?
A: instead of left maybe try
margin-left: 100px;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Css class nesting and grouping What is the difference between
#id .A.B x { }
#id .A .B y { }
in CSS file?
Both A and B are classes.
x and y are some tags
Does the spacing between .A and .B have any significance?
A: In the first case, it references an element that has both A and B as classes:
<div class="A B"></div>
The second is an element with class A that has an element with class B nested inside:
<div class="A">
<div class="B"></div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Validation with DDD in SOA application using IoC In my service facade layer, I have a service class with a method/operation that accepts a DTO (data contract) object. AutoMapper is used to map this DTO into an instance of my domain object to apply any changes. The request is passed onto my domain service which does the actual work. Here's what the method might look like:
public EntityContract AddEntity(EntityContract requestContract)
{
var entity = Mapper.Map<EntityContract, Entity>(requestContract);
var updatedEntity = Service.AddEntity(entity);
var responseContract = Mapper.Map<Entity, EntityContract>(updatedEntity);
return responseContract;
}
The Service and Mapper properties are set using constructor injection with Unity as the IoC container.
In performing the operation, the domain service makes changes to the entity then uses a repository to persist the changes like:
public Entity AddEntity(Entity entity)
{
// Make changes to entity
Repository.Add(entity);
// Prepare return value
}
The Repository is also set using constructor injection.
The issue is that the data becomes immediately available to other clients once it has been persisted so I have to ensure that no invalid data is persisted. I've read the "blue book" of DDD (Evans) as well as Nilsson and am not clear what approach to validation I should take.
If my goal is to prevent the entity from entering an invalid state, should I validate entityContract in my service method to ensure all rules are satisfied before ever passing the request on to my domain service? I hesitate to do so because it seems like I'm breaking encapsulation having these rules defined in the service facade.
The reason we are using a thin facade layer delegating to domain services is that we are exposing course-grained interfaces in our API but support reuse via composition of the fine-grained domain services. Keeping in mind that multiple facade services may be calling the same domain service method, perhaps delegating these rules into the domain service would be better so we know every use is validated. Or should I validate in both places?
I could also put guards in the property setters that prevent unacceptable values from ever putting the entity into an invalid state. This would mean that AutoMapper would fail when trying to map an invalid value. However, it doesn't help when no value is mapped.
I still can't get past the thinking that these rules are part of the entity's behavior and determining if the object is valid should be encapsulated within the entity. Is this wrong?
So first I need to determine when and where I perform these validation checks. Then I need to figure out how to implement with DI so the dependencies are decoupled.
What suggestions can you provide?
A:
I've read the "blue book" of DDD (Evans) as well as Nilsson and am not
clear what approach to validation I should take.
Blue book approaches the problem from a different angle. I think that the term 'Validation' is not used because it is a dangerous overgeneralization. A better approach is to think about object invariants, not validation. Objects (not only in DDD) should enforce their internal invariants themselves. It is not UI or services or contracts or mappers or 'validation frameworks' or anything else that is external to the objects. Invariants are enforced internally. You may find these answers helpfull: 1, 2, 3, 4.
I could also put guards in the property setters that prevent
unacceptable values from ever putting the entity into an invalid
state. This would mean that AutoMapper would fail when trying to map
an invalid value.
You probably should not care about AutoMapper failing or using AutoMapper at all. Domain objects should encapsulate and enforce their internal invariants and throw exception if the attempt to break it is made. It is very simple and you should not compromise the simplicity and expressiveness of your domain objects because of some infrastructural issues. The goal of DDD is not to satisfy AutoMapper's or any other framework's requirements. If the framework does not work with your domain objects don't use it.
A: You have two types of validation:
*
*Object consistency: is the responsibility of entities. Entities should not allow you to set them to invalid state, dependencies should be enforced, values should be in range. you have to design classes' methods and properties and constructors not to allow invalid state.
*Business roles validation: this type of validation requires server processing, like checking id availability, email uniqueness and the so. these types of validations should be processed in server as Validators or Specifications before persistence.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Detecting an Object in an Image using SIFT/SURF Features Given N SIFT/SURF features extracted from 100 training images describing a specific object, and given M SIFT/SURF features extracted from a new image A, that may or may not contain that object (as well as other objects we don't care about), how would you determine if image A depicts that object?
The only method I'm aware of is to cluster the training features, and generate a histogram for each training image, and then train a classifier (e.g. SVM) on these histograms. Then you would test for the object in image A by extracting the features, calculate the histogram, and then classify the histogram using the trained classifier.
The main problem with this approach is that it assumes image A only contains the object and nothing else, or it doesn't contain the object. In other words, if the object were a person, and it were trained on images of that person, it wouldn't be able to detect that person standing in a crowd, because the resulting histogram would be polluted with the features of all the other people in the crowd.
What are other methods for accomplishing this?
A: I would recommend to read papers on this topic by the author of SIFT features, David Lowe. See here http://www.cs.ubc.ca/~lowe/pubs.html, search for object recognition.
A: You can use sliding windows of varying scales to detect the object in any localised part of the image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Scroll down, ajax load more in another div I haven't seen this done anywhere before but I hope y'all geniuses here can help out. I have a very tall div which users will have to scroll to read more. I also have a div to it's top right which loads google ads. I want this div to load more ads based on the scroll level of the user.
I hope I am quite clear. If not, please check http://jsfiddle.net/NWgQx/ for a picture of what I mean.
Thanx in advance.
A: You could do something similar to:
$(window).scroll(function() {
var top = $(document).scrollTop();
var ad_offset = $('#ad').offset();
var ad_bottom = ad_offset.top + $('#ad').height();
if (top > ad_bottom) {
$('#more-ads').load('/more-ads.html');
}
});
I'm not a huge fan of binding on the scroll event, I think it's really slow. This might give you some ideas though. You should probably also set a variable to indicate whether or not more ads are currently loading and stop listening to the scroll event until more ads have been loaded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can i link a list element with the select dropdown I have a list of elements:
<li>A</li>
<li>B</li>
and a dropdown:
<select>
<options value="A">A</options>
<options value="B">B</options>
</select>
How can i link both of them together?
I want to change the value of select to the text of the <li> that the user clicks. So if the user clicks <li>A</li>, the <select> value would be set to A.
A: Try something like this:
$('ul li').click(function() {
var elem=$(this).text();
$("select option[value='"+elem+"']").attr('selected', 'selected');
});
A: $("#list li").click(function(){
var index = $(this).text();
$("#dropdown").val(index);
});
Here's one way, though you can change the index variable to suit your needs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: allocating memory when overriding + operator in c++ I am creating a custom object and overriding the + operator. I am return a new object of the same type. Is it bad practise to allocate memory inside this method? because I then I will need to delete the memory out of scope.
A: Yes, without further information, it is bad.
Usually you do:
struct X
{
int m_i;
X(int i) : m_i(i) { }
X operator+(const X& another) const
{
return X(m_i + another.m_i); // note, not new X(...)
}
}
That said, you could return a unique_ptr if you really had to allocate dynamically.
A: There's a nice example of overloading operator+ to return a new instance of the object as the result, without dynamic allocation.
The source is here, with a lot of explanations on how to overload operators.
The example is this:
// Add this instance's value to other, and return a new instance
// with the result.
const MyClass MyClass::operator+(const MyClass &other) const {
return MyClass(*this) += other;
}
It assumes you implemented operator+= and a copy constructor, if you don't have += - just put the assignment operations there directly. Read the link for more details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Anonymous user count using Spring Security I have managed to accomplish a couple features using Spring Security 3.0.5. The first is that I want a count and list of users that have a specific role. To accomplish this I instituted the HttpSessionEventPublisher and the spring configurations that go along with it. With these settings I can easily get the list of logged in users no matter what their privilege level - unless they are anonymous (ROLE_ANONYMOUS).
I'm using the anonymous tag in my security XML:
<security:anonymous />
I can debug the anonymous users coming in though AnonymousAuthenticationFilter.doFilter but the SessionRegistry.registerNewSession never gets called for these, most likely because there is no principal for anonymous users.
So I'm just looking for ideas. I would love to be able to list the count for the sessions that are anonymous, along with other registered users.
A: You can extend the AnonymousAuthenticationFilter and override the createAuthentication method (it's meant for overriding).
Then since this method is called only on a new anonymous authentication, whenever it's called you can increment a counter somewhere, or count them in any way convenient for you. You just need to count the calls to the method.
A: Here's an implementation of counting anonymous's in Spring Security.
public class ProxyAuthenticationFilter extends AnonymousAuthenticationFilter {
private String key = "key";
public ProxyAuthenticationFilter() {
super(key);
}
public ProxyAuthenticationFilter(String key, Object principal, List<GrantedAuthority> authorities) {
super(key, principal, authorities);
}
@Override
protected Authentication createAuthentication(HttpServletRequest request) {
// do increment and store somewhere
return super.createAuthentication(request);
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.anonymous().authenticationFilter(proxyAuthenticationFilter());
}
@Bean
protected ProxyAuthenticationFilter proxyAuthenticationFilter() {
return new ProxyAuthenticationFilter();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add multiple records into a google app engine datastore I am trying to update a datastore by uploading a formatted file(contains multiple lines). Each line in the file will create a new record in google app engine datastore. I am not sure how to add multiple rows to the datastore within a for loop. I tried:
class Records(db.Model):
something = db.StringProperty()
.....
for line in lines #lines is a file contains multiple lines
record = Records(parent = PARENT_KEY)
record.something = line
record.put()
It doesn't work and the error message is BadValueError: Property something is not multi-line. I am guessing it's because the 'record' variable refer to the same instance across each iteration.
Sorry if it's a stupid question. I am pretty new to python and google app engine. Thanks in advance for your input!
A: for line in lines will keep the newline characters at the end of the lines; newlines aren't allowed in a StringProperty unless it's designated as multiline.
try record.something = line.rstrip() to remove the newlines.
A: You can use the bulk loader to load data from a file into the datastore.
http://code.google.com/appengine/docs/python/tools/uploadingdata.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to configure roles with Apache Shiro 1.2-SNAPSHOT and Guice? I'm playing around with Shiro and would like to configure roles via the ShiroWebModule.
addFilterChain("/**", AUTHC);
this works, my loginpage is shown and I can login.
But
addFilterChain("/test/**", AUTHC, config(ROLES, "test")); //that does not seem to be the right way
does not. I can access /guest/** and /test/** as guest.
My Module:
public class HelloMavenShiroModule extends ShiroWebModule {
HelloMavenShiroModule(ServletContext sc) {
super(sc);
}
protected void configureShiroWeb() {
try {
bindRealm().toConstructor(IniRealm.class.getConstructor(Ini.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException("Code Problem.", e);
}
addFilterChain("/**", AUTHC);
addFilterChain("/guest/**", AUTHC, config(ROLES, "guest"));
addFilterChain("/test/**", AUTHC, config(ROLES, "[test]"));
//addFilterChain("/**", AUTHC);
bindConstant().annotatedWith(Names.named("shiro.loginUrl")).to("/account/login.jsp");
bindConstant().annotatedWith(Names.named("shiro.globalSessionTimeout")).to(30000L);
bindConstant().annotatedWith(Names.named("shiro.usernameParam")).to("user");
bindConstant().annotatedWith(Names.named("shiro.passwordParam")).to("pass");
bindConstant().annotatedWith(Names.named("shiro.rememberMeParam")).to("remember");
bindConstant().annotatedWith(Names.named("shiro.successUrl")).to("/index.html");
bindConstant().annotatedWith(Names.named("shiro.failureKeyAttribute")).to("helloMavenLoginFailure");
bindConstant().annotatedWith(Names.named("shiro.unauthorizedUrl")).to("/account/denied.jsp");
bind(AuthenticationFilter.class).to(VerboseFormAuthenticationFilter.class);
bind(CredentialsMatcher.class).to(HashedCredentialsMatcher.class);
bind(HashedCredentialsMatcher.class);
bindConstant().annotatedWith(Names.named("shiro.hashAlgorithmName")).to(Sha256Hash.ALGORITHM_NAME);
}
@Provides
Ini loadShiroIni() {
return Ini.fromResourcePath("classpath:shiro.ini");
}
}
The shiro.ini:
# -----------------------------------------------------------------------------
# Users and their (optional) assigned roles
# username = password, role1, role2, ..., roleN
# -----------------------------------------------------------------------------
[users]
root = 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b, admin
guest = 84983c60f7daadc1cb8698621f802c0d9f9a3c3c295c810748fb048115c186ec, guest
# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
I know it's not released yet, but maybe it's possible already and I just cannot find out.
A: I've found out myself after cleaning up everything and trying again it turns out that:
addFilterChain("/test/**", AUTHC, config(ROLES, "test"));
was already the right way to do it. I don't know what caused the problem, but now only users with the "test" role are allowed to access resources under /test/ ! Thats exactly what I wanted.
I'm happy now! :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Eclipse SVN : how to use Compare With ... branch? In Eclipse with SVN, I would like to see which changes (line by line!) are done in another branch (or trunk) and then decide for each changed file if I want to keep my working copy version or the changed file.
I think this is the way it should work, but apparently it doesn't in SVN/Eclipse. I tried the merge functions, and I kept getting tree conflicts, trunk out of date errors, etc. Even with a very simple project with only 2 files in it, everything goes wrong. The automated merge thing just doesn't work for me ! You have absolutely no control of what is actually going to happen to your files, and end up with a totally ruined working copy, in the case of conflicts. Which you have to fix AFTER the merge!
I do like the Compare With-function to compare branches with each other though. But I couldn't find any way to practically use this to update changed files. All I get is a nice treeview with all changed files, and the possibility to compare the actual changes, but no way of marking the changes as merged!
It seems what I want is just not possible with Compare With ?
Is there NO other tool at all then where you have total control of your merges ? Maybe I should change to GIT or Mercurial?!
Any idea's about the subject are welcome...
UPDATE:
Found these alternative SVN clients myself, both look promising for dealing with changes in different branches:
http://www.syncrosvnclient.com/
https://www.smartsvn.com/
A: As far as I know there is no such nice gui. There is a manual way, but it's not so easy and simple.
I don't Eclipse here, but I'll try to use my memory.
You can use the history view to see which commits were made on a branch. Just drag the branch from svn repositories view to history view. It will show the branch history.
Then you can select two commits (starting and ending) you want to make a diff from. Then you get a window where you can choose the graphical gui comparison or output to diff file. When you get the diff you can apply it to the workspace using package explorer and team menu.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dynamically adding buttons to ItemsControl I have a issue that i want your inouts on. I have a outer grid and it has two columns. On first column i am using a ItemsControl that is bind to a a view model (This view model is for dynamically creating buttons). I have a wrap pannel templete define for the Item templete. The 2nd column is for a list box.
I create the objects for the buttons in the view model and that gets binded to the view.The requiremnet is that if the window hieight fits then all buttons should appear in a single colum (one below the other) else it should come in two columns.
If one column
1
2
3
4
If Two Columns :
1 2
3 4
The code i have is given below :
ItemsControl:
<Grid>...
<ItemsControl ItemsSource="{Binding buttonsViewModelColl}"
ItemsPanel="{StaticResource WrapPanelTemplateA}"
ItemTemplate="{StaticResource ButtonsDataTempleteA}" Width="{Binding ActualWidth, ElementName=<OuterGrid>}" Grid.Row="2" HorizontalAlignment="Center"/>
</Grid>
WrapPannelTemplete:
<ItemsPanelTemplate x:Key="WrapPanelTemplate">
<WrapPanel/>
</ItemsPanelTemplate>
DataTempleteForButton :
<DataTemplate x:Key="ButtonsDataTempleteA">
<Button
Content="{Binding Path=Text}"
IsEnabled="{Binding Path=IsEnabled}"
Style="{StaticResource StyleButtonA}"
FontFamily="Segoe UI Semibold"
HorizontalAlignment="Left" />
</DataTemplate>
The problem is that on rendering only one or two buttons are visible. If i set teh WrapPannel Orientation to vertical all comes but they donot wrap automatically. Only if i drap and extend teh width of window all are visible. Also teh sequence is not correct :
They come as :
A C
B D
Any Ideas.
Another question : Is there a way i can increase the width of the inner grid column based on an outer grid height at runtime in XAML ?
A: I think what you need is a UniformGrid not WrapPanel because you want the total number of buttons, the height of the entire container and the number of columns in the panel to be interdependent. Wrap Panel cannot control the third factor (i.e. number of columns in the panel).
UniformGrid has Rows and Columns property which are perfectly bindable. They can be multi bound to the above 3 factors and a multi value converter can decide what number of rows and columns to display based on some custom heuristic algorithm.
I hope this guides you in correct direction.
A: I suspect it has something to do with the Width the ItemsControl is allowed. Does it work if you set the WrapPanel's Width manually?
As for your last question, setting the column's width based on the Grid's height, you can simply bind to it.
<ColumnDefinition Width="{Binding ElementName=OuterGrid, Path=ActualHeight}" />
If you need to perform a calculation on that value, I usually use a Converter which accepts a parameter of the Grid's height, and translates it into whatever value I want. I actually have a MathConverter that use for this kind of thing because I'm too lazy to write my own converter for every binding calculation I want, and the code can be found here
It can be used like:
Width="{Binding ElementName=OuterGrid, Path=ActualHeight,
Converter={StaticResource MathConverter},
ConverterParameter=@VALUE/2}"
Actually, you can probably use the MathConver to set the Width of your WrapPanel, and it should work correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Proving various runtimes have various big-O complexities? How can I prove the following:
*
*10 n log n ∈ O(2n2)
*n log n + 40 · 2n - 6n ∈ O(2n)
In the first one, I'm using this math:
10 n log n ≤ c · 2n2
10 n2 ≤ c · 2n2 divide by 2
5 n2 ≤ c · n2
I'm guessing that c = 5 and n0 = 1, but I'm not sure if that's true.
In the second one, I tried to multiply the left hand side by 2n but that didn't end up working. Does anyone have any suggestions?
A: For part (1), you want to prove
10 n log n = O(2n2)
It might help to note that for any n ≥ 1 that
log n < n
Therefore, you have that
10 n log n ≤ 10 n2 = 5(2n2)
Therefore, you can conclude that 10n log n = O(2n2) because you can choose n0 = 1 and c = 5 and use the formal definition of big-O.
For part (i), you want to prove
n log n + 40 · 2n - 6n = O(2n)
One useful fact you might want to use here is that n2 ≤ 2n for any n ≥ 4. Therefore, we get that, whenever n ≥ 4
n log n + 40 · 2n - 6n ≤ n log n + 40 · 2n ≤ 40 · 2n + n2 ≤ 40 · 2n + 2n = 41 · 2n
Therefore, if you pick n0 = 4 and c = 41, you can use the formal definition of big-O to prove that n log n + 40 · 2n - 6n = O(2n).
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Use one search string to search 4 website catalogs I frequent many libraries. The Brooklyn Public Libraries, Queens Public Libraries, New York Public Libraries and CUNY schools libraries. When I want a book I have to go to all 4 online catalogs and search for it. I want to instead write a program that takes the book, author, ISBN, or whatever keywords as a string and then return 4 search result as if I went to each catalog site manually. I think this would be considered a web crawler. I'm fairly good at following programming tutorials, and googling something when I know what I'm looking for. I really have no idea where to start and would appreciate some advice. Thanks in advanced.
A: Here are some python based scripts and examples of how you can automate the crawling/scraping of each online catalog. This can be done in any language, but python in my opinion would be the simplest.
Simple Web Crawler (Python recipe)
Scrapy
Or, to do it without a prewritten script you would use urllib2 to get the web page source and then parse that source with something like BeautifulSoup. And with the parsed source, do some keyword checks, and display the results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dreamweaver Phonegap Android Emulation Problem I'm having problems using the emulator for dreamweaver using the Jquery Mobile(phonegap) template. Specifically the emulator starts but the app doesn't load and there is no app icon for the app either. When i build and emulate the message "Dreamweaver is unable to open Tour Finder, please consult the build log. I have dreamweaver 5.5 and updates installed. I have the up to date android sdk and sdk tools installed also. I am able to emulate apps through eclipse. Any help is appreciated. Here is the build log:
<DW>
____________________
set ANT_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\CONFIG~1\NATIVE~1\APACHE~1
set ANDROID_HOME=D:\android-sdk
set JAVA_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\JDK
set PATH=%JAVA_HOME%\bin;%PATH%
cd D:\ANDROI~1\PLATFO~2
D:\android-sdk\platform-tools\adb.exe devices
____________________
</DW>
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
Launching the Android emulator
<DW>
____________________
set ANT_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\CONFIG~1\NATIVE~1\APACHE~1
set ANDROID_HOME=D:\android-sdk
set JAVA_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\JDK
set PATH=%JAVA_HOME%\bin;%PATH%
cd D:\ANDROI~1\tools
C:\Windows\SysWOW64\cmd.exe /u /c "D:\android-sdk\tools\emulator.exe -partition-size 1024 -cpu-delay 0 -no-boot-anim -avd Android_2.3.3_API_10_WVGA_480x800"
____________________
</DW>
WARNING: no splash screen was specified in app settings. using default.
<DW>
____________________
set ANT_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\CONFIG~1\NATIVE~1\APACHE~1
set ANDROID_HOME=D:\android-sdk
set JAVA_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\JDK
set PATH=%JAVA_HOME%\bin;%PATH%
cd C:\Users\David\Desktop\COMEXP~1.TOU
C:\Windows\SysWOW64\cmd.exe /u /c C:\PROGRA~2\Adobe\ADOBED~2.5\CONFIG~1\NATIVE~1\APACHE~1\bin\ant.bat debug
____________________
</DW>
Buildfile: C:\Users\David\Desktop\COMEXP~1.TOU\build.xml
[setup] Android SDK Tools Revision 13
[setup] Project Target: Google APIs
[setup] Vendor: Google Inc.
[setup] Platform Version: 2.2
[setup] API level: 8
[setup]
[setup] ------------------
[setup] Resolving library dependencies:
[setup] No library dependencies.
[setup]
[setup] ------------------
[setup]
[setup] WARNING: Attribute minSdkVersion in AndroidManifest.xml (2) is lower than the project target API level (8)
[setup]
[setup] Importing rules file: tools\ant\main_rules.xml
-debug-obfuscation-check:
-set-debug-mode:
-compile-tested-if-test:
-pre-build:
-dirs:
[echo] Creating output directories if needed...
-aidl:
[echo] Compiling aidl files into Java classes...
-renderscript:
[echo] Compiling RenderScript files into Java classes and RenderScript bytecode...
-resource-src:
[echo] Generating R.java / Manifest.java from the resources...
-pre-compile:
compile:
[javac] D:\android-sdk\tools\ant\main_rules.xml:385: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to C:\Users\David\Desktop\COMEXP~1.TOU\bin\classes
-post-compile:
-obfuscate:
-dex:
[echo] Converting compiled files and external libraries into C:\Users\David\Desktop\COMEXP~1.TOU \bin\classes.dex...
-package-resources:
[echo] Packaging resources
[aapt] Creating full resource package...
[aapt.exe] Warning: AndroidManifest.xml already defines debuggable (in http://schemas.android.com/apk/res/android); using existing value in manifest.
-package-debug-sign:
[apkbuilder] Creating tour_finder-debug-unaligned.apk and signing it with a debug key...
debug:
[echo] Running zip align on final apk...
[echo] Debug Package: C:\Users\David\Desktop\COMEXP~1.TOU\bin\tour_finder-debug.apk
BUILD SUCCESSFUL
Total time: 13 seconds
<DW>
____________________
set ANT_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\CONFIG~1\NATIVE~1\APACHE~1
set ANDROID_HOME=D:\android-sdk
set JAVA_HOME=C:\PROGRA~2\Adobe\ADOBED~2.5\JDK
set PATH=%JAVA_HOME%\bin;%PATH%
cd D:\ANDROI~1\PLATFO~2
D:\android-sdk\platform-tools\adb.exe kill-server
____________________
</DW>
Waiting for Android emulator to bootERROR: failed to launch Android emulator
A: I've came accross with the same problem.
I've runned into this solution: http://forums.adobe.com/message/3997853 and it works! However i have to have the emulator fully booted and running before i do "Build and Emulate" in DW (or just do 2x "Build and Emulate").
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between running rails tests from root and test directory What is the difference between running rails tests from the root directory and from the test directory? I've seen it done both ways, but I would imagine that one is preferred..
ruby test/unit/user_test.rb
vs
cd test
ruby unit/user_test.rb
A: The only difference is in relative paths - any requires are relative to the directory from which you run ruby.
For instance, if your test case has require 'test_helper.rb' in it, this will only work from the test directory (since that is where test_helper.rb is.
If you want to run your tests from the root directory, you would have to change this to require File.join(File.dirname(__FILE__), '..', 'test_helper.rb', where FILE is the path to the file that contains this line (your test case), and the rest is the path of test_helper.rb, relative to that file. This way, where you run the test from is irrelevant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery alternatives to Highslide? Are there any robust jQuery alternatives to the JavaScript popup/lightbox library Highslide? Highslide is too focused on the image gallery aspect and I'm just wondering if there are options.
I'm not looking for a triditional lightbox, rather floating/movable divs as in Highslide.
A: For lightboxes I've found that there is generally just one real candidate.
http://fancyapps.com/fancybox/
It's extremely flexible content wise and lends itself really well to be styled in whatever way you like.. heh.
I can say from experience that the code in it is really robust. It's popular, well tested and maintained. I wouldn't go for anything else UNLESS I need more expansive image gallery options which it has some limited options to. But even then I'd at least considder extending fancybox first.
A: MopBox might work for you (not limited just to images, not focused on image galleries): http://www.mopstudio.jp/mopBox2demo.html
A: I'm not entirely sure what it is you're looking for.
For large popup boxes I use simpleModal. I started using it a little while ago and it has served all my purposes flawlessly.
For tooltips with a small amount of content in them, I use TooltipsY. Which is an EXCELLENT way to do tooltips.
Those two jQuery plugins can serve pretty much any purpose you could want regarding popup boxes.
Edit: Nevermind, I just found out what you meant by dragging. Yeah, these can't drag and drop, I've never found a purpose for that before.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I invoke an immediate update to a Java GUI? (conflict with Thread.sleep()) I am making the game Memory, when you pick two cards and if they match you get to keep them, otherwise you turn them back. If you then remember cards you have already chosen, you can venture a better guess on the next two cards.
The problem I have involves the repaint() method not immediately repainting.
When I flip the second card, no matter the outcome, I want to show both cards flipped right-side up before either discarding them or flipping them back over. I do this by calling sleep().
Of course if I repaint() the cards to flip them right-side up, wait a second, and then repaint() again based on their values, helpful little Java will only repaint once (I miss C!).
Basically I want to force invoke a update before I sleep(). I have read some other threads that basically say the best way is to create two threads to keep your logic and graphics separate, and then you can sleep() your logic and keep your GUI updating, but I am in the first semester of a first year CS course in high school, and I would want to keep it on the course's level (although I spent quite a bit of time over the summer web developing and coding in C).
Because I know the helpful folks on StackOverflow love to read code, here is the part of the program I am referring to below. The class HitArea is the Card object and the cards[] array contains an amount of HitArea's.(I haven't gotten to renaming the HitArea class). activeCard1 and activeCard2 are HitArea instances I use to keep track of the user's two selections, and the blank constructor is a reserved "invisible" HitArea, although I will change it to null later. Finally, cards.flip() inverts a toggle boolean which determines whether the card is right-side up.
public void respond(HitArea choice)
{
if(choice.inGame)
{
if(activeCard1.value == 0 && activeCard1.value == 0)
activeCard1 = choice;
else if((!(activeCard1.value == 0) && activeCard2.value == 0) && (activeCard1.id != choice.id))
{
activeCard2 = choice;
check();
}
}
}
public void check()
{
update();
pause(250);
if(activeCard2.value == activeCard1.value)
{
score += 2;
activeCard1.inGame = false;
activeCard2.inGame = false;
}
activeCard1.flip();
activeCard2.flip();
activeCard1 = new HitArea();
activeCard2 = new HitArea();
}
public void pause(int milliseconds)
{
try{
Thread.currentThread().sleep(milliseconds);
}
catch(InterruptedException e){
System.out.println("Exception: " + e);
}
}
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
for (int i = 0; i < cardNum; i++)
if(cards[i].boundsCheck( x, y ) )
{
repaint();
cards[i].flip();
respond(cards[i]);
}
}
I have no doubt there are some issues in my code, so feel free to point them out. I think my basic structure is okay, and I would rather not create multiple threads for this project (remember, it's basic!).
A: Don't call Thread.sleep(...) on the main Swing thread, the EDT. Ever. Instead use a Swing Timer.
Consider using JLabels to display your images, and then you could "flip" your cards by simply swapping out ImageIcons. When the second card has been flipped, if there's no match, start a non-repeating Swing Timer with a delay for xxxx ms, and in the Timer's ActionListener's actionCommand method have it revert both JLabel's back to the default ImageIcon.
The javax.swing.Timer tutorial can be found here: How to use Swing Timers
Edit:
Regarding your comment about using g.drawString: it's even easier now since all you have to do is swap out your JLabel's text. But later if you decide to upgrade the program to display images, you've got it all set to do this.
Edit 2:
Regarding your question about making a new ActionListener class: I'd use an anonymous inner class for this. For example:
int delayTime = 2 * 1000;
javax.swing.Timer myTimer = new Timer(delayTime, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO: put in the code you want called in xxx mSecs.
}
});
myTimer.setRepeats(false);
myTimer.start();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Insert unique identifier foreign key into table in SQL Server I’m attempting to insert dummy search data using statements like this (the values differ for each one):
insert into SEARCHRESULTEXTENSIONBASE
(CAL_ISBN, CAL_SEARCHRESULTID, USAGEDATAIMPORTID)
VALUES('9780347011266', '1317168818', '925e3a5e-e971-11e0-9425-00219b71cde3')
But I’m getting this error:
[SQL Server] Conversion failed when converting from a character string
to uniqueidentifier.
The field USAGEDATAIMORTID is a uniqueidentifier field, and I'm using similar statements in another table which successfully accepts the data:
INSERT INTO IMPORTUNIVERSITY
(USAGEDATAIMPORTID, PAGENUMBERS, PUBLISHERNAME, RECORDID, DEPARTMENTNAME)
VALUES('925e3a5e-e971-11e0-9425-00219b71cde3', '2',
'Nationwide News Pty Limited',
'74', 'Business');
The only difference that I can see is the SEARCHRESULTEXTENSIONBASE table USAGEDATAIMPORTID is a foreign key to the IMPORTUNIVERSITY table.
Any ideas?
EDIT:
insert into SEARCHRESULTEXTENSIONBASE
(CAL_ISBN, CAL_SEARCHRESULTID, USAGEDATAIMPORTID)
VALUES('06463322521', '1317173481', convert(uniqueidentifier,'925e3a5e-e971-11e0-9425-00219b71cde3'))
gives me the same error.
A: Try this:
insert into SEARCHRESULTEXTENSIONBASE
(CAL_ISBN, CAL_SEARCHRESULTID, USAGEDATAIMPORTID)
VALUES('9780347011266', '1317168818',
convert(uniqueidentifier, 'b6c51461-e966-11e0-b87a-0219b71cde3'))
You need to convert your string to the uniqueidentifier datatype.
A: You have one less digit in the GUID you are using. Could be a copy paste error.
b6c51461-e966-11e0-b87a-0219b71cde3 - has 31 digits
F567D3BC-45E9-4891-A0FB-BDE143236867 - should have 32 digits (correct)
You can test it as
SELECT Cast('b6c51461-e966-11e0-b87a-0219b71cde3' as UniqueIdentifier)
throws
Conversion failed when converting from a character string to uniqueidentifier.
while
SELECT Cast('F567D3BC-45E9-4891-A0FB-BDE143236867' as UniqueIdentifier)
works fine.
A: Looks like CAL_ISBN or CAL_SEARCHRESULTID is uniqueidentifier and you are trying to insert a character string instead. Could you please provide schema definition of the table you are inserting to and getting a error.
A: The problem was caused by there being no matching UUIDs in the two tables, thus the foreign key relationship failed. Would've been easier to work out if the error message wasn't so misleading.
Thank you for your help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Date formatting on Action/Object publishing With the new Action/Object parts of Open Graph, I'm trying to publish a DateTime formatted absolutely, something like:
"Dave is attending EventName on ...
9/28/2011 at 9:30pm"
However, I can only get the date to render in two formats: "123456789" or "3 hours left".
I have created an Object, called Event. I've given it a custom field Time of type DateTime.
I have created an Action, called Attend, which is associated with an event.
On the Event's page, I'm writing the meta tag using the Event's time in the same format as php time().
In both the Aggregation and the Action, I am trying to output "{event.time}" in the correct format. Based on the Formatter section of this page of FB's documentation, I'd think that I could specific a specific date formatter, like date(“F d, Y”). However, I always get an error like "Invalid format date(“F d, Y”)".
Any ideas how to get proper date formatting? Thanks!
A: The closest you can get is {event.time | date("fb_absolute")}. This is done to keep consistency with other dates on Facebook.
A: I've reported this as a bug https://developers.facebook.com/bugs/198438833569505
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 'Unrecognized Selector' Error When Accessing Delegate I'm working on homework assignment #3 for CS193P (Fall 2010), the graphing calculator. I've successfully implemented the delegate to pass the expression and the scale, and am now trying to add an additional field to the delegate, as referenced in my earlier question.
Here is the error:
>2011-09-27 20:27:24.076 Graphing Calculator[8892:f803] -[GraphViewController errorForGraphView:]: unrecognized selector sent to instance 0x6c32d10
2011-09-27 20:27:24.077 Graphing Calculator[8892:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GraphViewController errorForGraphView:]: unrecognized selector sent to instance 0x6c32d10'
*** First throw call stack:
(0x13bb062 0x154cd0a 0x13bccfd 0x13bd093 0x13220d9 0x1321cf2 0x8876 0x8d83 0x5ca23 0x1d97c13 0x1daa129 0x1cca15d 0x1da9fce 0x1d97ced 0x1d9e27d 0x1d97d13 0x1da1c58 0x1d27fb5 0x1d29ea2 0x1d2957c 0x138f9de 0x1326680 0x12f2516 0x12f1dd4 0x12f1ceb 0x12a4879 0x12a493e 0x1e38b 0x287f 0x27d5 0x1)
terminate called throwing an exceptionCurrent language: auto; currently objective-c
(gdb)
And here is the line where the SIGABRT shows up:
BOOL error = [self.delegate errorForGraphView:self];
Which can be found in GraphView.m in my Graphing Calculator project on GitHub. I am using ARC with iOS 5 beta.
Update
I should add that there is an errorForGraphView method defined in the CalculatorBrain class. What am I missing (my understanding of delegates is pre-nascent) that causes everyone to look in GraphViewController to find the method? How should I pass information from CalculatorBrain to GraphView?
A: So like they said its because there is no method supposedly defined but here is an really really easy way to ensure that the method is defined:)
in whatever class that is calling [self.delegate errorForGraphView:self]; create a protocol
@protocol Whatevertheclassis <NSObject>
-(BOOL)errorForGraphView:self];
@end
and then declare your delegate as such
@property(nonatomic, retain) id <Whatevertheclassis> delegate;
and then synthesize the delegate
@sythesize delegate;
and then in the class that creates the whateverclassthisis simplye set delegate to self and implement the Whatevertheclassis protocol and write the method:)
As you type the header for the method after implementing the protocol the rest of the function should show up meaning you did it correctly:)
A: Well if you look at GraphViewController it has does not have the method you specified, so i suggest you look into why you are setting it as the delegate...and if its the right thing for it to be the delegate , then implement the method in question
A: The message means exactly what it say: A GraphViewController object was "sent" an "errorForGraphView:" "message" (ie, "errorForGraphView:" was called using a GraphViewController object pointer.
Either you have the wrong pointer (maybe you should have a GraphView object instead?), or you simply forgot to implement errorForGraphView: (or perhaps spelled it wrong when you implemented it).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: QComboBox fused to QSpinBox So I am writing a Qt GUI for some scientific software and I have QSpinBoxes and QDoubleSpinBoxes for a quantities that user should set the units of. Because I have several of these spinbox-combobox pairs in a row I think it would be least confusing to have the ComboBox on the right fused to the SpinBox on the left.
I have attempted this with stylesheets but I am losing the plastique style when I do this.
What would be a [preferably non-kludgy] way to do this?
Thanks,
Andreas
A: If by fused you mean that distance between spinbox and combobox should be zero, then you should create QProxyStyle descendant, reimplement styleHint to return -1 if asked for QStyle::PM_LayoutHorizontalSpacing, and declarie a slot called layoutSpacingImplementation (read QStyle documentation) that is recieving both widget types (as representing them enums).
MyClass::layoutSpacingImplementation( QSizePolicy::ControlType control1,
SizePolicy::ControlType control2,
Qt::Orientation orientation,
const QStyleOption * option = 0,
const QWidget * widget = 0 ) const
{
if (orientation == Qt::Horizontal &&
((control1 == QSizePolicy::SpinBox && control2 == QSizePolicy::ComboBox) ||
(control2 == QSizePolicy::SpinBox && control1 == QSizePolicy::ComboBox)))
return 0;
int spacing = baseStyle()->styleHint(QStyle::PM_LayoutHorizontalSpacing);
if (spacing >= 0) return spacing;
return baseStyle()->layoutSpacing(control1, control2, orientation, option, widget);
}
Then you set this style for widget those fused items lay on, using it's previous style as base style.
This will fuse all those elements together, so it would be best if you added some additional spaces between elements that shouldn't be fused. That is a small problem, but unfortunately documentation does not state which control describes left or right control (which i guess means that spaces are supposed to be ordering-independent), so there is no other way to achieve it.
EDIT:
Just seen posted image. There is no such control in standard qt, and achieving it by typical means is rather unlikely. You might try to create your own layout class or your own QWidget descendant, which will have your spinbox partially covering combobox (covering left round edges part to be exact), this way creating illusion of fusing. This however might look ugly if user uses style with wider edges of combobox, which will "look out" on the side of a sping box. This is quick and veeeeeery ugly workaround.
Apart from that I think the only option you have is to create your own widget - but even using painting functions from QStyle (mostly drawControl I guess) and scraps of code implementing separate QSpingBox and QCombobox this will mean lots and lots of work. Considering that what you want to achieve is simple graphical effect in UI, i would say that this is not worth the effort.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I expose my data model in a transactional form? Some software currently being written has a requirement for the data model to be transactional, implementing CRUD operations. (get a copy of data, make changes, submit it atomically, get fault messages for failures, etc.)
Is there a well documented design pattern for something like this? Maybe a library?
NOTE: I'm using C#/.NET 4.0
PLEASE NOTE, my data model is POCO! not SQL or anything.
A: Use an ORM like Entity Framework, nHibernate etc
They have built in change tracking system and implement "Unit of Work" pattern(single transaction)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySQL JOIN Not Using Primary Key When Joining on Result Returned From Function Description
I'm trying to JOIN a table using the result of a stored function. The stored function returns an unsigned integer, which is the same type as the field I'm joining against.
Problem
The field I'm trying to JOIN to is a primary key. My issue is that MySQL doesn't seem to be using the primary key here.
The relevant lines of the query (shown below) are:
LEFT JOIN second_db.s
ON s.id = first_db.find_spend_id(qi.other_type, qi.other_id)
If I replace my function call first_db.find_spend_id(...) with an integer, for example 30, EXPLAIN shows that the primary key is used, and the query is fast. If I use my function, EXPLAIN shows that the primary key is not used, and the query is slow.
Question
Is there some way I can use my function and have MySQL use the primary key when using the result of this function in this join? How should I modify my code in order to attain this most glorious resolution?
Information
Query
EXPLAIN SELECT *
FROM first_db.qhr
JOIN first_db.qi
ON qi.id = qhr.issue_id
AND qhr.status = 'Accepted'
LEFT JOIN second_db.s
ON s.id = first_db.find_spend_id(qi.other_type, qi.other_id)
JOIN second_db.spend_reports AS sr
ON sr.id = s.spend_report_id
JOIN first_db.companies AS b
ON b.id = s.member_id
JOIN first_db.brands
ON brands.id = sr.brand_id
LIMIT 0, 10
Function
CREATE DEFINER=`user`@`%` FUNCTION `find_spend_id`(lookup_other_type ENUM('One', 'Two'), lookup_other_id INT(10))
RETURNS int(10)
READS SQL DATA
BEGIN
(...snip actual code...)
return 30;
END
Explain
id select_type table type possible_keys key key_len ref rows Extra
(...snip...)
1 SIMPLE s ALL NULL NULL NULL NULL 5999 "Using join buffer"
(...snip...)
A: In my case, what I wanted to achieve was not possible with this approach.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: groupBy function in maphilight jquery plugin Does anyone know how to get the groupBy function to work in the maphighlight plugin? I want to be able to have a group of countries on a map all highlight no matter which country in the group you mouseover. I cannot get even one to work. The documentation that I have been able to find is pretty sparse.
I have added the following to each map area in the group of countries I want in the group:
href="#" class="no-hand centralasia" alt="Russia" data-maphilight='{"groupBy":".centralasia"}' onmouseover="MM_showHideLayers('Russia','','show')" onmouseout="MM_showHideLayers('Russia','','hide')">
I am not sure about this bit:
data-maphilight='{"groupBy":".centralasia"}'
I am only using the defaults in the head as I am not sure what I am supposed to add there, if anything. I have also loaded the metadata plugin as well.
<script>$(function() {
$('.map').maphilight({fade: false});
});
$.fn.maphilight.defaults = {
fill: true,
fillColor: '000000',
fillOpacity: 0.3,
stroke: false,
strokeColor: 'E77200',
strokeOpacity: 1,
strokeWidth: 1,
fade: true,
alwaysOn: false,
neverOn: false,
groupBy: ("philippines",true)
}
</script>
All help is very much appreciated as I really need to get this working ASAP.
Cheers everyone.
Dave
A: $.fn.maphilight.defaults = {
groupBy: 'rel'
}
you have to give an attribute as the string. and then you can group all using a common value
ex:-
<map>
<area rel="sri lanka" ....... />
<area rel="sri lanka" ....... />
<area rel="sri lanka" ....... />
<area rel="usa" ....... />
<area rel="japan" ....... />
<area rel="japan" ....... />
</map>
so which has the same "rel" value will be grouped. hope this will help you.
A: Just put the alt tags in map area like what "ehird" suggested first.
<map>
<area alt="sri lanka" ....... />
<area alt="sri lanka" ....... />
<area alt="sri lanka" ....... />
<area alt="usa" ....... />
<area alt="japan" ....... />
<area alt="japan" ....... />
</map>
Then call the groupBy...
$('.map').maphilight({fade: false, groupBy: 'alt'});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to download the sqlite database of an android app? I am using a sqlite database in my android app. I want to download the database to pc. Can anyone kindly tell me what to do ?
A: if your app is in emulator you can just use the DDMS and open /data/data/your.package.name/databases.
if you have your app in mobile. here is what i do to copy the db to the sdcard root folder.
/** The name of the database file */
static final String DATABASE_NAME = "mydatabase.db";
static final String DATABASE_NAME_FULL = "/data/data/com.my.application/databases/" + DATABASE_NAME;
public static boolean backUpDataBase(Context context){
boolean result = true;
// Source path in the application database folder
String appDbPath = DATABASE_NAME_FULL;
// Destination Path to the sdcard app folder
String sdFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DATABASE_NAME;
InputStream myInput = null;
OutputStream myOutput = null;
try {
//Open your local db as the input stream
myInput = new FileInputStream(appDbPath);
//Open the empty db as the output stream
myOutput = new FileOutputStream(sdFolder);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
} catch (IOException e) {
result = false;
e.printStackTrace();
} finally {
try {
//Close the streams
if(myOutput!=null){
myOutput.flush();
myOutput.close();
}
if(myInput!=null){
myInput.close();
}
} catch (IOException e) { }
}
return result;
}
you need this in your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
A: If your emulator is running you can access it by opening the DDMS perspective (Window > Open perspective > DDMS) and open data/data/your.package.name/databases and pulling it onto your computer.
You can't get it from your device if it is not rooted. If it is you can't access the directory where it is located because it is protected. You have to copy it with a root explorer onto your SD card and then you can pull it with DDMS onto your computer.
A: I solved this by using the android debug bridge. To get the database you have to execute in the directory of your sdk tools:
adb.exe exec-out run-as com.example.project cat databases/databasename > file.sqlite
where com.example.project is the packagename from the manifes and databasename is the name of your database. The database will be put to your current directory.
It works on emulators and devices (checked up to API Level 28).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Create a CSV file with PHP via fopen/fwrite but also write headers to it I feel like I am missing obvious here, but I will post anyway.
I have a 'csv.php' which creates a csv file, simple example:
// csv.php
$fh = fopen('report.csv', 'w') or die("can't open file");
while ($row = mysql_fetch_row($result)) {
fputcsv($fh, $row);
}
fclose($fh);
On a seperate page, there is a simple anchor element that links to the file above. So on home.html there is:
<a href='report.csv'>Report</a>
One user will run csv.php and another will goto home.html and click the link at a later point in time. This works fine, the CSV is created, the data is there, and the anchor links through.
I know that if I were echoing out the CSV, I would add the various headers such as:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
But how do I add these headers to the file report.csv? I assume this is required because firefox refuses to see the csv as a downloadable file (when the anchor is clicked, it just outputs the csv to the browser).
A: You won't be able to add the headers to the report.csv itself. You can alternately have a proxying script, something like download.php?report=report.csv
Then, you would do something like the following:
$csv = file_get_contents("./csv_directory/" . preg_replace("#/#", "", $_GET['report']);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csv;
Big Note
As @Pat mentioned (while I was looking for the appropriate syntax), you can use .htaccess or modify httpd.conf itself if you are using apache and have access. This, in my opinion, is a better way to solve your problem.
A: Headers aren't part of a file, they're part of an HTTP response.
If your web server is not setting the headers you want for csv files, you can probably convince it to do so.
Or, if you can't (or don't want to), see sberry2A's answer, to serve the file via php, and control the web server that way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to call a parent class's method from child class in c#? I have a master page with a method I use a lot from content page code behinds. In those code behinds, I have a method that gets duplicated a lot, so I thought I'll put it in something I can inherit from. Unfortunately, I now can't call the method in my master page code behind from the base class. I think I should know how and I'm probably being pretty stupid today but I can't figure it out.
Here's some code! Please ignore any howling errors, I just typed this off the top of my head :)
Master Page Code-behind
public partial class Site : MasterPage
{
public void MyMethod()
{
// Do Something...
}
}
Content (Child) Page
Declarative
<%@ MasterType VirtualPath="~/Site.Master" %>
Code-behind
Works
public class Test : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Master.MyMethod();
}
}
Does Not Work
public class Test : TestClass
{
protected void Page_Load(object sender, EventArgs e)
{
OtherMethod();
}
}
public class TestClass : Page
{
public void OtherMethod()
{
this.Master.MyMethod();
}
}
Now, looking at it, I intuitively know "this.Master" can't work but I don't have any lightbulbs going off for an answer. How do I get the reference to my master page method back?
Thanks,
Richard
A: You have to cast to the the type of the your MasterPage class first (in this case Site) and then you can call the public methods defined within the code behind class ...
public class TestClass : Page
{
public void OtherMethod()
{
((Site) this.Master).MyMethod();
}
}
A: You should cast this.Master to Site :
((Site)this.Master).MyMethod();
A: You have to cast this.Master to the type Site in order to access methods defined on Site : MasterPage.
public class TestClass : Page
{
public void OtherMethod()
{
((Site)this.Master).MyMethod();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Help with eraser from buffered Image So below I am working on a paint type project for class that lets you draw shapes lines etc, now my professor wants us to add a eraser tool that lets you erase parts of the image, it is on a buffered image any ideas? im fresh out
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class PaintProgram extends JPanel implements MouseListener,ActionListener
{
public static int stroke = 0;
private int xX1, yY1 , xX2, yY2, choice ;
public static void main(String [] args)
{
new PaintProgram();
}
PaintProgram()
{
JFrame frame = new JFrame("Paint Program");
frame.setSize(1200, 800);
frame.getContentPane().add(this);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu help = new JMenu("Help!!?");
menuBar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(this);
JButton button1 = new JButton("Clear");
button1.addActionListener(this);
JButton button2 = new JButton("Filled rectangle");
button2.addActionListener(this);
JButton button3 = new JButton("Filled oval");
button3.addActionListener(this);
JButton button4 = new JButton("Empty rectangle");
button4.addActionListener(this);
JButton button5 = new JButton("Empty oval");
button5.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
JRadioButton thin = new JRadioButton("Thin Line");
thin.addActionListener(this);
JRadioButton medium = new JRadioButton("Medium Line");
medium.addActionListener(this);
JRadioButton thick = new JRadioButton("Thick Line");
thick.addActionListener(this);
ButtonGroup lineOption = new ButtonGroup( );
lineOption.add(thin);
lineOption.add(medium);
lineOption.add(thick);
this.add(button1);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(button5);
this.add(button6);
this.add(thin);
this.add(medium);
this.add(thick);
addMouseListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if(grid == null){
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage)(this.createImage(w,h));
gc = grid.createGraphics();
}
g2.drawImage(grid, null, 0, 0);
check();
}
BufferedImage grid;
Graphics2D gc;
public void draw()
{
Graphics2D g = (Graphics2D)getGraphics();
int w = xX2 - xX1;
if (w<0)
w = w *(-1);
int h = yY2-yY1;
if (h<0)
h= h*(-1);
switch(choice)
{
case 1:
check();
gc.setColor(Color.YELLOW);
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.setColor(Color.CYAN);
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.setColor(Color.ORANGE);
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.setColor(Color.PINK);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
gc.setColor(Color.MAGENTA);
if (stroke == 0)
gc.setStroke(new BasicStroke (1));
if (stroke == 1)
gc.setStroke(new BasicStroke (3));
if (stroke == 2)
gc.setStroke(new BasicStroke (6));
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
//Acquire clear screen or gay
break;
}
}
public void check()
{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 =z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("About"))
{
System.out.println("stfu");
JFrame about = new JFrame("About");
about.setSize(300, 300);
BufferedImage img = null;
try{
img = ImageIO.read(new File("C:/Users/TehRobot/Desktop/Logo.png"));
}catch (IOException e1)
{
}
about.setVisible(true);
}
if (e.getActionCommand().equals("Empty rectangle"))
{
System.out.println("Empty Rectangle Has Been Selected~");
choice = 1;
}
if (e.getActionCommand().equals("Empty oval"))
{
System.out.println("Empty Oval Has Been Selected!");
choice = 2;
}
if (e.getActionCommand().equals("Filled rectangle"))
{
System.out.println("Filled Rectangle Has Been Selected");
choice = 3;
}
if (e.getActionCommand().equals("Filled oval"))
{
System.out.println("Filled Oval Has Been Selected");
choice = 4;
}
if (e.getActionCommand().equals("Line"))
{
System.out.println("Draw Line Has Been Selected");
choice = 5;
}
if (e.getActionCommand().equals("Thin Line"))
{
stroke = 0;
}
if (e.getActionCommand().equals("Medium Line"))
{
stroke = 1;
}
if (e.getActionCommand().equals("Thick Line"))
{
stroke = 2;
}
if (e.getActionCommand().equals("Clear"))
{
System.out.println("Clear All The Things!!!");
choice = 6;
repaint();
}
}
public void mouseExited(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mousePressed(MouseEvent evt)
{
xX1 = evt.getX();
yY1= evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
xX2 =evt.getX();
yY2=evt.getY();
draw();
}
}
A: One way: Graphics2D has a clearRect(...) method that allows you to set a rectangle to the background color (set via the setBackground(...) method). Why not use this in conjunction with a MouseListener and MouseMotionListener (combined in a MouseAdapter)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Parsing php data to get only individual data How do I parse this data?
This is a datetime that were from my database
2011-09-27 13:14:11
I want to get only the 13 14 and 11 separately.
the output should be:
13
14
11
Please be noted that this is a dynamic value
I could also get a datetime that has this value:
2011-09-27 1:12:00
How would I do that?
Any help would be greatly appreciated.
Thanks!
A: You can use the DateTime class to make this happen
$date = new DateTime('2011-09-27 13:14:11');
printf("%s <br />", $date->format('H'));
printf("%s <br />", $date->format('i'));
printf("%s <br />", $date->format('s'));
// Outputs:
// 13
// 14
// 11
A: Let's say you've assigned 2011-09-27 13:14:11 from db table to variable named $datetime
$result = strtotime($datetime);
$minute = date("i", $result );
$second = date("s",$result );
$hour = date("H", $result );
In your case $hour will be 13, $minute will be 14, $second will be 11. More detailed in PHP documentation
BTW
if you want to get seperate year, month, day too, use following piece of code
$year = date("Y", $result );
$month = date("m",$result );
$day = date("d", $result );
A: If you have access to the SQL query, you could simply do:
SELECT
HOUR( `dateTimeColumn` ) AS `hours`,
MINUTE( `dateTimeColumn`) AS `minutes`,
SECOND( `dateTimeColumn` ) AS `seconds`,
# etc...
FROM
`yourTable`
# etc...
... thereby letting MySQL do the parsing, and access them in PHP with something like:
$row[ 'hours' ];
$row[ 'minutes' ];
$row[ 'seconds' ];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: posts_per_page not working for new wp query I need to set the post_per_page to display only 1 post here's the code I use:
<?php
$yell = new WP_Query(array('posts_per_page' => 1,'post_type' => 'items', 'portfolio-category' => 'accessories'));
while ($yell->have_posts()) : $yell->the_post();
?>
<h2><?php the_title(); ?></h2>
<?php endwhile; wp_reset_query(); ?>
But it doesn't show 1 post, it shows all. not sure why
A: You can do it with the post_limits filter:
add_filter('post_limits', 'your_query_limit');
function your_query_limit($limit){
return "LIMIT 1";
}
Update: If you only want this to run for your custom query, you could do the following:
*
*Add it.
*Run the custom query.
*Remove it.
Code would be like so:
add_filter('post_limits', 'your_query_limit');
$yell = new WP_Query(
array(
'post_type' => 'items',
'portfolio-category' => 'accessories'
)
);
remove_filter('post_limits', 'your_query_limit');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: knockout loads, but does not work in IE I'm building a client-side application with jquery and knockoutjs. It works great in FF and Chrome, but crashes in a really puzzling way in IE v8.
For debugging, I'm running this code:
$(document).ready(function(){
//A bunch of code that works fine ...
//...
alert( viewModel );
alert( ko.toJSON );
alert( ko.toJSON(viewModel) );
ko.applyBindings(viewModel);
alert( "Done" );
});
IE gives me two alert boxes:
[object Object]
and
function(a){a=p.oa(a);return p.a.Y(a)}
The first one is my viewModel. I believe the second is the minimized ko.toJSON command. Why can't it run the third alert? This happens even if I set viewModel to something simple, like {};
(BTW, the ko.applybindings line doesn't work either. That's why I was debugging in the first place.)
A: It looks like you are running in IE 8 Compatibility Mode or in IE 7 Mode. Hit F12 and check your browser mode.
A: I know some versions of IE don't support JSON natively and so it has to be included as a JavaScript include. Crockford's JSON2 parser: https://github.com/douglascrockford/JSON-js
But the compatibility mode of IE, if set correctly should also resolve this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Trying to make App Store loading bar When an app is downloaded from the app store, it goes directly to the home screen with a nice looking loading bar (to show when the app is downloading/installing). JailbreakMe 3.0 utilizes this. Does anyone know how to use this? I'm trying to make an install script to install a set of .deb files on an iPhone, and I'd like the App Store install style. Thanks in advance.
(Got a picture of it if nobody understand's what I'm talking about)
A: Try checking the JailbreakMe 3.0 source code : https://github.com/comex/star_/tree/master/install
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using RackSpace to store data from 1,000 iPhones without "sharing" Is there a simple way to have all my users of an app have a part of RackSpace for some of their information, let's say key'ed by their UUID (an id unique to their iPhone), with that data encrypted just for them?
That way, all 1,000 could upload and download info, and if they wanted, could forward their info to me via that cloud. And if they freak out, they can destroy their cloud's data for their UUID.
Is this written, or do I have to write it? Can it use SQLite? Or should / can I use a csv attachment to an email to the RackSpace Cloud, that is public key encrypted?
In other words, can they each have their own sandbox, which may be quite small (50,000 bytes)?
And can there be 1 row per user, with the option that they can send up detailed info (10 megs of thousands of records) now and again if they run into a bug in my code?
A: You can look at Parse it is a no sql freeform database in the cloud
A: Look at iCloud. We can't talk about yet on here (because it is still under NDA). If you are an Apple developer, you can read the documentation there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails 3.1 Remote Button Unobtrusive Javascript event not caught (JQuery) I want to start using the Ajax events ajax:success, ajax:failure, ajax:complete and ajax:beforeSend as recommended for unobtrusive Javascript in posts like:
*
*http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/
*http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
But for some reason it's not working for me. I am missing something (something small) as I cannot get the events to trigger my Javascript. I am hoping someone could spot the "obvious" mistake/omission in my code.
Some details on my environment:
*
*Rails 3.1
*jQuery (jquery-rails gem)
*therubyracer for server side js processing (not that it should matter for my example)
To try and work out what I am missing I have created a simple test application which has a single remote button to. When the button is clicked, I want alert boxes to fire. The code of this app can be seen on github here:
http://github.com/jpmcgrath/rbtest
I have deployed the application to heroku here:
http://rbtest.heroku.com/projects/
If you look at the app, you can click the button and the button successfully creates a new project (to see it manually refresh), but ajax:success event doesn't seem to happen?
The guts of the code is as follows:
In projects_controller.rb
def remote_test
@project = Project.new(:name => "remote test")
respond_to do |format|
if @project.save
puts "project saved!\n\n\n"
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
In application.js
jQuery(document).ready(function() {
jQuery(".remote_button").click(function() {
alert('Handler for .click() called.');
})
.bind("ajax:complete", function() {
alert('complete!');
})
.bind("ajax:beforeSend", function () {
alert('loading!');
})
.bind("ajax:error", function (xhr, status, error) {
alert('failure!');
})
.bind('ajax:success', function(event, data, status, xhr) {
alert('success!');
});
});
In the view projects/index.html.erb
<%= button_to "remote test", remote_test_path, :remote => true, :class => 'remote_button' %>
If anyone could point out what I am missing (I suspect it has something to do with response type) it would be greatly appreciated.
A: The reason your event handler is not firing is because your selector is on the wrong element. button_to creates a form with a single input tag, and it's that input tag that has the class your selecting on, but the ajax events are triggered on the form, not the input tag.
Try this
jQuery(document).ready(function() {
jQuery(".remote_button").click(function() {
alert('Handler for .click() called.');
});
jQuery("form.button_to").bind("ajax:complete", function() {
alert('complete!');
})
.bind("ajax:beforeSend", function () {
alert('loading!');
})
.bind("ajax:error", function (xhr, status, error) {
alert('failure!');
})
.bind('ajax:success', function(event, data, status, xhr) {
alert('success!');
});
});
I did the equivalent in my firebug console and it fired the ajax:success handler when the callback was on the form.
To change the class on the form use the :form_class option to change it from button_to to something else
<%= button_to "remote test", remote_test_path, :remote => true, :class => 'remote_button', :form_class => 'remote_button_form' %>
Then add your ajax callbacks using
jQuery(".remote_button_form").bind ...
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to
A: Rails has changed how javascript files are handled.
Railscasts has a few examples.
http://railscasts.com/episodes/279-understanding-the-asset-pipeline
http://railscasts.com/episodes/267-coffeescript-basics?autoplay=true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ClassNotFound W/ Spring using Eclipse Tomcat Maven M2Eclipse Sorry I am new to this stack overflow stuff so pardon the long error message at the bottom.
I am trying to deploy a project called BroadLeaf to a Tomcat 7 server using eclipse. I have installed M2Eclipse/WTP Integration. I run a maven configuration (through eclipse) with clean package as the goals. Then I do a refresh and try to start the server, however, it fails.
UPDATE: I am trying to deploy the project found here... https://broadleaf.svn.sourceforge.net/svnroot/broadleaf/trunk/BroadleafCommerce/site/BroadleafCommerceDemo/pom.xml
Any ideas?
java.lang.ClassNotFoundException: org.springframework.web.util.Log4jConfigListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1664)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:406)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:388)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:117)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4268)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4771)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:772)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:424)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:648)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.startup.Catalina.start(Catalina.java:576)
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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415)
Sep 27, 2011 8:41:12 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.broadleafcommerce.profile.web.extensibility.MergeContextLoaderListener
java.lang.ClassNotFoundException: org.broadleafcommerce.profile.web.extensibility.MergeContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1664)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:406)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:388)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:117)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4268)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4771)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:772)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:424)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:648)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.startup.Catalina.start(Catalina.java:576)
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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415)
Sep 27, 2011 8:41:12 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.security.web.session.HttpSessionEventPublisher
java.lang.ClassNotFoundException: org.springframework.security.web.session.HttpSessionEventPublisher
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1664)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:406)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:388)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:117)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4268)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4771)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:772)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:424)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:648)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.startup.Catalina.start(Catalina.java:576)
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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415)
Sep 27, 2011 8:41:12 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)
Sep 27, 2011 8:41:12 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Sep 27, 2011 8:41:12 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/broadleaf] startup failed due to previous errors
A: The problem appears to be with WTP not integrating properly with the maven dependancies. Not the best solution I fixed the issue by....
*
*in eclipse right click on the project and go to properties
*Go to deployment assembly
*click add
*Select Java Build path entries
*select all the M2_HOME entries.
*Clean build and deploy project DO NOT USE THE M2ECLIPSE PLUGIN WITH ECLIPSE:ECLIPSE!
*Should get you around the error.
Anyone know the real solution?
UPDATE: Also the next time I imported WTP seemed to vibe with Maven, so maybe delete and reimport your project after installing the plugin?
A: Looking at the pom files in broadleaf source repository, it looks like none of them build a web application (war artifact). This is required for the m2eclipse/wtp integration to work correctly.
If this is not the case, please edit the question specifying the specific broadleaf sub project you are trying to deploy in tomcat.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577230",
"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.