text stringlengths 8 267k | meta dict |
|---|---|
Q: Pass an optional boolean variable Sometimes we want an optional parameter
function doSomething(foo:Integer; bar:TObject=nil)
begin
if bar <> nil then // do something optional with bar
....
end
How do I do the equivalent with a boolean, that allows me to differentiate between the two boolean values and "no value"?
function doSomething(foo:Integer; bar:Boolean=nil) // Won't compile
begin
if bar <> nil then // do something optional with bar
end
Obviously this won't compile as a Boolean cannot be nil.
Basically, I want a parameter with three possible states; true, false or "unspecified".
A: Values of the Boolean type can only be True or False. You can define your own type that has three states: True, False, and Unspecified:
type ThreeStateBoolean = (True, False, Unspecified);
Or, you can pass a pointer to a Boolean:
type PBoolean = ^Boolean;
function doSomething(bar: PBoolean = nil)
begin
if bar <> nil then
// do something with bar^
end
Passing a pointer to a Boolean might be awkward depending on how you're calling it.
A: Another option (if you have a relatively modern version to Delphi) is to implement this as a record, with implicit conversion to and from boolean values. With operator overloading, you can also enable 3-state logic.
This is overkill if all you require is occasional use, but if you do need a three-state logic system it works very nicely, particularly as you can assign boolean values to it.
Be careful with assignments from 3-state to 2-state thought. The example below assigns False to a Boolean <- 'Troolean' assignation where the troolean is TNil, as per an unassigned boolean in Delphi, but there are obvious complications.
Please note that this is not a complete or efficient implementation by any means, it's just a demo to indictate what is possible. Incidentally, there is a good CodeRage vidoe by Jeroen Pluimers on nullable types. This question provides a link.
unit UnitTroolean;
interface
type
TTroolean = record
private type
TThreeState = (TTrue = 1, TFalse = 0, TNil = -1);
var
fThreeState: TThreeState;
public
function AsString: string;
class operator Implicit(Value: boolean): TTroolean;
class operator Implicit(Value: TTroolean): boolean;
class operator Implicit(Value: TThreeState): TTroolean;
class operator Implicit(Value: TTroolean): TThreeState;
class operator LogicalAnd(Left, Right: TTroolean): TTroolean;
class operator LogicalOr(Left, Right: TTroolean): TTroolean;
class operator LogicalNot(Value: TTroolean): TTroolean;
end;
implementation
{ TRoolean }
class operator TTroolean.Implicit(Value: boolean): TTroolean;
begin
if Value then
result.fThreeState := TTrue
else
result.fThreeState := TFalse;
end;
class operator TTroolean.Implicit(Value: TTroolean): boolean;
begin
if not(Value.fThreeState = TNil) then
result := (Value.fThreeState = TTrue)
else
result := false;
end;
class operator TTroolean.Implicit(Value: TThreeState): TTroolean;
begin
result.fThreeState := Value;
end;
class operator TTroolean.Implicit(Value: TTroolean): TThreeState;
begin
result := Value.fThreeState;
end;
class operator TTroolean.LogicalAnd(Left, Right: TTroolean): TTroolean;
begin
if (Left.fThreeState = TNil) or (Right.fThreeState = TNil) then
result.fThreeState := TNil
else if ((Left.fThreeState = TTrue) and (Right.fThreeState = TTrue)) then
result.fThreeState := TTrue
else
result.fThreeState := TFalse;
end;
class operator TTroolean.LogicalNot(Value: TTroolean): TTroolean;
begin
begin
case value.fThreeState of
TNil: result.fThreeState:= TNil;
TTrue: result.fThreeState:= TFalse;
TFalse: result.fThreeState:= TTrue
end;
end;
end;
class operator TTroolean.LogicalOr(Left, Right: TTroolean): TTroolean;
begin
if (Left.fThreeState = TNil) or (Right.fThreeState = TNil) then
result.fThreeState := TNil
else if ((Left.fThreeState = TTrue) or (Right.fThreeState = TTrue)) then
result.fThreeState := TTrue
else
result.fThreeState := TFalse;
end;
function TTroolean.AsString: string;
begin
case ord(fThreeState) of
1:
result := 'TTrue';
0:
result := 'TFalse';
-1:
result := 'TNil';
end;
end;
end.
And an example of use
program ThreeStateLogicTest;
{$APPTYPE CONSOLE}
uses
SysUtils,
UnitTroolean in 'UnitTroolean.pas';
var
ABoolean: boolean;
ATroolean, Anothertroolean, AThirdTroolean: TTroolean;
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write(#10#13);
ATroolean := TFalse;
ABoolean := true;
ATroolean := ABoolean;
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write('Troolean:', ATroolean.AsString, #10#13);
write('Troolean as Boolean:', BoolToStr(ATroolean, true), #10#13);
write(#10#13);
ATroolean := TTrue;
ABoolean := false;
ATroolean := ABoolean;
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write('Troolean:', ATroolean.AsString, #10#13);
write('Troolean as Boolean:', BoolToStr(ATroolean, true), #10#13);
write(#10#13);
ABoolean := false;
ATroolean := TTrue;
ABoolean := ATroolean;
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write('Troolean:', ATroolean.AsString, #10#13);
write('Troolean as Boolean:', BoolToStr(ATroolean, true), #10#13);
write(#10#13);
ABoolean := true;
ATroolean := TFalse;
ABoolean := ATroolean;
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write('Troolean:', ATroolean.AsString, #10#13);
write('Troolean as Boolean:', BoolToStr(ATroolean, true), #10#13);
write(#10#13);
ABoolean := false;
ATroolean := Tnil;
ABoolean := ATroolean;
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write('Troolean:', ATroolean.AsString, #10#13);
write('Troolean as Boolean:', BoolToStr(ATroolean, true), #10#13);
write(#10#13);
ABoolean := true;
ATroolean := Tnil;
ABoolean := ATroolean;
write('Boolean:', BoolToStr(ABoolean, true), #10#13);
write('Troolean:', ATroolean.AsString, #10#13);
write('Troolean as Boolean:', BoolToStr(ATroolean, true), #10#13);
write(#10#13);
ATroolean := TTrue;
Anothertroolean := false;
AThirdTroolean := ATroolean and Anothertroolean;
write('And:', AThirdTroolean.AsString, #10#13);
AThirdTroolean := ATroolean or Anothertroolean;
write('Or:', AThirdTroolean.AsString, #10#13);
ATroolean := TNil;
Anothertroolean:= not ATroolean;
write('Not TNil:', Anothertroolean.AsString, #10#13);
ATroolean := TTrue;
Anothertroolean:= not ATroolean;
write('Not Ttrue:', Anothertroolean.AsString, #10#13);
ATroolean := Tfalse;
Anothertroolean:= not ATroolean;
write('Not Tfalse:', Anothertroolean.AsString, #10#13);
readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
A: You can do this other way, using overloading:
function doSomething(foo:Integer): Boolean; overload;
begin
// do something without bar
end;
function doSomething(foo:Integer; bar:Boolean): Boolean; overload
begin
// do something optional with bar
end;
Then you can use it as doSomething(1) , as well as doSomething(1, true)
Using your example, it will be equivalent to:
function doSomething(foo:Integer; bar:Boolean=nil): Boolean; // Won't compile
begin
if bar <> nil then
// do something optional with bar
else
// do something without bar
end;
A: Or... you could use an Integer and cast it to a Boolean as necessary. Use 0 for false, 1 for true, and -1 for "nil". Anyway you slice it, you can't use a Boolean variable to do what you want, you will need another type or a manipulation of parameters as lynxnake suggested.
EDIT: A variation on this, which is very inefficient, would be to use a Variant. With a variant you can pass in Null values (similar to nil in some ways but still a value) as well as Unassigned (also similar to nil, but representing "no value").
A: The cleanest way is to use enumeration (a.k.a. enumerated type).
This is already shown in the Greg Hewgill's answer — but incorrectly, you shouldn't use predefined false and true as enumeration identifiers¹. And within the HMcG's answer — but within the wrapper type (more complex example). I suggest writing something like: type TTrilean = (triFalse, triTrue, triNull);.
Alternatively, you can use existing TCheckBoxState type from StdCtrls module, if you don't mind bringing VCL modules into your project.
Additionally you can write wrapper functions per the Serhii Kheilyk's answer:
procedure DoSomething(Foo: Integer; Bar: TTrilean); overload;
begin
… //main code
end;
procedure DoSomething(Foo: Integer; Bar: Boolean); overload;
const
Trileans: array[Boolean] of TTrilean = (triFalse, triTrue);
begin
DoSomething(Foo, Trileans[Bar]);
end;
procedure DoSomething(Foo: Integer); overload;
begin
DoSomething(Foo, triNull);
end;
You can even make the first one private and the last two public, if you wish.
Notes:
1. I think (not sure), formally you can write type TMyType = (False, True, Unspecified);, as False and True aren't reserved words. But this will break your access to original False and True of type Boolean (you'll need to refer them as System.False and System.True after that). And that is not third-party-compiler-compatible (e.g. FPC won't allow that).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: how to insert word by word in database I'm having problems inserting data into a database after a tokenization process. I want to insert one by one word into database. I am using tokenization process to split the sentences. Below is my coding for tokenization process and inserting data:
//tokenization process
String speech = Report_tf.getText();
System.out.println(speech);
StringTokenizer st = new StringTokenizer(speech);
while (st.hasMoreTokens())
System.out.println(st.nextToken());
//insert in database
String token = st.nextToken(speech);
statement.executeUpdate("INSERT INTO laporan (text_laporan) VALUES ('"+ token +"')");
}
A: You are missing an opening brace on your while loop. That could be the problem. I'd be surprised if this even compiles.
A: Start with something like this:
String speech = Report_tf.getText();
String [] tokens = speech.split("\\s");
for (int x=0; x < tokens.length; x++) {
System.out.println(tokens[x]);
statement.executeUpdate("INSERT INTO laporan (text_laporan) VALUES ('"+ tokens[x] +"')");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: calculate button pressed - retrieve rates from database I need to link to the database (finance rates) when someone enters a number in the text box and clicks calculate that it will pull the rates from the database and display the calculation below in a 'form message'. What should I put in the homecontroller/index to link the code to the database?
Index.aspx:
<td>You wish to convert:
<input type="text" name="amount" size="30" onblur="test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="submitter" value="calculate" />
<tr><td colspan="2">That will produce:<%=ViewData["formmessage"] %></td></tr>
Home Controller:
public ActionResult Index()
{
financeInit();
if (Request.Params["submitter"] == "calculate")
calculatepressed();
return View();
public void calculatepressed()
{
.............
}
A: I would wrap your fields in a form like this:
<form action="Home" method="get">
<div>
You wish to convert:
<input type="text" name="amount" size="30" id="userValue" onblur=""test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="userSubmit" />
<br />
That will produce:<%=ViewData["formmessage"] %>
</div>
</form>
Then have your controller something like this:
public ActionResult Index()
{
int value;
if (int.TryParse(Request.Params["amount"], out value))
{
ViewData["formmessage"] = calculatepressed(value);
}
return View();
}
private string calculatepressed(int value)
{
// Do your magic here and return the value you calculate
return value.ToString();
}
If this ever expands from a simple page you might want to consider changing the form action to a post and having two different methods handling the initial view of the home page and the a view for the results of the calculation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set multiple items on LISTBOX MVVM LIGHT I'm using MVVM Light on an SL4 app. I would like to set the selected items on a listbox after it is databound.
I have no problem when there is one item to set, but I do not know how do do this when I have to set multiple items in the list.
A: Bind the IsSelected property of the ItemContainerStyle to a bool property on the view models that are bound to ItemsSource.
You can then just set that property to true or false to select or deselect the item in the listbox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't get getChildCategories to work when looping through parents Trying to print out a two tier navigation menu of my categories. For each parent category I would like to print out a list of it's child categories. All the demos I see use Mage::getModel, but trying to get it to work with getChildCategories. Check out the code below, the areas commented out are what is breaking it. Any help would be great.
$nl = chr(10);
$obj = new Mage_Catalog_Block_Navigation();
$main_cats = $obj->getStoreCategories();
echo '<ul>';
foreach ($main_cats as $main) {
// $sub_cats = $this->getChildCategories($main);
$main_class = ($this->isCategoryActive($main)) ? 'current' : '';
echo '<li class="'.$main_class.'"><a href="'.$this->getCategoryUrl($main).'">'.$main->getName().'</a>'.$nl;
/*
if ($sub_cats->count())) {
echo '<ul>';
foreach ($sub_cats as $sub) {
$sub_class = ($this->isCategoryActive($sub)) ? 'current' : '';
echo '<li class="'.$sub_class.'"><a href="'.$this->getCategoryUrl($sub).'">'.$sub->getName().'</a></li>'.$nl;
}
echo '</ul>'.$nl;
}
*/
echo '</li>';
}
echo '</ul>';
A: What do you think about this?
getting_and_using_categories_and_subcategories
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Making jquery.get a jquery.ajax - not working? I want to be able to show a loading div when making ajax requests, so I am trying to change my requests from $.get to $.ajax so I can use the beforeSubmit and complete actions.
For some reason, the get below works, but the ajax does not. Any thoughts as to why? The method is triggered, but in fiddler I can see no request goes back to the server.
WORKS:
$("#testBoundChart").click(function (e) {
$.get('/charter/bound', callbackFn);
function callbackFn(data) {
//Append markup to dom
$('body').append(data);
// call the js function from the partialview here
generateChart();
}
});
NO REQUEST SENT:
$("#testBoundChart").click(function (e) {
alert("triggered");
$.ajax({
url: '/charter/bound',
data: data,
success: (function(data) {
//Append markup to dom
alert("success");
$('body').append(data);
// call the js function from the partialview here
generateChart();
}),
error: (function () {
alert("error");
})
});
});
Many thanks
A: It looks like you are missing a semicolon for the error function. Though I'm not sure why it isn't giving a Javascript error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inexplicable Urllib2 problem between virtualenv's. I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser:
*
*Log in to a remote website
*Move to another page
*Perform a POST by filling in a form
I've created 4 separate, clean virtualenvs (with --no-site-packages) on 3 different machines, all with different versions of python but the exact same packages (via pip requirements file), and the code only works on the two virtualenvs on my local development machine(2.6.1 and 2.7.2) - it won't work on either of my production VPSs
In the failing cases, I can log in successfully, move to the correct page but when I submit the form, the remote server replies telling me that there has been an error - it's an application server error page ('we couldn't complete your request') and not a webserver error.
*
*because I can successfully log in and maneuver to a second page, this doesn't seem to be a session or a cookie problem - it's particular to the final POST
*because I can perform the operation on a particular machine with the EXACT same headers and data, this doesn't seem to be a problem with what I am requesting/posting
*because I am trying the code on two separate VPS rented from different companies, this doesn't seem to be a problem with the VPS physical environment
*because the code works on 2 different python versions, I can't imagine it being an incompabilty problem
I'm completely lost at this stage as to why this wouldn't work. I've even 'turned-it-off-and-turn-it-on-again' because I just can't see what the problem could be.
I think it has to be something to do with the final POST coming from a VPS that the remote server doesn't like, but I can't figure out what that could be. I feel like there is something going on under the hood of URLlib that is causing the remote server to dislike the reply.
EDIT
I've installed the exact same Python version (2.6.1) on the VPS as is on my working local copy and it doesn't work remotely, so it must be something to do with originating from a VPS. How could this effect the Http request? Is it something lower level?
A: You might try setting the debuglevel=1 for urllib2 and see what it comes up with:
import urllib2
h=urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(h)
...
A: This is a total shot in the dark, but are your VPSs 64-bit and your home computer 32-bit, or vice versa? Maybe a difference in default sizes or accuracies of something could be freaking out the server.
Barring that, can you try to find out any information on the software stack the web server is using?
A: I had similar issues with urllib2 (working with Zimbra's REST api), in the end switched to pycurl with success.
PS
for operations of login/navigate/post, I usually find Mechanize useful and easier to use. Maybe you can give it a show.
A: Well, it looks like I know why the problem was happening, but I'm not 100% the reason for it.
I simply had to make the server wait (time.sleep()) after it sent the 2nd request (Move to another page) before doing the 3rd request (Perform a POST by filling in a form).
I don't know is it because of a condition with the 3rd party server, or if it's some sort of odd issue with URLlib? The reason it seemed to work on my development machine is presumably because it was slower then the server at running the code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Making 2 or 3 INTs unique? Is hashing the way to go? The background is that from 2 or 3 unsigned integers I want something unique. I've done cantor pairs but they grow out of an BIGINT UNSIGNED when using 3.
Now I'm into hashing, first I went with MD5 and char(32) but know I'm into CRC32 with INT UNSIGNED since it's numeric, therefore fast. The goal is high performance reading from this index.
Is hashing the only way? Can I maintain a reasonable collision probability for ~200,000 rows?
A: The likelihood of an unintentional MD5 collision is 1.47×10-29. You reasonably assume safety with 200k rows. MD5/SHA1 are designed for speed, so fast shouldn't be a concern.
A: You can use binary(12) (12 bytes) which can uniquely store three 4 byte integers.
Or decimal(30) which also can do that and doesn't require you to first convert the integers to a binary encoding (just 0 pad them to 10 digits and append them together, MySql will do the conversion for you).
A: How well does MySQL handle compound keys/indexes?
If MySQL can handle them in a performant way then one option would be to simply store your three integers in three separate INT columns and have a compound key that spans all three columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: problems with multiples invitations to a event on facebook I'm tried use the multiples invitations method of facebook-graph API.
of according the documentation,this is the syntax to send multiples invitations:
/EVENT_ID/invited?users=USER_ID1,USER_ID2,USER_ID3
I wrote this code:
$ids = 'id123,id12345';
$ch = curl_init("https://graph.facebook.com/$e_id/invited?users=$ids?access_token={$token}");
curl_setopt_array($ch,
array(CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => 'POST'
)
);
I'm getting the following error:
{"error":{"message":"(#114) An id must be a valid ID string (e.g., \"123\")","type":"OAuthException"}}
How I fix this? Thanks in advance. :)
A: As it is written in error message it should be numeric strings i.e. "12345" and not "id12345", try real uids and don't invite your own uid.
hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The setting 'auto create statistics' causes wildcard TEXT field searches to hang I have an interesting issue happening in Microsoft SQL when searching a TEXT field. I have a table with two fields, Id (int) and Memo (text), populated with hundreds of thousands of rows of data. Now, imagine a query, such as:
SELECT Id FROM Table WHERE Id=1234
Pretty simple. Let's assume there is a field with Id 1234, so it returns one row.
Now, let's add one more condition to the WHERE clause.
SELECT Id FROM Table WHERE Id=1234 AND Memo LIKE '%test%'
The query should pull one record, and then check to see if the word 'test' exists in the Memo field. However, if there is enough data, this statement will hang, as if it were searching the Memo field first, and then cross referencing the results with the Id field.
While this is what it is appearing to do, I just discovered that it is actually trying to create a statistic on the Memo field. If I turn off "auto create statistics", the query runs instantly.
So my quesiton is, how can you disable auto create statistics, but only for one query? Perhaps something like:
SET AUTO_CREATE_STATISTICS OFF
(I know, any normal person would just create a full text index on this field and call it a day. The reason I can't necessarily do this is because our data center is hosting an application for over 4,000 customers using the same database design. Not to mention, this problem happens on a variety of text fields in the database. So it would take tens of thousands of full text indexes if I went that route. Not to mention, adding a full text index would add storage requirements, backup changes, disaster recovery procedure changes, red tape paperwork, etc...)
A: I don't think you can turn this off on a per query basis.
Best you can do would be to identify all potentially problematic columns and then CREATE STATISTICS on them yourself with 0 ROWS or 0 PERCENT specified and NORECOMPUTE.
If you have a maintenance window you can run this in it would be best to run without this 0 ROWS qualifier but still leave the NORECOMPUTE in place.
You could also consider enabling AUTO_UPDATE_STATISTICS_ASYNC instead so that they are still rebuilt automatically but this happens in the background rather than holding up compilation of the current query but this is a database wide option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rails 3: Passing a string from Ruby to Javascript? The Jist:
In a <script type="text/javascript"> I want to access a static (won't ever change after Rails delivers page to client) string from Ruby to Javascript.
More Detail (AKA: Why I want to do it.)
I use a push server called Juggernaut and it has to connect to the appropriate "channel", determined by a variable in the controller. The Juggernaut syntax for "listening" to the Juggernaut server is:
j.subscribe("channel", function(data) { })
I want it to be:
j.subscribe(<%= @myChannel %>, function(data) { })
A: Most likely your @myChannel doesn't contain ".
You should use:
j.subscribe("<%= @myChannel %>", function(data) { })
A: A different idea is to not embed your ruby code in your .js files but rather in the view itself.
So in your view, either set a javascript variable channel or add "channel" as an attribute of some html element, whichever is more natural for your case. Then in your application javascript you can access that variable once the document is ready.
This has the side benefit that if / when channel changes the client doesn't need to re-download your javascript but can instead keep using it from cache, and that rails doesn't need to render the .js every time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I add more after "this" in jQuery? I'm working on a script that fades in and out both an image and a div I have set behind the image when you hover over the image. I'm having two problems:
*
*The fades on the image and div don't seem to move at the same speed even though I have them set to.
*I can't figure out how to get the div's to only show for the image you hover over. If I could type ("this" div.info) as an object, it would work fine. Is there a way to do that?
I can't get $(".info",this), $(this).find(".info"), or $(".info", $(this).closest("li")) to work.
Result: I have found the solution. I was able to get it to work by using lthibodeaux's suggestion and using $(".info", $(this).closest("li")) as the object and making all the functions .fadeTo go here for the result:
http://jsfiddle.net/Z5p4K/7/
Edit:
*
*I found out the image and the div animations really were moving at the same speed, just the image only had it's z-index set on hover, so if you took your mouse off the image while the animation was running, it would appear to move at a different speed than the div when really the image was behind the div, it only appeared to be moving at different speeds because when the div became invisible you could see the image behind it but when it became opaque, the image was gone (making you think the image became invisible when really the div was in front of the image). This was easily fixed by moving the the z-index property from ul.columns li:hover img to ul.columns li img.
*The div only had a border around it while you hovered over it. This was easily fixed by changing the border properties from ul.columns li:hover .info to ul.columns li .info
Check out the final version here: http://jsfiddle.net/tV9Bw/
This is the final version because I can no longer find any problems with any of the code; everything is optimized, there are no glitches, and it looks great.
Thanks to everyone who answered and to Yi Jiang for editing this post with better formatting. I'm new to this site so I wasn't sure how to properly format my question.
and a Huge thanks to artyom.stv for fixing the last glitch in the script that I didn't know how to fix.
A: You've got the general idea. One thing you should know about a selector is that you are able to define a second argument as the scope of the selector, i.e.
$("selectorString", scopeObject)
In your case, make the second argument $(this).closest("li"). It will find the list item containing your image and select .info descendants of that container:
$(".info", $(this).closest("li")).fadeIn(1000);
A: Change $(".info") to $(this).find(".info") and all will be sweet.
A: Yes you can use something like $(this).find(".info") as mentioned by Bundy
but as The jQuery constructor accepts a 2nd parameter which can be used to override the context of the selection.
You can also do something like this:
$(".info",this)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: In CreateFile() what is the quickest way to assign Read-Only permissions to the standard user Everybody. And no permissions to anyone else In Windows, I have an application that needs to set the access control to the user/group 'Everybody' only. And sets permissions to Read-Only. Under Linux a Simple open() call with octal 004 permissions is sufficient. On Windows, how do I accomplish the same thing? Preferably in the call to CreateFile().
A: Create a SECURITY_DESCRIPTOR with the proper attributes. The functions linked to from there are a good starting point for creating the proper security descriptor (it's far from trivial). This page shows a good example of creating one, including how to get the SID for the "Everybody" group (pEveryoneSID in the code).
Then, just pass in that security descriptor to CreateFile as the lpSecurityAttributes parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I convert a string to a list in python? Let's say I have :
my_args = ["QA-65"]
as the desired result,
but in my function, I have:
m = re.search("([a-zA-Z]+-\d+)",line)
print 'printing m.group(1)'
print m.group(1)
m_args = m.group(1)
print 'my_args '
print m_args
print type(m_args)
so that the type of "m_args" is string, i.e
How can I convert m_args to a list with just one element with the same content as the string?
A: You do it this way:
m_args = [m_args, ]
A: Perhaps this:
my_args = [my_args]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery - Get White or Dark Text over Color Wheel This problem popped up when I looked at an almost perfect bit of jQuery code called Jar Two Wheel Color Picker:
http://www.jar2.net/projects/jquery-wheelcolorpicker/demo
If you notice in their demo when you move your cursor over the wheel, the developer appears to be using an inverse color algorithm that's slightly imperfect. I mean, if you use it and paste in 8072ff, you end up with something you can't read in the textbox.
The fix in my mind was to change the algorithm so that it shows black when over lighter colors, and white when over darker colors.
I looked into the source and found where it's updating the color of the textbox field. There, I'm able to get the R, G, and B color values from 0 to 255.
In Javascript and jQuery, knowing the R, G, and B values of a background color, how can I switch the foreground color to either white or black so that it is readable?
A: The conversion to hsl makes finding contrasting colors easy-
but it takes a bit to convert between rgb and hsl.
This works well enough for most cases- but it won't replace your eye.
function bW(r){
//r must be an rgb color array of 3 integers between 0 and 255.
var contrast= function(B, F){
var abs= Math.abs,
BG= (B[0]*299 + B[1]*587 + B[2]*114)/1000,
FG= (F[0]*299 + F[1]*587 + F[2]*114)/1000,
bright= Math.round(Math.abs(BG - FG)),
diff= abs(B[0]-F[0])+abs(B[1]-F[1])+abs(B[2]-F[2]);
return [bright, diff];
}
var c, w= [255, 255, 255], b= [0, 0, 0];
if(r[1]> 200 && (r[0]+r[2])<50) c= b;
else{
var bc= contrast(b, r);
var wc= contrast(w, r);
if((bc[0]*4+bc[1])> (wc[0]*4+wc[1])) c= b;
else if((wc[0]*4+wc[1])> (bc[0]*4+bc[1])) c= w;
else c= (bc[0]< wc[0])? w:b;
}
return 'rgb('+c.join(',')+')';
}
A: Given the RGB/HSV conversion functions from Michael Jackson and this bit of HTML to play with:
<input type="text" id="pancakes">
<button id="margie">go</button>
Then something like this might be a decent starting point:
$('#margie').click(function() {
var bg = $('#pancakes').val();
var rgb = bg.match(/../g);
for(var i = 0; i < 3; ++i)
rgb[i] = parseInt(rgb[i], 16);
var hsv = rgbToHsv(rgb[0], rgb[1], rgb[2]);
var fg = 'ffffff';
if(hsv[2] > 0.5)
fg = '000000';
$('#pancakes').css({
color: '#' + fg,
background: '#' + bg
});
});
Demo: http://jsfiddle.net/ambiguous/xyA4a/
You might want to play with the hsv[2] > 0.5 and possibly look at the hue and saturation as well but just a simple value check should get you started. You might want to play with HSL rather than HSV and see which one works better for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HttpRequestTask and https Is it possible to perform request to https using http-request phing task?
If no - what workaround could you propose? wget?
A: Yes, you are not limited to HTTP only - HTTPS works fine.
Examples are shown in the phing documentation:
<http-request url="https://accounts.google.com/"/>
Alternatively, you can use the curl adapter:
<http-request url="https://accounts.google.com/" verbose="true">
<config name="adapter" value="HTTP_Request2_Adapter_Curl"/>
</http-request>
A: It seems that by default you won't be able to connect using https. This is because the Phing http task uses the PEAR HTTP_Request2 libraries to make the connection. That in turn uses either PHP curl or sockets to make the connection. When connecting to https it needs to verify the CA certificate. That can be switched off so any certificate is supported but the Phing task doesn't support passing the option over to HTTP_Request2.
So if you otherwise like the Phing http task I suggest you either copy and modify the task or write your own that extends the original one so it supports the ssl_verify_peer option.
Or you can always default to the exec task and fetch whatever you need using curl of wget which however might not work on multiple platforms.
Here are links where you find more info:
*
*PEAR HTTP_Request2 configuration options
*Source code of the Phing http task
*HTTP_Request2 info about https and proxy servers (Search for https)
*How to write your own Phing task
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deploying a website to multiple environments with git Currently I deploy a project to production with git, using git push production master to a repository with the following post-receive hook:
#!/bin/bash
GIT_WORK_TREE=/home/username/www.example.com/myproject/ git checkout -f
production is a remote, added via git remote add production ssh://server/home/username/projects/myproject.git.
But now I need to deploy a separate branch to a separate path on the server. I did come up with a solution, but I suppose there's a better way to do it.
What I did was create a new repository on the server, myproject-alternate.git, with a similar post-receive hook (replacing /myproject/ with /myproject-alternate/), added this new repository with git remote add alternate ssh://server/home/username/projects/myproject-alternate.git. Now I can deploy to the alternate path with git push alternate branchname:master.
This works, but I have some issues:
*
*The command to deploy to the alternate server is not what I was expecting—more than once I forgot the :master at the end and the server's repository received a new branch and the post-receive hook wasn't triggered.
*I'm not sure if creating a new repository on the server was the best solution, and I wonder what would happen with a larger project.
Are there other ways to accomplish this deploy flow without the mentioned issues? Maybe a better post-receive hook that uses the received branchname to deploy to the right path? (is this even possible?)
A: I've written a blog post about a setup I use to deploy my website to a staging server and the live server. You could do something similar. The key is to configure which branches you're going to be pushing in the .git/config file of your local repository, something like this:
[remote "alternate"]
url = ssh://server/home/username/projects/myproject-alternate.git
fetch = +refs/heads/master:refs/remotes/alternate/master
pushurl = ssh://server/home/username/projects/myproject-alternate.git
push = refs/heads/branchname:refs/heads/master
[remote "production"]
url = ssh://server/home/username/projects/myproject.git
fetch = +refs/heads/master:refs/remotes/production/master
pushurl = ssh://server/home/username/projects/myproject.git
push = refs/heads/master:refs/heads/master
This will set it up so that whenever you type
git push alternate
it will automatically push the local branchname branch to the remote master branch in the alternate repository.
However, since your alternate and production work trees are on the same computer, you can probably get away with only creating one repository and just checking it out to two different places. To do that, ignore the previous paragraph, and instead put something like this in your post-receive hook:
#!/bin/bash
checkout_alt=
checkout_prod=
while read oldrev newrev refname; do
case "$refname" in
( "refs/heads/branchname" )
export checkout_alt=1 ;;
( "refs/heads/master" )
export checkout_prod=1 ;;
esac
done
test -n "$checkout_alt" && GIT_WORK_TREE=/home/diazona/tmp/gittest/alt/ git checkout -f branchname
test -n "$checkout_prod" && GIT_WORK_TREE=/home/diazona/tmp/gittest/prod/ git checkout -f master
(obviously you don't have to use an if statement). If you do this, I suggest making the repository bare so that it doesn't store its own working copy, just for simplicity. This way, you only need to have one remote, and whenever you push the master branch, it will update the production work tree, and whenever you push the branchname branch, it will update the alternate work tree.
Disclaimer: I haven't actually tested this, so try it out in a test folder first. If I find any errors I'll come back and edit.
A: I've also written a blog post on the set up I use, which allows me to git push each branch in my project up to my remote, deploying each into their own respective directories.
For example:
Branch | Directory on remote
--------------------------------------
master | /www/foo.com/master
staging | /www/foo.com/staging
production | /www/foo.com/produciton
So, to do this, add the following function to your server dotfiles:
function gitorigin() {
mkdir -p "$1"
cd "$1"
git init --bare
git config core.bare false
git config receive.denycurrentbranch ignore
cat <<EOF >hooks/post-receive
#!/bin/bash
while read oldrev newrev ref
do
branch=\`echo \$ref | cut -d/ -f3\`
mkdir -p ../\$branch
git --work-tree=../\$branch checkout -f \$branch
echo Changes pushed to \$branch
done
EOF
chmod +x hooks/post-receive
cd ..
}
On Remote, create a repository:
$ cd /www/foo.com
$ gitrepo foo.git
On Local, push a branch
$ cd ~/Sites/foo.com
$ git remote add origin ssh:///<USER>@<HOST>/www/foo.com/foo.git
$ git push origin <BRANCH>
Will push your master branch up to remote, into /www/foo.com/<BRANCH>/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Codeigniter issues, w/ Database on autoload I am starting a new CodeIgniter project and I get a 404 error when I autoload the database class. Has anyone else run into this issue. What is the cause of it? I would appreciate any advice. Also I have started with a new project and it worked. I encountered the issue when I added database to the autoload list...
Thanks
A: How familiar are you with arrays? in /application/config/autoload.php, your $autoload['libraries'] array should include 'database'.
If you have no other libraries autoloading, it should look like this:
$autoload['libraries'] = array('database');
FYI: Please post what you've tried next time you ask a question - but welcome to SO!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Comparison Operator in C# I have a vague requirement. I need to compare two values. The values may be a number or a string.
I want to perform these operations >, <, ==,<>, >=,<=
In my method I will pass, the parameter1, parameter 2 and the operators of above.
How can compare the two values based on the operator as effectively in .NET 2.0.
My method should be as simplified for both String and integer input values.
Sample Input Value:
param1 | param2 | operator
------------------------------
David Michael >
1 3 ==
A: Provided both parameters are always of the same type you could use a generic method where both parameters implement IComparable<T> (introduced in .NET 2.0)
public int CompareItems<T>(T item1, T item2) where T: IComparable<T>
{
return item1.CompareTo(item2);
}
(You can interpret the result of CompareTo() depending on the operator your pass in your implementation)
A: If you have to/want to build generic version you need to pass comparison as function/lambda - it is not possible to use operators in generic way. Somithing like:
class OpComparer<T>
{
Func<T,T,bool> operation;
public OpComparer(Func<T,T,bool> op)
{
operation = op;
}
int PerformOp(T item1, T item2)
{
return operation(item1, item2);
}
}
...
var comparerLess = new OpCompared<String>((a,b)=> a < b );
var result = comparerLess.PerformOp("aaa", "bbb");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is best tool to get EXIF data? I am looking for backend best tool to retrieve Exif data of images. There are various tool and even function are provided for some programming languages to get Exif data, but they are not reliable.
What is the best tool on the web to retrieve Exif data that work with various camera manufacturers?
A: Use the Perl module Image::EXIF
https://metacpan.org/pod/Image::EXIF
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I use domain masking plus get the URI passed? I have a dyndns.org account which goes to my home computer. That all works fine, wordpress is installed.
I want to buy a domain (mysite.com) and have it mask to mysite.dyndns.org while passing back all of the additional URI goodness.
For example, if I go to mysite.com/page2 it should go to mysite.dyndns.org/page2
Any thoughts on ways to accomplish this?
A: The answer turned out to be to use a CNAME record. CNAMES essentially act like symlinks.
A: Yes, assuming you want to keep hash parameters in addition to query parameters, you could accomplish such a thing with a little piece of JavaScript like the following:
if (window.location.host == 'mysite.com') {
var current_url = window.location.href;
var new_url = current_url.replace('mysite.com', 'mysite.dyndns.org');
window.location.href = new_url;
}
If you don't need to preserve hash parameters, then you could implement similar redirect logic in the web server or in the server-side scripting language of your choice, by checking the HTTP "Host" header for the current host name, and issuing a 301 redirect as needed.
However, I really do not understand why you would want your system to be set up in this way. Typically custom domains are more trustworthy than domains hanging off of "dyndns.org". Why not just have your custom domain configured to point to the correct IP address(es)? Most web hosting solutions will automatically provide the appropriate DNS configuration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Div's margin-top stays 20px when scrolling I want the div on the right side of this page to stop scrolling up when you scroll down the page. So that it is always 20px from the top of the window and the customer can read it's contents.
How can I achieve that? CSS? jQuery?
Thanks
A: jQuery. Do an on scroll event, and when scroll height gets past a certain point, make the div position:fixed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: unmount sdcard programmatically in Android?
*
*I am working to implement Mount/Unmount sdcard support in my Android application, Am able to get sdcard state by Environment.getExternalStorageState().I know we can call Settings Intent and Mount/Unmount, but my requirement has to do programmatically with out calling Settings Intent.
*Is it possible to Enable/Disable the Settings application in Android?
A: The settings app uses this permission <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> See if you can use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Twitter+OAuth still giving me warnings Its installed and working but I still get 10 warnings. Is this because the engine is out of date and not 100% compatible with new support libraries? has anyone manage to ge this installed clean with no warnings please share your sources.
I based my installation on "Mark Hammonds on Sep 22nd 2010 " tutorial.
WARNNINGS:
/xCode_Projects/Official Apps/WnS/APP/WnS/WnS/Twitter+OAuth/MGTwitterEngine/MGTwitterMessagesParser.m
'MGTwitterStatusesParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
'MGTwitterStatusesParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
file://localhost/xCode_Projects/Official%20Apps/WnS/APP/WnS/WnS/Twitter+OAuth/MGTwitterEngine/MGTwitterMessagesParser.m: warning: Semantic Issue: 'MGTwitterStatusesParser' may not respond to 'parser:didEndElement:namespaceURI:qualifiedName:'
/xCode_Projects/Official Apps/WnS/APP/WnS/WnS/Twitter+OAuth/MGTwitterEngine/MGTwitterMiscParser.m
'MGTwitterStatusesParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
'MGTwitterStatusesParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
/xCode_Projects/Official Apps/WnS/APP/WnS/WnS/Twitter+OAuth/MGTwitterEngine/MGTwitterStatusesParser.m
'MGTwitterXMLParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
'MGTwitterXMLParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
/xCode_Projects/Official Apps/WnS/APP/WnS/WnS/Twitter+OAuth/MGTwitterEngine/MGTwitterUsersParser.m
'MGTwitterStatusesParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
'MGTwitterStatusesParser' may not respond to '-parser:didEndElement:namespaceURI:qualifiedName:'
/xCode_Projects/Official Apps/WnS/APP/WnS/WnS/Twitter+OAuth/MGTwitterEngine/MGTwitterXMLParser.m
Class 'MGTwitterXMLParser' does not implement the 'NSXMLParserDelegate' protocol
Class 'MGTwitterXMLParser' does not implement the 'NSXMLParserDelegate' protocol
A: Solved. Turns out the folder needed to be at the root of the project. I Had it in a "external libs" folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stored procedure update problem The stored procedure work but update nothing!! I think is about those statements
if @... <>null .
Thank for Help
ALTER PROCEDURE [dbo].[sp_UpdateLocation]
@id_Location char(6),
@debut_Location smalldatetime,
@premier_Paiement smalldatetime,
@nombre_Mensualité char(2),
@id_Client char(6),
@no_Termes_location char(6),
@niv char(20)
AS
BEGIN
IF @nombre_Mensualité <> null
BEGIN
DECLARE @valeur_auto smallmoney;
DECLARE @paiment_Mensuel smallmoney;
SET @valeur_auto= (SELECT valeur FROM Véhicules where niv=@niv )
SET @paiment_Mensuel= (@valeur_auto/@nombre_Mensualité)
Update Location
SET paiment_Mensuel=@paiment_Mensuel,nombre_Mensualité=@nombre_Mensualité
WHERE (@id_Location=id_Location)
END
IF @debut_Location <> null
BEGIN
Update Location
SET debut_Location=@debut_Location
WHERE @id_Location=id_Location
END
IF @premier_Paiement <> null
BEGIN
Update Location
SET premier_Paiement=@premier_Paiement
WHERE @id_Location=id_Location
END
IF @id_Client <> null
BEGIN
Update Location
SET id_Client=@id_Client
WHERE @id_Location=id_Location
END
IF @no_Termes_location <> null
BEGIN
Update Location
SET no_Termes_location=@no_Termes_location
WHERE @id_Location=id_Location
END
IF @niv <> null
BEGIN
Update Location
SET niv=@niv
WHERE @id_Location=id_Location
END
END
select*from Location
A: Instead of <> null try IS NOT NULL.
MSDN is a good resource to consult on these types of issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: showing utf-8 character in chart generated by ggplot2 I want to use the symbol (u+2265):
in the y-axis label of my chart. How can I do that? Thanks.
UPDATE 01
I need to use add a >=95 in the y-axis label, showing the group of people aged more than 95, I tried expression(>=95) but fail as it seems to expect something before >=. What can I do?
A: qplot(1, 1, ylab=expression(phantom(.) >= 95))
By using phantom in the expression, you don't get anything printed. I put a period in there because phantom still leaves space, so I wanted something small.
A: In the y-axis or label?
plot(1,1, ylab = expression(X >= 5))
Try ?expression and ?plotmath.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Possible to use different forms authentication cookie names for multiple virtual directories mapped to one physical directory? Using ASP.NET 2.0, IIS 7.
I have an ASP.NET application using forms authentication setup as follows in web.config :
<authentication mode="Forms">
<forms name=".ASPXAUTH_LIVE" loginUrl="Login.aspx" defaultUrl="~/Default.aspx" protection="All" timeout="1440" path="/" requireSSL="true" slidingExpiration="true" cookieless="UseDeviceProfile"/>
</authentication>
There are two IIS virtual directories mapped to the one physical directory. Since they map to the same physical directory, they both use the cookieName : ".ASPXAUTH_LIVE".
Is there some way to get the two virtual directories to use different cookie names ? I know I could make multiple copies of the physical directory, and change the name attribute in the web.config, but I'd rather not have to maintain multiple physical directories.
A: I cannot guarantee this will be of any assistance, but my first instinct would be to override the defaults for each virtual directory by adding a <location> element to your site's root web.config:
<location path="Path/To/Virtual/Directory">
<system.web>
<authentication>
<forms name=".ASPXAUTH_LIVE2" />
</authentication>
</system.web>
</location>
At first blush I expect this to fail miserably, but if nothing else it's an idea to test. I apologize for not trying the configuration myself but this would require a bit of work on my part to configure a working test project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android ndk native code fopen() path I am new to programming and trying to learn android with native c++ code.
I am trying to open a bitmap file in native code so I can load it as a texture in opengl.
FILE* img = NULL;
img = fopen("banana.bmp","rb");
if (img == NULL)
{
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [%s]", "load texture file = null");
return -1;
}
the above code always return img as null.
Where should I put my banana.bmp file?
Right now I put it in the jni folder along with the android.mk and c++ source files.
Can someone please explain to me? Thanks
A: The NDK fopen() will open resources in the emulator or on the phone, not in your development workspace!
To try this, for example in the emulator, you should push the image to the SD card.
A: You should specify a folder where to write the "banana.bmp" file.
Like in this example:
fp = fopen("/sdcard/banana.bmp", "wb");
A: I think you need to specify the path to your file. To help you I found this link to explain, but exactly where your .bmp file resides I am not sure. You might have to do a bit of experimenting with file locations.
A: You're not specifying a path to banana.bmp. Where do you expect it to be found? If it's in a asset of your APK, you can't simply fopen() as such. If you've extracted/downloaded/etc. You'll need a path that is something like /data/data/your.package.name/banana.bmp (note that you'll want to get the actual path from Java/SDK)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: expressjs node.js serve different data to google/etc bot and human traffic I want to determine if incoming requests are from a bot (eg google, bing), or a human, and serve different data to each, for example, json data for client javascript to construct the site or preprocessed html.
Using expressjs, is there an easy way to do this? Thanks.
A: You can check the req.header('User-Agent') for 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html'. If it's that you know it's Google and can send it different data.
http://www.google.com/support/webmasters/bin/answer.py?answer=1061943
How to get headers
http://expressjs.com/4x/api.html#req.get
A: I recommend you to response according to the requested MIME type (which is present in the "Accept" header). You can do this with Express this way:
app.get('/route', function (req, res) {
if (req.is('json')) res.json(data);
else if (req.is('html')) res.render('view', {});
else ...
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: WebSockets connection I recently had WebSockets running on my laptop with XSockets. I then had to rebuild my laptop, installed just like before, and now WebSockets don't work.
I have Norton Internet Security installed just like before. I looked at all my acive ports, checked out my firewall rules, what have ya, and I'm dead in the water. When I try to connect to my server, it immediately closes.
I dont know what else to check. I even turned off firewall protection from norton, and still it doesn't work.
Any help on what else to check, I surely would appreciate it. I'm running Windows 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: After authorization, Facebook redirects to my website but userID is not set A user visits my application's canvas page which directs them to authorize the application. It then redirects them to my website where I use the PHP SDK to look up information about the user.
Unfortunately the userID is returning 0 after the redirect from Facebook.
$fb_user = $facebook->getUser();
This ONLY happens immediately after authorization. If the user navigates to another page on my site, or reloads the page, the correct UID is returned and everything works as expected.
Could the redirect happen before Facebook completes the authorization? Does Facebook send the userID in the redirect? (Can that be configured?)
A: Work-around for this issue:
On my canvas page, I access the request_ids and append them to the query string of the url for the authorization request. The authorization will forward the request_ids parameter on to my website.
Javascript on an "authorize" link:
top.location = "http://www.facebook.com/dialog/oauth?client_id=MY_CLIENT_ID&scope=PERMISSIONS,MORE_PERMISSIONS&redirect_uri=http://www.MY_WEB_SITE.com/?request_ids=<?php echo $_REQUEST['request_ids']; ?>";
Then, on my website, I check for the Faecbook user_id. If that is 0, I look for the request_id parameter. If there, I make an api call to the graph to get the associated user_id. I use the user_id INSTEAD OF calling /me:
if ($fb_user===0){ //if Facebook doesn't return the user (the bug)
$request_ids = explode( ',', $_REQUEST['request_ids'], 1 ); //get the request_ids param, limit this to one since all request_ids will reference the same user_id
$request_info = $facebook->api('/' + $request_ids[0],'GET'); //get the request info
$fb_user_profile = $facebook->api('/' + $request_info['to']['id']); // $request_info['to']['id'] is the associated user_id (who the request was sent to)
}
else {
$fb_user_profile = $facebook->api('/me');
}
A call to /me returns nothing since Facebook isn't returning a logged-in user. (The bug.)
This is boiled down a little bit, but you get the idea...
A: We get this, the first page after the authorisation callback either gives no user, no perms or both. Should be logged as a bug
A: Adam's workaround works great, but due to some reasons it didn't fully suit me. My solution was to get all required user data from JS authorization and write it into php session. Hope, it will help someone.
JS auth function:
FB.login( function( response ) {
if ( response.authResponse ) {
FB.api('/me', function( response ) {
$.ajax({
url: 'action.php',
type: 'POST',
data: {
id: response.id,
name: response.name,
birthday: response.birthday,
location_id: response.location.id,
location_name: response.location.name,
gender: response.gender,
email: response.email
},
success: function() {
location.href = 'some-page.php';
}
});
});
} else {
alert("Please agree to the Facebook permissions.");
}
}, { scope:'user_location, user_birthday, email, publish_actions' } );
Action.php
session_start();
$_SESSION['user_info']['id'] = $_REQUEST['id'];
$_SESSION['user_info']['name'] = $_REQUEST['name'];
$_SESSION['user_info']['birthday'] = $_REQUEST['birthday'];
$_SESSION['user_info']['location']['id'] = $_REQUEST['location_id'];
$_SESSION['user_info']['location']['name'] = $_REQUEST['location_name'];
$_SESSION['user_info']['gender'] = $_REQUEST['gender'];
$_SESSION['user_info']['email'] = $_REQUEST['email'];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using zlib filter with a socket pair For some reason, the zlib.deflate filter doesn't seem to be working with socket pairs generated by stream_socket_pair(). All that can be read from the second socket is the two-byte zlib header, and everything after that is NULL.
Example:
<?php
list($in, $out) = stream_socket_pair(STREAM_PF_UNIX,
STREAM_SOCK_STREAM,
STREAM_IPPROTO_IP);
$params = array('level' => 6, 'window' => 15, 'memory' => 9);
stream_filter_append($in, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
stream_set_blocking($in, 0);
stream_set_blocking($out, 0);
fwrite($in, 'Some big long string.');
$compressed = fread($out, 1024);
var_dump($compressed);
fwrite($in, 'Some big long string, take two.');
$compressed = fread($out, 1024);
var_dump($compressed);
fwrite($in, 'Some big long string - third time is the charm?');
$compressed = fread($out, 1024);
var_dump($compressed);
Output:
string(2) "x�"
string(0) ""
string(0) ""
If I comment out the call to stream_filter_append(), the stream writing/reading functions correctly, with the data being dumped in its entirety all three times, and if I direct the zlib filtered stream into a file instead of through the socket pair, the compressed data is written correctly. So both parts function correctly separately, but not together. Is this a PHP bug that I should report, or an error on my part?
This question is branched from a solution to this related question.
A: I had worked on the PHP source code and found a fix.
To understand what happens I had traced the code during a
....
for ($i = 0 ; $i < 3 ; $i++) {
fwrite($s[0], ...);
fread($s[1], ...);
fflush($s[0], ...);
fread($s[1], ...);
}
loop and I found that the deflate function is never called with the Z_SYNC_FLUSH flag set because no new data are present into the backets_in brigade.
My fix is to manage the (PSFS_FLAG_FLUSH_INC flag is set AND no iterations are performed on deflate function case) extending the
if (flags & PSFS_FLAG_FLUSH_CLOSE) {
managing FLUSH_INC too:
if (flags & PSFS_FLAG_FLUSH_CLOSE || (flags & PSFS_FLAG_FLUSH_INC && to_be_flushed)) {
This downloadable patch is for debian squeeze version of PHP but the current git version of the file is closer to it so I suppose to port the fix is simply (few lines).
If some side effect arises please contact me.
A: Looking through the C source code, the problem is that the filter always lets zlib's deflate() function decide how much data to accumulate before producing compressed output. The deflate filter does not create a new data bucket to pass on unless deflate() outputs some data (see line 235) or the PSFS_FLAG_FLUSH_CLOSE flag bit is set (line 250). That's why you only see the header bytes until you close $in; the first call to deflate() outputs the two header bytes, so data->strm.avail_out is 2 and a new bucket is created for these two bytes to pass on.
Note that fflush() does not work because of a known issue with the zlib filter. See: Bug #48725 Support for flushing in zlib stream.
Unfortunately, there does not appear to be a nice work-around to this. I started writing a filter in PHP by extending php_user_filter, but quickly ran into the problem that php_user_filter does not expose the flag bits, only whether flags & PSFS_FLAG_FLUSH_CLOSE (the fourth parameter to the filter() method, a boolean argument commonly named $closing). You would need to modify the C sources yourself to fix Bug #48725. Alternatively, re-write it.
Personally I would consider re-writing it because there seems to be a few eyebrow-raising issues with the code:
*
*status = deflate(&(data->strm), flags & PSFS_FLAG_FLUSH_CLOSE ? Z_FULL_FLUSH : (flags & PSFS_FLAG_FLUSH_INC ? Z_SYNC_FLUSH : Z_NO_FLUSH)); seems odd because when writing, I don't know why flags would be anything other than PSFS_FLAG_NORMAL. Is it possible to write & flush at the same time? In any case, handling the flags should be done outside of the while loop through the "in" bucket brigade, like how PSFS_FLAG_FLUSH_CLOSE is handled outside of this loop.
*Line 221, the memcpy to data->strm.next_in seems to ignore the fact that data->strm.avail_in may be non-zero, so the compressed output might skip some data of a write. See, for example, the following text from the zlib manual:
If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate().
In other words, it is possible that avail_in is non-zero.
*The if statement on line 235, if (data->strm.avail_out < data->outbuf_len) should probably be if (data->strm.avail_out) or perhaps if (data->strm.avail_out > 2).
*I'm not sure why *bytes_consumed = consumed; isn't *bytes_consumed += consumed;. The example streams at http://www.php.net/manual/en/function.stream-filter-register.php all use += to update $consumed.
EDIT: *bytes_consumed = consumed; is correct. The standard filter implementations all use = rather than += to update the size_t value pointed to by the fifth parameter. Also, even though $consumed += ... on the PHP side effectively translates to += on the size_t (see lines 206 and 231 of ext/standard/user_filters.c), the native filter function is called with either a NULL pointer or a pointer to a size_t set to 0 for the fifth argument (see lines 361 and 452 of main/streams/filter.c).
A: You need to close the stream after the write to flush it before the data will come in from the read.
list($in, $out) = stream_socket_pair(STREAM_PF_UNIX,
STREAM_SOCK_STREAM,
STREAM_IPPROTO_IP);
$params = array('level' => 6, 'window' => 15, 'memory' => 9);
stream_filter_append($out, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
stream_set_blocking($out, 0);
stream_set_blocking($in, 0);
fwrite($out, 'Some big long string.');
fclose($out);
$compressed = fread($in, 1024);
echo "Compressed:" . bin2hex($compressed) . "<br>\n";
list($in, $out) = stream_socket_pair(STREAM_PF_UNIX,
STREAM_SOCK_STREAM,
STREAM_IPPROTO_IP);
$params = array('level' => 6, 'window' => 15, 'memory' => 9);
stream_filter_append($out, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
stream_set_blocking($out, 0);
stream_set_blocking($in, 0);
fwrite($out, 'Some big long string, take two.');
fclose($out);
$compressed = fread($in, 1024);
echo "Compressed:" . bin2hex($compressed) . "<br>\n";
list($in, $out) = stream_socket_pair(STREAM_PF_UNIX,
STREAM_SOCK_STREAM,
STREAM_IPPROTO_IP);
$params = array('level' => 6, 'window' => 15, 'memory' => 9);
stream_filter_append($out, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
stream_set_blocking($out, 0);
stream_set_blocking($in, 0);
fwrite($out, 'Some big long string - third time is the charm?');
fclose($out);
$compressed = fread($in, 1024);
echo "Compressed:" . bin2hex($compressed) . "<br>\n";
That produces:
Compressed:789c0bcecf4d5548ca4c57c8c9cf4b57282e29cacc4bd70300532b079c
Compressed:789c0bcecf4d5548ca4c57c8c9cf4b57282e29cacc4bd7512849cc4e552829cfd70300b1b50b07
Compressed:789c0bcecf4d5548ca4c57c8c9cf4b57282e29ca0452ba0a25199945290a259940c9cc62202f55213923b128d71e008e4c108c
Also I switched the $in and $out because writing to $in confused me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to use FileSystem API to debug Javascript? The execution order issue I was debugging a complicated program written in Javascript. I need to watch the change of a large matrix. It is not convenient to see each elements in the matrix using Chrome Inspect Element. So, I want to write the data into a text File. I found the FileSystem API and terminal.
I have integrate FileSystem API into my project, with refer to the FileSystem terminal project. And I define a global variable to store the fs.root . What I want is to pass this variable into my program when debugging, so I can dump data into text file using this fs.root.
I request file system:
window.requestFileSystem(window.TEMPORARY, 5*1024*1024, onInitFs, errorHandler); // 5MB
But the "onInitFs" function seems like a message response function, which is called very late. Even after the "onLoad='MyFun();'". So, I do not know where to put my own function, to make sure that the variable "fs.root" is defined. Right now, I have put "MyFun()" to everywhere, all will generate an error that "fs.root" is not defined, since "onInitFs" function is not called.
I have tested the calling sequence:
-------------main.html
<html>
<header>
<script type='text/javascript' src='MyFun.js'></script>
<script type='text/javascript' >
console.log('01Position');
function onInitFs(fs)
{
aGlobalFsRoot = fs.root;
console.log('04Position');
}
window.requestFileSystem(window.TEMPORARY, 5*1024*1024, onInitFs, errorHandler);
</script>
</header>
<body onLoad="MyFun();">
<script>
console.log('02Position');
</script>
</body>
</html>
-------------MyFun.js
var aGlobalFsRoot;
function MyFun()
{
console.log('03Position');
// want to use "aGlobalFsRoot" to dump some matrix data, but it is not defined, which means "onInitFs()" is still not called.
}
So, in the console window of Chrome Inspect Element:
01Position
02Position
03Position
04Position
can I enable the "onInitFun()" function called ealier than "MyFun()". Or Where should I put "MyFun()", so it can be called later than "onInitFun()". I do not want user to click one button, since MyFun just do pre-processing work when loading. May I generate one message, so "MyFun()" will be called later than "onInitFs()"?
A: Either Andrey's comment, or the following, should work:
window.requestFileSystem(window.TEMPORARY, 5*1024*1024, function(fs) {onInitFs(fs); MyFun(fs); } , errorHandler);
As I understand, the fs api is deliberately designed to be asynchronous. So you can't force it to be called in any order. So you would have to adjust to an asynchronous mindset instead of a synchronous mindset.
If you want MyFun to be called when the file system request is done, then hook MyFun to run when the file system request is done (and not to the other, irrelevent onBodyLoad event):
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Beautiful Soup - how to fix broken tags I'd like to know how to fix broken html tags before parsing it with Beautiful Soup.
In the following script the td> needs to be replaced with <td.
How can I do the substitution so Beautiful Soup can see it?
from BeautifulSoup import BeautifulSoup
s = """
<tr>
td>LABEL1</td><td>INPUT1</td>
</tr>
<tr>
<td>LABEL2</td><td>INPUT2</td>
</tr>"""
a = BeautifulSoup(s)
left = []
right = []
for tr in a.findAll('tr'):
l, r = tr.findAll('td')
left.extend(l.findAll(text=True))
right.extend(r.findAll(text=True))
print left + right
A: Edit (working):
I grabbed a complete (at least it should be complete) list of all html tags from w3 to match against. Try it out:
fixedString = re.sub(">\s*(\!--|\!DOCTYPE|\
a|abbr|acronym|address|applet|area|\
b|base|basefont|bdo|big|blockquote|body|br|button|\
caption|center|cite|code|col|colgroup|\
dd|del|dfn|dir|div|dl|dt|\
em|\
fieldset|font|form|frame|frameset|\
head|h1|h2|h3|h4|h5|h6|hr|html|\
i|iframe|img|input|ins|\
kbd|\
label|legend|li|link|\
map|menu|meta|\
noframes|noscript|\
object|ol|optgroup|option|\
p|param|pre|\
q|\
s|samp|script|select|small|span|strike|strong|style|sub|sup|\
table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|\
u|ul|\
var)>", "><\g<1>>", s)
bs = BeautifulSoup(fixedString)
Produces:
>>> print s
<tr>
td>LABEL1</td><td>INPUT1</td>
</tr>
<tr>
<td>LABEL2</td><td>INPUT2</td>
</tr>
>>> print re.sub(">\s*(\!--|\!DOCTYPE|\
a|abbr|acronym|address|applet|area|\
b|base|basefont|bdo|big|blockquote|body|br|button|\
caption|center|cite|code|col|colgroup|\
dd|del|dfn|dir|div|dl|dt|\
em|\
fieldset|font|form|frame|frameset|\
head|h1|h2|h3|h4|h5|h6|hr|html|\
i|iframe|img|input|ins|\
kbd|\
label|legend|li|link|\
map|menu|meta|\
noframes|noscript|\
object|ol|optgroup|option|\
p|param|pre|\
q|\
s|samp|script|select|small|span|strike|strong|style|sub|sup|\
table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|\
u|ul|\
var)>", "><\g<1>>", s)
<tr><td>LABEL1</td><td>INPUT1</td>
</tr>
<tr>
<td>LABEL2</td><td>INPUT2</td>
</tr>
This one should match broken ending tags as well (</endtag>):
re.sub(">\s*(/?)(\!--|\!DOCTYPE|\a|abbr|acronym|address|applet|area|\
b|base|basefont|bdo|big|blockquote|body|br|button|\
caption|center|cite|code|col|colgroup|\
dd|del|dfn|dir|div|dl|dt|\
em|\
fieldset|font|form|frame|frameset|\
head|h1|h2|h3|h4|h5|h6|hr|html|\
i|iframe|img|input|ins|\
kbd|\
label|legend|li|link|\
map|menu|meta|\
noframes|noscript|\
object|ol|optgroup|option|\
p|param|pre|\
q|\
s|samp|script|select|small|span|strike|strong|style|sub|sup|\
table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|\
u|ul|\
var)>", "><\g<1>\g<2>>", s)
A: If that's the only thing you're concerned about td> -> , try:
myString = re.sub('td>', '<td>', myString)
Before sending myString to BeautifulSoup. If there are other broken tags give us some examples and we'll work on it : )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Inconsistent timeouts in javascript with setTimeout? I am making a game. The game has 1 main loops:
//draws a new frame and game logic
function draw()
{
player.gameTick();
game.gameTick();
lastTime=newTime;
background.draw(ctx);
player.draw(ctx);
enemies.draw(ctx);
setTimeout(draw,50);
}
Normally this operates fine, and I get 20fps reported to #console. Once in a while, however, the fps spikes up to >125. (meaning draw is being called less than 50 milliseconds after the previous call). When this happens, the game starts to lag for a couple of seconds, and then the fps goes back down. (that's also counter intuitive, why does HIGHER fps cause lag?)
Anyway, does anyone know why this is the case?
Yes I have tried setInterval() also, and the same thing happens. =/
A: JavaScript is single threaded. If you're scheduling two timeouts for 50 ms independently, there's a chance that they eventually collide, or come close to it, and cause an odd processing blockage for a second before they sort themselves out and can space out again. You should probably consolidate the code and create a single main loop that calls the other two functions. That way you can ensure that they both process once each per 50 ms.
Your flow looks something like this:
*
*Process1() -> takes some amount of time, hopefully less than 50ms, but guaranteed to be > 0ms.
*Process1 sets a timeout for itself 50ms in the future. The 2nd run of Process1 will occur more than 50ms after it started the 1st time.
*Process2() -> takes some amount of time, greater than 0ms. Same as Process1.
*Process2 sets a timeout for itself. Same rules apply. The 2nd run of Process2 will occur more than 50ms after it started the 1st time.
If, theoretically, Process1 takes 5ms and Process2 takes 7ms, every 7 runs of Process1 or 5 runs Process2 will cause the next timeout set for 50ms in the future to correspond exactly with the scheduled time for the next run of the other function. This type of collision will cause inconsistent behavior when the interpreter, which can only do one thing at a time, is asked to handle multiple events concurrently.
-- Edits for your revisions to the question --
You're still setting two independent timeouts for 50ms in the future. There's still no way to prevent these from colliding, and I'm still not entirely certain why you're approaching it this way. You should have something like this:
function mainLoop() {
player.tick();
game.tick();
background.draw();
players.draw();
enemies.draw();
setTimeout(mainLoop, 50);
}
mainLoop()
Note the absence of repetitive setTimeout calls. Everything can happen in one go. You're creating collisions in both versions of your demonstrated code.
A: This problem was caused by browser javascript timer throttling. I noticed the problem was exacerbated when I have many tabs open or when I switch between tabs. Chrome had less of an issue, most likely due to tabs being in isolated processes.
Firefox 7 seems to have fixed this problem for FF.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to filter an SSRS Dataset to return single record to be used in Textbox properties I'm a total newbie when it comes to SSRS, so please excuse any use of wrong terminology. But I have been given a task to create a report that will have have a dataset that will contain records that will be used to set Textbox's font size and weight, underlined, justification, and text values. Something like this...
Size Bold Underlined Text Identifier
10 Y N My Title Title
10 N N Some Def Def1
Sorry about the misalignment in spacing. Not sure how to do a table here. But basically, I'm wondering if there is a way to write an expression that would allow me to get the record with the Identifier of "Title" and use the other fields in the textbox properties. Something like the where clause of Inline Linq. But I'm at a total lose and would greatly appreciate some help on this. Thanks again.
A: You should be able to do this. In the TextBox properties, select the FontSize property and click on <Expression..>. Then in the expression box, pick the correct Dataset and field which will contain the font size.
Then repeat this process for the other attributes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I have a problem with pprint in python I have looked into the pprint function, which i tried below:
from pprint import pprint
a = [[1,2],[3,4]]
pprint(a)
But it didn't give me what i want, which is:
1 2
3 4
Is there a simple way to solve this ?
A: That's... not what pprint does.
for i in a:
print ' '.join(i)
A: You can either do what Ignacio said or change the width of pprint:
>>> pprint.pprint([[1,2],[3,4]], width=10)
[[1, 2],
[3, 4]]
But you would have to calculate the space that your list takes...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Print Out Security (Barcode?) I have been pondering this security issue and not exactly sure how to go about this. On my site people will be able to print out flyers and post them somewhere (like a university) and take a picture of themselves next to it. In return they will receive a user upgrade.
These are some of the problems that I have thought of:
*
*Users can print one flyer and take pictures in all sorts of places
*User can take a picture, turn the corner and take another picture
*Person A posts a flyer, Person B comes up and claims it as their own
Some possible solutions:
*
*Write the person's username on the flyer when printing out
*Have the user hold a piece of paper with their username and date
*Limit to 1 photo per week
*Print a barcode, alphanumeric code, or something else on the flyer as well.
My main focus for this question is the last solution. I have been thinking of storing a random salt for each time a flyer is printed.
What are other ways to keep the flyers as secure? (I know it's not possible to fully secure it.)
Programming Question: How should I generate a random code for each flyer? And how do I later verify it versus my system?
A: Use the username plus the current timestamp, then do a sha1() to the result. That should give you a very unique code.
For example
$code = sha1($username. time());
A: *
*Generate a random ID with something like base64_encode(uniqid("", TRUE)).
*Save it in your DB associated with the user's flyer.
*Include the unique ID on the flyer.
*When somebody posts a picture, look up in your DB to make sure it was a valid ID.
*Mark the DB entry as "redeemed" so nobody uses it again.
*Realize that no matter how clever you are, people will come up with ways to cheat your system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why can't I access JSON objects by key in JavaScript? This is my JSON object:
{ text: 'stuff',
user: 'user1
}
when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via console.log(jsonObj.text), I get undefined.
So how can I properly access everything in JavaScript?
I don't want to use jQuery as this is all node.js programming so it's serverside.
UPDATED - full JSON
{ text: '@junk_666 おかえりか',
user:
{ display_name: 'mono',
screen_name: 'monochrm',
klout_score: null,
location_str: '画面の前',
utc_offset: '32400' },
venue_id: 1304409836517,
match_type: 'twitter',
tweet_id: '116494264137023489',
created_at_unix: 1316609371,
meta:
{ matchedPhrase: 'junk',
venueName: 'deletemepls really long name' },
tags: [ '' ],
indexed_at_unix: 1316609416 }
A: The json seems to be invalid
{
"text": "stuff",
"user": "user1"
}
A: I copied and pasted your object into a FireBug console and it recognized it.
If you need to count the number of key/value pairs, you can use a function such as this one to do it:
function numMembers(o) {
var i=0;
for (a in o) {
i++;
}
return i;
}
You should be able to access the value of the text property via jsonObj.text. Are you sure that your object is being referenced by jsonObj? Also, can you access the values for simpler objects such as the ones mentioned in other posts if you create them? Furthermore, does anything work if you use only ASCII characters? For some reason, it might not be handling some of the non-Latin characters properly.
A: First, what you have is not JSON because JSON requires property name to be in double quotes. It is a valid JavaScript object literal though, so I'll assume that's how you're using it.
Secondly, JavaScript objects in general do not have a length property. Arrays do.
There's no problem with your object literal so there must be some other problem elsewhere in your code.
A: Try this:
{ text: 'stuff',
user: 'user1'
}
You left off an apostrophe.
Now that you've posted your full JS code (that's not JSON, as @josnidhin points out)... works fine in jsFiddle. http://jsfiddle.net/Rs9R4/ I don't believe a JS Object has .length, just Arrays.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any good iCal & vCal parser in php(library)? I'm creating a web app that need to upload iCal or vCal files. I wonder if there is any php library that can parse the information, so I can store it on my database?
A: that should help
http://www.phpbuilder.com/columns/chow20021007.php3?print_mode=1
A: This seems the most complete and updated.
http://kigkonsult.se/index.php
It goes from parsing to generation of .ics files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I import function from .pyx file in python? I'm trying to run Hadoopy, which has a file _main.pyx, and import _main is failing with module not found in __init__.py.
I'm trying to run this on OS X w/ standard python 2.7.
A: You need to make sure you have followed all steps:
*
*Install the Cython package using pip
pip install Cython
*Create a Cython file bbox.pyx
cimport cython
import numpy as np
cimport numpy as np
DTYPE = np.float32
ctypedef np.float32_t DTYPE_t
@cython.boundscheck(False)
def compare_bboxes(
np.ndarray[DTYPE_t, ndim=2] boxes1,
np.ndarray[DTYPE_t, ndim=2] boxes2):
...
*Create setup.py in the same directory
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
package = Extension('bbox', ['bbox.pyx'], include_dirs=[numpy.get_include()])
setup(ext_modules=cythonize([package]))
*Build the Cython
python3 setup.py build_ext --inplace
*Create your main python script run.py in the same directory
import pyximport
pyximport.install(setup_args={"script_args" : ["--verbose"]})
from bbox import compare_bboxes
def main(args):
boxes1 = args.boxes1
boxes2 = args.boxes2
result = compare_bboxes(boxes1, boxes2)
*Run your main script in the same directory
python run.py
A: Add this code before you try to import _main:
import pyximport
pyximport.install()
Note that pyximport is part of Cython, so you'll have to install that if it isn't already.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: content outgrows div 100% I'm currently trying to make a div that is 100% as wide as the whole screen. And I did it by writing the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>100% width</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style type="text/css">
html,body {
padding:0px;
margin:0px;
width:100%;
}
</style>
</head>
<body>
<div style="background-color:yellow;">
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</div>
</body>
</html>
It works fine in normal zoom settings but when I do max zoom in (FireFox 6.0.2) the letters inside the div outgrows the yellow box. Is there a way for the yellow box to extend to the end of the window as well?
Thanks.
A: You can force the really long word to wrap with:
word-wrap: break-word;
in your div style.
Does it really matter what happens at maximum zoom though?
A: Option 1
If you want to keep the text within the yellow box try adding this CSS styling.
div {word-wrap: break-word;}
It will cause the text to go to the next line rather than continue.
Option 2
OR you could try hiding the content that goes past the div border using CSS styling
div {overflow:hidden;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Faster to use individual resource file, or individual files? Is it faster to create an individual resource file like this, containing multiple icons/images: http://static.ak.fbcdn.net/rsrc.php/v1/y7/r/ql9vukDCc4R.png or create multiple files with an individual file in each. It seems like it would be faster with a single file, because you have to only download a file once, but it would take time to adjust the background-position CSS attribute for each class in your CSS file. I am a little lost here, because I see different websites doing different techniques, and I am wondering which would be best.
A: This is called "CSS sprites". As long as the single file is not so huge that it slows down the loading of the site, then it's a good technique to use.
If these are the main UI items for the site, it's worth the time to code them in CSS positons. It doesn't really take that much longer to code and there are few files to deal with.
Example: http://skyje.com/2010/02/css-sprites/
Example: http://coding.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can Jsoup simulate a button press? Can you use Jsoup to submit a search to Google, but instead of sending your request via "Google Search" use "I'm Feeling Lucky"? I would like to capture the name of the site that would be returned.
I see lots of examples of submitting forms, but never a way to specify a specific button to perform the search or form submission.
If Jsoup won't work, what would?
A: I'd try HtmlUnit for navigating trough a site, and JSOUP for scraping
A: According to the HTML source of http://google.com the "I am feeling lucky" button has a name of btnI:
<input value="I'm Feeling Lucky" name="btnI" type="submit" onclick="..." />
So, just adding the btnI parameter to the query string should do (the value doesn't matter):
http://www.google.com/search?hl=en&btnI=1&q=your+search+term
So, this Jsoup should do:
String url = "http://www.google.com/search?hl=en&btnI=1&q=balusc";
Document document = Jsoup.connect(url).get();
System.out.println(document.title());
However, this gave a 403 (Forbidden) error.
Exception in thread "main" java.io.IOException: 403 error loading URL http://www.google.com/search?hl=en&btnI=1&q=balusc
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:387)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:364)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:143)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:132)
at test.Test.main(Test.java:17)
Perhaps Google was sniffing the user agent and discovering it to be Java. So, I changed it:
String url = "http://www.google.com/search?hl=en&btnI=1&q=balusc";
Document document = Jsoup.connect(url).userAgent("Mozilla").get();
System.out.println(document.title());
This yields (as expected):
The BalusC Code
The 403 is however an indication that Google isn't necessarily happy with bots like that. You might get (temporarily) IP-banned when you do this too often.
A: Yes it can, if you are able to figure out how Google search queries are made. But this is not allowed by Google, even if you would success with that. You should use their official API to make automated search queries.
http://code.google.com/intl/en-US/apis/customsearch/v1/overview.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How do I pivot this SQL result? Whats the best way to PIVOT this SQL result? I was wondering if the count(*) can be done as part of the pivot instead of having to group the data prior?
SELECT
e.fullname,
e.BusinessUnit,
COUNT(*) as total
FROM EmpComplaints e
WHERE e.BusinessUnit in ('1-Sales', '2-Tech', '3-Marketing')
GROUP BY e.fullname, e.BusinessUnit
order by e.fullname, e.BusinessUnit
I am basically reporting on each employee the amount of reports they have in each of the three business units: sales, tech, marketing. and looking to get a result that will list fullnames on the left with each name appearing once and each name having a column for ('1-Sales', '2-Tech', '3-Marketing') with a number in it that would be the count(*)
A: Is this MS SQL Server? This might work, sorry, don't have it running, so can't verify:
select fullname,
sum(case BusinessUnit when '1-Sales' then 1 else 0 end) as Sales,
sum(case BusinessUnit when '2-Tech' then 1 else 0 end) as Tech,
sum(case BusinessUnit when '3-Marketing' then 1 else 0 end) as Marketing
FROM EmpComplaints
GROUP BY fullname;
A: Here is how to do it in SQL Server 2005/2008:
SELECT
FullName
,[1-Sales]
,[2-Tech]
,[3-Marketing]
FROM
(
SELECT
e.fullname,
e.BusinessUnit,
COUNT(*) AS Total
FROM EmpComplaints e
WHERE e.BusinessUnit in ('1-Sales', '2-Tech', '3-Marketing')
GROUP BY e.fullname,e.BusinessUnit
) AS bu
PIVOT
(
SUM(Total)
FOR BusinessUnit IN ([1-Sales], [2-Tech], [3-Marketing])
) AS pvt
ORDER by fullname
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JavaScript array.sort() Issue drafting up a quick listing tool to list local kids baseball teams. Takes a couple of inputs and writes to a text field. There's some validation and whatnot too, but that's out of scope and doesn't seem to be impacting things.
Problem is, I'm having trouble figuring out how to "capture" the existing text, add the new inputs and sort the whole lot, before writing the new result to the paragraph element (effectively replacing it).
So far I have:
var LeagueTeams = [];
var IndividualTeam = '';
LeagueTeams.push(document.forms[0].TeamName.value);
LeagueTeams.push(document.getElementById('TeamList')
LeagueTeams = LeagueTeams.sort();
for (j = 0; j < LeagueTeams.length; j++) {
IndividualTeam = LeagueTeams.pop();
IndividualTeam = IndividualTeam + '' + \n;
document.forms[0].TeamName.value += IndividualTeam;
}
What I end up getting is my input, and then an array of my input PLUS the previous contents, with a couple of line breaks. Setting the operator to = instead of =+ stops it from printing to the array at all.
i.e.
Enter: a
Text area: a
Then enter: b
Text area: a ab
(etc)
A: OK, now that we have a better idea of what you're trying to do, here's some code that will do that:
HTML:
<label>Enter Team Name: <input id="newTeam" type="text"></label>
<button id="add">Add</button><br>
All Teams:<br>
<textarea id="allTeams" rows="40" cols="40"></textarea>
Javascript (plain javascript, no framework, called after page is loaded):
var teamList = ["Dodgers", "Mets", "Giants"];
document.getElementById("add").onclick = function() {
var input = document.getElementById("newTeam");
if (input.value) {
teamList.push(input.value);
}
updateTeamList();
input.value = "";
}
function updateTeamList() {
teamList.sort();
var o = document.getElementById("allTeams");
o.value = teamList.join("\n");
}
updateTeamList();
And, you can see it working here: http://jsfiddle.net/jfriend00/HkhsL/
Comments on your existing code:
I'm not sure I understand what you're trying to do overall, but do you realize that this loop is going to have problems:
for (j = 0; j < LeagueTeams.length; j++) {
IndividualTeam = LeagueTeams.pop();
IndividualTeam = IndividualTeam + '' + \n;
document.forms[0].TeamName.value += IndividualTeam;
}
Each time you do LeagueTeams.pop() you are reducing the length of the array and you're continually comparing to LeagueTeams.length in the for loop. This will only get half way through the array because each time through the loop, you increment j and decrement LeagueTeams.length which means you'll only get half way through the array.
If you intend to iterate all the way through the array in your for loop, you should use this version that gets the length once initially and simplifies the code in the loop:
for (j = 0, len = LeagueTeams.length; j < len; j++) {
document.forms[0].TeamName.value += LeagueTeams.pop() + '\n';
}
or perhaps even better, this version that doesn't even use j:
while (LeagueTeams.length > 0) {
document.forms[0].TeamName.value += LeagueTeams.pop() + '\n';
}
Then further, I see that you're trying to use LeagueTeams.sort() on an array that has both strings in it and DOM object references. What are you trying to do with that sort because the built-in sort function does a lexigraphical sort (e.g. alpha) which will do something odd with a DOM reference (probably sort by whatever toString() returns which may be object type)?
If you want to sort the input by team name, then you would need to put both team name and the DOM reference into an object, insert that object into the array as one unit and then use a custom sort function that would sort by the name in the object. As your code is written above, you see to be using document.getElementById('TeamList') which is the same for all teams so I'm not sure why you're putting it into the array at all.
If you can show your HTML and a more complete version of your code, we could help further. What you have above is just a non-working piece of code and we don't know what your HTML looks like that it's trying to operate on.
FYI, there are several syntax errors in the code you posted, so this can't be running code:
*
*Missing paren at the end of this: LeagueTeams.push(document.getElementById('TeamList'))
*Missing quotes around \n: IndividualTeam = IndividualTeam + '' + '\n';
A: If you are just trying to make a list of the teams, try something like:
<script type="text/javascript">
function addTeam(form) {
var para = document.getElementById('teamList');
var teams = para.innerHTML.split(/<br\s*[\\]?>/);
teams.push(form.teamName.value);
para.innerHTML = teams.sort().join('<br>');
}
</script>
<form action="">
<input type="text" name="teamName">
<input type="button" value="Add team" onclick="addTeam(this.form)">
</form>
<p id="teamList"></p>
You may be using different elements or layout, but the strategy should be about the same. If you are making a set of options for a select, things are a little easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need help understanding Assembly interaction with stack Okay, so here's the deal. To my understanding you can do something like such with the stack in assembly:
push 5
push 6
Okay so now we have on the stack: 6
5
so
pop eax
would put 6 into eax correct? However, what if we wished to grab 5 or some value pushed onto the stack before 6 or 5. How would we grab it? (without popping top values off)
I looked at this : How does the stack work in assembly language?
And it seems that you cannot access things based on address in the stack in assembly. However that doesn't seem to make much sense to me. Or is there a way to iterate through the stack without "popping" things off the top. Thanks, sorry for the "silly" question!
A: The stack is a memory location just like any other. The ESP register points to the current top of the stack (the stack grows downward in memory, so a push instruction will decrease the ESP register).
You can access specific values on the stack by indexing from a register:
mov ebp,esp
mov eax,[ebp+4]
(If I remember correctly, you can't use offset addressing modes with ESP directly, but you can with EBP.)
A: The stack pointer (which is manipulated by push and pop) is just a register; esp. You can offset that register to access things relative to the current top of the stack.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook Share button returning error Example url:
http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fwww.rugbydump.com%2F2011%2F09%2F2124%2Frugby-world-cup-daily-tonga-beat-japan&src=sp
That's what's generated by the Share JS. If you visit the link (after decoding):
[...].com/2011/09/2124/rugby-world-cup-daily-tonga-beat-japan
You can view source and see open graph meta tags.
If the share url is changed to:
[...].com%2F2011%2F09%2F2124%2Frugby-world-cup-daily-tonga-beat-japan2&src=sp
(Adding a 2 to the end of the url) the result is fine. Likewise with other posts:
http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fwww.rugbydump.com%2F2011%2F09%2F2119%2Frugby-world-cup-daily-christchurch-revisted&src=sp
So all I'm getting is "Error" with no way of knowing what went wrong.
Any insight would be great. A thought was that the url was flagged or banned by FB but no way to tell.
[...] is used cause I can't use more than 2 urls.
A: I re-linted your URL in the Facebook developer debug page:
http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.rugbydump.com%2F2011%2F09%2F2124%2Frugby-world-cup-daily-tonga-beat-japan%2F
and it appears to work fine now. Facebook caches the data obtained from a page, so it's likely they hit your page during a period in which it had an error message instead of the usual contents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Way to check repeated messages within a string? The messages are exact dont need to worry about variation or simbols in between, right now I am just looking for a efficient way that can check messages like the below.
I have a message like:
string msg = "This is a small message !";
And I would like to check if that message was sent repeated times in the same string like this:
string msg = "This is a small message !This is a small message !";
or:
string msg = "This is a small message !This is a small message !This is a small message !";
or:
string msg = "This is a small message !This is a small message !This is a small message !This is a small message !This is a small message !";
I have a LinkedList<string> that stores the last 3 messages received and along with those last 3 message I would like to match the current messages to see if it is either equal to one of the current store messages or a repetition of any.
foreach (string item in myListOfMessages)
{
if (string.Equals(msg, item))
{
// the message matchs one of the stored messages
}
else if (msg.Lenght == (item.Lenght * 2) && string.Equals(msg, string.Concat(item, "", item)))
{
// the message is a repetition, and ofc only works when some one sends the message twice in the same string
}
}
Like I showed in the examples, the repetition could be quite large, also I am not sure if the method I presented above is the best one for what I need. It was the first idea that came to my mind but soon after I realised that it would produce a lot more work that way.
A: Linq to the rescue:
string msg = "This is a small message !";
string otherMsg = "This is a small message !This is a small message !This is a small message !This is a small message !This is a small message !";
bool isRepeated = Enumerable.Range(0, otherMsg.Length / msg.Length)
.Select(i => otherMsg.Substring(i * msg.Length, msg.Length))
.All( x => x == msg);
This approach basically takes a sub string of the length of the first message and compares each chunk with the original message.
Wrapped in a method with some pre-checking:
public bool IsRepeated(string msg, string otherMsg)
{
if (otherMsg.Length < msg.Length || otherMsg.Length % msg.Length != 0)
return false;
bool isRepeated = Enumerable.Range(0, otherMsg.Length / msg.Length)
.Select(i => otherMsg.Substring(i * msg.Length, msg.Length))
.All(x => x == msg);
return isRepeated;
}
Edit:
Above approach will generate unnecessary strings that will have to be gc'ed - a much more efficient and faster solution:
public bool IsRepeated(string msg, string otherMsg)
{
if (otherMsg.Length < msg.Length || otherMsg.Length % msg.Length != 0)
return false;
for (int i = 0; i < otherMsg.Length; i++)
{
if (otherMsg[i] != msg[i % msg.Length])
return false;
}
return true;
}
A: You could try using a Regular Expression
string msg = "This is a small message !";
string Input = "This is a small message !This is a small message !";
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(msg);
System.Text.RegularExpressions.MatchCollection Matches = r.Matches(Input);
int Count = Matches.Count; //Count = 2
A: private int countRepeats(string msg, string item)
{
if(string.Replace(msg, item).Length > 0)
return 0;
return msg.Length / item.Length;
}
A: static void Main(string[] args)
{
string msg = "This is a small message !This is a small message !This is a small message !";
string substring = "This is a small message !";
string[] split = msg.Split(new string[] { substring }, StringSplitOptions.None);
Console.WriteLine(split.Length - 1);
foreach (string splitPart in split)
{
if (!String.IsNullOrEmpty(splitPart))
Console.WriteLine("Extra info");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there an efficient way to check for an approximate floating point equality in C++?
Possible Duplicate:
Most effective way for float and double comparison
I have a function that calculates distance and then that distance is then later compared to the square root of 2 to see if two items are adjacent on a grid. In Java this works fine, apparently the Math.sqrt(Math.pow(x1-x2,2)....) produces the same as Math.sqrt(2) but in C++ cmath's sqrt(pow(x1-x2,2)...) is not equal.
I cout<<ed the doubles and to the precision shown (I will also output higher precision just to see) they looked equal but didn't evaluate as equal. On the other hand, if I test for values within +- 0.01 of sqrt(2) then this test for "approximate equality" works. Is this what I should do or is something else the matter? Is there some better way of doing this test if this is what I must do?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I try working check_box_tag and mysql but why always insert data to Boolean is null? below is my mysql table define
class CreateStudinfors < ActiveRecord::Migration
def change
create_table :studinfors do |t|
t.string :cname , limit: 45, :null => false
t.string :ename , limit: 45, :null => false
t.date :birthday
t.string :gender , limit: 1, :null => false
t.string :address , limit: 45, :null => false
t.string :telephone , limit: 45, :null => false
t.string :mobile_phone , limit: 45, :null => false
t.string :school , limit: 45, :null => false
t.string :email , limit: 45, :null => false
t.boolean :work
t.boolean :study
t.boolean :travel
t.boolean :lifeplan
t.text :other , :null => false
t.string :sales , limit: 45, :null => false
t.string :introduce , limit: 45, :null => false
t.timestamps
end
end
end
this is my part of my form ..
<div class="field">
<%= f.label :make select %><br />
<%= check_box_tag "work" %>
</div>
any advise? thanks and please
A: Could you please show your form as well? If it is a form for a specific model such as:
<%= form_for @studinfor do |f| %>
<% end %>
Then you need to create the check box like this:
<%= form_for @studinfor do |f| %>
<%= f.checkbox :work %>
<% end %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I build frameworks in Xcode? I'm trying to use the GData framework, so I downloaded it and it came as an Xcode project so I assumed I needed to build it. So I opened it up and and clicked run and it compiled fine, but where do I go to access the .framework it created? I'm new to frameworks and have only been using xcode for a month or two so you'll have to excuse my lack of knowledge about it.
A: The documentation will help you
Anyway, by default the target is GDataUnitTest, just change it to GDataFramework. Once you compile it you will find the framework in the folder of the XCode Project called target.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Not Adding Contents to New Line while writing to a file in Append Mode <?php
if(isset($_POST['submit'])){
$file="get.php";
$open = fopen($file, "a+"); //open the file, (get.php).
fwrite($open, "Name: " .$_POST['user'] . "/n"); //print / write the name.
fwrite($open, "Colour: ". $_POST['color'] . "/n"); //print / write the colour.
fclose($open); //close the opened file
echo "Log File Entry Had Been Made";
}
?>
But The Output is written to get.php as -> /nName: The Name Posted/nColour: Colour Posted/n
Please help if you have time, Thanks All.
A: The character is "\n", not "/n". Just replace that, it'll work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the new version of openssl to display in my phpinfo I updated my version of openSSL tonight but the phpinfo() still shows the old version. I restarted Apache and its still showing the old version. The update shows correctly when I check the version using Putty
A: In order to update OpenSSL within PHP, you will need to recompile PHP. By running the same configure command as before specifying --with-openssl=/usr/include it will link PHP to the upgraded OpenSSL library files. Then restart Apache again and it should be showing the upgraded version. You can try just --with-openssl and if it is in one of the default locations it will work. /usr/include is also common.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: xml resources or sqlite i am making an android application that will use a database. the user won't be able to edit the database, the database will be static most of the times, but i will need to update the database frequently for future releases. It will only contain 1 table but with hundreds or even thousands data.
Which one should i use so that it will be efficient and effective memory-wise ? XML or SQLite ?
Any help will be very appreciated.
P.S. I have read Raw resources versus SQLite database but i decide to make a new question rather than replying to an old question.
A: Go for Sqlite always , File Processing is Costlier than Sqlite. And also Sqlite will be more secure than XML. The Thing that you are trying , I had been gone these kind of issues. There I started with File but at one point of time , FILE IO was making my app very slow because of huge data processing. to Overcome that Issues I used Sqlite. As a result , My app became 10 times faster !
A: If you plan to work with alot of data i would recommend SQLite.
It will allow you to update or alter the database when your app is released without erasing any current information from the user's phone they have in the app.(Very beneficial)
It will also be good for querying with a cursor and pulling information fast.
I would recommend this!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xcode Gives Strange Output From NSArray When I run this code, the output is some 1084848 to the console. I can't figure out why such odd output... here is the code.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
NSLog(@"%i" , [array objectAtIndex:0]);
[pool drain];
return 0;
}
A: the "%i" format specifier expects an integer, not an Object.
Try NSLog(@"%i" , [[array objectAtIndex:0] intValue]);
XCode is probably giving you a warning on this line: something like "Conversion specifies type 'int', but argument has type 'id'".
A: Here's the pseudocode of your program:
//
// Inside of your main function....
//
// Set up the Autorelease pool and then create an array
//
// Declare an int
//
// Add the int to an array, while wrapping it in an NSNumber
//
// Log the value of the first object in the array, using the int formatter
//
// Clean up and return
//
You are logging the first object in the array, but NSArray cannot hold a primitive that's not wrapped in an Objective-C object.
To better understand your code, try changing these lines of code:
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
Expand them a little. Try this:
int someNumber = 3;
NSNumber *aNumber = [NSNumber numberWithInt:someNumber];
[array addObject:aNumber];
So, you've correctly wrapped the int in an NSNumber, but you're not unwrapping it. You need to ask your NSNumber for the int that it holds like so:
[[array objectAtIndex:0] intValue];
Or, to do the logging in one line:
NSLog(@"%i" , [[array objectAtIndex:0] intValue]);
The characters "%i" is called a "formatter". Different kinds of values require different formatters. When you are using an Objective-C object, you use "%@". For an NSInteger or int, you'd use %i. For a float, you'd use "%f". The point is that you need to either unwrap that number, or use the Objective-C formatter for strings.
A quick note about that weird value you were getting earlier: That's a memory address in RAM. It's the closest thing you're going to get when you use an incorrect formatter. In some cases, using the wrong formatter will cause an EXC_BAD_ACCESS. You were "lucky" and got a weird value instead of a dead program. I suggest learning about strings and formatters before you move on. It will make your life a lot easier.
A: When you use %i for integer values then you should give arguments as integer as below
NSLog(@"%i" , [[array objectAtIndex:0] intValue]);
But when you want object to be displayed then you must use %@ which identifies object in general case as below:
NSLog(@"%@", array);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UITableView won't scroll after keyboard is hidden I have a UITableView with custom cells. Based on an answer to this question I am resizing the view when to accommodate the keyboard and resizing when the keyboard is dismissed. After dismissing the keyboard the table view no longer scrolls.
These are the methods called when showing and hiding the keyboard:
-(void)keyboardWillShow:(NSNotification *)note
{
NSDictionary* userInfo = [note userInfo];
NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
if (!keyboardFrameValue) {
keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
}
// Reduce the tableView height by the part of the keyboard that actually covers the tableView
CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
CGRect viewRectAbsolute = [myTableView convertRect:myTableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
CGRect frame = myTableView.frame;
frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
myTableView.frame = frame;
[UIView commitAnimations];
UITableViewCell *textFieldCell = (id)((UITextField *)self.textFieldBeingEdited).superview.superview;
NSIndexPath *textFieldIndexPath = [myTableView indexPathForCell:textFieldCell];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[myTableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
-(void)keyboardWillHide:(NSNotification *)note
{
CGRect keyboardRect = [[[note userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval animationDuration = [[[note userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.myTableView.frame;
frame.size.height += keyboardRect.size.height + 49;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.myTableView.frame = frame;
[UIView commitAnimations];
myTableView.scrollEnabled = YES;
}
Any ideas what I am missing?
A: I've used the same question you link to to solve the same problem. It's been working great for me although I don't remember how much of the original code I ended up using.
For your problem, (though I imagine you've tried this) the first thing that comes to mind is to look in your code to see if your doing
self.tableView.scrollEnabled = NO;
and if so you should verify that you have a corresponding statement somewhere sets it back to YES; in fact you might set scrollEnabled to YES in keyboardWillHide just to test if that helps.
A: The problematic line is:
frame.size.height += keyboardRect.size.height + 49;
it should be:
frame.size.height += keyboardRect.size.height - self.navigationController.toolbar.frame.size.height;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I use Keymando To Bind Things With MonoDevelop? I'm working with the lovely Keymando and also with MonoDevelop, but I couldn't figure out how to use the bindings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Form Alignment CSS This is one thing that I really hate within development is forms. Below is my code and what I am trying to do is align the inputs with the labels Name: input. Is there a rule that you use to help remember when coding forms?
CSS:
#newwebsiteForm form{
padding:10px;
margin:10px 0;
width:480px;
position: relative;
}
#newwebsiteForm label{
width:240px;
display:block;
float:right;
}
#newwebsiteForm input{
width:240px;
display:block;
float:left;
}
HTML:
<section id="content">
<h1>Free Quote</h1>
<p>Please fill out the below questionnaire to receive your free web development quote</p>
<form action="" method="post" accept-charset="utf-8">
<select name="requiredOption" id="requiredOption">
<option id="pleaseselect" value="pleaseselect">Please Select Your Required Quote</option>
<option id="newwebsite" value="newwebsite">New Website</option>
<option id="websiteredevelopment" value="websiteredevelopment">Website Redevelopment</option>
<option id="other" value="other">Other</option>
</select>
</form>
<div id="newwebsiteSection">
<form action="" id="newwebsiteForm" method="get" accept-charset="utf-8">
<fieldset>
<label>Do You Require Hosting?</label><input type="radio" name="Yes" value="Yes">Yes</input><input type="radio" name="No" value="No">No</input>
<label>Do You Require A Domain?</label><input type="radio" name="Yes" value="Yes">Yes</input><input type="radio" name="No" value="No">No</input>
<label>Do You Have A Logo?</label><input type="radio" name="Yes" value="Yes">Yes</input><input type="radio" name="No" value="No">No</input>
<label>What is your Domain?</label>
<input type="url" name="domain" value="http://example.com"></input></div>
<label>Type of site Required?<label>
<select name="newwebsiteType" id="newwebsiteType">
<option value="shoppingCart">Shopping Cart</option>
<option value="CMS">Content Management System</option>
<option value="static">Static Website</option>
<option value="otherDevelopment">Other Development</option>
</select>
<label>Do You Require A Design?</label>
<input type="radio" name="Yes" value="Yes">Yes</input><input type="radio" name="No" value="No">No</input>
<label>Three Favorite colors?</label>
<input name="color1" value=""></input>
<input name="color2" value=""></input>
<input name="color3" value=""></input>
<label>What are your favorite websites?</label>
<input type="text" name="fav1" value=""></input>
<input type="text" name="fav2" value=""></input>
<input type="text" name="fav3" value=""></input>
<label>Comments?</label>
<textarea name="comments" id="comments"></textarea>
<input type="submit" name="submit" value="Send Quote Request">
</form>
</div>
<div id="websiteredevelopmentSection">
<p>Website Redevelopment</p>
</div>
<div id="otherSection">
<p>Other</p>
</div>
</section>
A: Just because tables are the easier option doesn't make using them right.
Here's a great article about css form design.
http://www.alistapart.com/articles/prettyaccessibleforms
The author suggests storing each label/input element in an ordered list element keeping them grouped.
I've just used this to implement a bunch of forms for various mini sites and it worked a treat!
You can align the label next to the input or above just by changing the ol li label element's display property from display:inline-block to display:block respectively.
Getting the text to align next to a radio button or checkbox can be a bit tricky but is possible by adding and styling a span element.
BEST OF ALL IT'S CROSS BROWSER COMPATIBLE!
Hope that helps.
A: You have to use the label element as follows to correctly align them:
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
A: I wrap each input/label pair in a <div>. This helps a lot with styling.
<div class="form-item">
<label for="first_name">First Name</label>
<input type="text" name="first_name" id="first_name" />
</div>
A: This is probably related to the question: <div> usage correctly? Can't get the columns to line up: You can also check my comments there for some reference when dealing with semantically-correct forms.
The approach you will need to be in habit of is always structure your markup correctly first before jumping to any CSS (or styling).
A <form> is composed of the following:
*
*The <form> itself.
*The <fieldset>: acts a the container of the different sections of your <form>
*The <legend>: acts as the heading of the <fieldset>
*The <input />: for fields, checkboxes, radio buttons, and submit button
*The <button>: an alternative for <input type="submit">, which can wrap something
inside of it.
*The <select>: a list of values inside a drop-down menu.
*The <label>: from the name itself, the label of the <input />, <button> and <select>
To illustrate, you can check this example:
<form>
<fieldset>
<legend>Form Heading: </legend>
<fieldset>
<legend>Group 1 Heading: </legend>
<label for="input-id">Input Label: </label>
<input id="input-id" />
</fieldset>
<fieldset>
<legend>Group 2 Heading: </legend>
<label for="select-id">Select Label: </label>
<select id="select-id">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</fieldset>
<input type="submit" value="Submit" />
</fieldset>
</form>
With the exception of radio (<input type="radio" />) and checkboxes (<input type="checkbox" />), where the <label> should come after the <input />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get information about the current page of a paginated post in Wordpress? Any suggestions on how I might get the word count of the current page of a paginated post in Wordpress? And in general, how to get information about only the current page of a paginated post (paginated using "").
I've made a wordcount function based on this helpful blog post: http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/how-to-display-word-count-of-wordpress-posts-without-a-plugin/ but that gets me the total word count for the entire post, not the count for the current page only.
Thanks much for your help!
A: Use $wp_query to access the post's content and the current page number, then split the post's content into the pages using PHP's explode(), strip all HTML-tags from the content using strip_tags(), because they don't count as words and finally count the words of just the current page with str_word_count().
function paginated_post_word_count() {
global $wp_query;
// $wp_query->post->post_content is only available during the loop
if( empty( $wp_query->post ) )
return;
// Split the current post's content into an array with the content of each page as an item
$post_pages = explode( "<!--nextpage-->", $wp_query->post->post_content );
// Determine the current page; because the array $post_pages starts with index 0, but pages
// start with 1, we need to subtract 1
$current_page = ( isset( $wp_query->query_vars['page'] ) ? $wp_query->query_vars['page'] : 1 ) - 1;
// Count the words of the current post
$word_count = str_word_count( strip_tags( $post_pages[$current_page] ) );
return $word_count;
}
A: You will have to count words of all the posts on the page. Assuming this is inside the loop, you can define a global variable initialized to zero and then count the words displayed in each post using the method suggested in the link you have posted.
Something on this lines -
$word_count = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post();
global $word_count;
$word_count += str_word_count(strip_tags($post->post_excerpt), 0, ' ');
endwhile;
endif;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: inserting char arrays in buttons I'm trying to put the alphabet in different buttons, but I cant make it work. My code looks like this:
char[] Letter = {'a','b','c','d','e','f','g','h'
,'i','j','k','l','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z'};
Button[] But;
for (int i = 0; i <= 26; ++i) {
But = new Button(Letter[i]);
this.add(But[i], BorderLayout.SOUTH);
}
A: char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(char c : letters) add(new JButton(new String(c)));
A: This should work for you. Its convention in Java to name variables starting with a lower case letter.
char[] letters = {'a','b','c','d','e','f','g','h'
,'i','j','k','l','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z'};
Button[] buttons = new Button[26];
for(int i = 0;i< 26;++i){
buttons[i] = new Button(Character.toString(letters[i])); //need to convert char to String first
this.add(buttons[i],BorderLayout.SOUTH);
}
A: You probably wanted this
But[i] = new Button(Letter[i]);
instead of this
But = new Button(Letter[i]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Linux VAS Management Where in the line of code which alternates between virtual address spaces (vas) in the Linux kernel? I know Linux describes the vas with struct mm_struct, but can't find the actual code.
A: Although I do not possess in-depth knowledge about the Linux kernel, I think looking at code in mm/memory.c ( http://lxr.linux.no/linux+v3.0.4/mm/memory.c ) could provide you some pointers for what you are looking for. LDT mentioned by @Ignacio Vazquez-Abrams is specifically for x86's Local Descriptor Table the code for which is present in arch/x86/kernel/ldt.c. Browsing through the source will be the best option to learn more I guess.
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inheritance in C++ EDIT 2:
Here is a simple summary of what I want to do (I think):
I want to dynamically create global instances based on conditions that are calculated at run time.
You can skip to EDIT1 if you'd like to take a look at sample code, but at this point, the above bolded-text is probably the easiest to understand...
END EDIT 2.
My question is about polymorphism and inheritance. Specifically, I want to know if there is a way I could inherit functions and pointers from another class.
I have a class called Globals which contains various pointers to objects to other classes as well as various functions. Instead of copy/pasting code, I'll write up a simple example:
(I've removed header guards for simplicity and cleanliness)
The following is my globals.h and globals.cpp, respectively:
// Example of globals.h
#include <iostream>
#include <cstdio>
using namespace std;
class Globals {
public:
Globals ();
virtual ~Globals ();
void function1(char*);
void function2();
class Input *input;
class Error *error;
};
// Example of globals.cpp
#include "globals.h"
Globals::Globals()
{
input = new Input();
error = new Error();
}
void Globals::function1(char*nm)
{
cout << nm << endl;
}
Now, in my code for my Input class, say I want to use the function1(char*) method, would this be possible without passing an object to the Input class? What I mean by this is that I currently have my Input class being passed a *globals object, so then I could call the function like so: globals->function2();. But this can get very messy if I have a lot of functions within different classes. Additionally, is there a way I could use the Error pointer to object initialized in Globals? If Error had a function called error_func(), how could I be able to call it like so: error->error_func() from within my Input functions?
Thanks, and I apologize if I were too confusing in my question. I'll be happy to elaborate if needed.
Amit
EDIT 1: Added a simplified code to present what I want to do in a clearer way
// Example of globals.h
#include <iostream>
#include <cstdio>
#include "input.h"
#include "error.h"
using namespace std;
class Globals {
public:
Globals ();
virtual ~Globals ();
class Input *input;
class Error *error;
};
// Example of globals.cpp
#include "globals.h"
Globals::Globals()
{
input = new Input();
error = new Error();
}
// Example of input.h
#include "globals.h"
class Input {
public:
Input();
virtual ~Input();
}
// Example of input.cpp
#include "globals.h"
Input::Input()
{
error->print("Hello\n"); // <-- THIS is really what I want to accomplish (without being sent a globals object and say globals->error->print();
}
// Example of error.h
#include "globals.h"
class Error {
public:
Error() { }
virtual ~Error() { }
void print(char*);
}
// Example of error.cpp
#include "globals.h"
Error::print(char* nm)
{
cout << nm << endl;
}
A: If I'm understanding your question right, functions are automatically "inherited", at least for the purposes you need.
For example, your global class has two methods, function1(char*) and function2(). If you make a class:
class Descendent
: public Global
{ };
int main()
{
Global * global = new Global();
Global * desc = new Descendant();
char * str = "string";
// These two will run the same function:
global->function1(str);
desc->function1(str);
}
To prevent that (functions being called based on the current type), you must use virtual, like:
class Global
{
virtual void function1(char *);
};
class Descendant
{
virtual void function1(char *);
};
int main()
{
Global * global = new Global();
Global * desc = new Descendant();
char * str = "string";
// These two will NOT run the same function:
global->function1(str);
desc->function1(str);
}
Now, I'm not entirely sure, but the singleton idiom may be of use here, depending on just how global your Global is. In that case, you would have a global like:
class Global
{
static Global * GetSingleton()
{
if (!Global::m_Instance) Global::m_Instance = new Global();
return Global::m_Instance;
}
void function1(char *);
static Global * m_Instance;
};
class Descendant
{
void function1(char *)
{
Global * global = Global::GetGetSingleton();
// ...
}
};
There are a variety of ways to work with globals and functions being needed between classes. One of these may be it, depending on what exactly you're doing. If not, I'll try to edit and suggest one that does work.
A: Updated response:
Its sounds like what you want is actually the Factory pattern. I'm going to use logging as an example, where I assume that in one configuration you want to log and in another you might not want to:
// logger_interface.h
class LoggerInterface {
public:
virtual ~LoggerInterface() {}
virtual void Log(const string& message) = 0;
protected:
LoggerInterface() {}
};
The first step is to create a pure virtual interface representing the behavior that is configurable as in the example above. We will then create a factory function that can construct one based on configuration:
// logger_factory.h
LoggerInterface* CreateLogger(LoggerOptions options);
When implementing the factory, we keep the different implementations hidden:
// logger_factory.cc
class DoNotLogLogger : public LoggerInterface {
public:
DoNotLogLogger() {}
virtual ~DoNotLogLogger() {}
virtual void Log(const string& message) {}
};
class LogToStdErrLogger : public LoggerInterface {
public:
LogToStdErrLogger() {}
virtual ~LogToStdErrLogger() {}
virtual void Log(const string& message) {
std::cout << message << std::endl;
}
};
LoggerInterface* CreateLogger(LoggerOptions options) {
if (options.IsLoggingEnabled() && options.ShouldLogToStdErr()) {
return new LogToStdErrLogger;
}
return new DoNotLogLogger;
}
There is no reason why the object that you create dynamically in this way needs to be global; in fact, making it global is a really bad idea. Just create it where you need it, and pass it as a parameter to the functions that need it.
Original response:
Inheritance isn't the word you are looking for. Basically, what you are asking for is a static function:
class ClassName {
public:
static void methodName();
};
In the above, methodName can be invoked using ClassName::methodName() without requiring a specific instance of the class named ClassName. However, if you are to do this, it is more consistent with C++ style conventions to make it a freestanding function in a namespace like:
namespace name_of_namespace {
void functionName();
}
The above is invoked using name_of_namespace::functionName() as in the previous example, except with the benefit that it is easier to change or remove the prefix (e.g. via a using directive).
NOTE: from a design standpoint, you should only use a freestanding or static function if it does not rely on any state (other than the parameters passed to it) and there is no possibility of alternative implementations. As soon as there is state or alternative implementations, you really should pass around an object encapsulating this state, even if it is a pain to do, since passing around the object makes it easier to configure, makes it easier to mock-out in tests, and avoids threading issues.
A: I'm imagining you have a situation like this:
struct A {
void f();
};
struct B {
void g();
};
struct C : virtual A, virtual B {
C(A *ap, B *bp)
: A(ap), B(bp) // This doesn't actually work -- theoretical
{
}
void h()
{
f(); // calls A::f()
g(); // calls B::g();
}
};
Normally, when you create a C, you would be creating new As and Bs, but you would like to re-use existing ones instead, but still treat it like inheritance so that you don't have to explicitly specify which object to call.
Unfortunately, C++ doesn't support this. There are a couple of options:
You can make proxy classes that defer the function calls:
struct AProxy {
AProxy(A *ap) : a(*ap) { }
void f() { a.f(); }
A &a;
};
struct BProxy {
BProxy(B *bp) : b(*bp) { }
void g() { b.g(); }
B &b;
};
struct C : AProxy, BProxy {
C(A *ap,B *bp) : AProxy(ap), BProxy(bp) { }
void h()
{
f(); // calls AProxy::f() which calls a.f()
g(); // calls BProxy::g() which calls b.g()
}
};
This may help if you are using A's and B's in lots of different places.
If instead, you don't have many classes, but lots of calls to f() and g(), you might just do this:
struct C {
C(A *ap,B *bp) : a(*ap), b(*bp) { }
void f() { a.f(); }
void g() { b.g(); }
void h1()
{
f(); // well at least the call is clean here
g();
}
void h2()
{
f(); // and clean here
g();
}
A &a;
B &b;
};
If you don't have either of these cases, then just using the proper object each time like you were doing may be best.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET MVC Model Binder returns null object I am having a problem where everytime I post a form back to the [HttpPost] version of my controller action, the ModelBinder returns a null object. I can't work out why. If I change the signature to use a FormCollection instead I can see that all the correct keys have been set. Can someone help me pin point what's wrong here, because I can't spot it.
Here are the models for working with my views
public class DeviceModel
{
public int Id { get; set; }
[Required]
[Display(Name = "Manufacturer")]
public int ManufacturerId { get; set; }
[Required]
[Display(Name = "Model")]
[StringLength(20)]
public string Model { get; set; }
[StringLength(50)]
[Display(Name = "Name")]
public string Name { get; set; }
[StringLength(50)]
[Display(Name = "CodeName")]
public string CodeName { get; set; }
public int? ImageId { get; set; }
}
public class DeviceCreateViewModel : DeviceModel
{
public IEnumerable<SelectListItem> Manufacturers { get; set; }
}
Which I use in my controller like so:
public ActionResult Create()
{
DeviceCreateViewModel viewModel = new DeviceCreateViewModel()
{
Manufacturers = ManufacturerHelper.GetSortedManufacturersDropDownList()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(DeviceModel model)
{
// if I check model here it is NULL
return View();
}
And the view looks like this:
@model TMDM.Models.DeviceCreateViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.ManufacturerId)
</div>
<div class="editor-field">
@Html.DropDownList("ManufacturerId", Model.Manufacturers)
@Html.ValidationMessageFor(model => model.ManufacturerId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CodeName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CodeName)
@Html.ValidationMessageFor(model => model.CodeName)
</div>
<p>
<input type="submit" value="Save" class="medium green awesome" />
@Html.ActionLink("Cancel", "Index", "Device", null, new { @class="medium black awesome" })
</p>
</fieldset> }
A: The problem is that there is a name collision between the property named Model in the class DeviceModel and the variable named model in the Create action. The name collision causes the DefaultModelBinder to fail, since it tries to bind the Model property to the DeviceModel class.
Change the name of the variable in the Create action to deviceModel and it will bind correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: I don't understand the width field in pprint in python I don't understand this concept clearly.
Could somebody give me some examples to demonstrate the concept for width in pprint in python?
A: Basically it tries to limit your output to a specific width.
Here's an example:
import pprint
stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
pp = pprint.PrettyPrinter(width=80)
pp.pprint(stuff)
result is:
['spam', 'eggs', 'lumberjack', 'knights', 'ni']
but if you do the same thing but change the width(say to 10):
import pprint
stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
pp = pprint.PrettyPrinter(width=10)
pp.pprint(stuff)
you get:
['spam',
'eggs',
'lumberjack',
'knights',
'ni']
This is a modified example from the python docs ( http://docs.python.org/library/pprint.html ). For things like this, I find it easier to just open the python interrupter and play around and see how the commands react to what you enter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can i adjust the height of the day view in FullCalendar? I am trying to restyle a instance of FullCalendar so that the day and week views run the entire height of the web page. i.e. I do not want a scrollbar to view the entire day. I tried removing overflow and the fixed height but that doesn’t work.
Is it possible to do this?
A: You can change the slotMinutes when creating the chart http://arshaw.com/fullcalendar/docs/agenda/slotMinutes/
and then you can adjust the content height to fit it all in there with this
http://arshaw.com/fullcalendar/docs/display/contentHeight/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to make a submodule via module pattern I was reading about JavaScript Module pattern. My Question is how do I make submodules with it, i.e how can I inherit from it, say I have this class
var MODULE = (function () {
my = function(){
this.params = ""
},
privateVariable = 1;
my.prototype.moduleMethod = function () {
console.log("mod");
};
return my;
}());
How do I make a child class of it with properties inherited from parent? How can I do the same with module pattern?
A: The module pattern is not a class pattern. You cannot simply pretend you now have classes in JavaScript. As for inheritance, if you really need to inherit stuff, you should make an object via constructor function and use prototypal inheritance, although it's sometimes slower to execute.
As for creating a submodule it's simple
MODULE.submodule = (function(){
// another module stuff that can even reference MODULE
return { submodule: 'property' }
})();
Now, as for subclassing in the classical sense, you can simulate it on objects with prototypes, like Douglas Crockford does http://www.crockford.com/javascript/inheritance.html
For simulating it with modules, you can try by creating a seal/unseal functions inside the original module and use them in your submodules. You can check here http://www.pallavlaskar.com/javascript-module-pattern-in-details/
for the
Cloning and Inheritance
var MODULE_TWO = (function (old) {
var my = {},
key;
for (key in old) {
if (old.hasOwnProperty(key)) {
my[key] = old[key];
}
}
var super_moduleMethod = old.moduleMethod;
my.moduleMethod = function () {
// override method on the clone, access to super through super_moduleMethod
};
return my;
}(MODULE))
or the
Cross-File Private State
var MODULE = (function (my) {
var _private = my._private = my._private || {},
_seal = my._seal = my._seal || function () {
delete my._private;
delete my._seal;
delete my._unseal;
},
_unseal = my._unseal = my._unseal || function () {
my._private = _private;
my._seal = _seal;
my._unseal = _unseal;
};
// permanent access to _private, _seal, and _unseal
return my;
}(MODULE || {}));
A: > var MODULE = (function () {
> my = function(){
If my is not declared with var, it becomes global when the function executes. Also, by convention constructors have names starting with a capital letter, so:
var My = function(){
but you may as well just declare the function and be done with it:
function My() {
.
> this.params = ""
> },
> privateVariable = 1;
>
> my.prototype.moduleMethod = function () {
> console.log("mod");
> };
If you are just implementing prototype inheritance, why use the module pattern at all?
>
> return my; }());
The module pattern is not meant for inheritance but to create "modules" of functionality and emulate public, priveleged and private members to some extent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Device Motion in accelerated environment I wrote an app which displays pitch and roll attitude (a glass cockpit app). When I rotate or tilt the iPhone/iPad the attitude is displayed accurately. When I'm flying in an airplane and rotate or tilt the device it also displays accurately. Now, when I hold the device against the panel and roll the airplane, the attitude does not change accurately - it doesn't move at all. This is strange behavior to me and I wonder if it has something to do with the accelerations of the airplane affecting the output of the gyro in the device.
Any insight is appreciated.
A: Randy, a roll is a one-G maneuver, right? So there is no acceleration for the accelerometer in the phone to sense.
Watch Bob Hoover roll his Shrike while pouring a glass of iced tea from a pitcher.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Objective-C sparse array redux First off, I've seen this, but it doesn't quite seem to suit my needs.
I've got a situation where I need a sparse array. Some situations where I could have, say 3000 potential entries with only 20 allocated, other situations where I could have most or all of the 3000 allocated. Using an NSMutableDictionary (with NSString representations of the integer index values) would appear to work well for the first case, but would seemingly be inefficient for the second, both in storage and lookup speed. Using an NSMutableArray with NSNull objects for the empty entries would work fairly well for the second case, but it seems a bit wasteful (and it could produce an annoying delay at the UI) to insert most of 3000 NSNull entries for the first case.
The referenced article mentions using an NSMapTable, since it supposedly allows integer keys, but apparently that class is not available on iPhone (and I'm not sure I like having an object that doesn't retain, either).
So, is there another option?
Added 9/22
I've been looking at a custom class that embeds an NSMutableSet, with set entries consisting of a custom class with integer (ie, element#) and element pointer, and written to mimic an NSMutableArray in terms of adds/updates/finds (but not inserts/removals). This seems to be the most reasonable approach.
A: A NSMutableDictionary probably will not be slow, dictionaries generally use hashing and are rather fast, bench mark.
Another option is a C array of pointers. Allocation a large array only allocates virtual memory until the real memory is accessed (cure calloc, not malloc, memset). The downside is that memory is allocated in 4KB pages which can be wasteful for small numbers of entries, for large numbers of entries many may fall in the same page.
A: What about CFDictionary (or actually CFMutableDictionary)? In the documentation, it says that you can use any C data type as a key, so perhaps that would be closer to what you need?
A: I've got the custom class going and it works pretty well so far. It's 322 lines of code in the h+m files, including the inner class stuff, a lot of blank lines, comments, description formatter (currently giving me more trouble than anything else) and some LRU management code unrelated to the basic concept. Performance-wise it seems to be working faster than another scheme I had that only allowed "sparseness" on the tail end, presumably because I was able to eliminate a lot of special-case logic.
One nice thing about the approach was that I could make much of the API identical to NSMutableArray, so I only needed to change maybe 25% of the lines that somehow reference the class.
A: I also needed a sparse array and have put mine on git hub.
If you need a sparse array feel free to grab https://github.com/LavaSlider/DSSparseArray
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: possible assignment in condition (C) I have to find is the number "a" a two-digit odd. Mistake comes on if
#include <stdio.h>
main ()
{
int a,k;
int count=0;
printf ("input number \n", a);
scanf ("%d", &a);
k = a % 2;
while (a)
{
a /= 10;
count ++;
}
if (k = 1 && count = 2)
printf ("It is \n");
else
printf ("It is not \n");
return (0);
}
A: The error is here:
if (k = 1 && count = 2)
you probably meant:
if (k == 1 && count == 2)
= is an assignment. == is a comparison for equality.
Also, the loop is not necessary. You can check if the number is two digits by checking if it's less than 100 and greater than or equal to 10.
A: GCC is complaining about this:
if (k = 1 && count = 2)
The equality operator is a double equals sign: ==. What you've used, the single equals sign =, is the assignment operator.
You are setting k to 1 and count to 2, and that if will always be executed.
The message you're getting is designed to help people quickly catch exactly this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can't render jquery.ui.tabs with LAB.js I have taken the default tab demo from jQuery-UI. I have only changed two things:
*
*I am loading all js scripts via LAB.js.
*I am calling $("#tabs").tabs() within .wait().
No errors are thrown. Everything is loading BUT the tabs do not render. Why?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Tabs - Default functionality</title>
<link rel="stylesheet" href="jslib/jquery-ui-1.8.16/development-bundle/demos/tabs/../demos.css">
</head>
<body>
<div class="demo">
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>
</div><!-- End demo -->
<div class="demo-description">
<p>Click tabs to swap between content that is broken into logical sections.</p>
</div><!-- End demo-description -->
<script src="jslib/LAB-min.js"></script>
<script type="text/javascript">
$LAB
.script('jslib/jquery-1.6.4.min.js')
.script('jslib/jquery-ui-1.8.16/js/jquery-ui-1.8.16.custom.min.js')
.script('jslib/jquery-ui-1.8.16/development-bundle/demos/tabs/../../ui/jquery.ui.core.js')
.script('jslib/jquery-ui-1.8.16/development-bundle/demos/tabs/../../ui/jquery.ui.widget.js')
.script('jslib/jquery-ui-1.8.16/development-bundle/demos/tabs/../../ui/jquery.ui.tabs.js')
.wait(function () {
$( "#tabs" ).tabs();
});
</script>
</body>
</html>
A: my bad, I din't include jquery.ui.all.css - it is rendering as expected now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Store UUID in sqlite manager I am a newbie here. I am trying to generate UUIDs using the following code..
- (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
//CFUUIDBytes number = CFUUIDGetUUIDBytes (theUUID);
DLog(@"Howwww :%@", theUUID);
CFRelease(theUUID);
return [(NSString *)string autorelease];
}
I am getting the result in a string as..
NSString *result = [self GetUUID];
Now the problem is I am unable to store it inside my sqlite database. I am trying to store it in a VARCHAR column using the statement
sqlite3_bind_text(compiledStatement, 10, [_idNumber UTF8String], -1, SQLITE_TRANSIENT);
Please can anyone help me out here. Thanks..
A: Here is a method that return the UUID as a NSString, just save it in the db as a string.
- (NSString *)newUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (NSString *)string;
}
If you need a c string:
NSString *uuidString = [self newUUID];
const char *uuidCString = [uuidString cStringUsingEncoding:NSASCIIStringEncoding];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cartesian join of two arrays I am trying to use a for next loop to iterate through the arrays and combine its strings
I can only get the first array. Don't know how to code to combine with the second one and create the third array using VB.NET. could you help please?
ex:
arrLetters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I"}
arrNumbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9"}
resulting array(81) = {A1, A2 ...A9, B1, B2...B9, ...I9}
A: In C# it would be:
from letter in arrLetters
from number in arrNumbers
select letter + number
In VB, with the result going in to an array variable:
Dim array = (From letter In arrLetters
From number In arrNumbers
Select letter + number).ToArray()
A: Use below logic (In C#)
var arrLetters= new string[] {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
var arrNumbers = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var array = arrLetters.Zip(arrNumbers, (letter, word) => letter + word);
Hope this helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Php report generation I would like to generate report from my php which now I have only the html version. Can any one suggest me good tools to generate excel and pdf based tool at minimum? Thank you.
A: for excel you can generate .csv file
try this one
Create a CSV File for a user in PHP
and for PDF read this
http://www.sitepoint.com/generate-pdfs-php/
A: you can use birt-viewer reports tool generate the reports to any lanuage php/java and its open source
http://www.eclipse.org/birt/phoenix/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android random NullPointerException on EditText For a Settings class and associated XML page, I receive NullPointerExeceptions about 50% of the time it is accessed. A typical session attempts to Load the current settings shortly after startup. The user can the proceed to fill out an order, review past orders, or update/view current settings.
Sometimes the settings don't load and other times they won't save.
Loading:
((EditText) parent.findViewById(R.id.txtCompanyName))
.append(companyName);
Saving:
companyName = ((EditText) parent.findViewById(R.id.txtCompanyName))
.getText().toString();
These are the first lines of their respective functions. I am uncertain why they would raise this Exception (mostly the saving function). As near as I can tell, the loading function may be called before the View is fully loaded, however, the save function can only occur after the the View IS fully loaded (it saves on a android:onClick for a Button).
A: What i would recommend to you is use a SharedPreference to save a persistant state of the user's settings.
This would be a better more efficient way.
And if there isnt anything in the SharedPreference it will never return null unless you set it to do so.
Let me know if you need an example of this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: error: function returning a function Although there is at least one similar question, I still ask mine since that one hasn't got solved and seems more complicated. I'm trying to simplify mine.
I have a .cpp file that uses .h as below, and compiling these sheds error as follows. Any idea is appreciated. Note that codes are simplified in order to minimally show the problematic parts only.
FC_boost_prove.h:
#ifndef FC_H
#define FC_H
#include <vector>
#include "iostream"
#include "boost/signal.hpp"
#include "boost/bind.hpp"
#include <boost/random.hpp>
typedef boost::signal0<void()> PreUpdateSignal;
typedef PreUpdateSignal::slot_function_type PreUpdateSlot;
typedef boost::signal0<void()> PostUpdateSignal;
typedef PostUpdateSignal::slot_function_type PostUpdateSlot;
class FC {
public:
FC(uint width, uint height) {
std::cout << "In constructor." << std::endl;
}
~FC() {
//Do ...
}
void connectPreUpdate(PreUpdateSlot s) {
preUpdateSignal_.connect(s);
}
void connectPostUpdate(PostUpdateSlot s) {
postUpdateSignal_.connect(s);
}
protected:
PreUpdateSignal preUpdateSignal_;
PostUpdateSignal postUpdateSignal_;
};
#endif
FC_boost_prove.cpp:
#include <iostream>
#include <string>
#include "FC_boost_prove.h"
int main() {
std::cout << "test." << std::endl;
}
Compile error:
$ g++ FC_boost_prove.cpp
In file included from /usr/include/boost/signals/signal_template.hpp:22,
from /usr/include/boost/signals/signal0.hpp:24,
from /usr/include/boost/signal.hpp:19,
from FC_boost_prove.h:7,
from FC_boost_prove.cpp:3:
/usr/include/boost/last_value.hpp: In instantiation of ‘boost::last_value<void()>’:
/usr/include/boost/signals/signal_template.hpp:178: instantiated from ‘boost::signal0<void(), boost::last_value<void()>, int, std::less<int>, boost::function0<void()> >’
FC_boost_prove.h:12: instantiated from here
/usr/include/boost/last_value.hpp:22: error: function returning a function
In file included from /usr/include/boost/signals/signal0.hpp:24,
from /usr/include/boost/signal.hpp:19,
from FC_boost_prove.h:7,
from FC_boost_prove.cpp:3:
/usr/include/boost/signals/signal_template.hpp: In instantiation of ‘boost::signal0<void(), boost::last_value<void()>, int, std::less<int>, boost::function0<void()> >’:
FC_boost_prove.h:12: instantiated from here
/usr/include/boost/signals/signal_template.hpp:330: error: function returning a function
/usr/include/boost/signals/signal_template.hpp:370: error: function returning a function
In file included from /usr/include/boost/function/detail/maybe_include.hpp:13,
from /usr/include/boost/function/function0.hpp:11,
from /usr/include/boost/signals/signal_template.hpp:38,
from /usr/include/boost/signals/signal0.hpp:24,
from /usr/include/boost/signal.hpp:19,
from FC_boost_prove.h:7,
from FC_boost_prove.cpp:3:
/usr/include/boost/function/function_template.hpp: In instantiation of ‘boost::function0<void()>’:
FC_boost_prove.h:24: instantiated from here
/usr/include/boost/function/function_template.hpp:1006: error: function returning a function
/usr/include/boost/function/function_template.hpp: In instantiation of ‘boost::detail::function::basic_vtable0<void()>’:
/usr/include/boost/function/function_template.hpp:856: instantiated from ‘void boost::function0<R>::clear() [with R = void()]’
/usr/include/boost/function/function_template.hpp:752: instantiated from ‘boost::function0<R>::~function0() [with R = void()]’
/usr/include/boost/signals/slot.hpp:105: instantiated from here
/usr/include/boost/function/function_template.hpp:486: error: function returning a function
/usr/include/boost/function/function_template.hpp:643: error: function returning a function
Environment: Ubuntu 10.10, g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
A: Why are you specifying boost::signal0<>? The signalN templates are for deficient compilers that can't properly parse function signatures.
Either use signal and specify the function signature, as recommended for modern compilers:
typedef boost::signal<void()> PreUpdateSignal;
typedef boost::signal<void()> PostUpdateSignal;
or use signalN and specify the return type (and every argument type) explicitly, as needed for deficient compilers:
typedef boost::signal0<void> PreUpdateSignal;
typedef boost::signal0<void> PostUpdateSignal;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make reference to a parent object property in the cloned object in PHP 5.3? I want to do this:
class T
{
public $a;
public $b;
public function __construct()
{
$this->a = new P;
$this->b = clone $this->a;
}
}
class P
{
public $name ="Chandler";
public function __clone()
{
$this->name = & $that->name;
}
}
$tour = new T;
$tour->a->name = "Muriel";
?>
But after this, $tour->b->name will be NULL, why ?
How can I make the clone name property reference to the parent object name property, so when I change the parent object name, the cloned object name will change accordingly ?
A: From the php.net cloning manual page,
When an object is cloned, PHP 5 will perform a shallow copy of all of
the object's properties. Any properties that are references to other
variables, will remain references.
but $name is a scalar variable (a string) and not an object. So when you clone $a to $b, $a->name and $b->name are distinct variables. ie) $b->name does not reference $a->name
In short, I do not believe that it is possible (please correct me if I am wrong). However, you could cheat and do something like:
class P
{
public $name;
public function __construct(){
$this->name = new StdClass();
$this->name->text = 'Chandler';
}
}
Then $a->name->text = 'Muriel'; will also change $b->name->text.
A: $that doesn't exist in the __clone function as said in George Schlossnagle: Advanced PHP Programming book... It gave me a couple of weeks headache...
So, you can do this with a simple trick in the constructor (in class P); make the variable reference to himself:
function __construct()
{
$this->name = & $this->name;
}
this works in PHP 5.3.6. I did not test it in other versions.
So when you do $tour->a->name = "Muriel";, then $tour->b->name will be "Muriel" too!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating a server to arbitrate a simple game I've created a simple game where 2 players make a simultaneous choice in each round, and the winner of the round is determined by a set of rules specific to the game. Sort of like how Rock Paper Scissors works.
I'd like to be able to offer this game online where 2 players can find and play against each other. There would be some central server to arbitrate the game, and then each player would interact with the game using some game client of his choice that we would provide (i.e. web-based, mobile-based, Flash, etc).
Obviously, a player could also play against a computer opponent that we could provide. I'd also like to have the capability to allow programmers to submit computer programs that they've written to act as players and play against other programs in some sort of tournament.
I realize that the specifics of my game would certainly need to be written from scratch, but it seems that all of the work that the servers would have to do to communicate with the clients and maintain the state of the game has probably been done many times before. This is probably the bulk of the work.
Does anyone have any ideas for how this could be done quickly and easily? Are there servers available with some sort of standard interface to drop new games into? Is there some sort of open source game server? How would you go about doing this?
A: Seeing as the clients only communicate with the game server occasionally (as opposed to continuously), a web framework should be able to serve as your "basic game server". While web frameworks may be made for providing "web pages", they can certainly be (ab)used to serve as request handlers.
This certainly doesn't force you to make the game a browser game; standalone game clients can be made easily, and they can communicate with your game server using basic http. I also heard this thing called Ajax is pretty nifty for such things.
Not only will you find a lot of ready-made http-based servers, as an added bonus, there is a lot more documentation on how to work with Web 2.0®©™ than "game servers". You just need to know that you want a web framework that lets you easily manage sessions and receive/respond to requests and a client library that does likewise.
As an added aside, "maintaining the state of the game", as you put it, falls 100% within the domain of the actual game logic. But many web frameworks come with good database support, and will surely be useful for this kind of thing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do you create bold axes in flot (jQuery plugin for graphing)?
Possible Duplicate:
display x-axis and y-axis lines with out the grid lines using flot
How do you make the x- and y-axis appear bold (and possibly with arrows) in flot? The default behavior is not to show the axes at all. Thanks.
A: Under the flot API, look for grid markings...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How is my user.config Settings file getting corrupted? I've had a user send me in a crash report from a call to Settings.Upgrade():
System.Configuration.ConfigurationErrorsException: Root element is missing.
I got him to send me his user.config file and the file was all zeroes. It had gotten corrupt somehow.
I found a way to recover from it by rooting around the %localappdata%\MyAppName directory and deleting all user config files and re-launching the app. If I let the app continue execution it would give further ConfigurationErrorsExceptions.
Could this corruption be the result of something I've done? I've had multiple reports of it from a base of a few thousand users, but I have not been messing with that file directly. Has anyone else run into this user.config corruption?
A: Just an idea I got from this article.
Can you check your .Net framework version and if so, did you did some update recently that might have altered any methods that you are using ?
Another though was this article (it's a bit old - 2008) but it gives some pointers on how to handle the corrupted config file.
Can it also be a memory issue caused by the application not being able to cop with the current user rate?
Hope it helps since it has not happened to me yet but still an interesting and puzzling dilemma.
A: Settings seem to get corrupted if running multiple instances of your application.
It seems to be a timing issue, but a relatively easy way to reproduce is to have the application launch itself and then quit, and try to save settings on exit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: CakePHP 2.0.0-RC2 Console baking error I originally thought this error had to do with my path setup - I had
separated the core from the app so I could work more easily with git
submodules, so I ignored it. I just did a fresh checkout from the git
repo / a download of the RC2 source / and a cakeinit install of the
2.0 package (also uses git) and all 3 installs have the same issue I
had before.
My code seems to work fine via the browser.
The output of a ./cake bake Model from inside the local copy of the
core in the lib/Cake/Console folder is here
https://gist.github.com/1233884
This totally prevents me from using bake. Baking a project doesn't
work, baking a new database config doesn't work - it also doesn't
matter which of the datasources I try.
Can someone point me in the right direction here? I want to use some
of the bake tools and work on converting some shells for 2.0.
I am using XAMPP (latest version for OS X - I reinstalled it 20
minutes ago as a last ditch attempt)
OSX 10.5.8
The database.php I am working with is here with the passwords removed
but otherwise working
https://gist.github.com/1233891
I have tested it with and without the unix_socket setting and encoding
settings. All works fine from the browser but again not via the cli.
A: Okay, the error message could have been be a little bit more specific:
Error: Database connection "Mysql" is missing, or could not be created.
DboSource::__construct() is throwing that error here because Mysql::enabled() returns false:
public function enabled() {
return in_array('mysql', PDO::getAvailableDrivers());
}
On Windows, I can reproduce your error by commenting out the following line from my PHP CLI's php.ini file (the one that running php --ini on the command-line returns):
extension=php_pdo_mysql_libmysql.dll
HTH.
A: I was MAMP on Mac and had the same problem with CakePHP 2.2. I solved the problem by installing the mysql pdo for my mac ports installation. sudo port install php5-mysql
A: For local testing, I have found that setting the host to the address works. In my config I use the following:
'host' => '127.0.0.1',
This works for Mamp Pro
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Loopback/Localhost Question i have a question about sockets/clients....
I just finished writing a client server program in C#. I was wondering, how do you connect to computers that have a different IP address. For instance, if i want to run a client and server seperately on two different machines, loopback (or using the localhost) won't allow for this....
Not too familiar with networking, any help would be greatly appreciated.. here is my code on the client side which deals with loopback:
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
A: You just need to know the IP address of the server, and specify that in the client side code.
You can get your IP by typing ipconfig /all on the command prompt. Note that this will only give you the connection to the local network.
If you're trying to do this over the Internet, you'll need to use a service that finds your WAN (wide-area network) IP address. You can google for how to do that, as there is no "standard" service to do this.
If you have a router, you'll need to forward a port to the machine your service is running on. Look up Network Address Translation, and check out the documentation for your router, or call tech support. Or google "how do I forward ports?".
Once you have your network set up, and know all your connection info, and assuming you are using TcpListener:
*
*On the server side, simply set up your TcpListener with IpAddress.Any. Specify any port number you like, that isn't already in use (8888).
*On the client side, connect to the server's IP address. Replace IPAddress.Parse("127.0.0.1") and 8888 with the port and address of the server.
A: OverMars' solution is not good because 3rd party websites like ipchicken will give you your WAN IP. Local connections will not work. Look up NAT(network address translation) if you need more info.
Just bind to the "Any" address if you want a seperate machine to connect.
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Any, 8888);
Note that "Any" translates to the address "0.0.0.0".
A: 127.0.0.1 is an internal address to "this computer" or device where the application is running. Each computer will have 127.0.0.1 and at least 1 other IP address on a modern network.
To find out the IP address of another Windows computer you can use ipconfig from the command prompt. You will get something like this:
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
IP Address. . . . . . . . . . . . : 10.0.0.2
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 10.0.0.1
In this case the 10.0.0.2 is the IP address you can use to connect to it from other computers. Like so:
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("10.0.0.2"), 8888);
client.Connect(serverEndPoint);
A Windows computer will also have a name such as JimsPC or JimsPC.abc.com that can also be used in the TcpClient constructor or BeginConnect, Connect methods like so.
TcpClient client = new TcpClient("JimsPC", 8888);
or
TcpClient client = new TcpClient();
client.Connect("JimsPC", 8888);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: GetChildAtPoint method is returning the wrong control My form hierarchy is something like this:
Form -> TableLayoutOne -> TableLayoutTwo -> Panel -> ListBox
In the MouseMove event of the ListBox, I have code like this:
Point cursosPosition2 = PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
Control crp = this.GetChildAtPoint(cursosPosition2);
if (crp != null)
MessageBox.Show(crp.Name);
The MessageBox is showing me "TableLayoutOne", but I expect it to show me "ListBox". Where in my code am I going wrong? Thanks.
A: a better code can be written as following:
Public Control FindControlAtScreenPosition(Form form, Point p)
{
if (!form.Bounds.Contains(p)) return null; //not inside the form
Control c = form, c1 = null;
while (c != null)
{
c1 = c;
c = c.GetChildAtPoint(c.PointToClient(p), GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Transparent); //,GetChildAtPointSkip.Invisible
}
return c1;
}
The usage is as here:
Control c = FindControlAtScreenPosition(this, Cursor.Position);
A: The GetChildFromPoint() method uses the native ChildWindowFromPointEx() method, whose documentation states:
Determines which, if any, of the child windows belonging to the
specified parent window contains the specified point. The function can
ignore invisible, disabled, and transparent child windows. The search
is restricted to immediate child windows. Grandchildren and deeper
descendants are not searched.
Note the bolded text: the method can't get what you want.
In theory you could call GetChildFromPoint() on the returned control until you got null:
Control crp = this.GetChildAtPoint(cursosPosition2);
Control lastCrp = crp;
while (crp != null)
{
lastCrp = crp;
crp = crp.GetChildAtPoint(cursorPosition2);
}
And then you'd know that lastCrp was the lowest descendant at that position.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: .js help with the Date object and if/else ok so im trying to create something where certain elements change based on time of day. that time of day is gotten via system clock.
heres my code:
var currTime = new Date();
var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();
if (currMins < 10){
currMins = "0" + currMins;
}
var suffix = "AM";
if (currHrs >= 12) {
suffix = "PM";
currHrs = currHrs - 12;
}
if (currHrs == 0) {
currHrs = 12;
}
//display thr and minutes .
var myTime = currHrs + ":" + currMins;
if(myTime< 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
problem im having is that the time isnt being written at all in the html "clock" div.
i know it works because if i take out the 'if' and just do the document.write etc, its prints to screen.
im assuming that the problem is the myTime > 12 part. if i do '>' or '<' , it still doesnt work.
what i want is that say for example, if its before 12pm something happens, etc. i just dont know how to target for example, morning time from noon, night etc.
any ideas, etc ill gladly appreciate.
thanks in advanced.
A: Yes, your problem is your if condition, or perhaps what comes before it.
//display thr and minutes .
var myTime = currHrs + ":" + currMins;
You have created myTime as a string e.g. "12:30". Obviously this is not suitable for comparison with a number.
It won't work with currHrs either because, with your logic, that is never a number less than 12.
I suggest you map out in pseudo code what it is you are trying to accomplish, as it all seems a bit muddled up there.
A: You were close. I simply moved a few things around for you.
Edited: Made a few mistakes in my haste. And apologies for syntax error. Fixed now.
var currTime = new Date();
var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();
if (currMins < 10) {
currMins = "0" + currMins;
}
var suffix = "AM";
if (currHrs >= 12) {
suffix = "PM";
currHrs = currHrs - 12;
} else if (currHrs == 0) {
currHrs = 12;
}
var myTime = (currHrs == 0 ? 12 : currHrs) + ":" + currMins + " " + suffix;
if (myTime.match(/(AM)/)) {
document.getElementById("clock").innerHTML = myTime;
} else {
// code here
}
A: After this line myTime is a string
var myTime = currHrs + ":" + currMins;
You're doing a string comparison to an int below.
if(myTime< 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
Did you mean to do this ?
if(currHrs < 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rails routing question - restful url pointing to different controller I have a Rails 3 app with a url like this: /books/1/pages/2
I want this to actually point to the Books controller but with a page_id param, rather than the Pages controller with the book_id param. Is this possible?
A: In routes.rb: match '/books/:id/pages/:page_id' => 'books#your_action'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get first three elements of jagged array My brain isn't working, I'm trying to grab the first three rows on this grid. I'm making a simple checkers game just to learn some new stuff. My code is grabbing the first three columns to initialize the placement of the red chess pieces. I want the first three rows instead.
This is what my code is doing now:
This is my (simplified) code. Square is a class of mine that just holds a few little items to keep track of pieces.
private Square[][] m_board = new Square[8][];
for (int i = 0; i < m_board.Length; i++)
m_board[i] = new Square[8];
//find which pieces should hold red pieces, the problem line
IEnumerable<Square> seqRedSquares =
m_board.Take(3).SelectMany(x => x).Where(x => x != null);
//second attempt with the same result
//IEnumerable<Square> seqRedSquares =
m_board[0].Union(m_board[1]).Union(m_board[2]).Where(x => x != null);
//display the pieces, all works fine
foreach (Square redSquare in seqRedSquares)
{
Piece piece = new Piece(redSquare.Location, Piece.Color.Red);
m_listPieces.Add(piece);
redSquare.Update(piece);
}
A: If you are using m_board.Take(3) to get the first three columns, then this should give you the first three rows:
m_board.Select(c => c.Take(3))
If you want to get the rows (or columns) as enumerables then do this:
var flattened = m_board
.SelectMany((ss, c) =>
ss.Select((s, r) =>
new { s, c, r }))
.ToArray();
var columns = flattened
.ToLookup(x => x.c, x => x.s);
var rows = flattened
.ToLookup(x => x.r, x => x.s);
var firstColumn = columns[0];
var thirdRow = rows[2];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to access MC inside movieclip added from library? I have the following code and I followed the answer from this question, but it doesn't seem to be working for me. I'm not getting an error or getting a trace response.
Basically I need to access this test_mc inside the added child. Am I doing something wrong?
for (var i:int=0; i<30; i++) {
var mc:panelClass = new panelClass();
all_mc.addChild(mc);
mc.x = allWidth * i;
// Accessing the test mc
mc.test_mc.addEventListener(MouseEvent.CLICK, ctaOnClickHandler);
}
function ctaOnClickHandler(e:MouseEvent) {
trace("Clicked");
}
A: Kind of hard to answer this without know what panelClass is and how it is built. I'm assuming test_mc is a movieclip that's using all it's default properties and is on the display list of panelClass and since there are no errors it's been instantiated. The only think I can think of is there anything being displayed on top of test_mc inside panelClass?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS Enterprise distribution problem It was working but after releasing another build, OTA wireless installation started not working any more.. Giving me error saying Unable to Download App.. Used the exactly same provisioning profile and did everything same.. But it's not working..
Grab the logs from phone while I was trying to install
Sep 22 12:16:51 Wills-iPhone lockdownd[17] <Error>: 2ff15000 handle_connection: Could not receive USB message #6 from iPhone Configuration Utility. Killing connection
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: entitlement 'keychain-access-groups' has value not permitted by a provisioning profile
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: entitlement 'com.apple.developer.ubiquity-container-identifiers' has value not permitted by a provisioning profile
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: entitlement 'com.apple.developer.ubiquity-kvstore-identifier' has value not permitted by a provisioning profile
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: entitlement 'application-identifier' has value not permitted by a provisioning profile
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: 2ffc4000 verify_signer_identity: Could not copy validate signature: -402620394
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: 2ffc4000 preflight_application_install: Could not verify executable at /var/tmp/install_staging.DCVRV3/foo_extracted/Payload/ON Test.app
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: 2ffc4000 install_application: Could not preflight application install
Sep 22 12:16:52 Wills-iPhone installd[608] <Error>: 2ffc4000 handle_install: API failed
Sep 22 12:16:52 Wills-iPhone com.apple.itunesstored[606] <Notice>: MobileInstallationInstall: failed with -1
A: Go to http://developer.apple.com/ios/ and make sure the certificate has not been revoke or expired on Apple's end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does the "Prefer 32-bit" compiler flag mean for Visual Studio (C#, VB)? Just got the Visual Studio 11 developer preview installed. I see a new option in the project properties called "Prefer 32-bit" when compiling a managed (C#, VB) application with the AnyCPU target specified. This doesn't appear to be an option for class libraries, just top-level apps.
What does this flag indicate?
A: EDIT:
Application compiled with "Any CPU 32-bit preferred" is compatible with x86, x64 and ARM, while x86 is compatible only with x86, x64 and not ARM. For details see this.
A: Here's right and simple answer:
A: It likely indicates the app is AnyCpu but when 32 bit is available it shouold run as such. This makes sense - 64 bit apps use more memory, and sometimes you just dont need the memory space ;)
A: There is an good article at What AnyCPU Really Means As Of .NET 4.5 and Visual Studio 11.
The short answer to your question is "When using that flavor of AnyCPU, the semantics are the following:
If the process runs on a 32-bit Windows system, it runs as a 32-bit process. IL is compiled to x86 machine code.
If the process runs on a 64-bit Windows system, it runs as a 32-bit process. IL is compiled to x86 machine code.
If the process runs on an ARM Windows system, it runs as a 32-bit process. IL is compiled to ARM machine code.
The difference, then, between “Any CPU 32-bit preferred” and “x86” is only this: a .NET application compiled to x86 will fail to run on an ARM Windows system, but an “Any CPU 32-bit preferred” application will run successfully."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Crystal Reports Split Function within the Color Function I have a field in a DB called option1 which holds RGB values like the following;
255.255.5
255.255.1 etc
I need my Crystal Report to read this field and change the color of a box. I tried the following;
color (Split({ac.option1}, ".")[1],Split({ac.option1}, ".")[2],Split({ac.option1}, ".")[3])
color (255,255,5) clearly works but this is giving me an error stating a number is required.
Any suggestions would be highly appreciated.
Regards,
Ash
A: You need to convert the results of the Split() function to numbers:
Color( ToNumber(Split({ac.option1}, ".")[1]), ToNumber(Split({ac.option1}, ".")[2]), ToNumber(Split({ac.option1}, ".")[3]) )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to print out x amount of results per line For this code I created that outputs the ASCII characters corresponding to ints, I need to print out 16 ASCIIs per line. How would I go about doing so? I'm not sure how to approach these? Do I create another for loop inside?
int main()
{
int x = 0;
for (int i = 0; i <= 127; i++)
{
int x = i;
char y = (char) x;
cout << y;
}
return 0;
}
Or should I put the cout outside with 16 separate lines? I am trying to print 17 ASCIIs starting from 1 in a row.
A: Use another variable that counts up along with i. When it reaches 16, reset it and print a new line. Repeat until the loop terminates.
i.e.(I may be off by one here, I didn't think about it too deeply)
for (int i=0, j=1; i<=127; i++,j++)
{
int x = i;
char y = (char) x;
cout << y;
if (j == 16) {
j = 0;
cout << '\n';
}
}
Alternatively, you could just check if (i % 16 == 0)
A: Yes, you need a second loop inside the first. (I misunderstood what is being requested.)
You also need to clean up the code. The first x is unused; the second x isn't needed since you could perfectly well use char y = (char)i; (and the cast is optional). You should normally use a loop for (int i = 0; i < 128; i++) with a < condition rather than <=.
You will also need to generate a newline somewhere (cout << endl; or cout << '\n';). Will you be needing to deal with control characters such as '\n' and '\f'?
Finally, I'm not sure that 'asciis' is a term I've seen before; the normal term would be 'ASCII characters'.
A: How about:
#include <iostream>
int main()
{
for(int i = 0, j = 0; i < 128; ++i, ++j)
{
if(j == 16)
{
j = 0;
std::cout << std::endl;
}
std::cout << static_cast<char>(i);
}
return 0;
}
Every iteration, j increases by 1; after 16 iterations, j is reset to 0, and a newline is printed.
Alternatively, as @Sujoy points out, you could use:
if((i % 16) == 0)
std::cout << std::endl;
But this introduces the problem of printing an extra newline character at the beginning of the output.
A: You don't need another variable to track it. i is already an int.
so if i modulo 16 equals 0 then print a newline
else print (char)i
EDIT:
Note, using variables like i is ok for simple iteration but its always good practice to name them better.
So think about how changing i to ascii in your program improves the readability. It instantly makes it even more clear what is it that you are trying to do here.
A: int main()
{
int charsThisLine =0;
for (int currentChar=0; currentChar<128; currentChar++)
{
if(charsThisLine==16)
{
cout<<endl;
charsThisLine = 0;
}
else
{
cout<<(char)currentChar;
charsThisLine++;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How package writing language is different than for personal use? I would like to know what are common in all package functions:
> sd
function (x, na.rm = FALSE)
{
if (is.matrix(x))
apply(x, 2, sd, na.rm = na.rm)
else if (is.vector(x))
sqrt(var(x, na.rm = na.rm))
else if (is.data.frame(x))
sapply(x, sd, na.rm = na.rm)
else sqrt(var(as.vector(x), na.rm = na.rm))
}
<environment: namespace:stats>
Should we provide the environment every time we write a package? or it is determined by where the function is located automatically ?
> var
function (x, y = NULL, na.rm = FALSE, use)
{
if (missing(use))
use <- if (na.rm)
"na.or.complete"
else "everything"
na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs",
"everything", "na.or.complete"))
if (is.data.frame(x))
x <- as.matrix(x)
else stopifnot(is.atomic(x))
if (is.data.frame(y))
y <- as.matrix(y)
else stopifnot(is.atomic(y))
.Internal(cov(x, y, na.method, FALSE))
}
<environment: namespace:stats>
It looks me that the function is more verbious, that exact calculation...so can you help me to explain how the function are different for a package than for own use?
Thanks;
A: The way you write your functions is the same for your personal script files as it is for your packages. The <environment: ...> line indicates that the functions you are looking at are part of packages that have namespaces. If you use this feature in your package, R will take care of the details.
Package namespaces, and writing packages in general, is a somewhat involved process, described in detail in the Writing R Extensions Manual. You may want to read a tutorial first, and read the manual after you have a rough idea of the basics..
The functions in official packages are indeed often more verbose than our personal functions. The main reason is that public packages, at least the widely-used ones, are designed to accommodate a wider range of inputs and options than any one typical user is likely to need. So there's more code to account for edge cases and uncommon options. If the function uses C or Fortran code, as in the example var above, there will be some arcane language to deal with that too.
So you don't need to change anything about the way you write your personal functions if you want to make them into a package. However, going through the process of making the package may inspire you to improve the code anyways!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: The different of view controller and view in objective-c I am new to Objective-c, I want to ask what is the different between view controller and view such as "UITableView" and "UITableViewController"?
What happen if I use UITableView instead of UITableViewController?
Thanks
A: You should look up the Model-View-Controller pattern in the Apple's documentation, since it is very important for using Cocoa. Basically, the idea in Model-View-Controller is a pattern for designing your class structure. Broadly, the model is where the application's data should be kept. The view is what controls the application's appearance and the controller is the place where the two are assembled. (Ideally, the view and the model classes do not even need to know about the other's existence).
Hence, the UITableView and UITableViewController are two different classes with two different purposes. The UITableView controls the appearance of the data and the UITableViewController "controls" the view (generally by passing it the correct data for display and layout). Since this pattern shows up again and again in Cocoa programming, you should take some time to become familiar with it.
A: They are two different things, they cannot be substituted for the other.
iOS follows the MVC design pattern, which stands for Model-View-Controller. The two classes you mention are 2 pieces of the overall puzzle.
The View is what gets displayed on the screen. That is its responsibility. So, the TableView is responsible for telling the phone what to render on the screen.
The View is also accompanied by the Controller. The controller decides what to do when something happens (user interaction, and other events that can happen at any time). So, the TableViewController is responsible for making the table do stuff (for example, telling the TableView what data to use for displaying on the screen).
So to sum it up, they are completely different, but they work very closely together in your application (you will almost always have 1 Controller for each View.
A: Well, the short answer is that one is the View and one is the Controller. Combine this with your data (the Model) and you have all the parts of MVC (Model - View - Controller).
Think of it this way, the UITableViewController controls the UITableview. They are complementary and they need each other to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to read in a string of Numbers into an array I am working on a programming assignment in which we are making our own BigNum class. One of the constructors needs to be set up so that it can take a number from a string (i.e. 342567) and reads it into an array. However if the number were 0000000342567 it would have to be able to skip over the 0s and just read 342567.
Where is what i have so far but am lost on trimming the 0s
BigNum::BigNum(const char strin[])
{
size_t size = strlen(strin);
positive = true;
capacity = size;
digits = new size_t[capacity];
used=0;
while(used<size)
{
if(strin[size - used -1] =='-')
{
positive = false;
size --;
}
else if(strin[size - used -1] =='+')
{
size --;
}
else
{
digits[used] = strin[size - used -1] - '0';
used++;
}
}
}
Here is the assignment description if it helps
http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/hw2/Homework2.pdf
A: Here's a hint:
Write a separate loop at the beginning that skips over all the zeros.
A: Add this just before your while loop:
for (int i=0; i < size; i++)
{
if (strin[i] >= '1' && strin[i] <= '9')
{
used = i;
break;
}
}
This way, your while loop begins reading the string only from the index where the number actually begins, skipping over all leading 0s.
This should handle the leading sign as well:
BigNum::BigNum(const char strin[])
{
size_t size = strlen(strin);
positive = true;
used=0;
if (strin[0] == '+' || strin[0] == '-')
{
//set positive or negative
used++;
}
while (used < size)
{
if (strin[used] != '0')
break;
used++; //used will only increment if above if condition failed.
}
int digitIndex = 0;
digits = new size_t[size-used]; //create digits array here so it isn't larger than needed
while(used<size)
{
digits[digitIndex++] = strin[used++];
}
}
A: You just need to add another while loop before the one you have.
But just some other hints:
You can't change the sign of the number at any digit, the sign depends only on the very first charachter. So if you had a string like -2345, that'll be ok, but if you had something other like: 234-88 then this should be invalid, what will you do with this then?
Also the digits array shouldn't really be equal to size, but rather should drop the sign digit if it did exist, so how will you deal with capacity?
Hope that's helpful!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Editing a plist in NSDictionary I'm importing a plist into an NSDictionary object and want to change the contents of the plist once in the dictionary to lowercase. I have tried several different ways with no luck. Maybe I am supposed to edit the strings that are inside the NSDictionary, but then I don't know how to do that.
What I have currently imports the plist correctly, but the lowercaseString line effectively does nothing.
NSString *contents = [[NSBundle mainBundle] pathForResource:@"Assets/test" ofType:@"plist"];
NSString *newContents = [contents lowercaseString];
NSDictionary *someDic = [NSDictionary dictionaryWithContentsOfFile:newContents];
for (NSString *someData in someDic) {
NSLog(@"%@ relates to %@", someData, [someDic objectForKey:someData]);
}
I NSLog'd the "content" string and it gave me a path value, so obviously changing that to a lowercaseString wouldn't do anything. I'm feeling like I have to access the strings within the dictionary.
A: This line
NSString *newContents = [contents lowercaseString];
is change the path string returned from
NSString *contents = [[NSBundle mainBundle] pathForResource:@"Assets/test" ofType:@"plist"];
so you will end up with something like ../assets/test.plist
you will need to walk through the contents of someDic an create a new dictionary based on the old turning strings into lowercase, if you are only concerned about values directly in someDic you can do something like
for( NSString * theKey in someDic )
{
id theObj = [someDic objectForKey:theKey];
if( [theObj isKindOfClass:[NSString class]] )
theObj = [theObj lowercaseString];
[theNewDict setObject:theObj forKey:theKey];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Help with URL as InputSource So I have been asking questions here trying to get the answer for myself but I just cant get it to work without running into a new error. If anyone can help me I would appreciate it. I want to replace this portion
"<a>\n" +
"<b>\n" +
"<c id=\"00001\" time=\"1:00\" day=\"Friday\" name1=\"John\" name2=\"Mary\"></c>\n" +
"<c id=\"00002\" time=\"2:00\" day=\"Monday\" name1=\"Ed\" name2=\"Kate\"></c>\n" +
"<c id=\"00003\" time=\"3:00\" day=\"Sunday\" name1=\"Mary\" name2=\"Ed\"></c>\n" +
"<c id=\"00004\" time=\"4:00\" day=\"Friday\" name1=\"Kate\" name2=\"John\"></c>\n" +
"</b>\n" +
"</a>"
with a XML url instead, as that information will be pulled from a server as the data changes.
Here is the source as you can see what I am trying accomplish once I have the data from the xml file. It works fine as it is, but whenever I try and implement a url as the InputSource I get tons of errors that no matter what ive tried does not resolve the problem.
package com.newxpath;
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class NewxpathActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputSource xml = new InputSource(new StringReader("<a>\n" +
"<b>\n" +
"<c id=\"00001\" time=\"1:00\" day=\"Friday\" name1=\"John\" name2=\"Mary\"></c>\n" +
"<c id=\"00002\" time=\"2:00\" day=\"Monday\" name1=\"Ed\" name2=\"Kate\"></c>\n" +
"<c id=\"00003\" time=\"3:00\" day=\"Sunday\" name1=\"Mary\" name2=\"Ed\"></c>\n" +
"<c id=\"00004\" time=\"4:00\" day=\"Friday\" name1=\"Kate\" name2=\"John\"></c>\n" +
"</b>\n" +
"</a>"));
String name = "Ed";
XPath xpath = XPathFactory.newInstance().newXPath();
String expr = String.format("//a/b/c[@name2='%s']", name);
Node c = null;
try {
c = (Node) xpath.evaluate(expr, xml, XPathConstants.NODE);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NamedNodeMap attribs = c.getAttributes();
String id = attribs.getNamedItem("id").getNodeValue();
String time = attribs.getNamedItem("time").getNodeValue();
// etc.
EditText id2 = (EditText) findViewById(R.id.id2);
EditText time2 = (EditText) findViewById(R.id.time2);
id2.setText(String.valueOf(id));
time2.setText(String.valueOf(time));
}
}
A: You probably need to add the INTERNET permission to your AndroidManifest.xml file (I assume from the Android imports that this is taking place on Android). Otherwise I don't see why this wouldn't work. I copied your XML to the URL http://pastebin.com/raw.php?i=RF8cL5YZ and then ran it against the following code at a command line and it worked just fine.
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import java.net.*;
public class test
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://pastebin.com/raw.php?i=RF8cL5YZ");
InputSource xml = new InputSource(url.openStream());
String name = "Ed";
XPath xpath = XPathFactory.newInstance().newXPath();
String expr = String.format("//a/b/c[@name2='%s']", name);
Node c = null;
try {
c = (Node) xpath.evaluate(expr, xml, XPathConstants.NODE);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NamedNodeMap attribs = c.getAttributes();
String id = attribs.getNamedItem("id").getNodeValue();
String time = attribs.getNamedItem("time").getNodeValue();
// etc.
System.out.println("["+String.valueOf(id)+"]["+String.valueOf(time)+"]");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check whether the executing code is running in either IIS or NUnit? How can I check whether the executing code is running in either IIS or NUnit? The reason I ask is because I want to load a different NHibernate configuration based on whether my site is live or running in NUnit.
var configuration = new Configuration();
if (IsRunningOnIIS)
{
configuration.Configure();
}
else // if (IsRunningInNUnit)
{
configuration.Configure("hibernate.cfg.test.xml");
}
A: This is a wrong approach and you should be using dependency injection. But since you asked:
Process currentProcess = Process.GetCurrentProcess();
if(currentProcess.ProcessName == "w3wp") {
// IIS
} else if (currentProcess.ProcessName == "nunit-agent") {
// NUnit
}
or
if(HttpContext.Current != null) {
// IIS
} else {
// NOT IIS
}
You may need to replace 'nunit-agent' with the name of your runner if you using something like Resharper. Ideally though, you would inject Configuration into initialization code on application startup (manually or using DI container). Order Dependency Injection in .NET book.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: vb.net activated fires multiple times I want to update a database based on the form that is currently activated. I had originally decided to use the GotFocus event. However I now understand that will not work as the form has controls on it. So I then thought I wouls use the activated event. This works but seems to fire multiple times. I put in the following code:
Private Sub frmNewTicket_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
MsgBox("Form Activated")
End Sub
I select the form and make it activated and the message box appears about 15 times.
Why does it do this? How should I handle this. I only want my code to execute once when the form is activated.
NOTE: There are several forms that the users will be changing between, incuding forms from other applications.
A: Each time you click OK on the messagebox, the form regains the focus and is activated again.
Put a static Boolean value in your frmNewTicket_Activated like someone has posted here:
Static HasRan As Boolean=False
If Not HasRan Then
HasRan=True
'put code here
End If
A: It sounds like you are wanting to do something everytime your form gets activated. The Form Activated event will work fine as long as what you are doing doesn't pull focus from the Form which will then trigger another Activation event when the Form gets focus again. Try using something other than a MessageBox for testing like Beep or changing the Form's Color
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I make the dependencies not upload to the company 's internal repository? My pom.xml use the following code to define the company 's internal Maven repository such that the dependencies will be downloaded from this repository if they cannot be found in my local repository.
<repositories>
<repository>
<id>XXXXXX</id>
<name>Internal Repository</name>
<url>http://private.ip/nexus-webapp/content/groups/public/</url>
</repository>
</repositories>
When I add some dependencies in pom.xml , I find that the dependencies I added will also be added to that internal repository . Besides deleting <repositories> section in pom.xml , can I configure its attributes such that the dependencies added in the pom.xml will not be added to this internal repository?
A: It sounds like what you're talking about is Nexus' proxying mechanism. You request artifacts from Nexus, and it looks at configured outside repos for the artifacts, caches them locally and returns them to you. That assumes the repositories in question are configured to be proxied through Nexus, of course. If someone set it up that way, then why do you want to circumvent it? You'd use Nexus in this way so the artifacts are closer to you and your builds work faster. The only way you'd get this not to happen is to change the settings in Nexus or else stop using it. You don't have to remove the repo entirely from the pom. Just put other repos ahead of it, and Maven will look in those first. But again, why would you not want to use Nexus as it was designed as a near cache for artifacts?
A: You need to configure it in your repository software (Artifactory, Nexus, ...).
I think you have set up a proxy repository here which downloads every artefact requested. You might want to try running a 'hosted repository' instead. More info here.
The equivalent concept in Artifactory is a 'local repository' (read here).
A: Download and install the dependencies you need manually using following command. It will add the package to your local repository such that you can use it. Read here
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to notify the host of a WCF service when a client connects? I have a WCF service that is hosted by a windows service. I can't figure out how to inform the windows service when a client connects to the WCF service. Basically all I have in the windows service to start the WCF service is this:
private ServiceHost sHost;
WCF.WCFService wcfService = new WCF.WCFService();
sHost = new ServiceHost(wcfService);
sHost.Open();
I am able to call methods in the WCF service with the windows service using the wcfService object. Is there some way to have some kind of event that would fire when a client connects to WCF service?
A: The service runs as an object which is instantiated according to the ServiceBehaviourAttribute property InstanceContextMode
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
// ...
The values for InstanceContextMode are
*
*Single - a single instance of the service runs for all sessions and calls
*PerSession - an instance of the service runs for each session (i.e. each client)
*PerCall - an instance of the service is instantiated for each call, even from a single client
The default value is PerSession, and this makes sense for most scenarios. Assuming you're using PerSession, you can put whatever 'connect logic' you like inside the constructor for the service.
// you don't need to specify PerSession as it is default, but I have for clarity
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
public MyService()
{
// constructor will be called for each new client session
// eg fire an Event, log a new client has connected, etc
}
// ...
}
You need to be careful running code in the constructor, because the service will not be available until the constructor has completed. If you want to do anything that may take time, fire an event or send a thread to perform that work.
A: I found the best answer here: Subscribe to events within a WCF service
As suspected you can create an event handler in the WCF service that can be picked up by the host.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.