text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: CCAnimate with sprite file names? CCAnimate requires CCSpriteFrames, while they require a texture2d.
Is it not possible to simply use CCAnimate by providing my file names? Like anim1.png, anim2.png, anim3.png...
A: Not directly.
If you are on versions 0.99.*, you can load the files into UIImages, then create CCTexture2Ds using the initWithImage: function, then create CCSpriteFrames.
If you are on version 1.0.0 or later, you can load the textures from files using the CCTextureCache singleton, then create CCSpriteFrames.
However, the whole point behind this API is that you can place all the frames of your animation into one image file, load it as a texture, and then carve out the individual frames using the rect property/argument. This should also improve performance, since the graphics chip only has to load one texture and then perform cheap clipping operation instead of loading multiple textures.
EDIT: Cocos2D has a function for direct CCSpriteFrame loading since version 1.1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery datatables editable plugin - Delete Confirmation Dialog I using editable plugin for my jquery datatable to do inline delete. Currently once the delete button is clicked, the controller delete action is called and the row will be deleted. However, i wish to show a confirmation dialog prior to deletion, and only if user click ok, the delete operation will proceed. I got no idea how to do this because the plugin just required the controller action url to be passed in the "sDeleteUrl" parameter. I cant get much information from the web too, hope can get some help here...... Really appreciate it
(Following is my code which initialize the datatable together with the editable plugin to enable inline delete)
// Initialize data table
var myTable = $('#stocktable').dataTable({
// Try styling
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
// To use themeroller theme
"bJQueryUI": true,
// To use TableTool plugin
"sDom": 'T<"clear">lfrtip',
// Allow single row to be selected
"oTableTools": {
"sRowSelect": "single"
}
// Use dataTable editable plugin to allow ajax delete
}).makeEditable({
// Reference to controller action
//sAddURL: "/Stock/AddData",
sDeleteURL: "/Stock/DeleteData",
sDeleteHttpMethod: "GET",
// Add "" for class for IE to works
oDeleteRowButtonOptions: {
label: "Remove",
"class": "buttons"
}
});
A: See http://jquery-datatables-editable.googlecode.com/svn/trunk/custom-messages.html. In the on row deleting you can put confirmation message and call delete function if true is returned from the confirm box.
In this example is used jConfirm but you can use the plain confirmation dialog and call fnDeleteRow(id); if user clicks "Ok".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How would I add a slider transition to my website with jQuery? I am using the jQuery library so that is available. I need to know how to add a sliding effect to this page:
http://qasim.x10.mx/iqbal/
Notice when you click it, it fades in and out, but I would much rather love it to slide, I have a small idea on how they work but, in the way it is currently coded, but not sure the proper technique in implementing one. what could be the easiest way?
Many thanks.
A: As I understand your site, you have this code that does the fading transition:
$('nav ul li').not('#line').click(function(){
selected = $(this).attr('id');
$('nav ul li').css({'background': '', 'color': '#999'});
$(this).css({'background': getColor(selected), 'color': '#FFF'});
$('.content').fadeOut('fast', function(){
$(this).html($('div#'+selected).html());
$(this).fadeIn('fast');
})
})
If you wanted it to slide, it'd probably be easier to use jQuery UI. If you want something like to slide and fade off to the left, then you could use the drop transition in jQuery UI to accomplish this:
$('nav ul li').not('#line').click(function(){
selected = $(this).attr('id');
$('nav ul li').css({'background': '', 'color': '#999'});
$(this).css({'background': getColor(selected), 'color': '#FFF'});
$('.content').hide('drop', {direction: 'left'}, 'fast', function(){
$(this).html($('div#'+selected).html());
$(this).show('drop', {direction: 'right'}, 'fast');
})
})
I obviously didn't try running this exact code on your site, but it will definitely look something like that.
You can find out more about the drop effect here:
*
*http://docs.jquery.com/UI/Effects/Drop
*http://jqueryui.com/demos/hide/ (click Drop on the dropdown menu)
Hopefully this helps. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .gitignore won't ignore the directory I'm trying to ignore the xcuserdata folders that xcode 4 modifies and they keep come back despite being in my .gitignore file.
My .gitignore file as one line:
xcuserdata
Yet as soon as I change anything UI in xcode, I get this:
# modified: XXXXXXXX.xcodeproj/project.xcworkspace/xcuserdata/XXXX.xcuserdatad/UserInterfaceState.xcuserstate
I have done a...
git rm -r --cached XXXXXXXX.xcodeproj/project.xcworkspace/xcuserdata/XXXX.xcuserdatad/UserInterfaceState.xcuserstate
...and tried...
git rm -r --cached XXXXXXXX.xcodeproj/project.xcworkspace/xcuserdata
...followed by a commit. I have done this close to 10 times and it just won't go away and be ignored. It keeps coming back.
What am I doing wrong? There is clearly something I am not understanding. The file did get added to the repository when I first created it and now I'm trying to get rid of it.
I just want that file to become completely untracked like it had never been added to the repository.
A: After doing
git rm -r --cached XXXXXXXX.xcodeproj/project.xcworkspace/xcuserdata
check that git status tells you that the files under that folder have been deleted. Then after your commit, ensure that git says there is nothing to commit.
The fact that you have done this "10 times" and it comes as modified shows that you are not doing it right and the folder ( actually the files within it) are still tracked.
Apart from that the content of the .gitignore seems fine and I have even confirmed on my repo that it works.
A: If you can't push your commit just because UserInterfaceState.xcuserstate has been modified, here's a quick fix:
*
*Open the Organizer, go to Repositories, copy your the commit's code (something like f01a2147218d by username)
*Open the terminal, go to your project's folder, do git reset --hard f01a2147218d
*Push the commit!
A: try using xcuserdata/ in your .gitignore
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: What does the jg instruction do on classic Intel processors? For the code:
cmp $5, %eax
jg 804940f
This compares by doing %eax - $5 and then sets a flag(s) if it's greater, equal, or negative, correct? Then jg will proceed to that address if the flags dictate that %eax is greater than $5?
A: It does do a subtraction, but it does not keep the result. It then sets the flags accordingly. You are also correct about the second line, if its greater then it jumps, if not then it skips the jump and continues executing whatever is next.
EDIT: In case you are new to assembly, you may also find it helpful to have access to the contents of the flags register. There are a few ways to do this in Intel assembly, if you need the lower 8 bits then you can do lahf which will load them into ah. If you want the entire contents of the register, then you can use pushf and popf. I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Resolve PowerShell Function Parameter Values Among Parameters I'm trying to figure out how to force the PowerShell runtime to parse a string in expression mode when passing a parameter that includes another parameter's value to a function. For example, I want to pass two parameters to a function with the second parameter using the first parameter's value. I know I need to have the parser evaluate the second parameter value in expression mode but the output doesn't seem to resolve the first parameter's value.
PowerShell Command #1
This example works as desired and proves the command is evaluated in expression mode when using a sub-expression around 2 + 2
& { param($test1,$test2); $test1; $test2 } "foo" "Test 1 value: $(2 + 2)"
Output
foo
Test 1 value: 4
PowerShell Command #2
Now when I try the same things to have parameter two ($test2) reference the value for parameter one ($test1), the expression doesn't seem to be evaluated or at least the value for $test1 is blank or null.
& { param($test1,$test2); $test1; $test2 } "foo" "Test 1 value: $($test1)"
Output
foo
Test 1 value:
Note how the Test 1 value is blank when I think it should be "foo", the value passed in the $test1 parameter. What am I missing about parameter scope in a PowerShell function? Why is the $test1 value not available to be referenced in the expression passed as the value for $test2? Is there a more elegant way to do this?
A: This is because the "expression" is evaluated outside the scriptblock, before even passing the arguments to the scriptblock.
So something like:
$test1 = 4
& { param($test1,$test2); $test1; $test2 } "foo" "Test 1 value: $($test1)"
will give the output:
foo
Test 1 value: 4
Workarounds:
& { param($test1,$test2); $test1; & $test2 } "foo" {"Test 1 value: $test1"}
But I suppose in the real situation, you wouldn't want to change the scriptblock ( or function etc. ) you are working with.
I would also question the need for this situation, as what you really want to do is this:
$test1 = "foo"
$test2 = "Test 1 value: $test1"
& { param($test1,$test2); $test1; $test2 } $test1 $test2
A: Thanks for the responses and that helps clarify some things. Ultimately, I want to pass parameters to a script from a database. The parameter values include references to other PowerShell parameters and they can't be resolved until the script runs. I'm running a PowerShell runspace in IIS and I couldn't figure out how to force the parser to evaluate an expression using the standard "" characters.
Alas, I found the $ExecutionContext.InvokeCommand.ExpandString() function in PowerShell that does exactly what I need. This function actually is executed under the covers by the "" characters as documented at http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-12-command-discovery-and-scriptblocks.aspx#executioncontext.
It takes a little extra work to do what I want but I was able to use the following pattern to resolve the values in the script. This forces the parser to re-evaluate $test2 in expression mode and perform the variable subsitution, resulting in a string that includes the proper variable values.
$test2 = $ExecutionContext.InvokeCommand.ExpandString($test2)
Thanks again for the comments and guidance!
A: reminds me of schema\lisp! You can pass functions as parameters in that language - I don't know if you can pass a scriptblock as a parameter in PS though.
Anyway, does it matter what that you refer to the name of the variable?
If not and you just want to refer to the first variable (or the variable of your choice) you could do something like this:
& { $args[0]; $args[1]; "Value of arg #$($args[1]): $($args[$($args[1])])"} "foo" "0"
works with other multiple variables:
& { $args[0]; $args[1]; "Value of arg #$($args[1]): $($args[$($args[1])])"} "foo" "3" 23 24 25 26
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i get the string after an element with jquery? I have several forms on my page. Each form is named according to the ID in the database.
<form id="spam-X" method="post">
So on my page, if there are 3 comments, there are 3 forms.
<form id="spam-1" method="post">...</form> <form id="spam-2" method="post">...</form> <form id="spam-3" method="post">...</form>
Now I want to run a set of functions for based on what form is submitted. So I have my submit function in jquery...
$("form#[id^='spam']").submit(function() {
Now the problem is, I want to get the contents within this specific form that was clicked, so I'm assuming I will need the trailing ID (spam-1, spam-2, spam-3).... How do I get that value?
A: Just use:
$("form#[id^='spam']").submit(function() {
var formThatWasSubmitted = this;
}
The to get the value of a particular input in that form:
var email = this.email.value;
A: You don't need to refer to the form by it's specific ID, because the function you bind to the submit handler will be called with 'this' being the DOM element of the form. You can get the text content of the form using the text() function:
$("form#[id^='spam']").submit(function() {
// 'this' is the dom element that is being submitted
var text = $(this).text();
});
A: Try using $(this).attr('id') inside the submit handler.
A: You can use the $(this) inside the function to get access to the form that was activated by the click.
Then using something like $(this).find("SELECTOR").val() to narrow down to the field that you need the information from. Where you'd need to substitute SELECTOR with the name or class selector for your field inside that form.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: objectdatasource search help i have my ObjectDataSource1 setup to use with my GridView. If I want to setup a Search text box for the GridView will I need to create a new ObjectDataSource2 to tie it to the Search textbox?
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="ShelterExpress.ShelterData"
DataObjectTypeName="ShelterExpress.Shelter"
InsertMethod="InsertShelter"
UpdateMethod="UpdateShelter"
DeleteMethod="DeleteShelter"
SelectMethod="GetShelters"
OldValuesParameterFormatString="original_{0}">
<DeleteParameters>
<asp:Parameter Name="shelterId" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
A: You'll need to setup select parameters like you've done for delete. You'll use control parameters.
<SelectParameters>
<asp:ControlParameter ControlID="txtSearch" PropertyName="text" Direction="input" Name="filterField" type="string"/>
</SelectParameters>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mouseover & hoverIntent I'm using mouseover to change the slide number on the jQuery Supersized plugin depending on which button you rollover.
However, if the fade animation to the next slide hasn't completed before rolling over another button, it doesn't change the slide.
Is there a way to re-check every few milliseconds whether the mouse is still over the button and load the slide if it hasn't been loaded already?
Also I'd like to load a different slide if the mouse hasn't been over any of buttons for a certain amount of time. How can I stack up the events so the mouseout refers to all of the buttons and also add a time event?
My code so far (mouseout currently only applies to the last button):
$(".mybutton1").mouseover(function() {
api.goTo(2);
});
$(".mybutton2").mouseover(function() {
api.goTo(3);
});
$(".mybutton3").mouseover(function() {
api.goTo(4);
}).mouseout(function(){
api.goTo(1);
});
Thanks in advance!
.
=====================UPDATE=====================
Thanks very much for your latest update. Unfortunately I couldn't get your code to work. However, I think I may have found an simpler solution modifying your original code and using jQuery hoverIntent…
I found out I could disable Supersized from stopping the slides changing during the animation and I can use hoverIntent to ensure that it waits enough time before changing the slide so the animations don't stack up.
The following code works perfectly changing slides on mouseover.
But I can't get mouseout to work because it's creating a new instance of it for each button, and it stacks up the animations when the mouse rolls out of one button and onto the next. Also there only seems to be a delayed timer for the mouseout and not an interval option like the mouseover.
So I just need to modify this slightly so that:
If the mouse is not over ANY of the buttons for 1000 ms, then api.goTo(1);
The only way I can think of would be to create an invisible link the entire size of the browser window and run a second hoverIntent function to change the slide when it rolls over this, but I don't think that would be the best way!
Thanks
var buttonNumber = <?php echo $project_count; ?>; //Change this number to the number of buttons.
var prefix = "#project-link";
var prefix2 = "#project-bullet";
for(var i=0; i<buttonNumber; i++){
(function(i){ //Anonymous function wrapper is needed to scope variable `i`
var id = prefix+i;
$(id).hoverIntent({
interval: 350,
over: mouseyover,
timeout: 1000,
out: mouseyout
});
function mouseyover(){
api.goTo(i+2);
$(".project-bullet").fadeOut(1);
$(prefix2+i).fadeIn(1000);
}
function mouseyout(){
//api.goTo(1);
}
})(i);
}
A: Updated answer (9 oct 2011):
Revisions:
*
*Line 4: var goToApiOne = false; //New: the "memory" of Api 1
*Func mouseyover, first line: goToApiOne = false; //Cancel any move to Api 1
*Func mouseyout: See below, the whole function has been replaced
The concept behind this code:
*
*Mouseover anything (goToApiOne = false)
*Mouseout anything goToApiOne = true + setTimeout with a delay of 1000ms
*IF hovered over another slide before 1000ms have been passed THEN go to step 1
*Function call by setTimeout: If goToApiOne == true THEN gotoApi(1); andgoToApiOne = false (reset).
var buttonNumber = <?php echo $project_count; ?>; //Change this number to the number of buttons.
var prefix = "#project-link";
var prefix2 = "#project-bullet";
var goToApiOne = false; //New: the "memory" of Api 1
for(var i=0; i<buttonNumber; i++){
(function(i){ //Anonymous function wrapper is needed to scope variable `i`
var id = prefix+i;
$(id).hoverIntent({
interval: 350,
over: mouseyover,
timeout: 1000,
out: mouseyout
});
function mouseyover(){
goToApiOne = false; //Cancel any move to Api 1
api.goTo(i+2);
$(".project-bullet").fadeOut(1);
$(prefix2+i).fadeIn(1000);
}
function mouseyout(){
goToApiOne = true; //Activate delay
setTimeout(function(){
if(goToApiOne){
goToApiOne = false; //Disable GoTo Api 1
api.goTo(1);
}
}, 1000);//Timeout of 1000ms
}
})(i);
}
Old answer (28 sept 2011):
I have changed your code, so that you can easily apply effects to multiple buttons without having to copy-paste the contents of the function.
Read the comments in the code below, and adjust the code to your wishes. It's important to have the fadeFinished variable in the scope of your fade function, and the button event handler.
var buttonNumber = 3; //Change this number to the number of buttons.
var poller = {interval:0, delay:0}; //timeout reference
var prefix = "#projectlink";
function pollerFunc(i, delay){
//i = buttonNumber.
//delay = number of intervals before activating a requested slide
if(delay !== true){
//Clean-up
poller.clearInterval(poller.interval);
poller.delay = delay || 0;
//Set new interval. 50 milliseconds between each call
poller.setInterval(function(){pollerFunc(i, true)}, 50);
}
else if(!vars.in_animation){
//Check whether a delay has been requested. If yes, decrease the delay
// counter. If the counter is still higher than zero, return.
if(poller.delay > 0 && --poller.delay > 0) return;
window.clearInterval(poller.interval);
var gotoNum = (i+2) % buttonNumber;
// % = Modulo = Go back to x when the number = buttonNumber + x
api.goTo(gotoNum);
}
}
for(var i=0; i<buttonNumber; i++){
(function(i){ //Anonymous function wrapper is needed to scope variable `i`
var id = prefix+i;
$(id).mouseover(function(){
pollerFunc(i, 0); //No delay, if possible.
})
.mouseout(function(){
pollerFunc(i, 10); //Delay 10 intervals (50x10 = 500 milliseconds
// before fading back to slide 1
})
})(i);
}
Another note: I recommend changing .projectlink to #projectLink, because the element should only occur once.
Expected behaviour:
*
*mouseover #projectlink2: Go to slide 4 (first time, no delay)
*mouseout: Set a slide 1 request with a delay of 500 ms.
*mouseover #projectlink1 (within 500ms) Aborts "slide 1 request". Initiates slide 3
*mouseout (before the animation has finished) Set a slide 1 request with a delay of 500ms
*mouseover #projectlink3: The previous (see 3) animation has not finished yet. "Slide 5" is requested without a delay
*The slide animation (3) has finished Immediately starts slide 5.
*mouseout Set a slide 1 request with a delay of 500ms
*500ms has passed: Initiates slide 1
*Et cetera.
The new function will only run one slide a time. If you want to see the code for multiple (queued) slides, see the revision history.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tutorial for iPhone calculator with decimal point
Possible Duplicate:
How do I change the number of decimal places iOS?
If using Xcode to make an iOS calculator, how would I add a decimal button?
I am looking for an iOS tutorial on how to make a (simple) iPhone calculator that can do at least the following:add, subtract, multiply, divide, and lets the user input decimal points. I have not been able to find a tutorial like this, so if anyone knows of one, please let me know. I actually did find one where you can add, subtract, multiply, divide, but not do decimal points. If you can tell me how to let the user input a decimal point, there is no need for a further tutorial. The code i am using right now is below.
in the header file:
#import <UIKit/UIKit.h>
@interface CalculatorViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
in the main file:
#import "CalculatorViewController.h"
@implementation CalculatorViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:@"%.1f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:@"%.1f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = @"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = @"0";
currentOperation = 0;
}
A: This should work. Simple and direct.
Changed the currentNumber to store the current string value of the ongoing calculation (Make this NSMutableString), added an outlet (buttonDecialPointPressed) for the decimal point button.
-(IBAction) buttonDigitPressed:(id)sender
{
currentNumber = [currentNumber appendFormat:@"%d"];
calculatorScreen.text = currentNumber;
}
- (IBAction) buttonDecialPointPressed:(id)sender
{
if(behindTheDecimal == YES)
return;
behindTheDecimal = YES;
currentNumber = [currentNumber appendString:@"."];
calculatorScreen.text = currentNumber;
}
-(IBAction)buttonOperationPressed:(id)sender
{
float number = [currentNumber floatValue];
switch (currentOperation)
{
case 0:
result = number;
break;
case 1:
result = result + number;
break;
case 2:
result = result - number;
break;
case 3:
result = result * number;
break;
case 4:
result = result / number;
break;
case 5:
currentOperation = 0;
break;
case 6:
break;
}
currentNumber = [currentNumber stringWithFormat:@"%f", result];
calculatorScreen.text = currentNumber;
// why is this needed, how is it used?
currentOperation = [sender tag];
}
-(IBAction)cancelInput
{
behindTheDecimal = NO;
currentNumber = @"0";
calculatorScreen.text = currentNumber;
}
-(IBAction)cancelOperation
{
behindTheDecimal = NO;
currentNumber = @"0";
calculatorScreen.text = currentNumber;
currentOperation = 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to backpress pass an activity? I have an activity that loads some content using an AsyncTask.
If the content is null then i launch an activty that contains a WebView to load the data.
The only problem is when i launch the activity using regular intents.
When the back button is pressed to return out of the WebView.
It returns to the following activity and the AsyncTask is ran again, and it does the same thing all over again.
I know how to Override the onBackPressed button. But what should i do to override this from happening each time?
A: If the content is null then when you launch the second Activity (with the WebView) you should call finish() on the first Activity.
EDIT: Alternatively you should use startActivityForResult and then in the onActivityResult method invoke finish().
A: If you don't want to go back to the that loads the content, then call its finish() method after launching the WebView activity. The back button will then exit the app (or go to the activity before the loading one.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Slow insertion speed on MYISAM table I need to create a table containing two attributes: id and author. These two attributes form the composite key. Moreover I need to perform an index search on the author field.
Therefore I create the table using the following statement:
CREATE TABLE IF NOT EXISTS authors (author VARCHAR(100) NOT NULL, id VARCHAR(200) NOT NULL, INDEX USING BTREE(author,id), PRIMARY KEY (author,id)) ENGINE=MYISAM;
Now, I when try to insert about 4.5 million records using JDBC, the insertion speed gets terribly slow at the end.
The id attribute refers to a publication which was created by the related author. One author is related to several ids and vice versa. The average number of identical id values is lower than the number of identical author values.
Therefore I tested the same procedure with swapped attributes. In this case, the insertion speed remains nearly constant.
Is there a way to optimize the table in order to gain performance?
I don't quite know how MYISAM manages indexing composite keys. May be the process of balancing is the reason...
Thanks in advance!
A: I notice a few problems:
*
*you're defining two indexes on the same couple of columns (author, id): a normal index and a primary key which is also a special type of unique index.
*the indexes are on very long VARCHAR values.
*your database is not in first normal form, because as you said the author can be repeated, you're using the full author name to create a relationship, while you should use an id and put authors in a separate table.
After these changes, your index will be on simple numeric types and your insert speed should be good.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Excel Data Connection to Active Directory I want to create a data connection in excel-2007 that pulls the result of an active-directory query into a sheet in my workbook.
I see that I can do this with VBA but I agree with Rob here that it should be easier than that, just using "OLE DB Provider for Microsoft Directory Services"
A bit of googling suggests that this is a hole in our collective knowledge that deserves to be filled!
A: After 4 hours trial & error, I gave up and did the AD stuff on the SQL-side, using
SELECT * FROM OPENQUERY(MyActiveDirectoryLinkedServer, 'SELECT ... FROM ''LDAP://...'' WHERE ...')
But this requires a linked server to be set up, which is against DBA best practice. Luckily in my case I had one already. ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Excel parse produces 40802 for date 16-Sep-11 I found a PHP script that parses excel files, but there seems to be some kind of numbering system or encoding that is associated with dates. For example, the original .xls spreadseets contains this date in this format:
16-Sep-11
However, the information that is parsed by the script shows the following integer to represent this date:
40802
If someone could help me by identifying what representation is being used for the date, then I think I can figure out how to do the conversion.
A: Depending on the properties of the file in question, Excel uses one of two incompatible formats to store dates, the "1900" system and the "1904" system. By default, a file that originated on Windows will use the "1900" system, while a file that originated on a Mac will use the "1904" system. In the 1900 system, the number stored is the number of days elapsed since 1 Jan 1900, while in the 1904 system, the number stored is the number of days elapsed since 1 Jan 1904. There are various historical reasons (or is that hysterical raisins?) why Excel uses the two formats. Times are also stored in a similar manner, with the integer part being the date and the fractional part being the portion of the day that has passed.
Here is a Microsoft Knowlegebase article with more information: http://support.microsoft.com/kb/214330
A: Excel dates are based on the number of days from Jan 1, 1900. This page provides good detailed information on the quesiton.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PostgreSQL 8.3 - issues with autovacuum I'm trying to encourage the use and monitoring of autovacuum in some PostgreSQL 8.3 databases.
One objection I hit often is that people don't "trust" autovacuum or there are bugs in autovacuum in 8.3 which mean that it's ignored in preference to scheduling vacuuming. Mostly our tables are small and this approach appears to work. However, with our larger (& also heavily updated tables) this really doesn't work (dead tuple counts increase, exceed max_fsm_pages, and the tables don't get cleaned up etc etc).
I'm just wondering if anyone has a reference for autovacuum in 8.3 being buggy or not working. My own experience has shown that autovac works fine and, where necessary, adding entries to the pg_autovacuum table does the trick but I'm not having any luck convincing anyone else.
I'd like to understand the problem with autovacuum (if one exists).
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Whats wrong with my C++ syntax here while input != 0
{
if input == "r";
cout << "Please input a floating point value for the height, and then a floating point value for the width, seperated by a comma." << endl;
cin >> height >> width;
}
I am trying to write a basic program that takes the dimensions of basic shapes and outputs the area. This is what I am starting with, but I am not sure what is wrong with this syntax. Could someone help?
A: The condition must be in parentheses. Here's your formatted code:
while (input != 0)
{
if (input == "r")
{
cout << "Please input a floating point value for the height, and then a floating point value for the width, seperated by a comma." << endl;
cin >> height >> width;
}
}
A: You need to have your conditions surrounded by brackets and if needs to have code to execute if the condition is true its not a function call, so :
while (input != 0)
{
if (input == "r"){
cout << "Please input a floating point value for the height, and then a floating point value for the width, seperated by a comma." << endl;
cin >> height >> width;
}
}
It also looks like your cin statement is wrong as well but without the rest of the code I don't know.
A: C++ parser/compiler isn't intelligent enough yet to understand what do you mean when you try to say
if input == "r"
when input != 0
compiler will get confused and won't be able to semantically understand your program. So you need to put parenthesis as mentioned in above answers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Drupal 7 mod_rewrite enabled, still no clean urls I have mode_rewrite enabled, but when I go to turn on clean url's, the page still simply refreshes to the 'test' screen. Is there a better way to test to be sure my mod-rewrite is enabled such taht drupal can use it?
I'm managing the server now on a cloud, so i'm new to this.
A: Go to your .htaccess file, comment out line 62 <IfModule mod_rewrite.c> and line 137 </IfModule>. This removes the conditional check for mod_rewrite. If you get a 500 server error when you visit your site after doing this then mod_rewrite is not enabled on the server.
That's a 'Drupal' way to do it I guess, but the best thing you can do is install the devel module and navigate to yoursite.com/?q=devel/phpinfo. Once there search the page for the text mod_rewrite. If it's missing, it's not installed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP : create variable dynamically I have one of my class method like this shown below :
public function something() {
$this->create_varible('test');
return $test;
}
I wanna create some variable(not class variable) by passing it's name as argument to create variable method(as shown above), then return it's value.
your help will be appreciated, thanks in advance.
A: I don't see the point in that either. But to answer your question literally:
You can use extract for that purpose:
public function something() {
extract($this->create_varible('test'));
return $test;
}
public function create_varible($varname) {
return array ($varname => 12345);
}
The ->create_varible by itself cannot create a variable in the invokers scope. That's why you need to wrap the call in extract() to get something like the desired effect; whatever its purpose.
(Yes, aware of the typo.)
A: How about using PHP's Magic Methods, specifically the __get and __set methods.
class Foo
{
public function __set($varName, $value)
{
$GLOBALS[$varName] = $value;
}
public function __get($varname)
{
return isset($GLOBALS[$varName]) ? $GLOBALS[$varName] : null;
}
}
$foo = new Foo();
$foo->test = "Bar";
echo $test; // output: Bar
Demo found here: http://www.ideone.com/nluJ5
P.S. I mention this because if your use of $this->, and assume you're dealing with objects.
P.P.S. I think @Francois has the better solution, but offering another alternative.
A: Example:
<?php
public function create_variable($name, $value) {
// Dynamically create the variable.
$this->{$name} = $value;
}
Or:
<?php
$stack = 'overflow';
${$stack} = 'example';
echo $overflow;
Please keep in mind the scope of variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: HTML Self Sorting Table This is going to be a two part question.
I have a feeling this first part is going to be pretty simple, but I can't seem to find a direct answer anywhere.
I'm using a blog created on Blogger and I have a bunch of events that I was to list on separate pages. I need the lists to auto arrange themselves in either alphabetical or numerical order based on the date set for them.
Because this is all going to be on a blogger page it has to be all HTML as far as I know.
I'm not sure if this second part is possible or not but I figured I'd ask.
Along with the self-sorting event list I would also like to add a widget on the main page of the blog that would show which event is coming up next based off the event lists.
If doing this with HTML is not possible I'm open to any other way that I can do something similar.
On a side note I would also like to be able to add a picture to each event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Format date to show Day (e.g. Friday) using fmt tag in JSTL I have a date object passed on to the JSP page as ${date}. I want to print the date in following format:
Last logged in on Friday, September 23, 2011 on 11:32 PM EDT.
I cant get the Friday part and the EDT part. All I am able to successfully print is:
Last logged in on September 23, 2011 on 11:32 PM.
What are the additional options I need to include for printing the Day and Timezone? Thanks in advance.
PS: I am using fmt tag in JSTL.
A: Look at the java.util.SimpleDateFormat. That's the basis for the <fmt>
You sound like you want either a custom format or FULL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Have I Implemented Mutal Exchange Correctly? I'm trying to implement mutual exchange on a multi-threaded program. I'm not sure if I'm doing it right, and it's difficult to test.
In main.cpp, I have something like this:
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE,NULL);
//main
while (1) {
Sleep(STEP);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
}
return 0;
And in a function used by the other thread:
void Case::account_login(Connection* Con) {
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE,NULL);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
return;
}
Is this correct? Are the sections of code even using the same HANDLE or am I declaring them locally and therefore screwing up the functionality?
If I've missed out any vital information, let me know.
Thanks.
A:
Are the sections of code even using the same HANDLE or am I declaring them locally and therefore screwing up the functionality?
No, they are not using the same handle or the same mutex, for that matter (there may be multiple handles to the same mutex). In the posted code, the two threads each have their own mutex, which means access to common data protected by these two mutexes will not be "mutually exclusive".
Your options are more or less:
*
*pass the mutex as a parameter to the thread function
*define the mutex handle as a member of the Connection struct/class
*use a named mutex (create the named mutex on one side and open the named mutex on the other side)
*make the handle a global variable.
Edit: I put "make the handle a global variable" last for a good reason: it's the worst choice in the group. However, since OP insisted on an example...
// globals.h
#include <windows.h>
extern HANDLE hIOMutex;
// globals.cpp
#include "globals.h"
HANDLE hIOMutex = INVALID_HANDLE_VALUE;
// main.cpp
#include "globals.h"
int main ()
{
// initialize global variables.
hIOMutex = CreateMutex (NULL,FALSE,NULL);
// main code.
while (1) {
Sleep(STEP);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
}
}
// case.cpp
#include "case.h"
#include "globals.h"
void Case::account_login(Connection* Con)
{
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
}
A: I would use a named mutex especially if the two places where the mutex is used are in different places. However, ensure you create the Mutex_Name in one place to avoid typo mistakes
LPCTSTR lpMutex_Name = <name>;
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE,lpMutex_Name);
//main
while (1) {
Sleep(STEP);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
}
return 0;
And in a function used by the other thread:
void Case::account_login(Connection* Con) {
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE, lpMutex_Name);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
return;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Slide div's off/on page using jQuery I'm trying to create a function that slides div's off/on a page depending on which button/link is clicked.
The basic structure:
<div class="button"><a href="#">Click Box #1</a> </div>
<div class="button"><a href="#">Click Box #2</a> </div>
<div class="button"><a href="#">Click Box #3</a> </div>
<div id="container">
<div id="box1" class="box">Box #1</div>
<div id="box2" class="box">Box #2</div>
<div id="box3" class="box">Box #3</div>
</div>
Currently I'm using
$('.button').click(function() {
$('.box').each(function() {
But of course that only works as a sort of loop and it only slides the first and last div, how can I make each button slides out and then in the appropriate div.
Example of what I have so far: http://jsfiddle.net/ykbgT/538/
A: If you always want to show the nth box, where n is the index of the link you clicked, try something like this:
$('.button').click(function() {
var index = $(this).index(".button");
var $box = $(".box:eq(" + index + ")");
$(".box").not($box).animate({
left: '150%'
}, 500);
if ($box.offset().left < 0) {
$box.css("left", "150%");
} else if ($box.offset().left > $('#container').width()) {
$box.animate({
left: '50%',
}, 500);
}
});
Updated example: http://jsfiddle.net/andrewwhitaker/2uV2h/
A: The most flexible way would be to add a custom attribute to your DIV tag which has the name of the corresponding box's ID. Eg:
<div class="button" boxid="box1">....
Then in your click function:
$('.button').click(function() {
mybox=$(this).attr("boxid");
$(mybox).[whatever code you need to slide the DIV in and out of the screen]
....
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Use lambda expression to count the elements that I'm interested in Python Can I use lambda expression to count the elements that I'm interested?
For example, when I need to count the elements in a list that is more than two, I tried this code which returns 0.
x = [1,2,3]
x.count(lambda x: x > 2)
A: Note: "more than" is > ... => is not a valid operator.
Try sum(y > 2 for y in x)
Or, as suggested by @Jochen, to guard against non-conventional nth-party classes, use this:
sum(1 for y in x if y > 2)
A: from functools import reduce
x = [1,2,3]
reduce(lambda a,i: a+1 if (i>2) else a, x, 0)
This will not create a new list. a is the accumulator variable, i is the item from the list, and the 0 at the end is the initial value of the accumulator.
A: You can try any of the following
len([y for y in x if y > 2])
or
len(filter(lambda y: y > 2, x))
or the nicer
sum( y > 2 for y in x )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: Anyone successfully installed openfire OR any xmpp server on mac os x lion? I'm trying to install openfire. It's just a package and should be brain dead simple. The setup wizard invariably fails after you assign an admin username and password. The failure is that the login username and/or password is incorrect.
Ejabberd won't work on Lion either; the post installation scripts don't work.
If anyone can point me to clear and verified directions, please let me know. I've wasted a day on this and while I'm not an expert, I do think that I can follow directions well.
Thanks
A: Java is not installed on Lion by default. Start "Java Preferences" app and install Java.
A: ejabberd work in lion (10.7 +) via mac ports simply do:
$ port install ejabberd
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to delete a folder with other files and folders inside with PHP
Possible Duplicate:
A recursive remove directory function for PHP?
With PHP
I want to know the easiest way for delete a folder with files and folders inside.
A: This trick from the PHP docs is pretty cool:
function rrmdir($path)
{
return is_file($path)?
@unlink($path):
array_map('rrmdir',glob($path.'/*'))==@rmdir($path)
;
}
It exploits array_map, which calls the given function on an array of results. It's also cross-platform.
A: system("rm -fr $foldername");
It only works on unix though, but it is easy.
A: This recursive function has been posted as a comment on the rmdir() function reference page:
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir")
rrmdir($dir . "/" . $object);
else
unlink($dir . "/" . $object);
}
}
reset($objects);
rmdir($dir);
}
}
A: This was posted here http://www.php.net/manual/en/function.rmdir.php
if(!file_exists($directory) || !is_dir($directory)) {
return false;
} elseif(!is_readable($directory)) {
return false;
} else {
$directoryHandle = opendir($directory);
while ($contents = readdir($directoryHandle)) {
if($contents != '.' && $contents != '..') {
$path = $directory . "/" . $contents;
if(is_dir($path)) {
deleteAll($path);
} else {
unlink($path);
}
}
}
closedir($directoryHandle);
if($empty == false) {
if(!rmdir($directory)) {
return false;
}
}
return true;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: netsh http add urlacl via Group Policy (GPO) I have self-hosted WCF application that needs to listen on a URL on port 80. In order to do this, I need to add an entry to the HTTP.sys url list for a given user.
I can do this with netsh http add urlacl or calling a Win32 API directly (http://stackoverflow.com/questions/6851161/net-or-win32-equivalent-of-netsh-http-add-urlacl-command). Neither of these are really desirable, as both require administrative rights and are specific to a particular user.
Is there an equivalent group policy setting to configure HTTP or some other way to centrally configure this?
A: In manual (netsh http add urlacl gives you more info) user parameter is said to be the user or user-group name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: A Clojure binding question just looking to re factor some simple code
I have a function
(defn foo
([x y]
(let [line [x y]]
(...))
([x y z]
(let [plane [x y z]]
(...))))
I know I can write
(let [[x y :as point] [1 0]])
Is there a similar destructuring for functions such as foo where I can write
[x y :as line] or [x y z :as plane] in the actual defn? (i.e plane would be assigned [x y z])
A: You can destructure in the arg list as well, but you'll have to use variadic args which means you can't have multiple signatures:
(defn foo [& [x y z :as plane]]
(...))
and then call like:
(foo 1 2 3)
but like I said above, with this approach the two and three arg forms become ambiguous so you'd have to have separate named functions.
A: You can always build the lets using a macro. This would enable you to two write something like:
(def foo
(build-foo-args [[x y] line]
(...))
(build-foo-args [[x y z] plane]
(...)))
Not sure how much this syntactic sugar really buys you though... the lets are pretty clear in the first place.
On the whole, I'd probably recommend rethinking your function signature:
*
*If you genuinely need different behaviours for different arities then
foo should probably be split into separate functions.
*If the behaviour is the same for different arities, then I would use
variadic args as suggested by Dave Ray, but call the combined
argument something neutral e.g. "normal-vector" which can refer to multiple
dimensionalities. You may find you don't actually need x,y,z to be named at all....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use Github with the shared repository model and Aptana? We have a small development team, all working in the same room. We're setting up Github to manage a number of medium/ large projects. We are all new to Github but want to use it as our projects are based on open source software hosted on Github.
With our situation the "shared repository model" looks ideal - where each developer has full Git privileges.
We'd like to use the following process:
*
*Each developer works with their own version of the project using Aptana as an IDE.
*Each developer regularly gets updates from, and commits to the repo
*We regularly update a demo version of the project sourced from the repo to show to project stakeholders.
All of this is pretty standard stuff but we're struggling to find some clear documentation or a "how to" for setting this up. The Github documentation seems to be aimed at open source collaboration.
It may be we don't fully understand the Git terminology, we come from a background of Subversion and one dev has used Mercurial.
Can someone please suggest some clear documentation or a how-to for a setup of this type.
Thanks in advance.
A: First, create several branches on your repo like:
*
*master - that's the one representing your current release
*develop - that's the one holding the latest completed dev tasks (i.e. user stories)
When a developer starts working on a new user story, he creates a new branch from develop using:
git fetch
git checkout develop
(git pull origin develop) <-- only if you are not yet on head of develop
git checkout -b new-feature-branch
Now the dev only works on this feature branch. After completing his work, he creates a pull request from his feature branch towards develop. Other devs will take a look at it on GitHub, review his changes. If rework is required, the dev continues pushing changes to his feature branch, because the pull request will be updated along with it. If everything is fine, the pull request is merged into develop.
From time-to-time, you merge your changes from develop to master, again using pull requests. If you have no good test coverage and continuous integration, you might need an additional branch between master and develop to first stabilise your code.
This model assumes that your feature branches are short lived, e.g. 1-2 days.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is STR Available Inconsistently? When I create a OLE DB source, I can use the following expression:
STR(1234.545, 8, 2)
But when I use a Derived-Column flow task, that expression is illegal. The design-time error states:
The function "SET" was not recognized. Either the function name is
incorrect or does not exist.
I'd like to know why the function is not available to the Derived-Column task. And in general, I'd like to know the rule governing which functions are in fact available, or perhaps a list of the functions that are available to the Derived-Column task.
A: To answer what functions available in a Derived Column Transformation, look at Integration Services Expression Reference. In particular, you are probably interested in String Functions and Other Functions (SSIS Expression)
Why SET works in OLE DB and not in derived column is rather straight forward, they're different technologies. The set statement runs against a database and is a declarative style language (SQL) while the derived column expression is an imperative style language (vb/c#/etc).
BTW, I have no idea what the reference SET statement would do or what OLE DB provider that would work for. Perhaps it was just an example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using two backquotes and commas, Common Lisp I'm learning common lisp and I have a problem with understanding the usage of two backquotes combined with two commas:
``(a ,,(+ 1 2))
I mean, I don't have a clue why it's evaluated to:
`(A ,3)
rather than something like that:
`(A 3)
I'm explaining myself that both commas were 'consumed' in order to evaluate two backquotes in front of the form so none of the commas should've left and yet there's still one.
How would look
``(a ,,(+ 1 2))
using only list and ' ?
A: From the specs
This is what the Common Lisp HyperSpec says about nested backticks:
If the backquote syntax is nested, the innermost backquoted form should be expanded first. This means that if several commas occur in a row, the leftmost one belongs to the innermost backquote.
The R5RS Scheme spec also includes these details about backticks:
Quasiquote forms may be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost backquote. The nesting level increases by one inside each successive quasiquotation, and decreases by one inside each unquotation.
Also keep in mind that only one backtick gets collapsed per evaluation, just like a regular quote, it's not recursive.
Rules in action
To see how these three details interact, let's expand your example a bit. This expression...
``(a ,,(+ 1 2) ,(+ 3 4))
Gets evaluated to this (in SBCL notation):
`(A ,3 ,(+ 3 4))
*
*The left backtick got collapsed, so it the (+ 1 2) got escaped by the matching comma (the 2nd comma, according to the HyperSpec).
*On the other hand, the (+ 3 4) didn't have enough commas to get expanded (which is what R5RS mentions).
*Only one backtick got collapsed, because backticks don't get recursively expanded.
Expanding both commas
To get rid of the other backtick, another level of evaluation is needed:
(eval ``(a ,,(+ 1 2) ,(+ 3 4)))
Both backticks are gone, and we're left with a plain list:
(A 3 7)
A: No, both commas were consumed. There were two levels of quoting and two levels of commas. Now there's one level of quoting and one level of commas. In fact, GNU Common Lisp (2.44.1) evaluates your expression as
(list 'a 3)
That's exactly the same thing as
`(a ,3)
but more explicitly has "evaluated" both commas.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: EF4 how can I convert anonymous type to strong type in LINQ The LINQ code returns a anonymous type how can I return a strong type of "Customers"?
I am returning a anonymous type as I only want to select certain fields from the entity.
var customer = from c in _entities.Customers
join con
in _entities.Contracts on c.CustomerID equals con.customerID
where con.contractNo == number
select new
{
Surname = c.Surname,
Forename= c.Forename,
Address = c.Address,
Suburb = c.Suburb,
State = c.State,
Postcode = c.PostCode,
PhoneNo = c.PhoneNo
};
Thanks
A: Either do
var customer = from c in _entities.Customers
join con
in _entities.Contracts on c.CustomerID equals con.customerID
where con.contractNo == number
select c;
to select the customer instances with as-is or
Customer customer = (from c in _entities.Customers
join con
in _entities.Contracts on c.CustomerID equals con.customerID
where con.contractNo == number
select new Customer{
Surname = c.Surname,
Forename= c.Forename,
Address = c.Address,
Suburb = c.Suburb,
State = c.State,
Postcode = c.PostCode,
PhoneNo = c.PhoneNo
}).FirstOrDefault();
to create new instances of customer with just the properties you are interested in filled out. (provided customer class has a parameterless constructor)
A: It looks like you are looking for all customers that have any contract with a contractNo that matches number - don't use a join, instead use the EF navigation property:
var customers = _entities.Customers
.Where( c => c.Contracts.Any( x => x.contractNo == number));
If there is just a single (or possibly none) of these customers use SingleOrDefault() to just retrieve a single Customer entity:
Customer customer = _entities.Customers
.Where( c => c.Contracts.Any( x => x.contractNo == number))
.SingleOrDefault();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Multi Accordion with mootools problem I created a mootools accordion with nested sections like this:
html:
<div class="accordion">
<h2 class="accordion_toggler_1 open">Section 1</h2>
<div class="sub_accordion accordion_content_1 open">
<h2 class="accordion_toggler_2 open">Section 1.1</h2>
<div class="sub_accordion accordion_content_2 open">
Content 1.1
</div>
<h2 class="accordion_toggler_3">Section 1.2</h2>
<div class="sub_accordion accordion_content_3">
Content 1.2
</div>
</div>
<h2 class="accordion_toggler_4">Section 2</h2>
<div class="sub_accordion accordion_content_4">
<h2 class="accordion_toggler_5">Section 2.1</h2>
<div class="sub_accordion accordion_content_5">
Content 2.1
</div>
<h2 class="accordion_toggler_6">Section 2.2</h2>
<div class="sub_accordion accordion_content_6">
Content 2.2
</div>
</div>
<h2 class="accordion_toggler_7">Section 3</h2>
<div class="sub_accordion accordion_content_7">
Content 3
</div>
</div>
JS:
window.addEvent('domready', function() {
// Adaption IE6
if(window.ie6) var heightValue='100%';
else var heightValue='';
// Selectors of the containers for switches and content
var togglerName='h2.accordion_toggler_';
var contentName='div.accordion_content_';
// Position selectors
var counter=1;
var toggler=$$(togglerName+counter);
var content=$$(contentName+counter);
while(toggler.length>0)
{
// Apply accordion
new Fx.Accordion(toggler, content, {
onComplete: function() {
var element=$(this.elements[this.previous]);
if(element && element.offsetHeight>0) element.setStyle('height', heightValue);
},
onActive: function(toggler, content) {
toggler.addClass('open');
},
onBackground: function(toggler, content) {
toggler.removeClass('open');
}
});
// Set selectors for next level
counter++;
toggler=$$(togglerName+counter);
content=$$(contentName+counter);
}
});
The problem is that all section are open when the page loads and I wanted just the first top section and sub section.
Example:
Section 1
Section 1.1
Content 1.1
Section 1.2
Section 2
Section 3
Can anyone help??
Thanks
A: may this will help you or get more detail here
//edit html
<div class="accordion">
<h2 class="accordion_toggler_1" id="open_accordion_entry">section</h2>
<div class=" accordion_content_1">
<h2 class="accordion_toggler_2" id="open_accordion_entry1">section 1.1</h2>
<div class=" accordion_content_2">
content 1.1
</div>
<h2 class="accordion_toggler_2">section 1.2</h2>
<div class=" accordion_content_2">
content 1.2
</div>
</div>
<h2 class="accordion_toggler_1">Section 2</h2>
<div class="accordion_content accordion_content_1"><p>content 2</p></div>
<h2 class="accordion_toggler_1">Section 3</h2>
<div class="accordion_content accordion_content_1"><p>content 3</p></div>
</div>
//js
window.addEvent('domready', function() {
if(window.ie6) var heightValue='100%';
else var heightValue='';
var togglerName='h2.accordion_toggler_';
var contentName='div.accordion_content_';
var counter=1;
var toggler=$$(togglerName+counter);
var content=$$(contentName+counter);
while(toggler.length>0)
{
new Accordion(toggler, content, {
opacity: false,
display: -1,
onComplete: function() {
var element=$(this.elements[this.previous]);
if(element && element.offsetHeight>0) element.setStyle('height', heightValue);
},
onActive: function(toggler, content) {
toggler.addClass('open');
},
onBackground: function(toggler, content) {
toggler.removeClass('open');
}
});
counter++;
toggler=$$(togglerName+counter);
content=$$(contentName+counter);
}
$$('#open_accordion_entry1').fireEvent('click');
$$('#open_accordion_entry').fireEvent('click');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: copy_from_user not working for char* I'm a bit new to kernel programming so please excuse the question. Essentially, I want to send a string (char*) to the kernel module to print out. Pretty simple.
I have the following in a user level code:
char *text = "some text.";
ioctl(fd,OUTPUT_TEST,text);
And there's inside the module:
char *text;
case OUTPUT_TEST:
copy_from_user(text,(char *)arg,sizeof(char*);
However, text remains null. Shouldn't this be a pointer to the character string?
I'm even more confused because the following does work:
In user level:
typedef struct
{
int size;
char *text;
}Message;
int fd = open ("/proc/ioctl_test", O_RDONLY);
Message message;
message.text = "This message was sent via OCTL.";
message.size = strlen(message.text);
ioctl(fd,OUTPUT_TEST,message);
And in kernel space:
copy_from_user(&message,(Message *)arg,sizeof(Message));
This works perfectly. I'm really confused and would love any help you guys could offer.
A: I don't mean to sound harsh but I think you need to learn C a bit before writing kernel modules :-)
copy_from_user does exactly what the name implies - it copies a buffer form user space provided buffer to kernel provided buffer. This means you need to provide a kernel allocated buffer for it, it does not allocate one for you!
Your char * text allocates a pointer to a buffer, but not a buffer. You need to do the buffer allocation yourself.
Note that in your second example the Message struct is defined as global or on stack (can't tell from your example) so the allocation occurs and it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Referencing argument in with statement Is there a way to reference the argument in a with statement? It's like when you have class variables and a constructor and you do this
var blah;
public function foo(blah) {
this.blah = blah;
}
Is there a way to do the same like
public function foo(blah) {
with(cat){
bar += blah;
}
}
I want to add cat.bar by the blah given to the function.
It's easy to just rename the argument, but I'm curious if there's a way to do it. Thanks
A: That's what the with is for
tried this in wonder.fl and it works fine. Can you specify what you were expecting to see vs what it did?
package {
import flash.text.TextField;
import flash.display.Sprite;
public class FlashTest extends Sprite {
public var myMC:Sprite = new Sprite();
public var tf:TextField = new TextField();
public function FlashTest() {
addChild(tf);
fooWith(20);
}
public function fooWith($x:Number):void{
with(myMC){
x+=$x;
}
tf.text = "' " + myMC.x + " '";
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Section vs Article HTML5 I have a page made up of various "sections" like videos, a newsfeed etc.. I am a bit confused how to represent these with HTML5. Currently I have them as HTML5 <section>s, but on further inspection it looks they the more correct tag would be <article>. Could anyone shed some light on this for me?
None of these things are blog posts or "documents" in the true sense of the word so it's kind of hard to see which element to apply.
EDIT: I have opted to use the article tag since it seems to be a container tag for unrelated elements which I guess my "sections" are. The actual tagname article however seems to be rather misleading and although they are saying HTML5 has been developed with greater consideration for web applications, I find a lot of the tags to be more blog-centric / document based.
Anyway thanks for your answers it appears to be fairly subjective.
A: Section
*
*Use this for defining a section of your layout. It could be mid,left,right
,etc..
*This has a meaning of connection with some other element, put simply, it's DEPENDENT.
Article
*
*Use this where you have independent content which make sense on its own .
*Article has its own complete meaning.
A: I'd use <article> for a text block that is totally unrelated to the other blocks on the page.
<section>, on the other hand, would be a divider to separate a document which have are related to each other.
Now, i'm not sure what you have in your videos, newsfeed etc, but here's an example (there's no REAL right or wrong, just a guideline of how I use these tags):
<article>
<h1>People</h1>
<p>text about people</p>
<section>
<h1>fat people</h1>
<p>text about fat people</p>
</section>
<section>
<h1>skinny people</p>
<p>text about skinny people</p>
</section>
</article>
<article>
<h1>Cars</h1>
<p>text about cars</p>
<section>
<h1>Fast Cars</h1>
<p>text about fast cars</p>
</section>
</article>
As you can see, the sections are still relevant to each other, but as long as they're inside a block that groups them. Sections DONT have to be inside articles. They can be in the body of a document, but i use sections in the body, when the whole document is one article.
e.g.
<body>
<h1>Cars</h1>
<p>text about cars</p>
<section>
<h1>Fast Cars</h1>
<p>text about fast cars</p>
</section>
</body>
Hope this makes sense.
A: A section is basically a wrapper for h1 (or other h tags) and the content that corresponds to this. An article is essentially a document within your document that is repeated or paginated...like each blog post on your document can be an article, or each comment on your document can be an article.
A: The flowchart below can be of help when choosing one of the various semantic HTML5 elements:
A: I like to stick with the standard meaning of the words used: An article would apply to, well, articles. I would define blog posts, documents, and news articles as articles. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.
Supporting this, the w3c defines an article element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.
Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.
What’s more problematic is that article and section are so very
similar. All that separates them is the word “self-contained”.
Deciding which element to use would be easy if there were some hard
and fast rules. Instead, it’s a matter of interpretation. You can have
multiple articles within a section, you can have multiple sections
within and article, you can nest sections within sections and articles
within sections. It’s up to you to decide which element is the most
semantically appropriate in any given situation.
Here is a very good answer to the same question here on SO
A: In the W3 wiki page about structuring HTML5, it says:
<section>: Used to either group different articles into different purposes or
subjects, or to define the different sections of a single article.
And then displays an image that I cleaned up:
It also describes how to use the <article> tag (from same W3 link above):
<article> is related to <section>, but is distinctly different.
Whereas <section> is for grouping distinct sections of content or
functionality, <article> is for containing related individual
standalone pieces of content, such as individual blog posts, videos,
images or news items. Think of it this way - if you have a number of
items of content, each of which would be suitable for reading on their
own, and would make sense to syndicate as separate items in an RSS
feed, then <article> is suitable for marking them up.
In our example, <section id="main"> contains blog entries. Each blog
entry would be suitable for syndicating as an item in an RSS feed, and
would make sense when read on its own, out of context, therefore
<article> is perfect for them:
<section id="main">
<article>
<!-- first blog post -->
</article>
<article>
<!-- second blog post -->
</article>
<article>
<!-- third blog post -->
</article>
</section>
Simple huh? Be aware though that you can also nest sections inside
articles, where it makes sense to do so. For example, if each one of
these blog posts has a consistent structure of distinct sections, then
you could put sections inside your articles as well. It could look
something like this:
<article>
<section id="introduction">
</section>
<section id="content">
</section>
<section id="summary">
</section>
</article>
A: also, for syndicated content "Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element."
A: My interpretation is:
I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).
So a section is like a div-container that holds articles.
A: Sounds like you should wrap each of the "sections" (as you call them) in <article> tags and entries in the article in <section> tags.
The HTML5 spec says (Section):
The section element represents a generic section of a document or
application. A section, in this context, is a thematic grouping of
content, typically with a heading. [...]
Examples of sections would be chapters, the various tabbed pages in
a tabbed dialog box, or the numbered sections of a thesis. A Web
site's home page could be split into sections for an introduction,
news items, and contact information.
Note: Authors are encouraged to use the article element instead of the
section element when it would make sense to syndicate the contents of
the element.
And for Article
The article element represents a self-contained composition in a
document, page, application, or site and that is, in principle,
independently distributable or reusable, e.g. in syndication. This
could be a forum post, a magazine or newspaper article, a blog entry,
a user-submitted comment, an interactive widget or gadget, or any
other independent item of content.
I think what you call "sections" in the OP fit the definition of article as I can see them being independently distributable or reusable.
Update: Some minor text changes for article in the latest editors draft for HTML 5.1 (changes in italic):
The article element represents a complete, or self-contained,
composition in a document, page, application, or site and that is, in
principle, independently distributable or reusable, e.g. in
syndication. This could be a forum post, a magazine or newspaper
article, a blog entry, a user-submitted comment, an interactive widget
or gadget, or any other independent item of content.
Also, discussion on the Public HTML mailing list about article in January and February of 2013.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "271"
}
|
Q: Rails 3/Ruby 1.9.2 Date.tomorrow not correct Using Ruby 1.9.2 and Rail 3 on Mac Snow leopard
ruby-1.9.2-p290 :001 > Date.today
=> Sun, 25 Sep 2011
ruby-1.9.2-p290 :002 > Date.tomorrow
=> Tue, 27 Sep 2011
Is there maybe something wrong with the ruby date class or is this something to do with the way i installed ruby?
Edit:
ruby-1.9.2-p290 :039 > Date.current
=> Mon, 26 Sep 2011
ruby-1.9.2-p290 :040 > DateTime.now
=> Sun, 25 Sep 2011 20:47:01 -0500
Ok so the rails Date class seems a little buggy. The DateTime class appears to work fine though. Thanks derp and Adam
A: I am also observing this. You can try DateTime.now.tomorrow.to_date.
A: Was looking info online and came across this:
https://rails.lighthouseapp.com/projects/8994/tickets/6410-dateyesterday-datetoday
Check the last comment:
I do agree with you that its a bit confusing that you need to use
Date.current with Date.yesterday instead of Date.today, but the
general rule of thumb is Rails does not change how Ruby methods work,
which Date.today is. All we can do is add better documentation and
make sure people are aware of the subtle difference.
In other words, use current(rails) instead of today(ruby) to avoid problems.
A: You can also do Date.today + 1.day.
A: If you're using newer version of ruby then you can use Date.current.tomorrow to print tomorrow's date.
For example : puts "Tomorrow's date is : #{Date.current.tomorrow}"
To know more about data and time please follow below links.
RubyOnRails.org and RailsGithub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: CouchDB - trigger code when creating or updating document I have a page which store data in CouchDB. The page accesses the database directly via javascript, so not much of the logic is hidden from the browser. When creating a new document there is some logic which extracts elements of the data into separate fields so that they can be searched on.
Is it possible to do this logic on the server when creating or updating the documents, or am I stuck doing it before hitting the database?
A: You have a couple of options.
First, see this question about CouchDB update functions. Update functions receive a request from the browser and can modify them in any way before finally storing them in CouchDB. For example, some people use them to automatically add a timestamp. Also see the wiki page on CouchDB document update handlers.
Another option is to receive CouchDB change notifications. In this case, a separate program (either your own browser, or even better, a standalone program that you run) can query CouchDB for _changes. CouchDB will notify this program after the document is saved. Next, the program can fetch the document and then store any new revisions that are necessary.
To me, it sounds like you should try the _update function first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Sorting an Excel Table that contains Merged Cells I have a fairly simple Excel file, mostly layout (it's a report I've written), but midway down the document (row 28), I have a table that contains merged cells.
i.e. A | B | D | E | F
is as follows:
A | BCD | E | F
the same is done on the three rows below it, which contain the data, as follows:
Cell B28:D28 is merged
Cell B29:D29 is merged
Cell B30:D30 is merged
Cell B31:D31 is merged
When I select range A28:F31 I cannot sort by any column, error as follows:
"this operation requires merged cells to be identically sized"
Microsoft's response is simply that I need to make sure my cells are merged.
http://support.microsoft.com/kb/813974
Any advice? Other than unmerging cells? I am aware that I can Center Across Selection for cells, but for the purposes of this report, I am required to use merged cells.
A: You can't just copy the merged cell and "Paste as value" into a single cell? More directly, WHY do you have to used merged cells on this report? I personally can't think of any report that I've ever made that just COULD NOT be redone in a few different ways.
If you can tell us, as much as possible, about the layout of the report (Fields, Datatypes) or just post a screenshot it would help alot.
Unless someone has something I've never seen before, Short of copying your entire table to an array in VBA and using a sorting algorithm, you're going to have to find a way around having those few cells merged.
Again, Give an example as a layout and we'll go from there.
A: here is my answer to sort a excel range containing non identical merged cells.
Here as specified in your question, we need to sort 'A' and accordingly others col i.e B,C,D.. will get sorted.
Here i have specified a range where the data exist in excel "SortRangeValue" and the basic concept is
run bubble sort on 'A' and if we find values to be swapped just Swap the entire row(which include both merged and separate rows)
in given range i am having one hidden row at last, that's why i am running my code till lastRow-3, here 3 represents 1 for hidden row, 1 for length-1 for bubble sort and 1 for 0 based indexing in excel.(1+1+1=3) and Here it takes some time to execute as no of rows increases
Private Sub Ascending_Click()
Dim myRange As Range 'variable to hold the Named Range
Dim rowCount As Long 'variable to hold the Number of Rows in myRange
Dim colCount As Long 'variable to hold the Number of Columns in myRange
Dim rowStartIndex As Long 'variable to hold the Starting Row index of myRange
Dim colStartIndex As Long 'variable to hold the Starting Col index of myRange
Dim iIndex As Long 'Variable used for iteration
Dim jIndex As Long 'Variable used for iteration
Dim current As Long 'used in bubble sort to hold the value of the current jIndex item
Dim currentPlusOne As Long 'used in bubble sort to hold the value of the jIndex+1 item
Dim rowIndex As Long
Application.ScreenUpdating = False 'dont update screen until we sort the range.
Set myRange = Range("SortRangeValue") 'Get the range
'
'get the columns and rows from where the row start, since Range can start from any cell
' also the no. of columns and rows in rows
rowStartIndex = myRange.Row
colStartIndex = myRange.Column
colCount = myRange.Columns.Count
rowCount = myRange.Rows.Count
Dim tempCal As Long
tempCal = rowCount + rowStartIndex ' get the row no of last range
'here colStartIndex is the very first column which is to be sorted
For iIndex = 0 To rowCount - 3 Step 1 ' Run a bubble sort loop
For jIndex = 0 To rowCount - iIndex - 3 Step 1
rowIndex = jIndex + rowStartIndex
current = Cells(rowIndex, colStartIndex) ' calculate the rowIndex
currentPlusOne = Cells(rowIndex + 1, colStartIndex) ' get current cell value, and next row cell value.
If current > currentPlusOne Then 'campair the values
' if match found, select entire row of the values and shift it m down by copying it to some temp location here it is (3,16)
'get entire row from firstCol(colStartIndex) to last column and copy it temp location (colStartIndex+colCount-1)
Range(Cells(rowIndex + 1, colStartIndex), Cells(rowIndex + 1, colStartIndex + colCount - 1)).Copy Destination:=Cells(3, 16)
Range(Cells(rowIndex, colStartIndex), Cells(rowIndex, colStartIndex + colCount - 1)).Copy Destination:=Cells(rowIndex + 1, colStartIndex)
Range(Cells(3, 16), Cells(3, 16 + colCount - 1)).Copy Destination:=Cells(rowIndex, colStartIndex)
Range(Cells(3, 16), Cells(3, 16 + colCount - 1)).Value = ""
End If
Next jIndex ' increment jINdex
Next iIndex 'Increment iIndex
Application.ScreenUpdating = True 'display result on screen
End Sub
A: Here is another solution which reduces time to execute from 30 sec to jst less than 2 sec. the problem with previous code was it was swapping rows so many times. in this code i am making copy of 'A' column and sorting it first, and then making one temp range in which i am saving entire rows of values which are sorted (Column 'A' entries) and then replacing temporary sorted range into original range.
Private Sub QuickAscending_Click()
Dim myRange As Range 'variable to hold the Named Range
Dim rowCount As Long 'variable to hold the Number of Rows in myRange
Dim colCount As Long 'variable to hold the Number of Columns in myRange
Dim rowStartIndex As Long 'variable to hold the Starting Row index of myRange
Dim colStartIndex As Long 'variable to hold the Starting Col index of myRange
Dim iIndex As Long 'Variable used for iteration
Dim jIndex As Long 'Variable used for iteration
Dim current As Long 'used in bubble sort to hold the value of the current jIndex item
Dim currentPlusOne As Long 'used in bubble sort to hold the value of the jIndex+1 item
Dim rowIndex As Long
Dim tempRowIndex, tempColIndex As Long
Application.ScreenUpdating = False
Set myRange = Sheets("Sheet1").Range("SortRangeValue")
rowStartIndex = myRange.Row
colStartIndex = myRange.Column
colCount = myRange.Columns.Count
rowCount = myRange.Rows.Count
Dim tempCal As Long
tempCal = rowCount + rowStartIndex - 2
tempRowIndex = 6
tempColIndex = 200
Range(Cells(rowStartIndex, colStartIndex), Cells(tempCal, colStartIndex)).Copy Destination:=Range(Cells(tempRowIndex, tempColIndex), Cells(tempRowIndex + tempCal, tempColIndex))
For iIndex = 0 To rowCount - 3 Step 1
For jIndex = 0 To rowCount - iIndex - 3 Step 1
rowIndex = jIndex + tempRowIndex
current = Cells(rowIndex, tempColIndex)
currentPlusOne = Cells(rowIndex + 1, tempColIndex)
If current > currentPlusOne Then
Cells(rowIndex, tempColIndex) = currentPlusOne
Cells(rowIndex + 1, tempColIndex) = current
End If
Next jIndex
Next iIndex
Dim tempFinalRowIndex, tempFinalColIndex As Long
tempFinalRowIndex = 6
tempFinalColIndex = 201
Dim orgRange, tempRange As Long
For iIndex = 0 To rowCount - 2 Step 1
rowIndex = iIndex + tempRowIndex
tempRange = Cells(rowIndex, tempColIndex)
'MsgBox (tempRange)
For jIndex = 0 To rowCount - 2 Step 1
rowIndex = jIndex + rowStartIndex
orgRange = Cells(rowIndex, colStartIndex)
If tempRange = orgRange Then
'MsgBox ("Match Found : \n (tempRange,orgRange) : (" & tempRange & "," & orgRange & ")")
Range(Cells(rowIndex, colStartIndex), Cells(rowIndex, colStartIndex + colCount - 1)).Copy Destination:=Cells(tempFinalRowIndex + iIndex, tempFinalColIndex)
End If
Next jIndex
Next iIndex
Application.ScreenUpdating = True
Range(Cells(tempFinalRowIndex, tempFinalColIndex), Cells(tempFinalRowIndex + rowCount - 2, tempFinalColIndex + colCount - 1)).Copy Destination:=Range(Cells(rowStartIndex, colStartIndex), Cells(rowStartIndex + rowCount - 2, colStartIndex + colCount - 1))
Range(Cells(tempFinalRowIndex - 1, tempFinalColIndex), Cells(tempFinalRowIndex + rowCount - 2, tempFinalColIndex + colCount - 1)).Delete
Range(Cells(tempRowIndex, tempColIndex), Cells(tempRowIndex + rowCount - 2, tempColIndex)).Delete
End Sub
A: Use Google Sheets. The sort and filter works exactly the same way but it doesn't give you an error when you want to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how can I make jquery mobile "pagebeforeshow" event fire every time, not just on refresh I have a jquery mobile page that uses the following code to hide a button when the page is accessed.
$('div:jqmData(role="page")').live('pagebeforeshow',function(){
$("#apply_btn").hide()
});
My problem is that the event only fires when the page is refreshed and not when arriving at the page from somewhere else in the site.
I have tried using the "pageshow" event and the "pageinit" event but it still only fires when the page is refreshed.
A: Have a look at http://jquerymobile.com/demos/1.1.0/docs/api/events.html
This is the syntax:
$( '#yourPage' ).live( 'pagebeforeshow',function(event){
$("#uniqueButtonId").hide();
});
Good Luck
A: Strangely enough the short version doesn't work for me:
$( '#yourPage' ).on( 'pagebeforeshow',function(event){
$('#uniqueButtonId').hide();
});
but I have to use:
$(document).on( 'pagebeforeshow' , '#yourPage' ,function(event){
$('#uniqueButtonId').hide();
});
A: Just to remember that live method has been removed from jQuery 1.9. You should use from now on the on method:
$( '#yourPage' ).on( 'pagebeforeshow',function(event){
$("#uniqueButtonId").hide();
});
A: try this..
$('div:jqmData(role="page")').live('pagebeforeshow',function(){
$("#apply_btn",context).hide()
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to speed up/optimize file write in my program Ok. I am supposed to write a program to take a 20 GB file as input with 1,000,000,000 records and create some kind of an index for faster access. I have basically decided to split the 1 bil records into 10 buckets and 10 sub-buckets within those. I am calculating two hash values for the record to locate its appropriate bucket. Now, i create 10*10 files, one for each sub-bucket. And as i hash the record from the input file, i decide which of the 100 files it goes to; then append the record's offset to that particular file.
I have tested this with a sample file with 10,000 records. I have repeated the process 10 times. Effectively emulating a 100,000 record file. For this it takes me around 18 seconds. This means its gonna take me forever to do the same for a 1 bil record file.
Is there anyway i can speed up/ optimize my writing.
And i am going through all this because i can't store all the records in main memory.
import java.io.*;
// PROGRAM DOES THE FOLLOWING
// 1. READS RECORDS FROM A FILE.
// 2. CALCULATES TWO SETS OF HASH VALUES N, M
// 3. APPENDING THE OFFSET OF THAT RECORD IN THE ORIGINAL FILE TO ANOTHER FILE "NM.TXT" i.e REPLACE THE VALUES OF N AND M.
// 4.
class storage
{
public static int siz=10;
public static FileWriter[][] f;
}
class proxy
{
static String[][] virtual_buffer;
public static void main(String[] args) throws Exception
{
virtual_buffer = new String[storage.siz][storage.siz]; // TEMPORARY STRING BUFFER TO REDUCE WRITES
String s,tes;
for(int y=0;y<storage.siz;y++)
{
for(int z=0;z<storage.siz;z++)
{
virtual_buffer[y][z]=""; // INITIALISING ALL ELEMENTS TO ZERO
}
}
int offset_in_file = 0;
long start = System.currentTimeMillis();
// READING FROM THE SAME IP FILE 20 TIMES TO EMULATE A SINGLE BIGGER FILE OF SIZE 20*IP FILE
for(int h=0;h<20;h++){
BufferedReader in = new BufferedReader(new FileReader("outTest.txt"));
while((s = in.readLine() )!= null)
{
tes = (s.split(";"))[0];
int n = calcHash(tes); // FINDING FIRST HASH VALUE
int m = calcHash2(tes); // SECOND HASH
index_up(n,m,offset_in_file); // METHOD TO WRITE TO THE APPROPRIATE FILE I.E NM.TXT
offset_in_file++;
}
in.close();
}
System.out.println(offset_in_file);
long end = System.currentTimeMillis();
System.out.println((end-start));
}
static int calcHash(String s) throws Exception
{
char[] charr = s.toCharArray();;
int i,tot=0;
for(i=0;i<charr.length;i++)
{
if(i%2==0)tot+= (int)charr[i];
}
tot = tot % storage.siz;
return tot;
}
static int calcHash2(String s) throws Exception
{
char[] charr = s.toCharArray();
int i,tot=1;
for(i=0;i<charr.length;i++)
{
if(i%2==1)tot+= (int)charr[i];
}
tot = tot % storage.siz;
if (tot<0)
tot=tot*-1;
return tot;
}
static void index_up(int a,int b,int off) throws Exception
{
virtual_buffer[a][b]+=Integer.toString(off)+"'"; // THIS BUFFER STORES THE DATA TO BE WRITTEN
if(virtual_buffer[a][b].length()>2000) // TO A FILE BEFORE WRITING TO IT, TO REDUCE NO. OF WRITES
{ .
String file = "c:\\adsproj\\"+a+b+".txt";
new writethreader(file,virtual_buffer[a][b]); // DOING THE ACTUAL WRITE PART IN A THREAD.
virtual_buffer[a][b]="";
}
}
}
class writethreader implements Runnable
{
Thread t;
String name, data;
writethreader(String name, String data)
{
this.name = name;
this.data = data;
t = new Thread(this);
t.start();
}
public void run()
{
try{
File f = new File(name);
if(!f.exists())f.createNewFile();
FileWriter fstream = new FileWriter(name,true); //APPEND MODE
fstream.write(data);
fstream.flush(); fstream.close();
}
catch(Exception e){}
}
}
A: Consider using VisualVM to pinpoint the bottlenecks. Everything else below is based on guesswork - and performance guesswork is often really, really wrong.
I think you have two issues with your write strategy.
The first is that you're starting a new thread on each write; the second is that you're re-opening the file on each write.
The thread problem is especially bad, I think, because I don't see anything preventing one thread writing on a file from overlapping with another. What happens then? Frankly, I don't know - but I doubt it's good.
Consider, instead, creating an array of open files for all 100. Your OS may have a problem with this - but I think probably not. Then create a queue of work for each file. Create a set of worker threads (100 is too many - think 10 or so) where each "owns" a set of files that it loops through, outputting and emptying the queue for each file. Pay attention to the interthread interaction between queue reader and writer - use an appropriate queue class.
A: I would throw away the entire requirement and use a database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Merge JS objects without overwriting Suppose you have two objects:
var foo = {
a : 1,
b : 2
};
var bar = {
a : 3,
b : 4
}
What's the best way to merge them (and allow deep merging) to create this:
var foobar = {
a : [1, 3],
b : [2, 4]
}
Edit for question clarification: Ideally, in the case of an existing property in one and not the other, I would expect an array to still be created, for normalization purposes and to allow for further reduction of the map, however the answers I'm seeing below are more than sufficient. For the purposes of this exercise, I was only looking for string or numerical merges, so I hadn't entertained every possible situational case. If you held a gun to my head and asked me to make a choice, though, I'd say default to arrays.
Thanks all for your contributions.
A: Presumably you would iterate over one object and copy its property names to a new object and values to arrays assigned to those properties. Iterate over subsequent objects, adding properties and arrays if they don't already exist or adding their values to existing properties and arrays.
e.g.
function mergeObjects(a, b, c) {
c = c || {};
var p;
for (p in a) {
if (a.hasOwnProperty(p)) {
if (c.hasOwnProperty(p)) {
c[p].push(a[p]);
} else {
c[p] = [a[p]];
}
}
}
for (p in b) {
if (b.hasOwnProperty(p)) {
if (c.hasOwnProperty(p)) {
c[p].push(b[p]);
} else {
c[p] = [b[p]];
}
}
}
return c;
}
You could modify it to handle any number of objects by iterating over the arguments supplied, but that would make passing the object to merge into more difficult.
A: https://lodash.com/docs/3.10.1#merge
// using a customizer callback
var object = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var other = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.merge(object, other, function(a, b) {
if (_.isArray(a)) {
return a.concat(b);
}
});
// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
A: This ought to do what you're looking for. It will recursively merge arbitrarily deep objects into arrays.
// deepmerge by Zachary Murray (dremelofdeath) CC-BY-SA 3.0
function deepmerge(foo, bar) {
var merged = {};
for (var each in bar) {
if (foo.hasOwnProperty(each) && bar.hasOwnProperty(each)) {
if (typeof(foo[each]) == "object" && typeof(bar[each]) == "object") {
merged[each] = deepmerge(foo[each], bar[each]);
} else {
merged[each] = [foo[each], bar[each]];
}
} else if(bar.hasOwnProperty(each)) {
merged[each] = bar[each];
}
}
for (var each in foo) {
if (!(each in bar) && foo.hasOwnProperty(each)) {
merged[each] = foo[each];
}
}
return merged;
}
And this one will do the same, except that the merged object will include copies of inherited properties. This probably isn't what you're looking for (as per RobG's comments below), but if that is actually what you are looking for, then here it is:
// deepmerge_inh by Zachary Murray (dremelofdeath) CC-BY-SA 3.0
function deepmerge_inh(foo, bar) {
var merged = {};
for (var each in bar) {
if (each in foo) {
if (typeof(foo[each]) == "object" && typeof(bar[each]) == "object") {
merged[each] = deepmerge(foo[each], bar[each]);
} else {
merged[each] = [foo[each], bar[each]];
}
} else {
merged[each] = bar[each];
}
}
for (var each in foo) {
if (!(each in bar)) {
merged[each] = foo[each];
}
}
return merged;
}
I tried it out with your example on http://jsconsole.com, and it worked fine:
deepmerge(foo, bar)
{"a": [1, 3], "b": [2, 4]}
bar
{"a": 3, "b": 4}
foo
{"a": 1, "b": 2}
Slightly more complicated objects worked as well:
deepmerge(as, po)
{"a": ["asdf", "poui"], "b": 4, "c": {"q": [1, 444], "w": [function () {return 5;}, function () {return 1123;}]}, "o": {"b": {"t": "cats"}, "q": 7}, "p": 764}
po
{"a": "poui", "c": {"q": 444, "w": function () {return 1123;}}, "o": {"b": {"t": "cats"}, "q": 7}, "p": 764}
as
{"a": "asdf", "b": 4, "c": {"q": 1, "w": function () {return 5;}}}
A: I just leave it here.
Shallow merging with values as arrays.
const foo = {a: 1, b: 2}
const bar = {a: 2, с: 4}
const baz = {a: 3, b: 3}
const myMerge = (...args) => args
.flatMap(Object.entries)
.reduce((acc, [key, value]) => {
acc[key] ??= []
acc[key].push(value)
return acc
}, {})
console.log(myMerge(foo, bar, baz))
//{ a: [1, 2, 3],
// b: [2, 3],
// с: [4] }
.as-console-wrapper { max-height: 100% !important; top: 0 }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Are sql triggers run in a separate thread? If I want to return the user a web page and write to a log or word by word processing, should I use a stored procedure call from CLR in a new thread or just use sql triggers?
A: You can't make a SQL Server trigger run asyncronously. The best you could do is utilize SQL Server's Service Broker to execute a stored proc call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Symbolic manipulation over non-numeric types I'm interested in a python library that permits symbolic manipulation where the symbols and can be unknowns of an arbitrary type.
This is the code that I want to write:
>>> myexpression = symbol("foo") == "bar"
>>> print myexpression
foo == "bar"
>>> print myexpression(foo="quux")
False
>>> myexpression.or_(True)
True
Or some rough approximation of that. It doesn't actually even need to be that clever, I'd be happy enough having to call a lot of extra introspection methods to get something like the above (for instance, even if the logical tautology is not directly simplified)
My first instinct was to look at sympy, but it seems that library makes the strong assumption that symbolic variables must be numbers; and I'd like to at least operate on sequences and sets:
>>> myexpression = sympy.Eq(sympy.Symbol("foo"), 5)
>>> myexpression
foo == 5
>>> myexpression = sympy.Eq(sympy.Symbol("foo"), "bar")
Traceback (most recent call last):
...
sympy.core.sympify.SympifyError: SympifyError: 'bar'
Is there a way to get sympy to understand non-numeric variables, or another library that can do similar things?
A: Not sure how well it fits the uses you have in mind, but the nltk (Natural Language Toolkit) has modules for symbolic manipulation, including first order logic, typed lambda calculus, and a theorem prover. Take a look at this howto.
A: Could you just map everything into a Sympy symbol? For instance, in your last expression:
sympy.Eq(sympy.Symbol("foo"), sympy.Symbol("bar")). Or do you mean you actually want to write logical statements about set relationships?
A: Boolean logic is in SymPy although not as easily expressible as it should be. Its definitely there though.
In [1]: x,y,z = symbols('x y z')
In [2]: A = Eq(x,y)
In [3]: A
Out[3]: x = y
In [4]: B = Gt(y,z)
In [5]: And(A,B)
Out[5]: x = y ∧ y > z
In [6]: C = Gt(x,z)
In [7]: And(A, Or(B,C))
Out[7]: x = y ∧ (y > z ∨ x > z)
I'm not aware of many methods to simplify these expressions. This is the sort of thing that would be easy to do if there was interest though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: how to load specific attributes from one table to another? I am trying to load data from one table to another. But I only need specific attributes from the table.
For example,
I have two tables, Source(the table I am loading from) and Dest(the table I am putting the loaded data)
Source has ID, Birthyday, HometownAddress, CurrentAddress, Gender and Dest will include ID, Birthday and Gender.
How can I only load what I need to the Dest table?
A: insert into dest ( select id, birthyday from source )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where is the ideal place for django's template? According to Brian's response, he recomends put template dir on the top level django project. In other responses find that every app should have its own template folder.
I wonder if there is an official recommendation or criteria as the peps in python, for the location of the template folder regardless of how many applications may have a django project
A: App-specific resources belong with the app. Project-wide resources or project-overridden resources belong with the project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Data Binding Error in cascading Drop downs in asp.net I have 2 drop down list within the edit item Template of a form view. The first drop down contains a lit of vehicle Makes and the second a list of Vehicle Models. The list of models needs to be filtered by the selection from the Makes drop down.
Here are the 2 Drop down List
<telerik:RadComboBox ID="RadComboBoxAssetMake" runat="server" DataTextField="AssetMakeName"
SelectedValue='<%# Bind("MakeId") %>' DataSourceID="odsAllAssetMakes" AutoPostBack="True" DataValueField="Id" Skin="Vista"
Width="212px" OnSelectedIndexChanged="RadComboBoxAssetMake_SelectedIndexChanged">
<telerik:Items>
<telerik:RadComboBoxItem Text="" Value="" />
</telerik:Items>
</telerik:RadComboBox>
<telerik:RadComboBox ID="RadComboBoxAssetModel" runat="server" DataTextField="AssetModelName"
SelectedValue='<%# Bind("ModelId") %>' DataSourceID="odsAssetModelByMake" DataValueField="Id" Skin="Vista" Width="212px">
<telerik:Items>
<telerik:RadComboBoxItem Text="" Value="" />
</telerik:Items>
</telerik:RadComboBox>
Initially I wanted to use a control select parameter on the object data source for the model Drop down. With the parameter getting the value from the Make drop down. However this doesn't seem to work as the select parameter on the object data source can't see the control with in the form view.
So now I am trying to use a session select parameter on the object data source.
<asp:ObjectDataSource runat="server" ID="odsAssetModelByMake" DataObjectTypeName="GPSO.Repository.AssetModel"
TypeName="GPSOnline.ATOMWebService" SelectMethod="GetAssetModelbyMake">
<SelectParameters>
<asp:SessionParameter DbType="Guid" SessionField="assetMakeId" Name="assetMakeId" />
</SelectParameters>
</asp:ObjectDataSource>
But now I get the this error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control." When I try to data bind the model drop down in the selected index changed method of the make drop down.
protected void RadComboBoxAssetMake_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
{
Session["assetMakeId"] = e.Value.ToString();
((RadComboBox) fvAsset.FindControl("RadComboBoxAssetModel")).DataBind();
}
Is there a simple way to achieve this kind of thing, it would seem like such a common scenario that there must be a standard way to do it?
A:
Initially I wanted to use a control select parameter on the object
data source for the model Drop down. With the parameter getting the
value from the Make drop down. However this doesn't seem to work as
the select parameter on the object data source can't see the control
with in the form view.
You need to move the ObjectDataSource into templates:
<EditItemTemplate>
<telerik:RadComboBox ....
<telerik:RadComboBox ....
<asp:ObjectDataSource ....
<asp:ObjectDataSource ....
</EditItemTemplate>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP - Checking for session in HTML page I have an HTML page that I do not want to be available unless the login is successful. My login starts a session, however I don't know how to check for the session in the HTML and if the session exists I want to display the page, if not I want to display a unauthorised message. How can I do this?
A: You can't check for the session in the HTML per se you'd have to do it in PHP. Depending on how your page is built using PHP you could try putting something like this at the top of your HTML file:
<?php
if (!isset($_SESSION['my_login_var'])) {
echo 'Unauthorised';
exit();
}
?>
But you'd be far better off doing this earlier on in your PHP code, in which case you could use the header function to send the user to a proper 403 page.
UPDATE
Usually PHP does some processing before the HTML is outputted and the headers are sent to the connecting client, so you want to send a 403 header before that output happens. This could be in an included PHP file that is run before the HTML is built, or even in the HTML file itself if no other content has been outputted before the script reaches that point.
You can make a small adjustment to the code above to send a 403 header and 'properly' deny access to the page:
<?php
if (!isset($_SESSION['my_login_var'])) {
header('HTTP/1.1 403 Forbidden');
exit();
}
?>
A: You're going to need to look up PHP sessions. See http://us.php.net/manual/en/function.session-start.php for PHP session_start() documentation.
Basically you will need to do session_start(). If the login is successful, set a session variable like $_SESSION['logged_in'] = true;. Then do some logic on your page and redirect/display message depending on the result.
You should attempt something and come back and ask a more specific question if you have problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: OpenGL + GLEW + MinGW application linking issue I'm getting some undefined references when building my project. Here's the build log:
**** Build of configuration Debug for project test ****
**** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\main.o ..\src\main.cpp
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\test.o ..\src\test.cpp
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\window.o ..\src\window.cpp
..\src\window.cpp: In member function 'void Window::StartRenderContext()':
..\src\window.cpp:150:24: warning: NULL used in arithmetic
..\src\window.cpp:161:28: warning: NULL used in arithmetic
..\src\window.cpp:174:24: warning: NULL used in arithmetic
g++ -mwindows -l glew32 -l glew32s -l glu32 -l opengl32 -o test.exe src\window.o src\test.o src\main.o
src\window.o: In function `ZN6Window18StartRenderContextEv':
C:\eclipse\workspace\test\Debug/../src/window.cpp:101: undefined reference to `wglCreateContext@4'
C:\eclipse\workspace\test\Debug/../src/window.cpp:102: undefined reference to `wglMakeCurrent@8'
C:\eclipse\workspace\test\Debug/../src/window.cpp:115: undefined reference to `glewInit'
C:\eclipse\workspace\test\Debug/../src/window.cpp:125: undefined reference to `wglMakeCurrent@8'
C:\eclipse\workspace\test\Debug/../src/window.cpp:126: undefined reference to `wglDeleteContext@4'
C:\eclipse\workspace\test\Debug/../src/window.cpp:148: undefined reference to `__wglewChoosePixelFormatARB'
C:\eclipse\workspace\test\Debug/../src/window.cpp:159: undefined reference to `__wglewChoosePixelFormatARB'
C:\eclipse\workspace\test\Debug/../src/window.cpp:185: undefined reference to `__wglewCreateContextAttribsARB'
C:\eclipse\workspace\test\Debug/../src/window.cpp:194: undefined reference to `__wglewCreateContextAttribsARB'
C:\eclipse\workspace\test\Debug/../src/window.cpp:204: undefined reference to `__wglewCreateContextAttribsARB'
C:\eclipse\workspace\test\Debug/../src/window.cpp:214: undefined reference to `__wglewCreateContextAttribsARB'
C:\eclipse\workspace\test\Debug/../src/window.cpp:227: undefined reference to `wglMakeCurrent@8'
collect2: ld returned 1 exit status
Build error occurred, build is stopped
Time consumed: 8128 ms.
Here's my link command:
g++ -mwindows -l glew32 -l glew32s -l glu32 -l opengl32 -o test.exe src\window.o src\test.o src\main.o
Is this correct? I'm using the 64-bit binaries of glew (I think the 32s don't mean anything). Were they only meant to be used with visual studio?
Here's the includes in my code:
#include "Windows.h"
#include "GL/glew.h"
#include "GL/wglew.h"
#include "GL/gl.h"
#include "GL/glu.h"
#include "test.h"
I am using Eclipse Indigo CDT, MinGW, Win32, OpenGL, and glew.
A: I solved "glew undefined reference" problems.
My development environment is eclipse CDT with MinGW on Windows 7 (x64).
The solution is the following 3 steps:
*
*Add source code: #define GLEW_STATIC
*Add linker flag: -lglew32s -lopengl32 -lfreeglut
*Add compiling flag: gcc -DGLEW_STATIC
If needed, you have to add -lglu32 -glut32 etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Django Match ForeignKey from ModelChoiceField to MySQL I have a ModelChoiceField called outage_name. I also have a simple form that allows you to select the item from the list. The ModelChoiceField is pulled from a MySQL DB. This queryset is located in forms.py
outage_name = forms.ModelChoiceField(queryset = Outage.objects.filter(published = True)
The models.py is listed below.
from django.db import models
from django.contrib.auth.models import User
class Outage(models.Model):
outage_name = models.CharField(max_length=60, unique=True)
published = models.BooleanField()
def __unicode__(self):
return self.outage_name
class Detail(models.Model):
detail = models.CharField(max_length=60, unique=True)
user = models.ForeignKey(User)
outage = models.ForeignKey(Outage)
def __unicode__(self):
return self.outage
When I select from the list and submit the form I can't seem to figure out how to match outage = models.ForeignKey(Outage) that was selected on the list. To the correct outage_name. In my views.py I can hard code the id and it submits to the database and everything works fine.
def turnover_form(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = TurnoverForm(request.POST)
if form.is_valid():
details = Detail.objects.get_or_create(
detail = form.cleaned_data['detail'],
user = request.user,
outage = Outage.objects.get(pk=1))
return HttpResponseRedirect('/turnover/user/')
else:
form = TurnoverForm()
variables = RequestContext(request, {'form': form})
return render_to_response('turnover_form.html', variables)
else:
return HttpResponseRedirect('/authorization/')
Any advice on how to match the id with the selected item would be appreciated. I'm sure my code is not very pythonic as I'm still learning.
A: outage = form.cleaned_data['outage'] # cleaned_data['outage'] is a model instance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c# datatypes and arrays I am creating an array for some monetary values. I created the array as an integer and realized it needs to be decimal values. When I change the variables to decimals and try and run it, I get "Cannot be implicitly converted from decimal to int." I hover over the variables and they all appear to be decimals. I remember in the past placing .00M after int's to force them to be a decimal, but this doesn't seem to make a difference. Does this make sense to anyone else?
//Global var
Decimal lastIndexUsed = -1;
Decimal[,] quarters = new Decimal[10, 5];
string[] Branch = new string[10];
//Calc button
decimal Q1;
decimal Q2;
decimal Q3;
decimal Q4;
Q1 = Decimal.Parse(txtQ1.Text);
Q2 = Decimal.Parse(txtQ2.Text);
Q3 = Decimal.Parse(txtQ3.Text);
Q4 = Decimal.Parse(txtQ4.Text);
lastIndexUsed = lastIndexUsed + 1;
quarters[lastIndexUsed, 0] = Q1;
quarters[lastIndexUsed, 1] = Q2;
quarters[lastIndexUsed, 2] = Q3;
quarters[lastIndexUsed, 3] = Q4;
Branch[lastIndexUsed] = txtBranch.Text;
The marked part is the first of many variables which error.
Decimal row;
Decimal col;
Decimal accum;
//Calculate
for (row = 0; row <= lastIndexUsed; row++)
{
accum = 0;
for (col = 0; col <= 3; col++)
{
*** accum = accum + quarters[row, col];***
}
quarters[row, 4] = accum;
A: lastIndexUsed is used as an array index and should remain an integer.
A: Even though you are using an array of decimals, the indexer is still an integer.
Decimal lastIndexUsed;
should be
int lastIndexUsed
A: Decimal[,] quarters = new Decimal[10, 5];
The index numbers are integers. You can't index by decimals. The array contains decimals.
I changed it to this to get it to run and it prints 10.15 like you'd expect
`//Global var
int lastIndexUsed = -1;
Decimal[,] quarters = new Decimal[10, 5];
string[] Branch = new string[10];
//Calc button
decimal Q1;
decimal Q2;
decimal Q3;
decimal Q4;
Q1 = Decimal.Parse("10.15");
Q2 = Decimal.Parse("13");
Q3 = Decimal.Parse("123.9877");
Q4 = Decimal.Parse("321");
lastIndexUsed = lastIndexUsed + 1;
quarters[lastIndexUsed, 0] = Q1;
quarters[lastIndexUsed, 1] = Q2;
quarters[lastIndexUsed, 2] = Q3;
quarters[lastIndexUsed, 3] = Q4;
Branch[lastIndexUsed] = "hello";
Console.WriteLine(quarters[0,0]);`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting MSB of a 32bit integer in MIPS, and merging it into the LSB of another value Is there any way to find the MSB of a 32bit integer in MIPS and then replace that to the LSB of another integer?
To elaborate, suppose A = 1000 and B = 1001 (4-bit examples to keep it short.)
I need to get the MSB of B ie 1 and swap this with the LSB of A.
Now A should become 1001.
A: # Integer 1 -> $a0
# Integer 2 -> $a1
# Result -> $a3
# Moving MSB to LSB, shifting in zeros
srl $t1, $a0, 31
# Applying r = a ^ ((a ^ b) & mask)
# a = $a1
# b = $t1 = $a0 >> 31
xor $t2, $a1, $t1
andi $t2, $t2, 1 # mask=1 - keep only the low bit
xor $a3, $a1, $t2
Assembly is fun!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Visual studio 2010 Code definition window with Resharper 6 I installed Resharper 6 with VS 2010. But whenever I press F12 for a type, it goes to metadataviewer, which Resharper provides. I want to use Code Definition Window instead. Is there a way to set it up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server Pagination w/o row_number() or nested subqueries? I have been fighting with this all weekend and am out of ideas. In order to have pages in my search results on my website, I need to return a subset of rows from a SQL Server 2005 Express database (i.e. start at row 20 and give me the next 20 records). In MySQL you would use the "LIMIT" keyword to choose which row to start at and how many rows to return.
In SQL Server I found ROW_NUMBER()/OVER, but when I try to use it it says "Over not supported". I am thinking this is because I am using SQL Server 2005 Express (free version). Can anyone verify if this is true or if there is some other reason an OVER clause would not be supported?
Then I found the old school version similar to:
SELECT TOP X * FROM TABLE WHERE ID NOT IN (SELECT TOP Y ID FROM TABLE ORDER BY ID) ORDER BY ID where X=number per page and Y=which record to start on.
However, my queries are a lot more complex with many outer joins and sometimes ordering by something other than what is in the main table. For example, if someone chooses to order by how many videos a user has posted, the query might need to look like this:
SELECT TOP 50 iUserID, iVideoCount FROM MyTable LEFT OUTER JOIN (SELECT count(iVideoID) AS iVideoCount, iUserID FROM VideoTable GROUP BY iUserID) as TempVidTable ON MyTable.iUserID = TempVidTable.iUserID WHERE iUserID NOT IN (SELECT TOP 100 iUserID, iVideoCount FROM MyTable LEFT OUTER JOIN (SELECT count(iVideoID) AS iVideoCount, iUserID FROM VideoTable GROUP BY iUserID) as TempVidTable ON MyTable.iUserID = TempVidTable.iUserID ORDER BY iVideoCount) ORDER BY iVideoCount
The issue is in the subquery SELECT line: TOP 100 iUserID, iVideoCount
To use the "NOT IN" clause it seems I can only have 1 column in the subquery ("SELECT TOP 100 iUserID FROM ..."). But when I don't include iVideoCount in that subquery SELECT statement then the ORDER BY iVideoCount in the subquery doesn't order correctly so my subquery is ordered differently than my parent query, making this whole thing useless. There are about 5 more tables linked in with outer joins that can play a part in the ordering.
I am at a loss! The two above methods are the only two ways I can find to get SQL Server to return a subset of rows. I am about ready to return the whole result and loop through each record in PHP but only display the ones I want. That is such an inefficient way to things it is really my last resort.
Any ideas on how I can make SQL Server mimic MySQL's LIMIT clause in the above scenario?
A: Unfortunately, although SQL Server 2005 Row_Number() can be used for paging and with SQL Server 2012 data paging support is enhanced with Order By Offset and Fetch Next, in case you can not use any of these solutions you require to first
*
*create a temp table with identity column.
*then insert data into temp table with ORDER BY clause
*Use the temp table Identity column value just like the ROW_NUMBER() value
I hope it helps,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GIS: How to read METAR & TAF values to get the pressure at sea level? I have this link on how to get the altitude in Android -> SensorManager.getAltitude(pressure at sea level, atmospheric pressure)
But... need to know the value for PRESSURE AT SEA LEVEL. I have read the below statement from Android documentation on how to obtain it.
The pressure at sea level must be known, usually it can be retrieved
from airport databases in the vicinity.
Then, I found url that may give the values by providing the airport code. In my case, it's Tokyo International Airport (Haneda). The airport code is HND.
Here's the web service provider url:
http://avdata.geekpilot.net/
Here's the sample output for Tokyo International Airport (http://avdata.geekpilot.net/weather/HND)
<weather>
<ident>RJTT</ident>
<error/>
<metar>
2011/09/22 08:00
RJTT 220800Z 04019KT 9999 -SHRA FEW012 BKN025 BKN040 21/18 Q1000 NOSIG
</metar>
<taf>
2011/09/22 04:12
TAF
AMD TAF
AMD RJTT 220409Z 2204/2306 08016KT 9999 FEW030 SCT050
BECMG 2204/2206 05014KT
TEMPO 2207/2209 36018G30KT SHRA
BECMG 2303/2306 10008KT
</taf>
</weather>
Problem: don't know on how to read the above information to obtain the value.
A: METAR altimeter (sea level pressure) data are usually presented as A2992 or ALTSG 2992 where 29.92 is the value in in. Hg or at airports using millibars as Q1000 as in your example, which is exactly 1 atmosphere or bar.
A: I found url to translate obtain it and translate it to readable format.
find local sea level pressure
My airport code there is RJTT (Tokyo International Airport Haneda)
Here's the sample output (Pressure (altimeter): 30.21 inches Hg (1023.0 mb)):
METAR text: RJTT 260100Z 03011KT 9999 FEW025 BKN110 BKN170 20/14 Q1023 NOSIG RMK 1CU025 6AC110 7AC170 A3021
Conditions at: RJTT (TOKYO INTL AIRPO, JP) observed 0100 UTC 26 September 2011
Temperature: 20.0°C (68°F)
Dewpoint: 14.0°C (57°F) [RH = 68%]
Pressure (altimeter): 30.21 inches Hg (1023.0 mb)
Winds: from the NNE (30 degrees) at 13 MPH (11 knots; 5.7 m/s)
Visibility: 6 or more miles (10+ km)
Ceiling: 11000 feet AGL
Clouds: few clouds at 2500 feet AGL
broken clouds at 11000 feet AGL
broken clouds at 17000 feet AGL
Weather: no significant weather observed at this time
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are the performance implications of using require_dependency in Rails 3 applications? I feel like I understand the difference between require and require_dependency (from How are require, require_dependency and constants reloading related in Rails?).
However, I'm wondering what should happen if I use some of the various methods out there (see http://hemju.com/2010/09/22/rails-3-quicktip-autoload-lib-directory-including-all-subdirectories/ and Best way to load module/class from lib folder in Rails 3?) to get all files loading so we:
*
*don't need to use require_dependency all over the place in the application and
*don't have to restart development servers when files in the lib directory change.
It seems like development performance would be slightly impacted, which is not that big of a deal to me. How would performance be impacted in a production environment? Do all of the files generally get loaded only once if you are in production anyway? Is there a better way that I'm not seeing?
If you could include some resources where I could read more about this, they would be greatly appreciated. Some blog posts said that this behavior changed recently with Rails 3 for autoreloading lib/* files and that it was contentious, but I didn't see any links to these discussions. It would be helpful for considering the pros/cons. Thanks!
A: The code reloader is disabled by default in production. So if you are calling require_dependency at the top of a file it is going to be executed only once.
The Rails 3 change you mentioned is really small. You can usually call Foo and it will be loaded from app/models/foo.rb automatically. Before it could also be loaded from lib/foo.rb. (These directories app/models and lib are called autoload paths.) Rails team decided to remove lib from autoload paths in the 3rd version. You can still put it back. But it is encouraged to leave in lib less frequenttly-changed and project-specific files. If you have something that does not belong to any of the default app subdirectories like app/models or app/controllers you don't have to put it in lib. You can add your own subdirectory. I have app/presenters, for example. There is a discussion on the old issue tracker if you want more info on that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Grouping and sorting Folders and Files in a ListView I'd like to display folders and files in a ListView the same way they are in the windows explorer i.e. folders first, then the files, and both groups sorted alphabetically.
I thought at first about using 2 ListViewGroup (one for Folders and one for files), but not only I can't hide the group header, it's not active when the ListView is in List mode.
Another solution would be to keep 2 underlying lists (one for folders and one for files) and populate the ListView from the 2 lists (first the folders and then the files). But this seems a bit clumsy as I'd have to sort my 2 lists and refresh the ListView content every time the user sorts the ListView.
Can anybody suggest solution to this issue? I feel like there's a simple answer and/or that I've missed something in the ListView control...
A: OK after a bit more searching here's how I've implemented this.
I used the custom sort functionality in the list view (see how to on http://support.microsoft.com/kb/319401).
The only change is in the Compare function of the ListViewColumnSorter.
If both X and Y items are of the same type (Folder or File) I return the "normal" result based on the item name sort. And if not, I return -1 if X is a folder and 1 if not.
That way folders always come first and both folders and files are sorted alphabetically
Each list view item gets is identified as a folder or file by its Tag property set when the items are added to the list.
A: One way to handle this is to use a TreeView for the folders (on the left), and a Listview for the files (on the right). Whenever the selection changes in the Treeview, you can update the file names in the Listview.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Version control system help for a single developer I'm currently a single developer working with the following.
*
*Mac for all computing / code requirements
*Eclipse / Dreamweaver for code editing
*Windows Server 2008, CF8 IIS for my dev server
Currently when I develop all my apps, I'm starting to find that I'm really in need of an VCS to manage the code as I'm playing that fun game of simply renaming files with v1, v2 etc but this is becoming a nightmare when I start work the next week as you can probably imagine.
My issue is, I'm not sure where to start, what VCS should I use as I would like to store everything on my local network and as my code writing machine is a Mac, and my dev server is a windows machine I'm not sure what products should I look at for an VCS.
If anyone out there is in a similar position i would love to hear how you have your environment set up so you can manage your code as this is proving to be a bit of a nightmare..
thanks in advance
A: I have the same requirement and setup.
I use Visual SVN Server on my dev machine to host all of my repositories. (Windows 2008 R2)
http://www.visualsvn.com/server/
I use TortoiseSVN on Windows for general SVN tasks:
http://tortoisesvn.tigris.org/
I use AnkhSVN for Visual Studio SVN support:
http://ankhsvn.open.collab.net/
I use the built in SVN command in Mac for general SVN tasks:
http://svnbook.red-bean.com/
On Mac I also use Versions for a graphical SVN front end:
http://versionsapp.com/
Everything except Versions for Mac in this list is free.
A: As for the client, you can use the subversive plugin for Eclipse. Simply go to Help -> Install New Software -> (Select your version of Eclipse) -> Collaboration -> Subversive. Very easy to use.
There are many, many SVN options for windows. http://willperone.net/Code/svnserver.php This tutorial refers to TortoiseSVN, but that's just one option of many. Also consider that running it under IIS may not be desirable (http://stackoverflow.com/q/2165540/684934).
A: I would sign up for a free hosted SVN service
http://www.atlassian.com/hosted/bitbucket/
And use either a SVN plugin or a Tortise / SmartSVN tool to commit.
Commit your code daily, or whenever you get to a working set. You will have unlimited history etc. Its also great as your happy to delete chunks of code / files when you think they aren't needed, and if you find they are needed later, you can still get them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to get form values from referrer in asp.net web forms in asp.net webforms is there a way to get the posted values of the previous page without having to send through query strings?
I want to pickup TxtSearch on the next page and I though I remember someway of doing without session or querystring (i thought you could you something like Request.Form();)
<tr>
<td><asp:TextBox ID="TxtSearch" runat="server"></asp:TextBox></td>
<td><asp:LinkButton ID="BtnSearch" runat="server" onclick="BtnSearch_Click">Search</asp:LinkButton></td>
<td><asp:LinkButton ID="BtnShowAll" runat="server" onclick="BtnShowAll_Click">Show All Shelters</asp:LinkButton></td>
</tr>
</table>
enter code here
A: If the values are posted you should be able to use Request and then your variable inside square brackets and quotes.
A: Try this from MSDN: How to Pass Values Between ASP.NET Web Pages.
An ASP.NET page posts to itself by default but you can post to a different page. See How to Post ASP.NET Web Pages to a Different Page and Cross-Page Posting in ASP.NET Web Pages.
A: var txtSearch = Request["TxtSearch"];
A: <asp:Button ID="button1" Runat=server Text="submit" PostBackUrl="~/NewPage.aspx" />
Then, in the NewPage.aspx.cs, you can access the TextBox control on Default.aspx as follows:-
public void page_load()
{
if(!IsPostBack)
{
TextBox tb = (TextBox)PreviousPage.FindControl("Text1");
Response.Write(tb.Text);}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ManagementScope.Connect failing with error E_ACCESSDENIED error while being run from Windows Service I am trying to connect to Windows WMI through service by filling the ManagementScope variables and trying to connect to remote machine. The Connect is succeeding if I am running as windows console, but failing when I am running the same code from windows service.
The code Iam using is as follows:
ManagementScope scope = null;
scope = new ManagementScope("\\\\" + m_sComputerName + "\\root\\cimv2");
if (m_sLoginName != null && m_sPassword != null)
{
scope.Options.Username = m_sLoginName;
scope.Options.Password = m_sPassword;
}
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
scope.Options.Impersonation = ImpersonationLevel.Impersonate;
scope.Connect();
I am running the windows service as Local System. The code is being written in C# with .net version 4.0
Any help much appreciated.
Thanks
A: By default, the LocalSystem account does not have access to network resources - see here. If you need to access network resources from your service, consider running it as a domain account. While it is possible to authorize access to remote resources for LocalSystem, doing so is not recommended. Another option would be to run the service as NT AUTHORITY\NetworkService - see here, in which case the service will be authenticated as the machine account when accessing network resources.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Determine file type from ImageFormat.MemoryBMP After resizing an image, my resize function returns a newly drawn Image. I'm running into an issue where I need to determine what the file extension of the returned Image should be. I was using the Image.RawFormat property previously but everytime an Image is returned from this function it has ImageFormat.MemoryBMP, rather than ImageFormat.Jpeg or ImageFormat.Gif for example.
So basically my question is, how can I determine what file type the newly resized Image should be?
public static Image ResizeImage(Image imageToResize, int width, int height)
{
// Create a new empty image
Image resizedImage = new Bitmap(width, height);
// Create a new graphic from image
Graphics graphic = Graphics.FromImage(resizedImage);
// Set graphics modes
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
// Copy each property from old iamge to new image
foreach (var prop in imageToResize.PropertyItems)
{
resizedImage.SetPropertyItem(prop);
}
// Draw the new Image at the resized size
graphic.DrawImage(imageToResize, new Rectangle(0, 0, width, height));
// Return the new image
return resizedImage;
}
A: The resized image is not in any file based format, it is an uncompressed memory representation of the pixels in the image.
To save this image back to disk the data needs to be encoded in the selected format, which you have to specify. Look at the Save method, it takes an ImageFormat as a second argument, make that Jpeg or whatever format best fits your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Jsoup URL.get()/post() out of memory error I'm executing this code:
//doc = Jsoup.connect(data[0].getURL()).get();
Document doc = Jsoup.connect(url).post();
and am getting an out of memory exception. Obviously the web page's HTML is too much too download. All I want from the webpage are all of the elements within the following tags
<div class="animal-info">...</div>
Is there a way for me to do this using Jsoup without having to download the whole webpage, or a way to get around the out of memory exception?
A: Try
Document doc = Jsoup.connect(url).get();
Elements divElements = doc.getElementsByTag("div");
for(Element divElement : divElements){
if(divElement.attr("class").equals("animal-info")){
textList.add(divElement.text());
text = textList.toString();
Log.e("Content", text);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ruby classes, include, and scope How does including a module affect scope? Specifically, in this example:
module ModuleA
class ClassA
def initialize
puts "test passed"
end
end
end
module ModuleB
include ModuleA
# test 1
C = ClassA.new
class ClassB
def initialize
c = ClassA.new
end
end
end
# test 2 and 3 fail without this
#include ModuleB
module ModuleC
# this doesn't help
include ModuleB
# test 2
ClassB.new
# test 3
ModuleB::ClassB.new
end
test 1 works fine, but test 2 and test 3 fail without the commented-out import ModuleB.
*
*Why is ClassA in scope inside of ModuleB (test 1) but not in ClassB?
*Why does the import ModuleB bring ClassA into scope in ClassB?
A: The keywords class, module and def are what is known as "scope gates". They create new scopes.
#!/usr/bin/env ruby
module ModuleA
class ClassA
def initialize
puts "test passed"
end
end
end
module ModuleB
include ModuleA
# test 1
c = ClassA.new # this works as ModuleA has been included into this module
class ClassB # class is a scope gate, creates new scope
def initialize # def is a scope gate, creates new scope
c = ModuleA::ClassA.new # must fully qualify ClassA
end
end
ClassB2 = Class.new do # no scope gate
define_method :initialize do # no scope gate
c = ClassA.new # this works, no need to fully qualify
end
end
end
b = ModuleB::ClassB.new
b2 = ModuleB::ClassB2.new
I began to understand scopes in Ruby after reading the book "Metaprogramming Ruby". It is truly enlightening.
Edit: In response to also's comment below.
A class is essentially a Ruby constant (notice that it is an object with a capitalized name). Constants have a defined lookup algorithm within scopes. The Ruby Programming Language O'Reilly book explains it well in section 7.9. It is also briefly described in this blog post.
Top-level constants, defined outside of any class or module, are like top-level methods: they are implicitly defined in Object. When a top-level constant is referenced from within a class it is resolved during the search of the inheritance hierarchy. If the constant is referenced within a module definition it does an explicit check of Object after searching the ancestors of the module.
That's why include ModuleB at the top level makes the class in ModuleB visible in all modules, classes and methods.
A: The reason is (I think) to do with bindings. The clue for me is that the following also won't work:
module ModuleB
include ModuleA
class ClassB
def initialize
c = ClassA.new
end
end
ClassB.new
end
ClassA doesn't mean anything in the ClassB definition because it's not a constant in ClassB - the module has only been included in its parent module. Making this change should make everything work:
module ModuleB
include ModuleA
class ClassB
def initialize
c = ModuleA::ClassA.new
end
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Passing raw Markdown text to Jade I'm playing around with my first Node.js Express application, and as every programmer knows, the first thing you should build when testing out a new framework is a blog! Anyway, I'd like to write the articles in Markdown and then render it in the view. I saw that Jade allows for this to be done inside the view itself, using filters, but I can't get that working.
To simplify the situation, here's an example of what I'm talking about.
//app.js
res.render("article", {
md : "Hello World!\n\n*Woo*"
});
//article.jade
section
:markdown
#{md}
But, that outputs this: <section><h1>{md}</h1></section>... it isn't substituting in the variables I've passed to it.
Then I tried this:
//article.jade
section
:markdown
!{md}
And the output is this:
<section><p>Hello World!
*Woo*</p></section>
So, now it's not parsing the markdown!
I have been able to get this to work by parsing the markdown in the app.js file and then passing the HTML to the view to display, but I don't know, that seems a bit messier.
Is there a way to pass variables into Jade filters?
A: I don't think jade can do this out of the box. One way to accomplish it that might feel slightly cleaner than pre-rendering the markdown is to create a helper function called markdown that takes a markdown string and returns HTML. Then you could do something like
section
!= markdown(md)
The markdown function should be included in the locals data when you render the jade template and can directly use a markdown library to convert the markdown syntax to HTML.
A: You can do this with a function passed in to jade from node:
var md = require("node-markdown").Markdown;
Then pass it into the view as a local:
res.render('view', { md:md, markdownContent:data });
Then render it in the jade view by calling the function:
!= md(markdownContent)
A: The node module node-markdown is deprecated. The marked is advanced new version. You can try like this
var md = require('marked');
Inside your router
res.render('template', { md: md });
Inside your jade template
div!= md(note.string)
A: If you are using Scalate's Jade support you can enter:
section
:&markdown
#{md}
You can also import external files with:
section
:&markdown
#{include("MyFile.md")}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Whats wrong with the following unbind script? (dolist (abcc '("C-a" "C-b"))
(global-unset-key (kbd abcc)))
It keeps on giving the error :
Debugger entered--Lisp error: (wrong-type-argument integer-or-marker-p abcc)
read-kbd-macro(abcc)
#[(keys) "\301!\207" [keys read-kbd-macro] 2 2180088](abcc)
(kbd abcc)
(global-unset-key (kbd abcc))
(while --dolist-tail-- (setq abcc (car --dolist-tail--)) (global-unset-key (kbd abcc)) (setq --dolist-tail-- (cdr --dolist-tail--)))
(let ((--dolist-tail-- ...) abcc) (while --dolist-tail-- (setq abcc ...) (global-unset-key ...) (setq --dolist-tail-- ...)))
(dolist (abcc (quote ...)) (global-unset-key (kbd abcc)))
eval-buffer(#<buffer *load*> nil "/home/name/.emacs" nil t) ; Reading at buffer position 63
load-with-code-conversion("/home/name/.emacs" "/home/name/.emacs" t t)
load("~/.emacs" t t)
#[nil "\205\264
A: I initially thought that this is a bug in Emacs. I was very surprised nobody's come across this before.
Here is a workaround you can use:
(dolist (abcc '("C-a" "C-b"))
(global-unset-key (read-kbd-macro abcc)))
What happens is kbd is a macro that wraps a function, however it doesn't evaluate its parameter explicitly. So the symbol abcc is getting passed straight to the function.
After a bit more thinking (and reading the docs). It's actually user error.
The doc-string for kbd clearly states that it should be used on string constants.
So kbd should be used when you only want a key's internal representation to appear in the compiled byte-code. e.g.
(define-key foo-mode-map (kbd "C-a") 'foo)
But read-kbd-macro should be used when you want the argument to be evaluated.
A: (keys) is a macro that just passes right through to (read-kbd-macro). The former also errors out for me for some reason, but the latter doesn't. Try that instead?
A: kbd is a macro, so it does not evaluate its arg.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Jquery "Delay is Not A Function" with Jquery 1.6.4 I looked at some of the other questions on here pertaining to this problem but they were all using an older version of Jquery. I am having a problem with the latest version of jquery which I am grabbing from the goolge link:
http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
When I execute this code it is giving the error "delay is not a function". It didn't use to do this and I can't figure out why it might be doing it now.
$('.news_title_main').children('ul').delay(1500).slideUp(1000).queue(function(next) {
removeLast();
});
A: Check the <head></head> of your html page because that is where you usually put scripts such as javascript scripts.
Cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compilation error when calling function with default arguments I'm getting errors when I call a function which uses a default argument.
The two files are cache.cpp and cache.h
Command I use to compile is
g++ -c cache.cpp
and the error is:
cache.cpp: In member function ‘bool mem::read(long unsigned int)’:
cache.cpp:205:88: error: no matching function for call to ‘vcache::swap(long unsigned int&, bool&)’
cache.h:97:23: note: candidate is: long unsigned int vcache::swap(long unsigned int, bool, int)
cache.cpp: In member function ‘void mem::write(long unsigned int)’:
cache.cpp:367:92: error: no matching function for call to ‘vcache::swap(long unsigned int&, bool&)’
cache.h:97:23: note: candidate is: long unsigned int vcache::swap(long unsigned int, bool, int)
As you can see on line #569 where the function vcache::swap has been defined, I've provided a default value to the 3rd argument.
The problem arises when I don't specify the 3rd argument during the function call. If I run this by explicitly specifying a 3rd argument, it compiles properly.
Am unable to understand why this is happening.
A: That's not how default arguments work. The default argument has to go in the declaration, not the definition:
// foo.h
void foo(int, int, int = 5); // default values here
// foo.cpp
void foo(int a, int b, int c)
{
// ...
}
Think about it: Every TU that wants to use the function has to know the default value. This only makes sense in the declaration, which every user of the function must see.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: set delimiter when calling stored procedure The quotes in strings being passed to sql for insertion into a table, are causing the stored proc to fail. This seems to be common, and PHP users are told to escape the quotes. If i understand this correctly, I'll have to escape the whole text, for sql storage, then unescape it for html display. there must be a better way. it occurred to me that setting the delimiter when calling the stored proc, might be a way. or with php, redefining the quote symbol. so far, i haven't found anything on either of these ideas.
DEFINING THE DELIMITER IN SP CALL
call blog.postNewBlog(delimiter // begin {$blogText} end//, 'my text1', null, null, @out_dt, @out_title, @out_text)
A: A different delimiter still doesn't save you from SQL injection: if someone knows what your delimiter is, they could manipulate your query to make it do bad things, simply by abusing the delimiter string within whatever text they submit.
The proper solution to this kind of issue is to use a database binding that uses placeholders in queries. For example, there are a bunch of database abstraction layers in PEAR that give you a syntax roughly like this:
$db->query("INSERT INTO table VALUES(?, ?, ?, ?)", $var1, $var2, $var3, $var4);
The great thing about this is that the abstraction layer will automatically take care of quotes (if necessary) and you don't have to care about them at all. (I'm fairly sure this will work for passing stuff to stored procedures, too, but I don't have specific experience with SPs and MySQL).
By the way, even with the standard kinds of approaches you don't need to unescape the values when getting them from the database: the escaping is only used within queries. Quotes are not stored in the database in escaped form, and in the same vein query results are not escaped either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Stream redirection and pipes when making a Linux shell I have an assignment to create a Linux shell in C. Currently, I am stuck on implementing redirections and pipes. The code that I have so far is below. The main() parses user's input. If the command is built in, then that command is executed. Otherwise, the tokenized input is passed to execute() (I know that I should probably pull the built-in commands into their own function).
What execute() does is loop through the array. If it encounters <, >, or | it should take appropriate action. The first thing I am trying to get to work correctly is piping. I am definitely doing something wrong, though, because I cannot get it to work for even one pipe. For example, a sample input/output:
/home/ad/Documents> ls -l | grep sh
|: sh: No such file or directory
|
My idea was to get each of the directions and piping work for just one case, and then by making the function recursive I could hopefully use multiple redirections/pipes in the same command line. For example, I could do program1 < input1.txt > output1.txt or ls -l | grep sh > output2.txt.
I was hoping that someone can point out my errors in trying to pipe and perhaps offer some pointers in how to approach the case where multiple redirections/pipes are inputted by the user.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int MAX_PATH_LENGTH = 1024; //Maximum path length to display.
int BUF_LENGTH = 1024; // Length of buffer to store user input
char * delims = " \n"; // Delimiters for tokenizing user input.
const int PIPE_READ = 0;
const int PIPE_WRITE = 1;
void execute(char **argArray){
char **pA = argArray;
int i = 0;
while(*pA != NULL) {
if(strcmp(argArray[i],"<") == 0) {
printf("<\n");
}
else if(strcmp(argArray[i],">") == 0) {
printf(">\n");
}
else if(strcmp(argArray[i],"|") == 0) {
int fds[2];
pipe(fds);
pid_t pid;
if((pid = fork()) == 0) {
dup2(fds[PIPE_WRITE], 1);
close(fds[PIPE_READ]);
close(fds[PIPE_WRITE]);
char** argList;
memcpy(argList, argArray, i);
execvp(argArray[0], argArray);
}
if((pid = fork()) == 0) {
dup2(fds[PIPE_READ], 0);
close(fds[PIPE_READ]);
close(fds[PIPE_WRITE]);
execvp(argArray[i+1], pA);
}
close(fds[PIPE_READ]);
close(fds[PIPE_WRITE]);
wait(NULL);
wait(NULL);
printf("|\n");
}
else {
if(pid == 0){
execvp(argArray[0], argArray);
printf("Command not found.\n");
}
else
wait(NULL);*/
}
*pA++;
i++;
}
}
int main () {
char path[MAX_PATH_LENGTH];
char buf[BUF_LENGTH];
char* strArray[BUF_LENGTH];
/**
* "Welcome" message. When mash is executed, the current working directory
* is displayed followed by >. For example, if user is in /usr/lib/, then
* mash will display :
* /usr/lib/>
**/
getcwd(path, MAX_PATH_LENGTH);
printf("%s> ", path);
fflush(stdout);
/**
* Loop infinitely while waiting for input from user.
* Parse input and display "welcome" message again.
**/
while(1) {
fgets(buf, BUF_LENGTH, stdin);
char *tokenPtr = NULL;
int i = 0;
tokenPtr = strtok(buf, delims);
if(strcmp(tokenPtr, "exit") == 0){
exit(0);
}
else if(strcmp(tokenPtr, "cd") == 0){
tokenPtr = strtok(NULL, delims);
if(chdir(tokenPtr) != 0){
printf("Path not found.\n");
}
getcwd(path, MAX_PATH_LENGTH);
}
else if(strcmp(tokenPtr, "pwd") == 0){
printf("%s\n", path);
}
else {
while(tokenPtr != NULL) {
strArray[i++] = tokenPtr;
tokenPtr = strtok(NULL, delims);
}
execute(strArray);
}
bzero(strArray, sizeof(strArray)); // clears array
printf("%s> ", path);
fflush(stdout);
}
}
A: Part of the problem is in the pipe handling code - as you suspected.
else if (strcmp(argArray[i], "|") == 0) {
int fds[2];
pipe(fds);
pid_t pid;
if ((pid = fork()) == 0) {
dup2(fds[PIPE_WRITE], 1);
close(fds[PIPE_READ]);
close(fds[PIPE_WRITE]);
char** argList;
memcpy(argList, argArray, i);
execvp(argArray[0], argArray);
}
if ((pid = fork()) == 0) {
dup2(fds[PIPE_READ], 0);
close(fds[PIPE_READ]);
close(fds[PIPE_WRITE]);
execvp(argArray[i+1], pA);
}
close(fds[PIPE_READ]);
close(fds[PIPE_WRITE]);
wait(NULL);
wait(NULL);
printf("|\n");
}
The first execvp() was probably intended to use argList since you've just copied some material there. However, you've copied i bytes, not i character pointers, and you've not ensured that the pipe is zapped and replaced with a null pointer.
memcpy(argList, argArray, i * sizeof(char *));
argList[i] = 0;
execvp(argList[0], argList);
Note that this has not verified that there is no buffer overflow on argList; Note that there is no space allocated for argList; if you use it, you should allocate the memory before doing the memcpy().
Alternatively, and more simply, you can do without the copy. Since you're in a child process, you can simply zap replace argArray[i] with a null pointer without affecting either the parent or the other child process:
argArray[i] = 0;
execvp(argArray[0], argArray);
You might also note that the second invocation of execvp() uses a variable pA which cannot be seen; it is almost certainly incorrectly initialized. As a moderately good rule of thumb, you should write:
execvp(array[n], &array[n]);
The invocations above don't conform to this schema, but if you follow it, you won't go far wrong.
You should also have basic error reporting and a exit(1) (or possibly _exit(1) or _Exit(1)) after each execvp() so that the child does not continue if it fails to execute. There is no successful return from execvp(), but execvp() most certainly can return.
Finally for now, these calls to execvp() should presumably be where you make your recursive call. You need to deal with pipes before trying to deal with other I/O redirection. Note that in a standard shell, you can do:
> output < input command -opts arg1 arg2
This is aconventional usage, but is actually permitted.
One good thing - you have ensured that the original file descriptors from pipe() are closed in all three processes (parent and both children). This is a common mistake which you have avoided making; well done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Reversing a HashMap from Map to Map> Is there a more elegant/built-in way to reverse the keys and values of a Hashmap?
I currently have the following.
private Map<Boolean, List<String>> reverseMap(Map<String, Boolean> permissions) {
List<String> allow = new ArrayList<String>();
List<String> deny = new ArrayList<String>();
Map<Boolean, List<String>> returnvalue = new HashMap<Boolean, List<String>>();
for (Entry<String, Boolean> entry : permissions.entrySet()) {
if(entry.getValue()) {
allow.add(entry.getKey());
} else {
deny.add(entry.getKey());
}
}
returnvalue.put(true, allow);
returnvalue.put(false, deny);
return returnvalue;
}
A: You might consider using one of Guava's Multimap implementations. For example:
private Multimap<Boolean, String> reverseMap(Map<String, Boolean> permissions) {
Multimap<Boolean, String> multimap = ArrayListMultimap.create();
for (Map.Entry<String, Boolean> entry : permissions.entrySet()) {
multimap.put(entry.getValue(), entry.getKey());
}
return multimap;
}
Or more generally:
private static <K, V> Multimap<V, K> reverseMap(Map<K, V> source) {
Multimap<V, K> multimap = ArrayListMultimap.create();
for (Map.Entry<K, V> entry : source.entrySet()) {
multimap.put(entry.getValue(), entry.getKey());
}
return multimap;
}
A: I'd do something similar (but if you must do this kind of thing frequently, consider Guava), only replacing the List with Set (seems a little more consistent) and prefilling the reversemap:
private Map<Boolean, Set<String>> reverseMap(Map<String, Boolean> permissions) {
Map<Boolean, Set<String>> returnvalue = new HashMap<Boolean, Set<String>>();
returnvalue.put(Boolean.TRUE, new HashSet<String>());
returnvalue.put(Boolean.FALSE, new HashSet<String>());
for (Entry<String, Boolean> entry : permissions.entrySet())
returnvalue.get(entry.getValue()).add(entry.getKey());
return returnvalue;
}
A: First thing to note is that you don't really need a reverse map if your values are only true or false. It will make sense if you have a broader range of values.
One easy (but not very elegant) way to get the entries with a specific value is:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
keys.add(entry.getKey());
}
}
return keys;
}
You can see that this is not so good if you need to call it every now and then. It makes sense to have two different maps (straight and reverse) and add entries to both. You can't use Bidi maps since there is no 1:1 relation between keys and values.
UPDATE: The following solution won't work. See comments.
You can also consider using a TreeMap and keep it sorted based on the value. This way you can have a sorted set by calling map.entrySet() any time (denies entries first, then allows). The drawback is that it is only one set.
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Boolean> sorted_map = new TreeMap(bvc);
class ValueComparator implements Comparator {
Map base;
public ValueComparator(Map base) {
this.base = base;
}
public int compare(Object a, Object b) {
return (Boolean)base.get(a).compareTo((Boolean)base.get(b));
}
}
A: Guava's BiMap already provides a method for reversing its key-value pairs. Perhaps you could change the interface of the Map in question to BiMap, or else use the following code:
private BiMap<Boolean, String> reverseMap(Map<String, Boolean> permissions) {
BiMap<String, Boolean> bimap = HashBiMap.create(permissions);
return bimap.inverse();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: XmlWriterSettings, XmlTextWriter, XmlWriter not formatting output?! No new lines, no indentation Using .Net 3.5 SP1 in VS2008 I have a XmlDocument and have tried writing it to file:
using (XmlTextWriter tw = new XmlTextWriter(outXmlFileName, System.Text.Encoding.UTF8))
{
tw.Formatting = Formatting.Indented;
tw.Indentation = 3;
tw.IndentChar = ' ';
tw.QuoteChar = '\'';
doc.Save(tw);
}
And
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(outXmlFileName, settings))
{
doc.Save(writer);
}
What is unclear from the documentation, http://msdn.microsoft.com/en-us/library/kkz7cs0d.aspx, is if I should be using XmlWriter.Create() above .Net 2, anyway either way neither methods format the output! I just get what is in the XmlDocument instance:
<?xml version='1.0' encoding='utf-8'?>
<root>
<node1 />
<node2 value='Data' />
<node3 value='ID' /><node4><item>
<from value='1 Jan 1870' />
<id value='PF' />
<to value='1 Jan 1940' /></item></node4>
</root>
How can I tidy my XML before writing it file from .Net?!
A: I got it to work by loading the XML into an 2nd intermediary XmlDocument instance so it forgot the original white space:
XmlWriterSettings settings = new XmlWriterSettings(); // http://msdn.microsoft.com/en-us/library/kkz7cs0d(VS.85).aspx
settings.Indent = true;
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(doc.OuterXml);
using (XmlWriter writer = XmlWriter.Create(outXmlFileName, settings))
{
doc2.Save(writer);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery - delete last object by key Hi i have this object :
object {
key1:[.....],
key2:[....],
key3:[.... ]
}
how does i can delete the last object key (key3)?
i would like to be free to delete last object key without knowing anything about that key.
A: Thsi is the ES5-compatible way of doing it:
obj = {a : 1, b : 2, c : 3};
var k = Object.keys(obj);
delete obj[k[k.length-1]];
or shorter:
delete obj[Object.keys(obj)[Object.keys(obj).length-1]];
A: There is not "last" object key within an object in Javascript. Object keys are not ordered and hence, there cannot be first or last.
A: I guess, technically, the keys aren't in any specific order, but anyway...
var key;
for (key in obj);
delete obj[key];
It iterates over the whole object, and then deletes whatever was the last thing to be visited.
edit to illustrate
obj = {a : 1, b : 2, c : 3};
for (key in obj); // loops over the entire object, doing nothing *EXCEPT*
// updating the `key` variable
alert(key); // "c" ... the last value of `key` was 'c'
delete obj[key]; // remove obj.c
A: You can't assume that the last element added will be the last element listed in a javascript object. See this question: Elements order in a "for (… in …)" loop
In short: Use an array if order is important to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Yahoo! Finance API DOW Until now, I've been using the INDU ticker to follow the DOW with the Yahoo! API. For whatever reason you were unable to directly follow ^dji ^djia or any other reasonable combination. Up until yesterday, INDU was working fine. However now I receive no data when requesting indu.
What other ticker can I use with the Yahoo! finance API that will return the DJIA?
A: This index is not available under any other name.
However, this problem was just a temporary glitch, now resolved by Yahoo. Unfortunately, their financial data availability is very flaky lately. E.g. data available on the web page, but CSV downloads give "N/A" for all fields, etc. There were similar incidents in recent months, with stock prices for random stocks given wrong values, and more.
So, if you're building a new service around these Yahoo services, be aware that:
*
*These services are not reliable.
*You're breaking Yahoo ToS, so there's nothing you can do if they are broken / not working, you cannot even complain to Yahoo in good faith.
According to Yahoo (post by Yahoo Developer Network Community Manager Robyn Tippins on Yahoo developer forums):
The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.
A: The formula for the DJIA isn't very complicated. If you are still able to pull quotes from individual stocks, you could use your code to pull the prices of the existing 30 components of the DJIA, add them up and divide by the current divisor. Of course, this has several disadvantages.
*
*You need to make 30 requests instead of one.
*You will have to adjust the divisor if there is a stock-split.
*You will have to change the the queries when the components
change.
The components of the DJIA are
AA AXP BA BAC CAT CSCO CVX DD DIS GE HD
HPQ IBM INTC JNJ JPM KFT KO MCD MMM MRK
MSFT PFE PG T TRV UTX VZ WMT XOM
The current divisor is 0.132129493.
The divisor changes whenever there is a stock split in on of the components. The components of the DOW changed 48 times from 1896-2009.
A: It seems like Yahoo Finance does not support the web service to query ^DJI or INDU.
Check out this discussion:
http://developer.yahoo.com/forum/General-Discussion-at-YDN/Dow-Jones-Industrial-Average-Quote-Error/1317052217631-f9173931-04fd-4519-b1b3-efb65d7ff8fa/1317065435082
A: Assuming that your application does not need to be real time market data (to the second), you can use the RAW data that is provided to build the interactive graph on yahoo. This data is comma separated and updates about once every minute. The downside: it will include all the data from the trading day. The time given is in Unix time so a conversion would be needed. I tried this out for the ticker symbols you listed and the only one I was able to get data with was ^dji. Hopefully this is what you are looking for!
You can mess with the link and see what happens to the data. For example you can change the amount of days.
http://chartapi.finance.yahoo.com/instrument/1.0/%5Edji/chartdata;type=quote;range=1d/csv/
A: I think Yahoo Finance All Currencies quote API Documentation will help you.
I found a Yahoo forum answer that says we cannot download CSV data for ^DJI.
Check also YQL console. This console will fetch values in JSON format.
A: The DIA ticker (SPDR Dow Jones Industrial Average) closely imitates the Dow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Best R data structure to return table value counts The following function returns a data.frame with two columns:
fetch_count_by_day=function(con){
q="SELECT t,count(*) AS count FROM data GROUP BY t"
dbGetQuery(con,q) #Returns a data frame
}
t is a DATE column, so output looks like:
t count(*)
1 2011-09-22 1438
...
All I'm really interested in is if any records for a given date already exist; but I will also use the count as a sanity check.
In C++ I'd return a std::map<std::string,int> or std::unordered_map<std::string,int> (*).
In PHP I'd use an associative array with the date as the key.
What is the best data structure in R? Is it a 2-column data.frame? My first thought was to turn the t column into rownames:
...
d=dbGetQuery(con,q)
rownames(d)=d[,1]
d$t=NULL
But data.frame rownames are not unique, so conceptually it does not quite fit. I'm also not sure if it makes using it any quicker.
(Any and all definitions of "best": quickest, least memory, code clarity, least surprise for experienced R developers, etc. Maybe there is one solution for all; if not then I'd like to understand the trade-offs and when to choose each alternative.)
*: (for C++) If benchmarking showed this was a bottleneck, I might convert the datestamp to a YYYYMMDD integer and use std::unordered_map<int,int>; knowing the data only covers a few years I might even use a block of memory with one int per day between min(t) and max(t) (wrapping all that in a class).
A: Contingency tables are actually arrays (or matrices) and can very easily be created.The dimnames hold the values and the array/matrix at its "core" holds the count data. The "table" and "tapply" functions are natural creators. You access the counts with "[" and use dimnames( ) followed by an "[" to get you the row annd column names. I would say it was wiser to use the "Date" class for dates than storing in "character" vectors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Objective-C Testing values in a range I have an objective-c question. I have an app that detects the rotation of the iOS device. I want to be able to have a timer started when the value is between two ranges. Basically if the rotation is between 0.1 and -0.1 then the timer will trigger.
I have tried while loops, for loops and I'm sure it is something simple I need to implement.
Thanks in advance for the suggestions!
-Brian
A: Regarding your comment, it looks like you might have the logic reversed.
You had:
if (rotationValue >= 0.1 && rotationValue <= -0.1) {
// doSomethingHere;
}
If you're looking for when the "rotation is between 0.1 and -0.1 then the timer will trigger", then you'd want:
if (rotationValue >= -0.1 && rotationValue <= 0.1) {
// doSomethingHere;
}
(I switched the order around, putting the negative on the left and the positive on the right, as that seems more logical to me, but anyway).
Or you could do:
if (ABS(rotationValue) <= 0.1) {
// doSomethingHere;
}
A: Take a NSTImer
if you are entering that range (just store a bool for that) you create a new timer using
[NSTimer scheduledTimer...] and if you are existing that region you will need to invalidate your timer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the tie up ID3D11DeviceContext::PSSetShaderResource() PSSetShaderResource()'s first parameter:
void PSSetShaderResources(
[in] UINT StartSlot,
[in] UINT NumViews,
[in] ID3D11ShaderResourceView *const *ppShaderResourceViews
);
StartSlot: "Index into the device's zero-based array to begin setting shader resources"
So what's the tie up between integer indices and your .hlsl variables? In d3d9, everything was by string-based name. Now these integer indices seem to have something missing......
Say you have one shader file:
// shader_1.psh
Texture2D tex ;
And another..
// shader_2.psh
TextureCube cubeTex ;
If you're only using shader_1.psh, how do you distinguish between them when they are in separate files?
// something like this..
d3d11devicecontext->PSSetShaderResources( 0, 1, &texture2d ) ;
// index 0 sets 0th texture..
// what index is the tex cube?
A: This is still an experimentally verified guess (didn't find reference documentation), but I believe you can do it like so:
// HLSL shader
Texture2D tex : register( t0 );
Texture2D cubeTex : register( t1 );
SamplerState theSampler : register( s0 );
So now, from the C++ code, to bind a D3D11Texture2D* to tex in the shader, the tie up is:
// C++
d3d11devicecontext->PSSetShaderResources( 0, 1, &texture2d ) ; // SETS TEX @ register( t0 )
d3d11devicecontext->PSSetShaderResources( 1, 1, &textureCUBE ) ;//SETS TEX @ register( t1 )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: MVC3/LINQ/EF4.1 selecting distinct col values from a result set? How can I select a list of column values from a result set (as distinct) and put into a list?
class T {int id; string name;}
-- Controller...
var query = @"exec someStoredProc";
IEnumerable<T> bb =
db2.Database.SqlQuery<T>(query);
// Something like???:
List<string> Names = bb.SelectDistinct("name"); // returns distinct list of names from result set
A: Since you just need the distinct list of names, you can project to the name property and the just use Distinct() :
List<string> Names = bb.Select( x=> x.name)
.Distinct()
.ToList();
This requires that you make the name property public, also I would rethink your class name T, how about CustomerName (or whatever else is expressive enough so you know what it means) ?
public class CustomerName
{
public int id{get;set;}
public string name {get;set;}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to save added google maps overlays in an android app? I created an app in which users can add various markers on google maps using overlays. I want the app to save the overlay when the user creates it so that when they re-open the app later the markers will still be present.
Currently anytime the app is re-opened the created markers are gone. I have searched the internet and have not gotten a clear understanding of how to save my markers/overlays offline for later use.
A: As mentioned, you need to use some persistent storage. Perhaps, database would be an excess in your particular case (if you simply need to save a bunch of longitude-latitude pairs), and Shared Preferences would fit your needs. If you rarely need to read/store this data, then putting JSONArray as a String to Shared Preferences would be the simplest (in terms of reading and extracting data) solution:
SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
JSONArray jsonArr = new JSONArray();
JSONObject json;
for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
json = new JSONObject();
json.put("lat", user_markers.get(i).getLat());
json.put("long", user_markers.get(i).getLong());
jsonArr.put(json);
}
editor.putString("markers", jsonArr.toString());
editor.commit();
If you need to read/store this data a bit more often, then you may assign ids/indexes to separate SharedPreferences's values, but this may require more complicated extraction method. For example:
SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
int id;
for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
id = user_markers.get(i).getId(); // some Id here
// or simply id = i;
editor.putString("markers_lat_" + id, user_markers.get(i).getLat());
editor.putString("markers_long_" + id, user_markers.get(i).getLong());
}
editor.commit();
After all, you should consider using database if you plan to store big amount of data or data of complicated structure.
A: It just an idea, but you can save your markers in database and when you reopen your map just query database and put it on the map again...
A: You should use some persistent storage. SQLite would probably be the best option here. Overlays have their lat and lng. Just get them and whatever data you need along with them and put all these in the SQLite database. Then on Activity start get the points from database and show them on the map.
A: Use a SQLite database to save the user data. They are simple and for a large amount of data they are better than SharedPreferences.
More Info
Example
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: When do background images from a style sheet get downloaded? When a user downloads a style sheet, do all background images specified in that style sheet get downloaded as well? Or, are background images only downloaded as needed based on the CSS rules that apply to the current page?
A: They only get downloaded as they are needed. To verify, use Chrome Debugger tools network tab and watch what gets requested.
A: Images, scripts, and stylesheets are downloaded as needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: for loop iterates into a NoneType only during a __str__ statement? So I'm working in Python trying to create a ShapeSet instance that contains a list of Shape instances and I need it to print out the list of Shape instances.
I can use the for loop in other parts of the code without running into an error. However, when I attempt a print statement it prints out the whole list and at the end results in error:
__str__ returned non-string (type NoneType)
I don't understand why it fails to understand to stop at the end of the list here. (At least that's what I think it's doing).
Any help is greatly appreciated.
class ShapeSet:
def __init__(self):
"""
Initialize any needed variables
"""
self.collect = []
self.place = None
def __iter__(self):
"""
Return an iterator that allows you to iterate over the set of
shapes, one shape at a time
"""
self.place = 0
return self
def next(self):
if self.place >= len(self.collect):
raise StopIteration
self.place = self.place + 1
return self.collect[self.place-1]
def addShape(self, sh):
"""
Add shape sh to the set; no two shapes in the set may be
identical
sh: shape to be added
"""
s_count = 0
c_count = 0
t_count = 0
self.collect.append(sh)
for i in self.collect:
if type(sh) == Square and type(i) == Square:
if sh.side == i.side:
s_count = s_count + 1
if s_count == 2:
self.collect.remove(sh)
print('already there')
if type(sh) == Circle and type(i) == Circle:
if sh.radius == i.radius:
c_count = c_count + 1
if c_count == 2:
self.collect.remove(sh)
print('already there')
if type(sh) == Triangle and type(i) == Triangle:
if sh.base == i.base and sh.height == i.height:
t_count = t_count + 1
if t_count == 2:
self.collect.remove(sh)
print('already there')
def __str__(self):
"""
Return the string representation for a set, which consists of
the string representation of each shape, categorized by type
(circles, then squares, then triangles)
"""
for i in self.collect:
if type(i) == Square:
print ('Square with measurements ' + str(i.side))
if type(i) == Circle:
print ('Circle with measurements ' + str(i.radius))
if type(i) == Triangle:
print ('Triangle with measurements, base/height ' + str(i.base)+ ' ' + str(i.height))
A: Read the docstring in your __str__ function. You're suppose to "return the string representation" not print it. Since there is no return statement in the __str__ function, it returns None, which print chokes on.
Instead, actually return the desired string, and let the external print call display it:
def __str__(self):
"""
Return the string representation for a set, which consists of
the string representation of each shape, categorized by type
(circles, then squares, then triangles)
"""
strings = []
for i in self.collect:
if type(i) == Square:
strings.append('Square with measurements ' + str(i.side))
if type(i) == Circle:
strings.append('Circle with measurements ' + str(i.radius))
if type(i) == Triangle:
strings.append('Triangle with measurements, base/height ' + str(i.base)+ ' ' + str(i.height))
return '\n'.join(strings)
A: You wrote
def __str__(self):
"""
**Return** the string representation for a set, which consists of
the string representation of each shape, categorized by type
(circles, then squares, then triangles)
"""
but you don't return anything - you just print stuff.
Put a appropriate __str__ method on all your classes:
class Square:
def __str__(self):
return 'Square with measurements ' + str(i.side)
class Circle:
def __str__(self):
return 'Circle with measurements ' + str(i.radius)
# and so on
and a representation for your ShapeSet:
class ShapeSet:
def __str__(self):
return '\n'.join(str(x) for x in self.collect)
Now you can print(some_shapeset) as well as print(some_circle).
A: You could also do whatever you like within the str method, itterate, print outputs, more logic, etc, as long as at the end, you return a string i.e. return "" just to satisfy the requirement.
In Your case:
def __str__(self):
"""
Return the string representation for a set, which consists of
the string representation of each shape, categorized by type
(circles, then squares, then triangles)
"""
for i in self.collect:
if type(i) == Square:
print ('Square with measurements ' + str(i.side))
if type(i) == Circle:
print ('Circle with measurements ' + str(i.radius))
if type(i) == Triangle:
print ('Triangle with measurements, base/height ' + str(i.base)+ ' ' + str(i.height))
return ""
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Where to input my website URL In my website settings of Facebook developers I'm looking for a field to input my website URL. Program I'm using says this is a must. Can you show me where to make the input?
A: In your application summary page, at the bottom
https://developers.facebook.com/apps/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change Applescript into single line NSApplescript source Im building an app for learning purposes of using applescript to send multiple commands during an action. Below is the code I'm messing with but I have stripped out the actions in between the "" and replaced them with numbers. Everything works fine in applescript but making this into an NSApplescript initwithsource: line has been a bother.
tell application "Terminal"
activate
set currentTab to do script "1"
do script "2" in currentTab
do script "3" in currentTab
do script "4" in currentTab
delay 0.5
tell application "Finder" to set visible of process "Terminal" to false
end tell
What is the best way to combine this applescript into a single line? Thanks!
A:
"What is the best way to combine this applescript into a single line?"
Use AppleScript? :-D
First, in AppleScript Editor, open the Preferences window and click the option to Show Script menu in menu bar.
Then choose Open Scripts Folder from the script menu item up in the upper right of the screen.
Create a new AppleScript .scptd document with the following script:
tell application "AppleScript Editor"
set string_ to text of first document
-- make a list with each line of the script
set stringLines to paragraphs of string_
set originalDelims to AppleScript's text item delimiters
-- add newlines
set AppleScript's text item delimiters to "\\n"
-- now combine the items in the list using newlines
set stringNewlines to stringLines as string
set AppleScript's text item delimiters to "\""
set stringNewlines to text items of stringNewlines
set AppleScript's text item delimiters to "\\\""
set stringNewlines to stringNewlines as string
set AppleScript's text item delimiters to originalDelims
set stringNewlines to "@\"" & stringNewlines & "\""
set the clipboard to stringNewlines
end tell
(Note that this script isn't perfect: it works fine for simple scripts like the one you provided, but isn't able to convert itself).
Save that as a script in the Scripts folder you revealed earlier.
Then open your script document you want to convert and make it the front document in AppleScript Editor. Then invoke the conversion script by choosing it from the Script menu.
Given the script you provided, it should produce the following constant NSString:
@"tell application \"Terminal\"\n activate\n set currentTab to do script \"1\"\n do script \"2\" in currentTab\n do script \"3\" in currentTab\n do script \"4\" in currentTab\n delay 0.5\n tell application \"Finder\" to set visible of process \"Terminal\" to false\nend tell\n"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php Validate latitude/longitude strings in decimal format Alright I have what I would call a massive list of longitude and latitude coordinates. That said I also have a handful of sources I pull these coordinates in from. Some of them come from get/post methods which can cause potential security holes in my site/service. So I am trying to figure out how to validate longitude and latitude via PHP. I was thinking something regex via preg_match. But I could be wrong, maybe there's an easier way someone would like to suggest. I've tried my own concepts, and I have tried various internet brew concepts of trying to find a regex pattern that will validate these for me via preg_match (or similar again if you got a better suggestion I am all ears).
My Last failed attempt prior to finally caving in and coming here was..
preg_match('^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$', $geoResults['latitude']))
which yields " preg_match() [function.preg-match]: No ending delimiter '^' found " as my error. Last couple attempts I have tried yielded that error so I have no idea what it is or means.
A: It's a bit old question, but anyway I post my solution here:
preg_match('/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?);[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/', $geoResults['latlng']);
I assumed here that u split lat. from lng. by semicolon. If u want to check only lat. or only lng. here are regexp's;
Rgx for lat.:
/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/
Rgx for lng.:
/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/
Here is an improved online demo:
https://regex101.com/r/bV5fA1/1
A: Add forward slashes to the beginning and end of the match sequence to make it valid regex syntax:
preg_match('/^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$/', $geoResults['latitude']);
For your question on whether to use regular expressions (regex) or not, in this case using regex (PCRE preg_match()) is the best way to secure your site. When matching variable complex string arrangements, regex is the way to go. It's common for developers to turn to regex for matching a static string such as 'abc'. This is when strpos() or str_replace() are better choices.
A: Why not use modern and unit tested Assertion library for that?
Example Value Object class:
<?php
namespace MyApp\ValueObject;
use Assert\Assertion;
class Location
{
private $lat;
private $lon;
public function __construct($lat, $lon)
{
Assertion::greaterOrEqualThan($lat, -90.0);
Assertion::lessOrEqualThan($lat, 90.0);
Assertion::greaterOrEqualThan($lon, -180.0);
Assertion::lessOrEqualThan($lon, 180.0);
$this->lat = $lat;
$this->lon = $lon;
}
public function latitude()
{
return $this->lat;
}
public function longitude()
{
return $this->lon;
}
public function __toString()
{
return $this->lat . ' ' . $this->lon;
}
Usage:
$location = new \MyApp\ValueObject\Location(24.7, -20.4059);
echo $location->latitude() , ' ' , $location->longitude();
// or simply
echo $location;
A: I want to validate latitude and longitude, too, and have this result:
-90.0000 - 90.0000
^-?([0-9]|[1-8][0-9]|90)\.{1}\d{4}$
-180.0000 - 180.0000
^-?([0-9]|[1-9][0-9]|1[0-7][0-9]|180)\.{1}\d{4}$
I have tested here with pcre.
A: regex
/([0-9.-]+).+?([0-9.-]+)/
A: Function to validate Latitude
function validateLatitude($lat) {
$lat_array = explode( '.' , $lat );
if( sizeof($lat_array) !=2 ){
return '_n_';
}
if ( ! ( is_numeric($lat_array[0]) && $lat_array[0]==round($lat_array[0], 0) && is_numeric($lat_array[1]) && $lat_array[1]==round($lat_array[1], 0) ) ){
return '_n_';
}
if( $lat >= -90 && $lat <= 90 ){
return '_s_';
}
else {
return '_n_';
}
}
Function to validate Longitude
function validateLongitude($long) {
$long_array = explode( '.' , $long );
if( sizeof($long_array) !=2 ){
return '_n_';
}
if (!( is_numeric($long_array[0]) && $long_array[0]==round($long_array[0], 0) && is_numeric($long_array[1]) && $long_array[1]==round($long_array[1], 0) ) ){
return '_n_';
}
if( $long >= -180 && $long <= 180 ){
return '_s_';
}
else {
return '_n_';
}
}
A: It's real work unicum solution in net
"
-90.0000 - 90.0000
^-?([0-9]|[1-8][0-9]|90)\.{1}\d{4}$
-180.0000 - 180.0000
^-?([0-9]|[1-9][0-9]|1[0-7][0-9]|180)\.{1}\d{4}$
"
For &lat=90.000000 &lon=180.000000 :
"/^-?([0-9]|[1-8][0-9]|90)\.{1}\d{1,6}$/"
"/^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}/"
A: These didn't seem very accurate being that:
latitude is between -90 and 90
longitude is between -180 and 90
and
\d in regex matches more than [0-9]
Also a whole library just for some regex didn't seem logical...
So I built and tested:
//Latitude
if(preg_match('/^-?(90|[1-8][0-9][.][0-9]{1,20}|[0-9][.][0-9]{1,20})$/', '89.33333')) {
echo "<br>a match<br>";
} //will pass ->89.33333
//Longitude
if(preg_match('/^-?(180|1[1-7][0-9][.][0-9]{1,20}|[1-9][0-9][.][0-9]{1,20}|[0-9][.][0-9]{1,20})$/', '180.33333')) {
echo "<br>b match<br>";
} // will fail anything over 180 ->180.33333
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: How do i create a simple expandable list in android i want to make an expandable list in android ( with only one group ) that has item1, sub-item1, seperator, item2, sub-item2, sperator and so on..., where item1 and item2's values are taken from an array of numbers and sub-item1 and sub-item2's values are taken from an array of strings. I did attempt to find out but im pretty new and dont understand most of it(yet):D.
Thanks in advance.
A: You can use http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.html link for expandable list.
All The Best
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I import Landslide CRM data into Salesforce? I'm importing some customer information from Landslide CRM into Salesforce.
Anyone have advice on the best methodology for doing the import?
It seems like the Apex Data Loader is the best way to go, but I don't know
if there are any issues with handling the objects in question, or if there
might be a specific tool or script to perform this migration.
Any experience with this import in specific or importing data into Salesforce
in general would be appriciated.
A: Importing Data to salesforce can be achieved in multiple ways depending on the type of data nd the requirements you have.
The first thing to do is get your data into CSV files so you'll need to find a way to export the dat afirst. For UTF-8 encoded data don't use Excel use something like OpenOffice (only required if you have UTF-8 Characters)
If its account and contact data for example. There is an import wizard available in Setup > Administration Setup > Import Business Accounts/Contacts
Next Option is as you say to use the Apex Data Loader. This probably the best approach.
The first thing and this is critical for big migrations is to Create a Field on your account object which will be a Unique Field for reference purposes. When creating this field set it as an External ID field and populate it with a unique reference for your accounts, the same goes for anything else which will be a parent. (you'll see why shortly.)
Next use the Insert option in the Data Loader to load the data mapping all the fields, especially the External Id
Now when you upload child objects use the Upsert option and map your Account Id via the External Id created earlier. This will match the accounts using your unique Id instead of you having to use the Salesforce id, saves alot of time.
Repeat the same for other objects and you should be good to go.
Apologies for the lack for structure here... doing this while in work and don't have alot of time but hope this helps.
A: The data loader works great for most types of imports. The one suggestion I would give you is to create a new custom field on your target objects (presumably Account and Contact) called "Landslide ID" or similar, identify it as an external ID field, and then import the primary keys from your source system into this field (along with the "real" data).
Doing this achieves a couple things - first, you have an easy unique link back to the source data for troubleshooting or tracing back to the source system. Second, if you find yourself in a situation where you need to import more fields or related data from the original source system, you'll be able to do so in an easy and correct way. It's just a good standard practice to adopt when doing data migrations -- it's almost no additional effort and can save you many hours in the future.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Populating foreign key on create action I have a Evaluation similar to this:
Evaluation.rb
has_one :cardio
has_one :neuro
Cardio.rb
belongs_to :evaluation
Neuro.rb
belongs_to :evaluation
My evaluation controller is similar to this:
def create
@patient = Patient.find(params[:id])
@evaluator = Evaluator.find(session[:evaluator_id]) if session[:evaluator_id]
@evaluation = Evaliation.new(:patient_id => @patient.id, :evaluator_id => @evaluator.id)
@neuro = Neuro.new(:evaluation_id => @evaluation.id)
@cardio = Cardio.new(:evaluation_id => @evaluation.id)
if (@evaluation.save! && @neuro.save! && @cardio.save!)
redirect_to evaluation_path(@evaluation.id), :notice => "Evaluation created"
else
render ("new")
end
end
When the evaluation is created the cardio and neuro are created too, but with null evaluation_id.
I tried to move the @cardio = Cardio.new(:evaluation_id => @evaluation.id) inside the if but it didnt worked too.
A: @evaluation won't have an id set until you save it, so @evaluation.id will be nil when you are creating @neuro and @cardio. In other words:
@evaluation = ...
if (@evaluation.save!)
@neuro = Neuro.new(:evaluation_id => @evaluation.id)
@cardio = Cardio.new(:evaluation_id => @evaluation.id)
if (@neuro.save! && @cardio.save!)
redirect_to evaluation_path(@evaluation.id), :notice => "Evaluation created"
else
render ("new")
end
else
render ("new")
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: obtaining UINavigationController in an UIView a custom tab bar controller I am using applies the ViewController or UINavigationController like this: UIViewController* viewController = [data objectForKey:@"viewController"];
I dont knw exactly how it works but "viewController" comes out as a UINavigationController. Next, the custom tab bar controller class adds a tag like so, viewController.view.tag = THE_TAG;
Retrieving the controller is uses UIView* currentView = [self.window viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];
This part is where I get confused because now when I nslog this
"currentView" I get a UILayout etc... instead of my UINavigationController. I'm assuming it applied the tag to the UIView that contained the nav controller?
How do I reference the UINavigationController within this UIView?
A: In the above what is THE_TAG, and can you confirm that it is unique (i.e. not zero, and not matching something being used elsewhere by the same mechanism)?
I'd be pretty wary overusing tag since there is no easy way to gaurentee globally unique tags, and when using something like self.window viewWithTag you could see just about every view in the app being checked.
A: It seems like you have a view and a viewController confused. A UINavigationController is a subclass of UIViewController. It is not a subclass of UIView. UIViewControllers do have a property which is a UIView class. It is probably this property that you are accessing when you use viewWithTag: . So maybe, when you use that method, you are not accessing the UINavigationController but the UINavigationController's view property (which is actually something you should probably not be messing with.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Shell script help I need help with two scripts I'm trying to make as one. There are two different ways to detect if there are issues with a bad NFS mount. One is if there is an issue, doing a df will hang and the other is the df works but there is are other issues with the mount which a find (mount name) -type -d will catch.
I'm trying to combine the scripts to catch both issues to where it runs the find type -d and if there is an issue, return an error. If the second NFS issue occurs and the find hangs, kill the find command after 2 seconds; run the second part of the script and if the NFS issue is occurring, then return an error. If neither type of NFS issue is occurring then return an OK.
MOUNTS="egrep -v '(^#)' /etc/fstab | grep nfs | awk '{print $2}'"
MOUNT_EXCLUDE=()
if [[ -z "${NFSdir}" ]] ; then
echo "Please define a mount point to be checked"
exit 3
fi
if [[ ! -d "${NFSdir}" ]] ; then
echo "NFS CRITICAL: mount point ${NFSdir} status: stale"
exit 2
fi
cat > "/tmp/.nfs" << EOF
#!/bin/sh
cd \$1 || { exit 2; }
exit 0;
EOF
chmod +x /tmp/.nfs
for i in ${NFSdir}; do
CHECK="ps -ef | grep "/tmp/.nfs $i" | grep -v grep | wc -l"
if [ $CHECK -gt 0 ]; then
echo "NFS CRITICAL : Stale NFS mount point $i"
exit $STATE_CRITICAL;
else
echo "NFS OK : NFS mount point $i status: healthy"
exit $STATE_OK;
fi
done
A: The MOUNTS and MOUNT_EXCLUDE lines are immaterial to this script as shown.
You've not clearly identified where ${NFSdir} is being set.
The first part of the script assumes ${NFSdir} contains a single directory value; the second part (the loop) assumes it may contain several values. Maybe this doesn't matter since the loop unconditionally exits the script on the first iteration, but it isn't the clear, clean way to write it.
You create the script /tmp/.nfs but:
*
*You don't execute it.
*You don't delete it.
*You don't allow for multiple concurrent executions of this script by making a per-process file name (such as /tmp/.nfs.$$).
*It is not clear why you hide the script in the /tmp directory with the . prefix to the name. It probably isn't a good idea.
Use:
tmpcmd=${TMPDIR:-/tmp}/nfs.$$
trap "rm -f $tmpcmd; exit 1" 0 1 2 3 13 15
...rest of script - modified to use the generated script...
rm -f $tmpcmd
trap 0
This gives you the maximum chance of cleaning up the temporary script.
There is no df left in the script, whereas the question implies there should be one. You should also look into the timeout command (though commands hung because NFS is not responding are generally very difficult to kill).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ListBox Binding with Global Index My application has a couple of ObservableCollections, one which is nested within an element of the other. Each contain a number of fields e.g.
ObservableCollectionA (called Listings)
*
*Title
*Description
*Address
*Images As MediaItems
ObservableCollectionB (called MediaItems)
*
*ImageName
*Src
*DisplayTime
Currently I have been accessing ObservableCollections as follows:
Listings(0).MediaItems(0).ImageName
My application has the main Window display the items from Listings and a UserControl which contains a ListBox which displays the items from MediaItems.
Currently my Window is bound to Listings using code in the New method:
Dim AppLocal As Program = Application.CurrentItem
AppLocal.CurrentItem = 0
Me.DataContext = Listings.Item(AppLocal.CurrentItem)
For the Listings ObservableCollection, the UserControl has a XAML DataContext which references a local method which pulls the records from the nested MediaItems ObservableCollection.
<UserControl.DataContext>
<ObjectDataProvider ObjectType="{x:Type local:ThumbImageLoader}" MethodName="LoadImagesv2" IsAsynchronous="True" />
</UserControl.DataContext>
<Grid x:Name="ThumbListBoxGrid">
<ListBox x:Name="ThumbListBox" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" />
</Grid>
The method is here:
Public NotInheritable Class ThumbImageLoader
Public Shared Function LoadImagesv2() As List(Of MediaItems)
Dim AppLocal As Program = Application.Current
Dim ThumbImages As New List(Of MediaItems)
ThumbImages = Listings(AppLocal.CurrentItem).MediaItems
Return ThumbImages
End Function
End Class
Whilst developing the UI layout I have just been binding the first item (0 index). I now want to be able to set AppLocal.CurrentItem from anywhere in the application so the Window and the ListBox are updated.
Ideally I would like it so when the global property index changes, the UI is updated.
How do I do this?
Is there a better way to go about it?
Ben
A: Ok, I discovered the joy of CollectionView. Offered exactly what I was after and was excrutiatingly easy to implement. I was blown away at not only how easy it was to implement, but I managed to cut out more lines of code than I used to implement it.
I implemented a public CollectionViewSource
Public ListingDataView As CollectionViewSource
In my main Window, I implemeted it as follows:
<CollectionViewSource x:Key="ListingDataView" />
and bound my top-level Grid to it:
<Grid DataContext="{Binding Source={StaticResource ListingDataView}}">
In my Application Startup I set the CollectionView Source
AppLocal.ListingDataView = CType(Application.Current.MainWindow.Resources("ListingDataView"), CollectionViewSource)
AppLocal.ListingDataView.Source = Listings
The next part which impressed me the most was implementing it for my User Control. I remembered the UserControl is inheriting from the main window so it has access to the CollectionView already, so I ditched the separate Class and Method binding in favour for this:
<ListBox ItemsSource="{Binding Path=MediaItems}" VerticalAlignment="Top" IsSynchronizedWithCurrentItem="True" />
Now whene I want to set the Current List Index, I simply call this:
AppLocal.ListingDataView.View.MoveCurrentToPosition(AppLocal.CurrentProperty)
A few milliseconds later, the UI updates automatically.
Done!!
A: When you want multiple source data (like your observable collection properties and the index for the observable collection) to a single target you should use MultiBinding.
So in your case somethign like this should help...
<ListBox x:Name="ThumbListBox" IsSynchronizedWithCurrentItem="True" >
<ListBox.ItemsSource>
<MultiBinding Converter="{StaticResource CollectionAndIndexCollaborator}">
<Binding Path="Listings" />
<Binding Path="Application.CurrentItem.CurrentItem" />
</MultiBinding>
</ListBox.ItemsSource>
</ListBox>
provided that ....
*
*Your data context is some class that holds the Application object via a property of same name Application and the Listings collection via property of same name Listings.
*Your DataContext class and Application class must have INotifyPropertyChanged implemented. It should also raise notifications for Application and Setter of CurrentItem and CurrentItem.CurrentItem properties.
*CollectionAndIndexCollaborator.Convert() method returns the same indexed value as the final collection....
return ((ObservableCollection)values[0]).Item(int.Parse(values[1])) ;
where assuming MyListingType is the T of your Listings collection.
This way when anyone changes the global Application.CurrentItem.CurrentItem the multi binding above will get notified and will select the required Listings item.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implementing Observers and Subjects using IObserver/IObservable I want to create a class that can be used to represent a dynamically computed value, and another class that represents a value can be the source (subject) for these dynamically computed values. The goal is that when the subject changes, the computed value is updated automatically.
It seems to me that using IObservable/IObserver is the way to go. Unfortunately I can't use the Reactive Extensions library, so I am forced to implement the subject/observer pattern from scratch.
Enough blabla, here are my classes:
public class Notifier<T> : IObservable<T>
{
public Notifier();
public IDisposable Subscribe(IObserver<T> observer);
public void Subscribe(Action<T> action);
public void Notify(T subject);
public void EndTransmission();
}
public class Observer<T> : IObserver<T>, IDisposable
{
public Observer(Action<T> action);
public void Subscribe(Notifier<T> tracker);
public void Unsubscribe();
public void OnCompleted();
public void OnError(Exception error);
public void OnNext(T value);
public void Dispose();
}
public class ObservableValue<T> : Notifier<T>
{
public T Get();
public void Set(T x);
}
public class ComputedValue<T>
{
public T Get();
public void Set(T x);
}
My implementation is lifted mostly from: http://msdn.microsoft.com/en-us/library/dd990377.aspx.
So what would the "right" way to do this be? Note: I don't care about LINQ or multi-threading or even performance. I just want it to be simple and easy to understand.
A: If I were you I would try to implement your classes as closely as possible to the way Rx has been implemented.
One of the key underlying principles is the use of relatively few concrete classes that are combined using a large number of operations. So you should create a few basic building blocks and use composition to bring them all together.
There are two classes I would take an initial look at under Reflector.NET: AnonymousObservable<T> & AnonymousObserver<T>. In particular AnonymousObservable<T> is used through-out Rx as the basis for instantiating observables. In fact, if you look at the objects that derive from IObservable<T> there are a few specialized implementations, but only AnonymousObservable<T> is for general purpose use.
The static method Observable.Create<T>() is essentially a wrapper to AnonymousObservable<T>.
The other Rx class that is clearly a fit for your requirements is BehaviorSubject<T>. Subjects are both observables and observers and BehaviorSubject fits your situation because it remembers the last value that is received.
Given these basic classes then you almost have all of the bits you need to create your specific objects. Your objects shouldn't inherit from the above code, but instead use composition to bring together the behaviour that you need.
Now, I would suggest some changes to your class designs to make them more compatible with Rx and thus more composible and robust.
I would drop your Notifier<T> class in favour of using BehaviourSubject<T>.
I would drop your Observer<T> class in favour of using AnonymousObserver<T>.
Then I would modify ObservableValue<T> to look like this:
public class ObservableValue<T> : IObservable<T>, IDisposable
{
public ObservableValue(T initial) { ... }
public T Value { get; set; }
public IDisposable Subscribe(IObserver<T> observer);
public void Dispose();
}
The implementation of ObservableValue<T> would wrap BehaviourSubject<T> rather than inherit from it as exposing the IObserver<T> members would allow access to OnCompleted & OnError which wouldn't make too much sense since this class represents a value and not a computation. Subscriptions would use AnonymousObservable<T> and Dispose would clean up the wrapped BehaviourSubject<T>.
Then I would modify ComputedValue<T> to look like this:
public class ComputedValue<T> : IObservable<T>, IDisposable
{
public ComputedValue(IObservable<T> source) { ... }
public T Value { get; }
public IDisposable Subscribe(IObserver<T> observer);
public void Dispose();
}
The ComputedValue<T> class would wrap AnonymousObservable<T> for all subscribers and and use source to grab a local copy of the values for the Value property. The Dispose method would be used to unsubscribe from the source observable.
These last two classes are the only real specific implementation your design appears to need - and that's only because of the Value property.
Next you need a static ObservableValues class for your extension methods:
public static class ObservableValues
{
public static ObservableValue<T> Create<T>(T initial)
{ ... }
public static ComputedValue<V> Compute<T, U, V>(
this IObservable<T> left,
IObservable<U> right,
Func<T, U, V> computation)
{ ... }
}
The Compute method would use an AnonymousObservable<V> to perform the computation and produce an IObservable<V> to pass to the constructor of ComputedValue<V> that is returned by the method.
With all this in place you can now write this code:
var ov1 = ObservableValues.Create(1);
var ov2 = ObservableValues.Create(2);
var ov3 = ObservableValues.Create(3);
var cv1 = ov1.Compute(ov2, (x, y) => x + y);
var cv2 = ov3.Compute(cv1, (x, y) => x * y);
//cv2.Value == 9
ov1.Value = 2;
ov2.Value = 3;
ov3.Value = 4;
//cv2.Value == 20
Please let me know if this is helpful and/or if there is anything that I can elaborate on.
EDIT: Also need some disposables.
You'll also need to implement AnonymousDisposable & CompositeDisposable to manage your subscriptions particularly in the Compute extension method. Take a look at the Rx implementations using Reflector.NET or use my versions below.
public sealed class AnonymousDisposable : IDisposable
{
private readonly Action _action;
private int _disposed;
public AnonymousDisposable(Action action)
{
_action = action;
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
_action();
}
}
}
public sealed class CompositeDisposable : IEnumerable<IDisposable>, IDisposable
{
private readonly List<IDisposable> _disposables;
private bool _disposed;
public CompositeDisposable()
: this(new IDisposable[] { })
{ }
public CompositeDisposable(IEnumerable<IDisposable> disposables)
{
if (disposables == null) { throw new ArgumentNullException("disposables"); }
this._disposables = new List<IDisposable>(disposables);
}
public CompositeDisposable(params IDisposable[] disposables)
{
if (disposables == null) { throw new ArgumentNullException("disposables"); }
this._disposables = new List<IDisposable>(disposables);
}
public void Add(IDisposable disposable)
{
if (disposable == null) { throw new ArgumentNullException("disposable"); }
lock (_disposables)
{
if (_disposed)
{
disposable.Dispose();
}
else
{
_disposables.Add(disposable);
}
}
}
public IDisposable Add(Action action)
{
if (action == null) { throw new ArgumentNullException("action"); }
var disposable = new AnonymousDisposable(action);
this.Add(disposable);
return disposable;
}
public IDisposable Add<TDelegate>(Action<TDelegate> add, Action<TDelegate> remove, TDelegate handler)
{
if (add == null) { throw new ArgumentNullException("add"); }
if (remove == null) { throw new ArgumentNullException("remove"); }
if (handler == null) { throw new ArgumentNullException("handler"); }
add(handler);
return this.Add(() => remove(handler));
}
public void Clear()
{
lock (_disposables)
{
var disposables = _disposables.ToArray();
_disposables.Clear();
Array.ForEach(disposables, d => d.Dispose());
}
}
public void Dispose()
{
lock (_disposables)
{
if (!_disposed)
{
this.Clear();
}
_disposed = true;
}
}
public IEnumerator<IDisposable> GetEnumerator()
{
lock (_disposables)
{
return _disposables.ToArray().AsEnumerable().GetEnumerator();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public bool IsDisposed
{
get
{
return _disposed;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Adding an Item to QGraphicsItemGroup Makes It Invisible The code below
QGraphicsEllipseItem *ellipse = addEllipse(x, y, 6, 6, series_pen);
ellipse->translate(-ellipse->boundingRect().width() / 2,
-ellipse->boundingRect().height() / 2);
ellipse->setToolTip(label);
draws the QGraphicsEllipseItem on a QGraphicsScene. However, the following code doesn't:
QGraphicsEllipseItem *ellipse = addEllipse(x, y, 6, 6, series_pen);
ellipse->translate(-ellipse->boundingRect().width() / 2,
-ellipse->boundingRect().height() / 2);
ellipse->setToolTip(label);
QGraphicsItemGroup *g = new QGraphicsItemGroup;
g->addToGroup(ellipse);
What is wrong if I add a QGraphicsItem in QGraphicsItemGroup?
I'm using Qt Creator 2.2.1, Qt 4.7.4 (32 bit) on Windows 7.
A: QGraphicsItemGroup is also a QGraphicsItem, so you need to add it to the scene, for its children to be drawn too.
A: From the Qt manual page for QGraphicsItemGroup:
There are two ways to construct an item group. The easiest and most
common approach is to pass a list of items (e.g., all selected items)
to QGraphicsScene::createItemGroup(), which returns a new
QGraphicsItemGroup item. The other approach is to manually construct a
QGraphicsItemGroup item, add it to the scene calling
QGraphicsScene::addItem(), and then add items to the group manually,
one at a time by calling addToGroup().
Sounds like your code needs to call QGraphicsScene::addItem().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: flex2gateway problem I have a test server which has been working up until recently. Its running ColdFusion 8
But now when I browse from the server or externally
http://localhost/flex2gateway
I get the following error
500
No configured channel has an endpoint path '/flex2gateway/eurl.axd/f902379d5cc8514ba3feca5933aee37d'
javax.servlet.ServletException: No configured channel has an endpoint path '/flex2gateway/eurl.axd/f902379d5cc8514ba3feca5933aee37d'.
at coldfusion.filter.FlashRequestControlFilter.doFilter(FlashRequestControlFilter.java:87)
at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46)
at jrun.servlet.FilterChain.doFilter(FilterChain.java:94)
at jrun.servlet.FilterChain.service(FilterChain.java:101)
at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106)
at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42)
at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286)
at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543)
at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203)
at jrunx.scheduler.ThreadPool$DownstreamMetrics.invokeRunnable(ThreadPool.java:320)
at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428)
at jrunx.scheduler.ThreadPool$UpstreamMetrics.invokeRunnable(ThreadPool.java:266)
at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)
This may or may not relate to us having recently installed and modified some IIS settings.
Everything is working ok, except for the flex2gateway. IIS & CF all talk properly. I managed to get it to work by setting ASP.NET to 2.0 and creating an empty web.config file. Setting it to ASP.NET 4 however still has the same issue, must be missing a configuration somewhere.
A: I discovered that the web.config files that .NET 2.0 were pointing to in the IIS configuration were missing.
Adding empty web.config files fixed this problem.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
</system.web>
</configuration>
A: If you recently installed IIS; are you sure that IIS and CF8 are set up to "Talk" to each other? There is a tool that comes with CF called the Web Server Configuration tool. You can use it to tell your IIS Instance to send CF related requests to your instance of CF8. If you are using CF Standard you can only have one instance of CF8.
Since your URL specifies 127.0.0.1 you may also have issues with virtual hosts. Do you have multiple instances of IIS? If so, how does IIS know which one to send 127.0.0.1 to?
A: Did you check your crossdomain.xml?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add regression line equation and R^2 on graph I wonder how to add regression line equation and R^2 on the ggplot. My code is:
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point()
p
Any help will be highly appreciated.
A: I've modified Ramnath's post to a) make more generic so it accepts a linear model as a parameter rather than the data frame and b) displays negatives more appropriately.
lm_eqn = function(m) {
l <- list(a = format(coef(m)[1], digits = 2),
b = format(abs(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3));
if (coef(m)[2] >= 0) {
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
} else {
eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
}
as.character(as.expression(eq));
}
Usage would change to:
p1 = p + geom_text(aes(x = 25, y = 300, label = lm_eqn(lm(y ~ x, df))), parse = TRUE)
A: Another option would be to create a custom function generating the equation using dplyr and broom libraries:
get_formula <- function(model) {
broom::tidy(model)[, 1:2] %>%
mutate(sign = ifelse(sign(estimate) == 1, ' + ', ' - ')) %>% #coeff signs
mutate_if(is.numeric, ~ abs(round(., 2))) %>% #for improving formatting
mutate(a = ifelse(term == '(Intercept)', paste0('y ~ ', estimate), paste0(sign, estimate, ' * ', term))) %>%
summarise(formula = paste(a, collapse = '')) %>%
as.character
}
lm(y ~ x, data = df) -> model
get_formula(model)
#"y ~ 6.22 + 3.16 * x"
scales::percent(summary(model)$r.squared, accuracy = 0.01) -> r_squared
Now we need to add the text to the plot:
p +
geom_text(x = 20, y = 300,
label = get_formula(model),
color = 'red') +
geom_text(x = 20, y = 285,
label = r_squared,
color = 'blue')
A: Inspired by the equation style provided in this answer, a more generic approach (more than one predictor + latex output as option) can be:
print_equation= function(model, latex= FALSE, ...){
dots <- list(...)
cc= model$coefficients
var_sign= as.character(sign(cc[-1]))%>%gsub("1","",.)%>%gsub("-"," - ",.)
var_sign[var_sign==""]= ' + '
f_args_abs= f_args= dots
f_args$x= cc
f_args_abs$x= abs(cc)
cc_= do.call(format, args= f_args)
cc_abs= do.call(format, args= f_args_abs)
pred_vars=
cc_abs%>%
paste(., x_vars, sep= star)%>%
paste(var_sign,.)%>%paste(., collapse= "")
if(latex){
star= " \\cdot "
y_var= strsplit(as.character(model$call$formula), "~")[[2]]%>%
paste0("\\hat{",.,"_{i}}")
x_vars= names(cc_)[-1]%>%paste0(.,"_{i}")
}else{
star= " * "
y_var= strsplit(as.character(model$call$formula), "~")[[2]]
x_vars= names(cc_)[-1]
}
equ= paste(y_var,"=",cc_[1],pred_vars)
if(latex){
equ= paste0(equ," + \\hat{\\varepsilon_{i}} \\quad where \\quad \\varepsilon \\sim \\mathcal{N}(0,",
summary(MetamodelKdifEryth)$sigma,")")%>%paste0("$",.,"$")
}
cat(equ)
}
The model argument expects an lm object, the latex argument is a boolean to ask for a simple character or a latex-formated equation, and the ... argument pass its values to the format function.
I also added an option to output it as latex so you can use this function in a rmarkdown like this:
```{r echo=FALSE, results='asis'}
print_equation(model = lm_mod, latex = TRUE)
```
Now using it:
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$z <- 8 + 3 * df$x + rnorm(100, sd = 40)
lm_mod= lm(y~x+z, data = df)
print_equation(model = lm_mod, latex = FALSE)
This code yields:
y = 11.3382963933174 + 2.5893419 * x + 0.1002227 * z
And if we ask for a latex equation, rounding the parameters to 3 digits:
print_equation(model = lm_mod, latex = TRUE, digits= 3)
This yields:
A: Here is one solution
# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups
A: Here's the most simplest code for everyone
Note: Showing Pearson's Rho and not R^2.
library(ggplot2)
library(ggpubr)
df <- data.frame(x = c(1:100)
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point()+
stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown
p
A: Statistic stat_poly_eq() in my package ggpmisc makes it possible add text labels based on a linear model fit.
This answer has been updated for 'ggpmisc' (>= 0.4.0) and 'ggplot2' (>= 3.3.0) on 2022-06-02.
In the examples I use stat_poly_line() instead of stat_smooth() as it has the same defaults as stat_poly_eq() for method and formula. I have omitted in all code examples the additional arguments to stat_poly_line() as they are irrelevant to the question of adding labels.
library(ggplot2)
library(ggpmisc)
#> Loading required package: ggpp
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
# artificial data
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$yy <- 2 + 3 * df$x + 0.1 * df$x^2 + rnorm(100, sd = 40)
# using default formula, label and methods
ggplot(data = df, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq() +
geom_point()
# assembling a single label with equation and R2
ggplot(data = df, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label), sep = "*\", \"*"))) +
geom_point()
# adding separate labels with equation and R2
ggplot(data = df, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq(aes(label = after_stat(eq.label))) +
stat_poly_eq(label.y = 0.9) +
geom_point()
# regression through the origin
ggplot(data = df, aes(x = x, y = y)) +
stat_poly_line(formula = y ~ x + 0) +
stat_poly_eq(formula = y ~ x + 0, aes(label = after_stat(eq.label))) +
geom_point()
# fitting a polynomial
ggplot(data = df, aes(x = x, y = yy)) +
stat_poly_line(formula = y ~ poly(x, 2, raw = TRUE)) +
stat_poly_eq(formula = y ~ poly(x, 2, raw = TRUE),
aes(label = after_stat(eq.label))) +
geom_point()
# adding a hat as asked by @MYaseen208 and @elarry
ggplot(data = df, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq(eq.with.lhs = "italic(hat(y))~`=`~",
aes(label = paste(after_stat(eq.label),
after_stat(rr.label), sep = "*\", \"*"))) +
geom_point()
# variable substitution as asked by @shabbychef
# same labels in equation and axes
ggplot(data = df, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq(eq.with.lhs = "italic(h)~`=`~",
eq.x.rhs = "~italic(z)",
aes(label = after_stat(eq.label))) +
labs(x = expression(italic(z)), y = expression(italic(h))) +
geom_point()
# grouping as asked by @helen.h
dfg <- data.frame(x = c(1:100))
dfg$y <- 20 * c(0, 1) + 3 * df$x + rnorm(100, sd = 40)
dfg$group <- factor(rep(c("A", "B"), 50))
ggplot(data = dfg, aes(x = x, y = y, colour = group)) +
stat_poly_line() +
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label), sep = "*\", \"*"))) +
geom_point()
ggplot(data = dfg, aes(x = x, y = y, linetype = group, grp.label = group)) +
stat_poly_line() +
stat_poly_eq(aes(label = paste(after_stat(grp.label), "*\": \"*",
after_stat(eq.label), "*\", \"*",
after_stat(rr.label), sep = ""))) +
geom_point()
# a single fit with grouped data as asked by @Herman
ggplot(data = dfg, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label), sep = "*\", \"*"))) +
geom_point(aes(colour = group))
# facets
ggplot(data = dfg, aes(x = x, y = y)) +
stat_poly_line() +
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label), sep = "*\", \"*"))) +
geom_point() +
facet_wrap(~group)
Created on 2022-06-02 by the reprex package (v2.0.1)
A: Using ggpubr:
library(ggpubr)
# reproducible data
set.seed(1)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
# By default showing Pearson R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300) +
stat_regline_equation(label.y = 280)
# Use R2 instead of R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300,
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"))) +
stat_regline_equation(label.y = 280)
## compare R2 with accepted answer
# m <- lm(y ~ x, df)
# round(summary(m)$r.squared, 2)
# [1] 0.85
A: Similar to @zx8754 and @kdauria answers except using ggplot2 and ggpubr. I prefer using ggpubr because it does not require custom functions such as the top answer to this question.
library(ggplot2)
library(ggpubr)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
ggplot(data = df, aes(x = x, y = y)) +
stat_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point() +
stat_cor(aes(label = paste(..rr.label..)), # adds R^2 value
r.accuracy = 0.01,
label.x = 0, label.y = 375, size = 4) +
stat_regline_equation(aes(label = ..eq.label..), # adds equation to linear regression
label.x = 0, label.y = 400, size = 4)
Could also add p-value to the figure above
ggplot(data = df, aes(x = x, y = y)) +
stat_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point() +
stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")), # adds R^2 and p-value
r.accuracy = 0.01,
p.accuracy = 0.001,
label.x = 0, label.y = 375, size = 4) +
stat_regline_equation(aes(label = ..eq.label..), # adds equation to linear regression
label.x = 0, label.y = 400, size = 4)
Also works well with facet_wrap() when you have multiple groups
df$group <- rep(1:2,50)
ggplot(data = df, aes(x = x, y = y)) +
stat_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point() +
stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")),
r.accuracy = 0.01,
p.accuracy = 0.001,
label.x = 0, label.y = 375, size = 4) +
stat_regline_equation(aes(label = ..eq.label..),
label.x = 0, label.y = 400, size = 4) +
theme_bw() +
facet_wrap(~group)
A: really love @Ramnath solution. To allow use to customize the regression formula (instead of fixed as y and x as literal variable names), and added the p-value into the printout as well (as @Jerry T commented), here is the mod:
lm_eqn <- function(df, y, x){
formula = as.formula(sprintf('%s ~ %s', y, x))
m <- lm(formula, data=df);
# formating the values into a summary string to print out
# ~ give some space, but equal size and comma need to be quoted
eq <- substitute(italic(target) == a + b %.% italic(input)*","~~italic(r)^2~"="~r2*","~~p~"="~italic(pvalue),
list(target = y,
input = x,
a = format(as.vector(coef(m)[1]), digits = 2),
b = format(as.vector(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3),
# getting the pvalue is painful
pvalue = format(summary(m)$coefficients[2,'Pr(>|t|)'], digits=1)
)
)
as.character(as.expression(eq));
}
geom_point() +
ggrepel::geom_text_repel(label=rownames(mtcars)) +
geom_text(x=3,y=300,label=lm_eqn(mtcars, 'hp','wt'),color='red',parse=T) +
geom_smooth(method='lm')
Unfortunately, this doesn't work with facet_wrap or facet_grid.
A: I changed a few lines of the source of stat_smooth and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!
library(devtools)
source_gist("524eade46135f6348140")
df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
df$class = rep(1:2,50)
ggplot(data = df, aes(x = x, y = y, label=y)) +
stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
geom_smooth(method="lm",se=FALSE) +
geom_point() + facet_wrap(~class)
I used the code in @Ramnath's answer to format the equation. The stat_smooth_func function isn't very robust, but it shouldn't be hard to play around with it.
https://gist.github.com/kdauria/524eade46135f6348140. Try updating ggplot2 if you get an error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "305"
}
|
Q: Automatically take a Picture I have tried to take a picture and save it to the photo library automatically with UIImagePicker and AVFoundation, but I couldn't make it work.
I would like to take the photo when the view appears, not showing the camera view to the user, and then use it as a simple image in the app.
Thanks
A: Apple actually has an entire guide devoted to this sort of thing, "Camera Programming Topics for iOS," with a subsection "Taking Pictures and Movies." There's even a sample project, "Photo Picker." Here's an excerpt, the action method for your take-a-picture button:
- (IBAction)cameraAction:(id)sender {
[self showImagePicker:UIImagePickerControllerSourceTypeCamera];
}
Note: It won't work unless [UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera] returns YES, indicating that the device has a camera.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Boost spirit grammar based string splitting I am using Boost 1.44, The Spirit parser works well for numeric parsing but really is tricky for string parsing. I am trying to parse a string to be split using multiple delimiters: ',' ,';' or ' '. It works well for numbers when I do this (where vect = vector < double >):
qi::parse(first,last,double_ >> *(',' >> double_ | ' ' >> double_ | ';' >> double_),
vect,space);
However when I modify the grammer for strings using vect = vector< string >,
+char_ >> *(',' >> +char_ | ' ' >> +char_ | ';' >> +char_)
I get the following error:
/usr/include/boost/spirit/home/qi/detail/assign_to.hpp:109:13: error: invalid conversion from ‘char’ to ‘const char*’/usr/include/boost/spirit/home/qi/detail/assign_to.hpp:109:13: error: initializing argument 1 of ‘std::basic_string<_CharT, _Traits,_Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’
I narrowed down the error to being the first +char_ in the grammar syntax which is being taken as a series of chars rather than a string. Is there any way to fix this issue?
Thanks
A: String handling (the way you do it) got a lot easier with more recent versions of Spirit. I'd suggest to use Spirit from Boost V1.47, which got a major rewrite of the attribute handling code.
But even if it compiled the way you want, it wouldn't parse the way you expect. Spirit is inherently greedy, that means that +char_ will consume whatever is left in your input unconditionally. It seems to be better to have
+~char_(", ;") % char_(", ;")
i.e. one or more (+) characters which are not (~) in the set ", ;" interpersed with exactly one of those characters. The list parser (%) exposes a vector<A>, where A is the attribute of the left hand expression, a vector<string> in the case above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: ActiveAdmin, Formtastic, and Paperclip: Not Rendering File Dialog I'm implementing a generic media gallery using Ruby on Rails. I've chosen ActiveAdmin to handle the administration portion of my task and it's worked well so far, except for one thing: It's not displaying the "Choose file" dialog as intended.
This is a form for my "Media" section of ActiveAdmin. I have a model called "Medium" with the following fields (in addition to id and timestamp:
*
*asset_file_name
*asset_file_size
*asset_content_type
*asset_updated_at
My Medium model looks like this:
class Medium < ActiveRecord::Base
has_and_belongs_to_many :galleries
has_and_belongs_to_many :entities
has_attached_file :asset, :styles => { :medium => "300x300>", :thumb => "100x100>" }
attr_accessible :asset
end
And I'm adding it to the ActiveAdmin form like this:
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :asset, :as => :file
f.buttons
end
Here's a screencap of my ActiveAdmin page:
I see nothing wrong with how I'm implementing this. I've read that Formtastic has historically had issues with paperclip and I'm not averse to switching to attachment_fu or any other suitable solutions.
I should also note: I know that I can add in a custom partial. It's not my ideal solution, as I'd like to keep everything in the Formtastic DSL.
Thanks!
A: Or you can do:
form :html => {:multipart => true} do |f|
which is easier to remember, imho.
A: Formtastic requires that you wrap all calls to #input in a call to #inputs. It's definitely something that I would like to see fixed in Active Admin.
It should work if you wrap your input in a call to inputs:
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs do
f.input :asset, :as => :file
end
f.buttons
end
Let me know if this works for you.
A: the latest active admin handle it automatic
A: I use carrier wave with active admin and works as above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unexpected behavior for python set.__contains__ Borrowing the documentation from the __contains__ documentation
print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
This seems to work fine for primitive objects such as int, basestring, etc. But for user-defined objects that define the __ne__ and __eq__ methods, I get unexpected behavior. Here is a sample code:
class CA(object):
def __init__(self,name):
self.name = name
def __eq__(self,other):
if self.name == other.name:
return True
return False
def __ne__(self,other):
return not self.__eq__(other)
obj1 = CA('hello')
obj2 = CA('hello')
theList = [obj1,]
theSet = set(theList)
# Test 1: list
print (obj2 in theList) # return True
# Test 2: set weird
print (obj2 in theSet) # return False unexpected
# Test 3: iterating over the set
found = False
for x in theSet:
if x == obj2:
found = True
print found # return True
# Test 4: Typcasting the set to a list
print (obj2 in list(theSet)) # return True
So is this a bug or a feature?
A: For sets and dicts, you need to define __hash__. Any two objects that are equal should hash the same in order to get consistent / expected behavior in sets and dicts.
I would reccomend using a _key method, and then just referencing that anywhere you need the part of the item to compare, just as you call __eq__ from __ne__ instead of reimplementing it:
class CA(object):
def __init__(self,name):
self.name = name
def _key(self):
return type(self), self.name
def __hash__(self):
return hash(self._key())
def __eq__(self,other):
if self._key() == other._key():
return True
return False
def __ne__(self,other):
return not self.__eq__(other)
A: This is because CA doesn't implement __hash__
A sensible implementation would be:
def __hash__(self):
return hash(self.name)
A: A set hashes it's elements to allow a fast lookup. You have to overwrite the __hash__ method so that a element can be found:
class CA(object):
def __hash__(self):
return hash(self.name)
Lists don't use hashing, but compare each element like your for loop does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: C++ environment with intellisense
*
*does any one know of a good development environment for C++
that as working intellisense? VS seems not to have that ability on a very good scale
Plus I couldn't figure out how to enable intellisense in Visual Studios 2010.
*
*How to enable intellisense in Visual Studios 2010?
A: Visual Studio has excellent support for intellisense and it is enabled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Power Mock - Assertion error when mocking final class I was trying to mock certain scenarios using Power Mock.
I am getting assertion error on below test method - returnSevenTest().
Class to be Tested
package tutorial.one;
public class TutorialOne {
//fields
private int number;
private String name;
private final DependentFinalClass finalObj;
public TutorialOne (DependentFinalClass dep) {
this.finalObj= dep ;
}
public TutorialOne(int number, String name) {
super();
this.number = number;
this.name = name;
finalObj = new DependentFinalClass();
}
public static int returnTwo()
{
return 2;
}
public int returnThree()
{
return (returnTwo()+1);
}
public final int returnFour()
{
return (returnThree()+1);
}
private final int returnFive(int addOne)
{
return (returnFour()+addOne);
}
public int returnSix(int addOne)
{
return (returnFive(1)+addOne);
}
public int returnSeven()
{
final int addValue= finalObj.callMeToAddOne(true);
return (returnSix(1)+ addValue);
}
}
Final Class
package tutorial.one;
public final class DependentFinalClass {
final int callMeToAddOne(Boolean need)
{
if(need.equals(true))
return 1;
else
return 1;
}
}
Test performing Class using Power Mock+ Easy Mock
package tutorial.one;
import stmts ....
@RunWith(PowerMockRunner.class)
//We prepare the IdGenerator for test because the static method is normally not
//mockable
@PrepareForTest({TutorialOne.class, DependentFinalClass.class}) public class TutorialOneTests {
@Test
public void returnSevenTest() throws Exception
{
int expected=7;
TutorialOne privateTest =createPartialMock(TutorialOne.class,"returnFive" );
DependentFinalClass finalDependentTest = createPartialMock(DependentFinalClass.class,"callMeToAddOne" );
expect(finalDependentTest.callMeToAddOne(true)).andReturn(1);
expectNew(TutorialOne.class, finalDependentTest).andReturn(privateTest);
expectPrivate(privateTest, "returnFive", 1).andReturn(5);
replayAll(TutorialOne.class,finalDependentTest,privateTest);
int actual = privateTest.returnSeven();
verifyAll();
assertEquals("Expected and actual did not match", expected, actual);
resetAll();
}
}
Error Recieved:
java.lang.AssertionError:
Expectation failure on verify:
tutorial.one.TutorialOne(tutorial.one.DependentFinalClass$$EnhancerByCGLIB$$fa2e41a0@5a9de6): expected: 1, actual: 0
at org.powermock.api.easymock.internal.invocationcontrol.NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(NewInvocationControlAssertionError.java:20)
at org.powermock.api.easymock.PowerMock.verifyClass(PowerMock.java:2279)
at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1646)
at org.powermock.api.easymock.PowerMock.verifyAll(PowerMock.java:1586)
at tutorial.one.TutorialOneTests.returnSevenTest(TutorialOneTests.java:174)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
Any help is well appreciated!! Thanks
A: I think the problem is that you've declared expectation :
expectNew(TutorialOne.class, finalDependentTest).andReturn(privateTest);
but in your method call it's not called , try to add anyTimes() after return :
expectNew(TutorialOne.class, finalDependentTest).andReturn(privateTest).anyTimes();
or remove this expectation because you don't use constructor in testing you just use partial mocked instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set the the timeout for an asychronous Connection with a TcpClient? I've been looking at numerous examples such as this, this, and this but none of them seem to work. I'm not sure what's wrong but for each example I've tried the wait is just ignored and I just get the standard unhandled socket exception in approximately 1 second, regardless of the specified wait time. No connection could be made because the target machine actively refused it.
Here's an excerpt to help understanding:
public void Connect(string host, int port)
{
tcpClient.BeginConnect(host, port, OnConnect, null);
}
private void OnConnect(IAsyncResult async)
{
tcpClient.EndConnect(async);
}
Been trying a bunch of different examples but for all of them my client application either just failsfast after a second or throws a socket exception. Would a try-catch be a better solution here and just avoid using WaitHandles?
A: the error
No connection could be made because the target machine actively
refused it.
usually means that there is nothing running on that port on the remote machine, or there is a firewall somewhere blocking the request.
there is a
tcpClient.SendTimeout
and tcpClient.ReceiveTimeout to answer your specific question, but it probably isn't your issue here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php checking if form was submitting with null field As the title says, I'm trying to figure out how to check if there were any null entries in a form after the submit button has been clicked.
if(isset($_POST['submit']) && ($selected == ''|| $text == '' || $email == ''))
{
// *do things*
}
else{
//*more things*
}
is this incorrect?
A: You would reference them in the same way that you handled the submit button.
That is: $_POST['input_name']
From there check it using the appropriate function: isset(), empty(), is_null() (although form variables rarely come across as null)
I'd also encourage you to read up on PHP external variables.
A: What you could do is to loop over the $_POST variables. Exclude those in which you're not interested in, and make something like:
$allIsOk = true;
foreach ($_POST as $index => $value) {
if (strlen($value)<1) {
$allIsOk = false;
}
}
...and then you make your choice on $allIsOk.
This approach is for two reasons:
*
*With suggestion above, you need to combine checks, since empty()
will return true for 0 or even "0" and might cause headbanging
problems.
*With this approach you can add parameters, without
making a huge if statement
Of course, this is just the idea. It's always wise to check documentation. Also, you could substitute the foreach cycle with an array_walk invocation to make things fancier (esp. from PHP 5.3 onwards). ;-)
Good luck!
PS Also, to find out whether your script has been invoked by a POST action, instead of taking into account the submit element, I suggest you to use the $_SERVER global. http://php.net/manual/en/reserved.variables.server.php Just check for the 'REQUEST_METHOD' parameter.
So, you might have:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
// It's ok for these to be null - or empty
$exclude = array('submit', 'other_param');
$allIsOk = true;
foreach ($_POST as $index => $value) {
if (!in_array($index, $exclude) && strlen($value)<1) {
$allIsOk = false;
}
}
}
if ($allIsOk) {
// Do Something
} else {
// Do Something Else
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7549719",
"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.