text stringlengths 8 267k | meta dict |
|---|---|
Q: Not getting all data when making .ajax call I am trying to get data from a page that generates the following object displayed as text in the body and pre tag, but it seems not to get all 4 key|value pairs (only 3)?
Please note that I have changed the urls of the jSON output and and removed most of the data to shorten it here. hopefully I didn't introduce any errors.
{"nodes":[{"node":{"title":"NLT bottle 14","bottle_code":"NL_T14","bottle_img":"http:\/\/site.dev\/files\/bottles\/bottleimages\/nlt%20bottle%2014_bottle.jpg","swatch":"http:\/\/site.dev\/files\/bottles\/swatches\/nlt-bottle-14_swatch.jpg"}},{"node":{"title":"DS Bottle 033","bottle_code":"DS_033","bottle_img":"http:\/\/site.dev\/files\/bottles\/bottleimages\/ds%20bottle%20033_bottle.jpg","swatch":"http:\/\/site.dev\/files\/bottles\/swatches\/ds-bottle-033_swatch.jpg"}}]}
I am trying to get it with via:
var url = "http://site.dev/getinfo";
$.ajax({
url: url,
type: "GET",
dataType: "json",
async: true, // false loads and processes the data (function) before rendering the page
success: function(stuff){
console.log(stuff); // <- This output of the stuff object->nodes does not show the swatch key value pair!
process_data(stuff);
},
complete: function(){
doneprocess();
},
error: function(code){
error_get_data(code);
}
});
but I get this without the swatch key|value pair. I do not know why!
{"nodes":[{"node":{"title":"NLT bottle 14","bottle_code":"NL_T14","bottle_img":"http://site.dev/files/bottles/bottleimages/nlt%20bottle%2014_bottle.jpg"}},{"node":{"title":"DS Bottle 033","bottle_code":"DS_033","bottle_img":"http://site.dev/files/bottles/bottleimages/ds%20bottle%20033_bottle.jpg"}}]}
Greatly appreciate your expertise!
A: Since you munged the data we can't tell, so one obvious question is: Are you sure the JSON data structure is valid?
Check with Web Inspector or Firebug that the browser is getting the same data you think the server is sending.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mongodb in production We are planning to use mongodb in production for a subset of data. In past, I have read that mongodb has issues with blocking writes and write durability. Are they resolved with 2.0 release? Are there anything else which one should be careful of, before deploying mongodb in production?
A: There are no issues with blocking writes. Atomic write operations is MongoDB's strategy to deal with concurrency and consistency. This does mean that if your write load is high (monitor using mongostat tool and keep an eye on "locked %", this should typically stay very low) you will have to start using sharding to minimize per-instance write lock contention
Durability actually has been improved in 2.0 with the journaling feature but was already pretty solid with replica sets. Basically, if you invest the resources (instances) then durability and fail-over is pretty solid in MongoDB. Journaling improves (crash) recovery more than anything.
TL;DR with the appropriate measures MongoDB is a production ready storage solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Form submit a signature captured using SVG I came across an example SVG signature capture by @heycam here:
Capture Signature using HTML5 and iPad
Example: http://mcc.id.au/2010/signature.html
Much simpler than any previous example I have seen, and it works with mouse and touch!
But how would I submit the result as part of a form?
I think I'd want it submitted as a base64 string but I'm open to other options...
For bonus points... any way to strip the yellow background and line from the submitted data?
Thanks!
A: That SVG-based sig capture hack by @heycam is technically awesome, if limited browser support for SVG does not scare you, by all means, call into the iframe, extract the source and push it server-side as text:
var strokes = window.frames[0].getSignature()
To get a string line:
"M182,46 M141,30 L136,34 L136,36 L134,40 L134,47 L135,52 L146,64"
Push it into SVG template like so:
var svgstring = '<svg xmlns="http://www.w3.org/2000/svg" width="300" height="100">' +
'<path stroke="navy" stroke-width="2" fill="none" d='+ strokes +'/></svg>'
And push that to server in hidden input field.
However, there is an easier way:
http://willowsystems.github.com/jSignature/
It works in almost all browsers (mobile and desktop) and can export nice, de-noised, smooth curves SVG.
A: If you look at his code, you can see how he extracts the signature into the div tag.
There's a script in the inline SVG that records the content into the "signaturePath" variable as events are fired. He then calls "getSignature" within the iframe to return the path. In order to extract the path, when the form is submitted, you'd need to call that function and create a hidden input tag which has a value of the path returned. You would extract the submitted value (which is the path) on the server side. You can later recreate the SVG using the saved path (which wouldn't have the yellow background).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Ruby Class variable and on access assignments I have a module that has multiple class variables. I'm looking for a class level getter implementation that will only instantiate the @@ variable when the class tries to access it like the following
module MyProducts
@@products = nil
def self.get_product(id)
# i'm looking for a way that the first call on @@products does a find via AR like the following
# @@products = Product.all
# this module is in the lib directory of a Rails 2.3.5 app
@@products.find do |prod|
prod.id.eql?(id)
end
end
end
I'm looking for this to be transparent so that i don't have to modify the whole module. There are about 10 class level variables with similar functions, all the results of an ActiveRecord .find call
A: Just use the ||= operator. It would evaluate the right expression only if the right part is nil or false
def foo
@@any ||= some_value
end
The first time you call the method it will initialize the variable with the result of some_value, and following calls will return the @@any value with no need of recomputing some_value.
Update
Here it's a little script which shows you how to do that. If you execute that you'll see that the method complex_function is called once since the two print statements both returns 1. However from your comment I see that your Product is an active record, so don't use this approach for what your asking for, it will be very inefficient (read the last part of my answer)
#!/usr/bin/env ruby
module Foo
def self.products
@@products ||=complex_function
end
@@a = 0
def self.complex_function
@@a += 1
end
end
p Foo.products
p Foo.products
Update end
However your approach to save Product.all is pretty inefficient:
*
*First it will fetch all the products in the database which could consume a lot of memory when you have lot of products
*Second your iteration code will be much slower than the db when you have a lot of products
Replace your whole method with a Product.find(id) call.
If your Product model isn't stored in the db (maybe an ActiveResource) ignore my previous comment.
You could also take a look to mattr_accessor and this SO question Difference between mattr_accessor and cattr_accessor in ActiveSupport?
Finally also take a look to this article which explains the above technique called memoization
A: Best not to use class variables - they have very odd behavior. See
http://www.oreillynet.com/ruby/blog/2007/01/nubygems_dont_use_class_variab_1.html
In every case you can use civars (class instance variables):
module MyProducts
class << self
@products = nil
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I specify a customers default shipping address in a database table? Here is a simple example:
Assume I have a customer table that has a one-to-many relationship with the address table (a customer can have multiple shipping addresses but a shipping address can only belong to a single customer).
Customer Table
-------------
customer_id (PK)
Address Table
-------------
address_id (PK)
customer_id (FK)
Now I want each customer to be able to specify a default shipping address.
I can think of 2 ways but both have drawbacks.
Option 1
Add a Boolean column to the Address Table called "is_default".
Pros
*
*Select queries are simple
*Straightforward for other people to understand if they see the DB model
Cons
*
*The application is forced to enforce and maintain the "only one row can be a default" constraint.
*Updating the default field is a pain because it requires the application to check and reset the previous default option.
Option 2
Add a column to the Customer table called "address_id" and make it a foreign key (also allow nulls just in case no address exists).
Pros
*
*Easy to update the default address if the user decides to change it.
*Database maintains the "only one row can be a default" constraint.
Cons
*
*I have to add a new indexed column to the Customers Table every time I decide to add some kind of default metadata.
*Seems like a hack
My question is, is there a standard way to handle this kind of scenario that I am overlooking? Of course there are other options (maybe creating an EAV default options table?) but I'd prefer to keep it as simple as possible because the change is being made to an existing code base so I don't want to break anything.
A:
(maybe creating an EAV default options table?)
I would do this, especially if you're worried about breaking existing code.
Customer_Defaults
------------------------------------
customer_id PK, FK -> Customer
default_shipping_address_id FK -> Address
Isn't that tidy? By pulling the whole thing into a separate table, you leave the existing tables alone. If you're using some kind of ORM layer, the object over this new table can be queried for directly, and then you can walk to the Address object. No need to even introduce the new object to the existing Customer or Address objects.
A: When you grow new requirements, think about new tables. Here are two different ways to approach your problem. The first is less stringent than the second. (I would use the second.) I'll assume "Address Table" is named "customer_addresses".
create table default_shipping_addresses (
customer_id integer primary key references customers (customer_id),
shipping_addr_id integer not null unique references addresses (addr_id)
);
create table default_shipping_addresses (
customer_id integer primary key references customers (customer_id),
shipping_addr_id integer not null unique references addresses (addr_id),
-- Add a UNIQUE constraint on customer_addresses (customer_id, address_id).
-- Since address_id is the primary key, it's unique, so (customer_id,
-- address_id) will also be unique. But you need the UNIQUE constraint to
-- allow a foreign key to reliably reference it, even in MySQL.
foreign key (customer_id, shipping_addr_id)
references customer_addresses (customer_id, address_id)
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can I load a google map into a div container? I have current code that loads my google map into a colorbox but I'd like to load it into a div tag that can be loaded into a colorbox from another page.
Here is my current colorbox code (works)
$.fn.colorbox({width:"643px", height: "653px", inline:true, href:"#map_container"}, function() {
$.getJSON('users.php', function(data){
initialize();
setMarkers(map, data);
});
});
Here is my attempt at loading the same data into my div container (doesn't work, returns a 403 error)
$('#map_container').load('users.php', function(data){
var jqxhr = $.getJSON(data);
initialize();
setMarkers(map, jqxhr);
});
Any idea why I'm getting a 403 error or have I missed something?
A: $('#foo').load('users.php') will load the data from users.php into the #foo div.
You want to do the .getJSON call with a callback, something along the lines of
jQuery.getJSON("users.php", {}, function(data, status) {
initialize(); // should setup #map_container with a map with the maps API
setMarkers(map, data);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET activation code I'm going to install a ASP.NET in a third party server, I would like some way to protect this code against copying it to other server so I was thinking in some way of activation code... Given I'm not very advanced in encryption I thought:
*
*Generating a code with the_install_domain+some_secret_key, for example SHA1
*Save this code in web.config or split it and save a part in web.config and another part in DB or a file
*In every Page_Load check if SHA1(current_domain+secret_key) is equal to activation key in web.config (or re-joined activation key if I split it)
*If not, exit execution
Is it smart enough or is it really silly? I know there's nothing perfect, but would the first geek lookin to the de-compiled code catch this thig at first sight?
Thank you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery selectable plugin to select the first level childs, not the childs of childs <ol id="selectable">
<li class="ui-widget-content">
<div><input type="checkbox" /></div>
<div>Item1</div>
<div>Khanput</div>
<div>1/2/3</div>
<div>15:03:16</div>
<div>--------</div>
<div>23m</div>
<div>Chakwal</div>
</li>
</ol>
I just want to select the 'li' element not the 'div' but it selects them all.
I have tried a few things but they did not work out.
A: If you make the <li> element selectable it stands to reason that the content inside it would also become 'selected' when the <li> is clicked.
As far as jQuery UI is concerned though, only the <li> is actually 'selected'. You can see this as your <li> will be given a class of ui-selected when it's selected; the content within, conversely, is given the ui-selectee class.
A: You can add this custom plugin
$.widget("xim.singleSelectable", {
options: {
select: null
},
_create: function () {
var self = this;
this.element.addClass('ui-selectable');
this.element.delegate('li', 'click', function (e) {
self.element.find('>li').removeClass('ui-selected');
$(this).addClass('ui-selected');
if ($.isFunction(self.options.select)) {
self.options.select.apply(self.element, [e, this]);
}
});
},
selected: function () {
return this.element.find('li.ui-selected');
},
destroy: function () {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
}
});
then your code will be
$( "#selectable" ).selectable({
stop: function() {
$( "li.ui-selected", this ).each(function() {
var index = $( "#selectable li" ).index( this );
alert(index);
});
}
});
I found the solution here
How to prevent multiple selection in jQuery UI Selectable plugin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: keydown function not enabling alert function in jquery I have this code right now:
$(document).ready(function () {
$("div#main-edit").click( function() {
var cursorExists = $("input#cursor").length;
if (cursorExists == false){
$("div#cursor-start").append("<input type='text' id = 'cursor' />");
$("input#cursor").focus();
}
});
$("input#cursor").keydown(function() {
$("div#cursor-start").enterText();
});
jQuery.fn.enterText = function(){
alert("hello");
};
});
The function enterText is not called in this situation though. It seems like the fix should be easy for this. Is it because jquery finds nothing to select (input#cursor) when the document loads up?
A: A few things:
Checking an int (.length) against false doesn't make a whole lot of sense, even if JS will allow you to do it. It should be $("input#cursor").length == 0)
Have you tried just an alert('hello') inside of the keydown function, just to make sure it works? What about alert($("div#cursor-start").length). If that's 0 then your selector is bad.
Simplify your script down to the bare bones until you find the problem. It's most likely a bad selector.
A: I think this code has problems because you are calling this;
$("input#cursor").keydown(function() {
$("div#cursor-start").enterText();
});
before the object input#cursor has been created by your code. Thus, it won't find the object and can't install an event handler for it. I would suggest you change your code to this which installs the event handler only after the object is created:
$(document).ready(function () {
$("div#main-edit").click( function() {
var cursorExists = $("input#cursor").length;
if (cursorExists == false) {
$("div#cursor-start").append("<input type='text' id = 'cursor' />");
$("input#cursor").focus();
// install event handler, now that we know the object exists
$("input#cursor").keydown(function() {
$("div#cursor-start").enterText();
});
}
});
jQuery.fn.enterText = function(){
alert("hello");
};
});
The alternative would be to use .live("keydown", function() {}) instead of .keydown() which allows you to install some event handlers before the object exists (you can read the jQuery doc on it to understand further).
FYI, you get a lot worse performance in jQuery when you use selectors like "input#cursor" instead of just "#cursor". The latter gets optimized to use document.getElementById(). The former does not and takes a much longer code path. Since there is only one object in the page with any given ID, there should be no reason to quality it with the tag type. Just use "#main-edit", not "div#main-edit".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I cascade delete a collection in Hibernate? Let's say I have two entities, a Post and a Comment (in ColdFusion):
component persistent="true" table="post"
{
property name="Id" fieldtype="id";
property name="Comments" fieldtype="one-to-many" cfc="Comment" fkcolumn="post_id" cascade="all";
}
component persistent="true" table="comment"
{
property name="Id" fieldtype="id";
property name="Post" fieldtype="many-to-one" cfc="Post" column="post_id";
}
Post has a collection of Comments. Now I'd like to delete a Post, and have the Comments automatically deleted as well. I've tried the straightforward method:
var post = EntityLoadByPK("Post", 13);
EntityDelete(post);
But I'm getting a Hibernate error that says that post_id cannot be set to null. What am I doing wrong, and how can I fix this issue?
A: You need to adjust your mappings. Try making the Post property of comment not null and marking the Comments property of post as inverse.
component persistent="true" table="post"
{
property name="Id" fieldtype="id";
property name="Comments" fieldtype="one-to-many" cfc="Comment" fkcolumn="post_id" cascade="all" inverse="true";
}
component persistent="true" table="comment"
{
property name="Id" fieldtype="id";
property name="Post" fieldtype="many-to-one" cfc="Post" column="post_id" notnull="true";
}
A: You'll have to make post_id in Comment table nullable in your DB. That's how hibernate does cascade delete. It'll set all Comments with post_id = 13 as null, then delete all comments where post_id IS NULL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Parse Binary Data I have an application that receives data in binary form through Bluetooth. I read the data using inputstream from a bluetoothsocket to a byte[]. But I must parse all messages, because they must have a given format to be valid. All messages are in binary.
My solution was to convert the byte[] to a string and then split the string and parse all received messages.
An example of the data to parse:
0000000010000001
I should know that the first 8 zeros are the header and 10000001 the real data.
My idea was to create a string (from the byte[]) that represents -> 0000000010000001
using new String(byte[])
and then split the whole string in one byte and check the value, like:
string1 had 00000000
string2 had 10000001
I know that 8 zeros are the header, therefore string2 has the representation of the data.
My question is about the efficiency of this method. Is this the best method to do this in a mobile environment?
A: String manipulation for parsing binary data is quite inefficient in terms of speed, memory consumption and also puts quite some burden on the garbage collector - because you always generate new string objects and forget them immediately.
In Java you have several choices to do it better:
*
*DataInputStream: is a wrapper for an InputStream where you read bytes, shorts, longs, doubles, etc directly from the stream.
*NIO using ByteBuffers and "derived" types like ShortBuffer... these are good for bulkd data transfers and also for binary parsing.
As long as your data is byte-aligned, these are easy ways to go. If that's not the case - well, then better learn how to do bit-manipulation using operators like &, |, ~, <<, >>.
My suggestion is that you stick to DataInputStream as long as possible.
A: just FYI, there is free OSS library called Java Binary Block Parser (JBBP), it is compatible with Android (2.1+) and it allows just describe structure of data in text format and automatically parse data stream (or array), if you want to parse whole stream to bits then it can be executed in single string
byte [] parsedBits = JBBPParser.prepare("bit:1 [_];").parse(new byte[]{1,2,3,4,5}).findFieldForType(JBBPFieldArrayBit.class).getArray();
A: Strings are the least efficient way to do this indeed.
If your binary 0000000010000001 is actually byte[] {0, 0, 0, 0, 2, 0, 0, 1} in decimal, then just check if b[0] == b[1] == b[3] == b[4] == 0.
Edit: Ignore the "in decimal" part, it's irrelevant as long as you only want to check the if your array begins with 00000000 (i.e. 4 zero bytes)
A: It is a very low efficiency way, and is not recommended.
To parse binary data, we should have the protocol, and always use bit operation. If you are not fimiliar with that,
FastProto is a better choice, what you need to do is annotating the fileds of the data object, FastProto would help you complete all.
Imagine the binary data has fixed length of 20 bytes:
65 00 7F 69 3D 84 7A 01 00 00 55 00 F1 FF 0D 00 00 00 07 00
The binary data contains 3 different types of signals, the specific protocol is as follows:
Byte Offset
Bit Offset
Data Type(C/C++)
Signal Name
Unit
Formula
0
unsigned char
device id
2-9
long
time
ms
12-13
short
temperature
℃
import org.indunet.fastproto.annotation.*;
public class Weather {
@UInt8Type(offset = 0)
int id;
@TimeType(offset = 2)
Timestamp time;
@Int16Type(offset = 12)
int temperature;
}
byte[] bytes= ... // binary need parsing
Weather weather = FastProto.parse(datagram, Weather.class);
Maybe you have noticed that FastProto describes the field information in binary data through annotations, which is very simple and efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: saving state between program restarts How can I declare a variable which would save sting forever?
I mean if the user closes and restarts the program, this string value is not lost.
How can this be done?
A: There are a number of different ways to store state for an application. The approach really depends on the type of data you are storing and other requirements
Options
*
*Use the Settings classes built into .NET
*
*http://msdn.microsoft.com/en-us/library/aa730869(v=VS.80).aspx
*Store the data in some type of file or database
*Send the data to a webservice or the cloud
A: Save the variable value to a database or other storage.
A: You could save it to a file, a database, a USB drive, somewhere in the cloud... somewhere other than the computer's memory.
Here's a quick example in C# (to write to a file):
string someString = "I will be here forever... well kind of";
using (StreamWriter outfile = new StreamWriter(@"C:\myfile.txt"))
{
outfile.Write(someString);
}
A: I recommend a database, in particular SQLite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Tomcat Application Manager won't authenticate I'm running a local Tomcat 6.0 server. I can get to the main admin page from a browser. I've created a user for the Tomcat Application Manager by configuring tomcat-users.xml like so:
<tomcat-users>
<role rolename="manager-gui" />
<user username="myUsername" password="myPswd" roles="manager-gui" />
</tomcat-users>
When I type a cmd for TAM e.g. http://localhost:8080/manager/list, it prompts for credentials w/ the Authentication Required dialog. I enter myUsername/myPswd, and the dialog just re-prompts for credentials again.
What am I missing here?
A: The roles required to use the Manager application in Tomcat 7 were changed from the single manager role in Tomcat 6 to the following four roles:
*
*manager-gui - allows access to the HTML GUI and the status pages
*manager-script - allows access to the text interface and the status
*pages manager-jmx - allows access to the JMX proxy and the status
*pages manager-status - allows access to the status pages only
If you are using Tomcat 6 you need to change the role to "manager".
A: I had a problem like this too, I don't know if its a problem with my version of the manager/tomcat or if I have a newer tomcat then manager version but I've found that I have to use the legacy role 'manager' despite being on 6.0.x.
<role rolename="manager" />
<user username="myUsername" password="myPswd" roles="manager" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Azure Table Storage & Dynamic TableServiceEntity I am looking for a way to create objects in the Azure Table Storage that are essentially dynamic in nature. In other words they have no defined class structure of exposed properties, except for the base ones required by TableServiceEntity. In other words, like a JSON object. Has anyone done something like this?
A: Yes, I just had a property on the table called 'Value', which I used to store a JSON string. It works very well, as long as you don't want to use it in a query.
Edit
I have created a small library for using dynamic types (or dictionaries) with table storage. Available here (see DynamicTableContext): https://github.com/richorama/AzureSugar
A: If you're looking to achieve so in .Net code, may I suggest you take a look at the source code for Azure Storage Explorer on CodePlex (http://azurestorageexplorer.codeplex.com/). I think the name of the class is GenericEntity.
A: I am working on an open source client that allows exactly that.
The Table Storage service is schema free but the provided .NET client does not expose it, it doesn't even mimic the REST API making very difficult to follow the existing API documentation.
With Cyan I am trying to provide a less "leaky abstraction" (hi Joel!) of the service using .NET 4 dynamic features.
It's still a work in progress, but you can use some of the code if you want.
A: I have written an client that supports dynamic (unspecified) columns by using a dictionary to hold the name/value pairs. It also supports many other features like arrays, enums and data larger than 64K.
You can download Lucifure Stash, from http://www.lucifure.com via NuGet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Updating a bare git repository from a git-svn cloned remote repository I have a remote SVN repository (X) where a freelance developer is committing his work. However, in my company we work with GIT and are using git-svn to interoperate GIT and SVN. That's ok!
So, I've cloned the SVN repository (X) into a GIT local repository (A). After this, I've made a clone of the local git repository (A) into a local GIT bare repository (B) to be able to pull it from everywhere through SSH.
The problem is: everytime the developer commits to his SVN repository, I do "git svn fetch && git svn rebase" in order to get updates local repos (A) , but I can't update my local bare repository (B) from A. From B, I ran "git fetch", so it fetched changes from (A) into FETCH_HEAD, but I want to "merge" these changes to the bare repository (B) HEAD, so that I can pull changes from a remote repos.
Any ideas?
I hope I've been clear enough. Thanks!
A: In Git, merging requires a working copy in order to actually perform the merge (because there might be conflicts). This is probably why you can't merge inside your bare repository (B).
What you can do is merge in your working repository (A), then push the result of the merge to repository (B).
A: Simple answer - You can push from A to the bare repository B.
A: You may install SubGit into your repository X, so that a bare Git repository (Y) will be created on that machine, so that syhchroinzation X<->Y will be performed automatically.
So you may use Y as a replacement of B or sync them by running "git pull --all " on B periodically. The repository A is redundant in this case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Request object, what are the pros and cons? Let's say I have the following method:
public Stream GetMusic(string songTitle, string albumName) { ... }
A colleague of mine is convinced that this a bad method signature. He would like me to use a Request object, which would transform the method signature into this:
public Stream GetMusic(SongRequest request) { ... }
I really don't see the point of doing that. The only benefit I see is that it will be easier to add parameters in the future. We won't have to change the method signature, but the Request object still have to change.
Personally, I don't think it is a good idea. Using parameters makes it explicit what the method requires to run. In addition, this force us to create another object for not much.
What are the pros and cons of using Request objects? Are you using it in your projects and why?
A: There is one major advantage to passing an object -
If you have an object used as the parameter, such as SongRequest, the object can be responsible for its own validation. This allows you to dramatically simplify the validation in each method that uses the object, as you pretty much only need to check for null, instead of checking each and every parameter.
In addition, if you have many parameters, it can often be simpler to generate a single object. This is especially true if you find you need multiple overloads to manage different combinations of parameters.
That being said, each situation is unique. I would not recommend one approach over the other for every situation.
A: You are getting data using GetMusic(...) method. If so, it whould probably too much effort to use an additional entity without really need.
Indeed, in a situation, where is only one input parameter, you can use a custom class. But if that class is the only place to use, so if SongSignature as the class name says, have to be used specifically for this class, that is a bad practice of using "parameter bags", because it lucks readability.
Additionally, if someone stupid says that SongSignature must be a structure, and in that structure there is a pointer to some data to be changed inside method, that pointer would never really changes because every time GetMusic is called, it will take a copy of a property bag.
Even if it is a class, you have to change the accessor for that class to public, and in general this is not the best method to pass an arguments forward to a function and getting results from a function, because you have already getting a stream from that method.
Let's assume the following situation:
If in a team one programmer replaces the parameters with a class SongRequest, second programmer did not find that it is used as a parameter to a functions (because it lucks info in a name of a class), and changed it to a structure on next iteration, third programmer used this method in such a way, that it have to be a class (for example have used class references inside SongRequest)... As a result no one did really knowns why something is not working because each of them have dome right thing... There is no excuse to use a class for a local usage instead of implicit declaration of parameters.
Generally you have a good chances to get such a situation in a future, because:
*
*you are not the one who changes your code (i.e. GetMusic)
*someone can review the code and find the class 'SongReqest' useful (so situation goes even worse - from a local usage to a global usage of a class)
*adding the SongReuest class can add an additional dependencies for you method (is someone changes this class, most likely you founction will not compile)
*using SongRequest as a property bag locks it usage only as as a class, as mentioned before.
*using this class, you method would probably never share it parameters with other function calls (for what reason?)
*finally, using SongRequest class only for passing parameters for a specific function, gives additional memory overhead footprint, because if this method is called often, at one hand, it will create a lot of unnecessary objects in memory have to be garbage collected, in the other hand, if such a method is used rarely, it will be simply not practical to create a class to pass several variables to a single call
There is only one real reason to use class instead of a two string arguments: you programmer likes such calls and wants to make all code "more beautiful than before", more monadic, despite the fact that this is not very practical and useful.
I would never advice you to make a code looks like this until you want to make it looks better.
Generally, I suppose that using a custom class for passing an arguments for a function is a bad practice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I fetch only the top 20 objects from core data I need to find the 20 objects most recently viewed (date-stamped) by the user. Each object has a property in the core data model called dateVisited. When the user views a particular object, the dateVisited property is assigned the current date stamp.
So, I have a 'Recent' view that shows the 20 most recently viewed objects. I'm currently using the code below to fetch and sort the data.
[fetchRequest setEntity:[NSEntityDescription entityForName:@"object" inManagedObjectContext:self.moc]];
predicate = [NSPredicate predicateWithFormat:
@"objectNumber contains[cd] %@", searchTerm];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateVisited" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.moc
sectionNameKeyPath:nil
cacheName:nil];
[fetchRequest release];
The code returns the set of 3,000 objects in order, and I display the first 20. However, it's sorting all 3,000 objects and takes time to do so. It would be far more efficient if the sort only kept track of the 20 'top' encountered objects and dropped each one along the way if that object already was not in the top 20 encountered so far.
So my question is this: Is there a way to do a fetch/sort that only keeps track of the running top 20 objects?
A: [fetchRequest setFetchLimit:20];
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++ Passing *this as reference during construction of self Is the following safe? I know, strictly speaking, dereferencing a pointer before the thing to which it points has been properly constructed seems dangerous, but I imagine the compiler will just provide a pointer without actually doing any dereferencing. Well, I assume.
(Note: gInst doesn't actually use the reference until much later.)
TU 1
Sys::System::System::System(const sf::VideoMode& rVM, const std::string& rSTR, unsigned long settings) :
win(rVM, rSTR, settings),
gInst(*this)
{
}
Header A
namespace Sys
{
namespace System
{
struct System;
}
namespace UI
{
struct GUI
{
System::System& topl;
MenuBar menu;
GUI(System::System&);
private:
GUI();
GUI(const GUI&);
GUI& operator=(const GUI&);
};
}
}
Header B
namespace Sys
{
namespace System
{
struct System
{
sf::RenderWindow win;
Sys::UI::GUI gInst;
Sys::Editor::Editor eInst;
System(const sf::VideoMode&, const std::string&, unsigned long);
private:
System();
System(const System&);
System& operator=(const System&);
};
void start();
}
}
A:
(Note: gInst doesn't actually use the reference until much later.)
Then it's completely safe. (Taking note you say "the reference", not "the value".)
Compilers will just warn about it for the reason you've stated, but there's nothing undefined about it, just "risky". Note that you can often trump compiler warnings (if they bother you) with something like this:
struct foo
{
foo() : b(self())
{}
private:
foo& self() { return *this; }
bar b;
};
A: The short answer: Maybe, if you're careful.
The long answer: https://isocpp.org/wiki/faq/ctors#using-this-in-ctors
Relating to your specific issue: That's fine, as long as gInst really is a reference.
(a class called System in the namespace System in the namespace Sys? o.O)
A: As long as gInst never accesses a data member or member function of gInst or attempts to perform run-time type introspection via RTTI or dynamic_cast, until after the constructor has completed, then it is safe.
A: How is gInst declared? if it takes a reference and stores it as reference(Sys::System::System &)/pointer(Sys::System::System *) its safe. If it takes a raw class (Sys::System::System) or stores it as a raw class, it will not be safe as it will copy it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to include package data with setuptools/distutils? When using setuptools, I can not get the installer to pull in any package_data files. Everything I've read says that the following is the correct way to do it. Can someone please advise?
setup(
name='myapp',
packages=find_packages(),
package_data={
'myapp': ['data/*.txt'],
},
include_package_data=True,
zip_safe=False,
install_requires=['distribute'],
)
where myapp/data/ is the location of the data files.
A: Using setup.cfg (setuptools ≥ 30.3.0)
Starting with setuptools 30.3.0 (released 2016-12-08), you can keep your setup.py very small and move the configuration to a setup.cfg file. With this approach, you could put your package data in an [options.package_data] section:
[options.package_data]
* = *.txt, *.rst
hello = *.msg
In this case, your setup.py can be as short as:
from setuptools import setup
setup()
For more information, see configuring setup using setup.cfg files.
There is some talk of deprecating setup.cfg in favour of pyproject.toml as proposed in PEP 518, but this is still provisional as of 2020-02-21.
A: Update: This answer is old and the information is no longer valid. All setup.py configs should use import setuptools. I've added a more complete answer at https://stackoverflow.com/a/49501350/64313
I solved this by switching to distutils. Looks like distribute is deprecated and/or broken.
from distutils.core import setup
setup(
name='myapp',
packages=['myapp'],
package_data={
'myapp': ['data/*.txt'],
},
)
A: I had the same problem for a couple of days but even this thread wasn't able to help me as everything was confusing. So I did my research and found the following solution:
Basically in this case, you should do:
from setuptools import setup
setup(
name='myapp',
packages=['myapp'],
package_dir={'myapp':'myapp'}, # the one line where all the magic happens
package_data={
'myapp': ['data/*.txt'],
},
)
The full other stackoverflow answer here
A: I found this post while stuck on the same problem.
My experience contradicts the experiences in the other answers.
include_package_data=True does include the data in the
bdist! The explanation in the setuptools
documentation
lacks context and troubleshooting tips, but
include_package_data works as advertised.
My setup:
*
*Windows / Cygwin
*git version 2.21.0
*Python 3.8.1 Windows distribution
*setuptools v47.3.1
*check-manifest v0.42
Here is my how-to guide.
How-to include package data
Here is the file structure for a project I published on PyPI.
(It installs the application in __main__.py).
├── LICENSE.md
├── MANIFEST.in
├── my_package
│ ├── __init__.py
│ ├── __main__.py
│ └── _my_data <---- folder with data
│ ├── consola.ttf <---- data file
│ └── icon.png <---- data file
├── README.md
└── setup.py
Starting point
Here is a generic starting point for the setuptools.setup() in
setup.py.
setuptools.setup(
...
packages=setuptools.find_packages(),
...
)
setuptools.find_packages() includes all of my packages in the
distribution. My only package is my_package.
The sub-folder with my data, _my_data, is not considered a
package by Python because it does not contain an __init__.py,
and so find_packages() does not find it.
A solution often-cited, but incorrect, is to put an empty
__init__.py file in the _my_data folder.
This does make it a package, so it does include the folder
_my_data in the distribution. But the data files inside
_my_data are not included.
So making _my_data into a package does not help.
The solution is:
*
*the sdist already contains the data files
*add include_package_data=True to include the data files in the bdist as well
Experiment (how to test the solution)
There are three steps to make this a repeatable experiment:
$ rm -fr build/ dist/ my_package.egg-info/
$ check-manifest
$ python setup.py sdist bdist_wheel
I will break these down step-by-step:
*
*Clean out the old build:
$ rm -fr build/ dist/ my_package.egg-info/
*Run check-manifest to be sure MANIFEST.in matches the
Git index of files under version control:
$ check-manifest
If MANIFEST.in does not exist yet, create it from the Git
index of files under version control:
$ check-manifest --create
Here is the MANIFEST.in that is created:
include *.md
recursive-include my_package *.png
recursive-include my_package *.ttf
There is no reason to manually edit this file.
As long as everything that should be under version control is
under version control (i.e., is part of the Git index),
check-manifest --create does the right thing.
Note: files are not part of the Git index if they are either:
*
*ignored in a .gitignore
*excluded in a .git/info/exclude
*or simply new files that have not been added to the index yet
And if any files are under version control that should not be
under version control, check-manifest issues a warning and
specifies which files it recommends removing from the Git index.
*Build:
$ python setup.py sdist bdist_wheel
Now inspect the sdist (source distribution) and bdist_wheel
(build distribution) to see if they include the data files.
Look at the contents of the sdist (only the relevant lines are
shown below):
$ tar --list -f dist/my_package-0.0.1a6.tar.gz
my_package-0.0.1a6/
...
my_package-0.0.1a6/my_package/__init__.py
my_package-0.0.1a6/my_package/__main__.py
my_package-0.0.1a6/my_package/_my_data/
my_package-0.0.1a6/my_package/_my_data/consola.ttf <-- yay!
my_package-0.0.1a6/my_package/_my_data/icon.png <-- yay!
...
So the sdist already includes the data files because they are
listed in MANIFEST.in. There is nothing extra to do to include
the data files in the sdist.
Look at the contents of the bdist (it is a .zip file, parsed
with zipfile.ZipFile):
$ python check-whl.py
my_package/__init__.py
my_package/__main__.py
my_package-0.0.1a6.dist-info/LICENSE.md
my_package-0.0.1a6.dist-info/METADATA
my_package-0.0.1a6.dist-info/WHEEL
my_package-0.0.1a6.dist-info/entry_points.txt
my_package-0.0.1a6.dist-info/top_level.txt
my_package-0.0.1a6.dist-info/RECORD
Note: you need to create your own check-whl.py script to produce the
above output. It is just three lines:
from zipfile import ZipFile
path = "dist/my_package-0.0.1a6-py3-none-any.whl" # <-- CHANGE
print('\n'.join(ZipFile(path).namelist()))
As expected, the bdist is missing the data files.
The _my_data folder is completely missing.
What if I create a _my_data/__init__.py? I repeat the
experiment and I find the data files are still not there! The
_my_data/ folder is included but it does not contain the data
files!
Solution
Contrary to the experience of others, this does work:
setuptools.setup(
...
packages=setuptools.find_packages(),
include_package_data=True, # <-- adds data files to bdist
...
)
With the fix in place, redo the experiment:
$ rm -fr build/ dist/ my_package.egg-info/
$ check-manifest
$ python.exe setup.py sdist bdist_wheel
Make sure the sdist still has the data files:
$ tar --list -f dist/my_package-0.0.1a6.tar.gz
my_package-0.0.1a6/
...
my_package-0.0.1a6/my_package/__init__.py
my_package-0.0.1a6/my_package/__main__.py
my_package-0.0.1a6/my_package/_my_data/
my_package-0.0.1a6/my_package/_my_data/consola.ttf <-- yay!
my_package-0.0.1a6/my_package/_my_data/icon.png <-- yay!
...
Look at the contents of the bdist:
$ python check-whl.py
my_package/__init__.py
my_package/__main__.py
my_package/_my_data/consola.ttf <--- yay!
my_package/_my_data/icon.png <--- yay!
my_package-0.0.1a6.dist-info/LICENSE.md
my_package-0.0.1a6.dist-info/METADATA
my_package-0.0.1a6.dist-info/WHEEL
my_package-0.0.1a6.dist-info/entry_points.txt
my_package-0.0.1a6.dist-info/top_level.txt
my_package-0.0.1a6.dist-info/RECORD
How not to test if data files are included
I recommend troubleshooting/testing using the approach outlined
above to inspect the sdist and bdist.
pip install in editable mode is not a valid test
Note: pip install -e . does not show if data files are
included in the bdist.
The symbolic link causes the installation to behave as if the
data files are included (because they already exist locally on
the developer's computer).
After pip install my_package, the data files are in the
virtual environment's lib/site-packages/my_package/ folder,
using the exact same file structure shown above in the list of
the whl contents.
Publishing to TestPyPI is a slow way to test
Publishing to TestPyPI and then installing and looking in
lib/site-packages/my_packages is a valid test, but it is too
time-consuming.
A: I just had this same issue. The solution, was simply to remove include_package_data=True.
After reading here, I realized that include_package_data aims to include files from version control, as opposed to merely "include package data" as the name implies. From the docs:
The data files [of include_package_data] must be under CVS or Subversion control
...
If you want finer-grained control over what files are included (for example, if
you have documentation files in your package directories and want to exclude
them from installation), then you can also use the package_data keyword.
Taking that argument out fixed it, which is coincidentally why it also worked when you switched to distutils, since it doesn't take that argument.
A: Ancient question and yet... package management of python really leaves a lot to be desired. So I had the use case of installing using pip locally to a specified directory and was surprised both package_data and data_files paths did not work out. I was not keen on adding yet another file to the repo so I ended up leveraging data_files and setup.py option --install-data; something like this
pip install . --install-option="--install-data=$PWD/package" -t package
A: I realize that this is an old question, but for people finding their way here via Google: package_data is a low-down, dirty lie. It is only used when building binary packages (python setup.py bdist ...) but not when building source packages (python setup.py sdist ...). This is, of course, ridiculous -- one would expect that building a source distribution would result in a collection of files that could be sent to someone else to built the binary distribution.
In any case, using MANIFEST.in will work both for binary and for source distributions.
A: Moving the folder containing the package data into to module folder solved the problem for me.
See this question: MANIFEST.in ignored on "python setup.py install" - no data files installed?
A: Just remove the line:
include_package_data=True,
from your setup script, and it will work fine. (Tested just now with latest setuptools.)
A: Like others in this thread, I'm more than a little surprised at the combination of longevity and still a lack of clarity, BUT the best answer for me was using check-manifest as recommended in the answer from @mike-gazes
So, using just a setup.cfg and no setup.py and additional text and python files required in the package, what worked for me was keeping this in setup.cfg:
[options]
packages = find:
include_package_data = true
and updating the MANIFEST.in based on the check-manifest output:
include *.in
include *.txt
include *.yml
include LICENSE
include tox.ini
recursive-include mypkg *.py
recursive-include mypkg *.txt
A: Following @Joe 's recommendation to remove the include_package_data=True line also worked for me.
To elaborate a bit more, I have no MANIFEST.in file. I use Git and not CVS.
Repository takes this kind of shape:
/myrepo
- .git/
- setup.py
- myproject
- __init__.py
- some_mod
- __init__.py
- animals.py
- rocks.py
- config
- __init__.py
- settings.py
- other_settings.special
- cool.huh
- other_settings.xml
- words
- __init__.py
word_set.txt
setup.py:
from setuptools import setup, find_packages
import os.path
setup (
name='myproject',
version = "4.19",
packages = find_packages(),
# package_dir={'mypkg': 'src/mypkg'}, # didnt use this.
package_data = {
# If any package contains *.txt or *.rst files, include them:
'': ['*.txt', '*.xml', '*.special', '*.huh'],
},
#
# Oddly enough, include_package_data=True prevented package_data from working.
# include_package_data=True, # Commented out.
data_files=[
# ('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
('/opt/local/myproject/etc', ['myproject/config/settings.py', 'myproject/config/other_settings.special']),
('/opt/local/myproject/etc', [os.path.join('myproject/config', 'cool.huh')]),
#
('/opt/local/myproject/etc', [os.path.join('myproject/config', 'other_settings.xml')]),
('/opt/local/myproject/data', [os.path.join('myproject/words', 'word_set.txt')]),
],
install_requires=[ 'jsonschema',
'logging', ],
entry_points = {
'console_scripts': [
# Blah...
], },
)
I run python setup.py sdist for a source distrib (haven't tried binary).
And when inside of a brand new virtual environment, I have a myproject-4.19.tar.gz, file,
and I use
(venv) pip install ~/myproject-4.19.tar.gz
...
And other than everything getting installed to my virtual environment's site-packages, those special data files get installed to /opt/local/myproject/data and /opt/local/myproject/etc.
A: For a directory structure like:
foo/
├── foo
│ ├── __init__.py
│ ├── a.py
│ └── data.txt
└── setup.py
and setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
NAME = 'foo'
DESCRIPTION = 'Test library to check how setuptools works'
URL = 'https://none.com'
EMAIL = 'gzorp@bzorp.com'
AUTHOR = 'KT'
REQUIRES_PYTHON = '>=3.6.0'
setup(
name=NAME,
version='0.0.0',
description=DESCRIPTION,
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
license='MIT',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
],
packages=['foo'],
package_data={'foo': ['data.txt']},
include_package_data=True,
install_requires=[],
extras_require={},
cmdclass={},
)
python setup.py bdist_wheel works.
A: Starting with Setuptools 62.3.0, you can now use recursive wildcards ("**") to include a (sub)directory recursively. This way you can include whole folders with all their folders and files in it.
For example, when using a pyproject.toml file, this is how you include two folders recursively:
[tool.setuptools.package-data]
"ema_workbench.examples.data" = ["**"]
"ema_workbench.examples.models" = ["**"]
But you can also only include certain file-types, in a folder and all subfolders. If you want to include all markdown (.md) files for example:
[tool.setuptools.package-data]
"ema_workbench.examples.data" = ["**/*.md"]
It should also work when using setup.py or setup.cfg.
See https://github.com/pypa/setuptools/pull/3309 for the details.
A: include_package_data=True worked for me.
If you use git, remember to include setuptools-git in install_requires. Far less boring than having a Manifest or including all path in package_data ( in my case it's a django app with all kind of statics )
( pasted the comment I made, as k3-rnc mentioned it's actually helpful as is )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "184"
} |
Q: How to detect a framed image from a photo in iOS I'm wondering if there's a way to, after allowing a user to take a photograph, analyze the photograph and find a framed image within it. (For example, if someone took a photograph of a framed family portrait or something, I want to be able to programmatically sense the image and where the border of the portrait begins and work with the image).
Any help at all is really appreciated, I don't know much about graphics. Thanks!
A: This would take tons of coding. If you aren't very with graphics manipulation, then maybe you should do a little research on it. Unless there is an apple-provided shortcut that I don't know about...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: uart problem with linux and user written operating system statement: i have tried almost all the options for getting to work, trying to send data thru UART from a intel pentium 2 system using a device driver in polled io mode written by me, its very simple the code can be seen in http://pastebin.com/8snzeaXu
also the linux code for sending data http://pastebin.com/YRszQqRv
baud rate and properties like 8-N-1 is set on both the sides ... if u want details regarding serial uart registers use http://www.lammertbies.nl/comm/info/serial-uart.html#LSR
issue: i miss some data in the transmission
A: Missing data usually means that data is overwritten when sending. Instead of sleeping some usecs between sending bytes, can't you query the status register, like check the LSR for THR empty? Maybe you add flow control like xon/xoff, too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't include SendGrid in my Rails3 project I'm very new to ruby and rails (3 days and counting), so my problem is probably something stupid. However, it seems to be something stupid that couldn't be resolved by searching for answers online. :(
I'm creating a simple blog app following this guide: http://guides.rubyonrails.org/getting_started.html. It works fine, no issues.
Then I set up SendGrid and I'm able to send emails through it just fine as well.
Now, I'm trying to use this sendgrid gem: https://github.com/stephenb/sendgrid. I installed it using 'gem install sendgrid' and it seemed to work without problems.
According to the instructions on github, I just need to add "include SendGrid" in my mailer class and I'm good to go. I did just that:
class Emailer < ActionMailer::Base
include SendGrid
...
end
But when I run the app, I get this error: uninitialized constant Emailer::SendGrid
I did a couple of other things that seemed to make sense based on what I've read so far:
*
*Added 'gem sendgrid' in my Gemfile. This added three lines to my Gemfile.lock:
*
*sendgrid (1.0.1)
*json
*json
*Added 'require sendgrid' in my environment.rb file.
Yet, the error still persists. One thing that might be indicative of a problem is that when I look at the $LOAD_PATH, it doesn't have the sendgrid directory. For comparison, another gem included in the same manner is sqlite3 and I see the ".../sqlite3-1.3.4/lib" path there, but I don't see ".../sendgrid-1.0.1/lib".
Can somebody discern what kind of stupidity has afflicted me this time?
EDIT:
I discovered something very interesting. For me at least... If I go into the rails console, things actually seem to work fine. Here is the output of my session:
ruby-1.9.2-p290 :006 > include SendGrid
=> Object
ruby-1.9.2-p290 :007 > sendgrid_category :use_subject_lines
=> :use_subject_lines
ruby-1.9.2-p290 :008 > sendgrid_category "Welcome"
=> "Welcome"
ruby-1.9.2-p290 :009 > p = Post.new(:title => "A new post", :content => "With garbage text")
=> #<Post id: nil, name: nil, title: "A new post", content: "With garbage text", created_at: nil, updated_at: nil>
ruby-1.9.2-p290 :010 > Emailer.send_email("nick@sidebark.com", p).deliver
=> #<Mail::Message:2194904560, Multipart: false, Headers: <Date: Thu, 22 Sep 2011 16:52:41 -0700>, <From: ... blah, bah, blah...>>
The email got sent AND the category got registered by SendGrid (I could see it on the Statistics page).
So, the big question is: Why is it that my app only allows me to include SendGrid when I'm running commands form the console? What's the difference in environment, etc.?
Also note that the emails get sent form the console, but NOT from the app flow, even though the development.log says that an email was sent in both situations...
A: For anyone who didn't read the comments on the original post, the answer is that the server needs to be restarted once you make changes to the dependencies or the configuration of your app.
As far as the reason things were working in the console, every time you load up a Rails console, you're reloading your entire app including the new dependencies and config files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: In DirectX 11, how to create and register two buffers in SwapChain (DXGI_SWAP_CHAIN_DESC) I am a beginner of DirectX 11, and following the book Beginning DirectX 11, in chapter 2, there is a code for creating a buffer using the following code:
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory( &swapChainDesc, sizeof( swapChainDesc ) );
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = width;
swapChainDesc.BufferDesc.Height = height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hwnd;
swapChainDesc.Windowed = true;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
My question is that in the description of swap chain, apparently there is space for only one buffer, as there is only one BufferDesc (DXGI_MODE_DESC struct). So if BufferCount is set to 2 or more, how is the second buffer registered? Is it using another DXGI_SWAP_CHAIN_DESC? Please post some example code.
Also BufferCount has type UNIT, which means more than two buffers can be added. While 2 buffers are used in double buffering technique, in which one buffer is used to draw on, and another buffer is used to display on the scene, and buffers are swapped. What is the use, advantages of more than two buffers?
A: Having more buffers generally means a speed improvement. When the buffers are swapping, you can't do any rendering on any of them. You have to wait until they are fully swapped. This could take some time which you could have used rendering another frame. Triple buffering is exactly this. You can go up to 4 (6?) buffers, when doing some stereoscopic stuff. Any more would be useless.
Haven't got my hands on DX for a while, but I remember it handling it automatically when swapChainDesc.BufferCount is set to a value. Also, I know this is only chapter two, but please, use two buffers. No matter what they say, your code won't change, and you'll have a speed increase .And anyways, it is better to have two buffers. What if your one and only buffer can't be fully rendered on the next VBlank ? Oops, missing image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Passenger Error message: Could not find cancan-1.6.5 in any of the sources I'm trying to deploy a Rails app to a Ubuntu 10.04 Lucid. I keep on getting this error:
Error message: Could not find cancan-1.6.5 in any of the sources (Bundler::GemNotFound)
Even though the gem is there. I packaged the gems and did a bundle local. Didn't work.
So then I tried bundle install and didn't worked either.
I did use RVM, but I'm using the same thing in my development machine and runs with no problem.
I get this too on the error page: Further information about the error may have been written to the application's log file. Please check it in order to analyse the problem. So I go to look for the production.log file and it's not even there, there is just a development.log file
A: It sounds like you have an environment specific gem requirement.
Make sure you don't have any config.gem references in your config/environments/*.rb files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL database structure question How would one structure a database where you have City, State, and Country, and Cities sometimes have states and sometimes don't? Would you simply put State_ID (default NULL) and Country_ID in City or is there a better way to approach it?
A: Your approach seems spot on. If there is no enforceable hierarchy, then you're not left with much choice.
When the real world doesn't conform to our schema, then we've got no choice than to make our schema conform to the real world.
A: If your DBA's a stickler for really tight normalization, an alternative would be to have special "No State" records in the State table. You would need one of these for each Country (at least, each one that has "stateless" cities).
A: Going to accept the answer offered. But just want to note that one other approach not mentioned here would be a City_States many to many table. This would be an especially useful approach for some cities which are in two states.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ABMultiValueRef memory leak? When I use Instruments, it complains of a memory leak on emailProperty. Analyzer complains about mobileLabel. The code snippet is below. Given that I use release and CFRelease, is there an obvious reason why it's complaining? Thanks in advance for any responses.
// Email is a multi value property, take "Home"
ABMultiValueRef emailProperty = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *email;
NSString *mobileLabel;
for (CFIndex i = 0; i < ABMultiValueGetCount(emailProperty); i++)
{
mobileLabel = (NSString *)ABMultiValueCopyLabelAtIndex(emailProperty, i);
if ([mobileLabel isEqualToString:@"_$!<Home>!$_"])
{
email = (NSString *)ABMultiValueCopyValueAtIndex(emailProperty,i);
self.emailAddress.text = email;
self.emailAddress.enabled = NO;
self.emailAddress.borderStyle = UITextBorderStyleNone;
[email release];
break;
}
[mobileLabel release];
}
CFRelease(emailProperty);
A: I switched from using NSString* to CFString + CFRelease, and that seemed to do the trick. The Analyzer still complains, but it seemed to run fine under Profile -> Leaks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Splitting a file into multiple files I have a text file which has
DXS....
1Line
2Line
DXE
DXS
1Line
2Line
DXS
I need code to read the above file and write into the another file till it sees the DXE. So basically I will have multiple files which will consist of lines from DXS till DXE.
In the above case I will have 2 files created.
A: Here is a good introduction to learn how to read and write text files in C#. I would also take a look at File.ReadAllText or File.ReadLines and their counterparts File.WriteAllText and File.WriteAllLines.
If you already have code and it's simply not working right, edit your question to include it and we can help you iron out the kinks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: Parallels Plesk + IIS7 asp.net 4.0 error: Unrecognized attribute 'targetFramework' I'm using a godaddy VPS with parallels plesk. Since my application is asp.net 4.0 I get the error:
"Unrecognized attribute 'targetFramework'
I realize it's because the application pools are set to asp.net 2.0, which I can't change in plesk, so I remote connect to my server, open IIS7, go into my application pools and set all of them to asp.net 4.0, but then I get this detailed error: (caused by changing plesk(default)(2.0)(pool) to 4.0)
HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by
the static file handler.
Most Likely Causes:
•The request matched a wildcard mime map. The request is mapped to the
static file handler. If there were different pre-conditions, the
request will map to a different handler.
How can I get my asp.net 4.0 web application to run properly? There must be a decent way to get my asp.net application to run with parallels plesk. Any help would be greatly appreciated.
A: Getting the following error when you deploy your first asp.net 4.0 website:
Unrecognized attribute ‘targetFramework’. Note that attribute names are case-sensitive.
is most likely because of either of 2 reasons:
1. You installed the .net 4.0 bits after IIS was set up, resulting in the wrong version of the .NET framework beeing registered with IIS.
Most often the above results in conflicting versions of the framework, and so the easiest way of solving this is to re-register the .NET extensions with IIS using the aspnet_regiss tool. Make sure you run it from an elevated command prompt and that you use the correct version (in the v4.xx folder that is, not the v2.xx one). On my dev machine this tool is located in:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319
and you run it with the -iru flags like so:
aspnet_regiis.exe -iru
2. You haven’t set the framework of the IIS application to the correct version of .NET (4.0 that is)
Change this using either the IIS Manager or the command line. In IIS Manager you select ‘Application Pools’, click the Application you’ve pointed you site to use, select ‘Basic Settings’ in the ‘Actions’ pane and change the ‘.NET framework version’.
This post over at MSDN should also be of great help. Gotta love Microsoft’s documentation!
http://msdn.microsoft.com/en-us/library/dd483478(VS.100).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting iphone app to universal woes? I've converted my app to a universal app in xCode 4. This created me my MainWindow-iPad.xib automatically and modified my info.plist to include the iPad version of my Main Nib File Base Name....(MainWindow-iPad).
Sadly though, my app appears to be still using my iphone version of my MainWindow.xib.
This can't be right. My target is set to Universal.
Can anyone suggest why my iPad version isn't being used?
Thanks
A: Open up the Project and Find your plist
Right click in the plist and select "Show raw keys/value pairs"
You should see two ipad entries
NSMainNibFile~ipad
and
UISupportedInterfaceOrientations~ipad
NSMainNibFile~ipad should have the name of your ipad interface.
inside UISupportedInterfaceOrientations~ipad
you should have at least one key.
My app is Landscape so here are the ones I have
UIInterfaceOrientationLandscapeRight
UIInterfaceOrientationLandscapeLeft
Sometimes the project editor does not edit the Plist correctly.
verify these settings and verify the class types and connections in the ipad xib file are correct.
Hope that helps.
A: Sorted it!
I needed to do a ios reset on the ipad simulator. Just stumbled upon it
Thanks for the input.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get a list of all my facebook status posts of all time? I want the easiest way to download all the status updates I've done since inception of my account?
A: You can go to https://www.facebook.com/settings
and click on download facebook data at the bottom.
A: Go to https://www.facebook.com/settings, click "Download a copy of your facebook data", down at the bottom of the page.
Or, using the graph API, access /me/statuses repeatedly, setting the until parameter to the date of the last post you parsed, something like this:
# pseudocode:
until = now
do:
posts = fetch https://graph.facebook.com/me/statuses?access_token=xxx&until=until
for each post in posts:
savepost(post)
if post.updated_time is before until:
until = post.updated_time
while posts.length > 0
But be aware that some have observed that some posts mysteriously go missing using any API to download all posts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: insanity is free() In my simple C program (gnu linux) I am getting the rss value from proc/stat.
int GetRSS() returns the RSS value from proc/stat for my process.
In this instance:
printf("A RSS=%i\n", GetRSS());
char *cStr = null;
cStr = malloc(999999);
if (cStr != NULL)
{
printf("B RSS=%i\n", GetRSS());
free(cStr);
printf("C RSS=%i\n", GetRSS());
}
I get:
A RSS=980
B RSS=984
C RSS=980
I can't explain why C did not return 984.
If I run the same procedure twice I get:
A RSS=980
B RSS=984
C RSS=980
B RSS=984
C RSS=980
Looks fine.
But, in this instance:
struct _test
{
char *pChar;
}
struct _test **test_ptr;
int i = 0;
printf("D RSS=%i\n",GetRSS());
assert(test_ptr = (struct _test **)malloc( (10000) * sizeof(struct _test *)));
for (i = 0; i < 1000; i++)
{
assert(test_ptr[i] = (struct _test *)malloc(sizeof(struct _test)));
test_ptr[i]->pChar=strdup("Some garbage");
}
printf("E RSS=%i\n", GetRSS());
for (i=0; i<1000; i++)
{
free(test_ptr[i]->pChar);
free(test_ptr[i]);
}
free(test_ptr);
printf("F RSS=%i\n", GetRSS());
I get:
D RSS=980
E RSS=1024
F RSS=1024
D RSS=1024
E RSS=1024
F RSS=1024
Huh? Why is the memory not freeing here?
A: The fact that a block of memory has been freed does not necessarily make that block the most eligible for a subsequent allocation. There are several strategies for a memory manager to select a block of memory (best fit, worst fit, first fit).
Most memory managers also attempt to coalesce free blocks, but some try to let the free blocks "age" as long as possible before coalescing, on the theory that as they age, there's a better chance that blocks next to them will also be freed, improving the success rate at coalescing blocks (thus reducing fragmentation).
The fact that the block wasn't used to satisfy your next allocation request does not mean it wasn't freed.
A: From the free() man page: "Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc."
A: Your malloc library elected not to do that. It may be for strategic reasons (to avoid having to go to the system for more memory later) or it may be due to limitations (in that particular cause, it doesn't recognize that it can free the memory).
In general, it doesn't matter. Address space and virtual memory are typically not considered scarce resources. So excessive effort to minimize their consumption is generally worthless at best and often harmful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: JSESSIONID getting changed I have a web app that makes heavy use of jQuery.ajax() and jQGrid. In a typical flow:
*
*User comes to index.html
*Does userid/password authentication via ajax
*On success, they are directed to home.html
*home.html does multiple ajax requests to populate items on the page.
*These requests are: getBriefProfile, getAuthenticatedUser and getProperties.
*The getProperties call originates from jQGrid that has to display the properties in a table.
I was running into a problem where the getProperties call on the server was not attached to the authenticated session and hence failing. Looking at XHR captures in Chrome/Safari/Firefox developer tools, I see different behavior on different browsers.
In Firefox, I see that all XHR requests submit the correct JSESSIONID cookie, except the getProperites call, which seems to not submit any cookie and thus results in a new session.
In Chrome I see strange Cookie request headers with two values of JSESSIONID:
Cookie:JSESSIONID=hncGp+UQxJ4X+FUEwj-gdejS; JSESSIONID=NCj6wdLOxh3zwutXEvB1UQYr; __utma=199763511.429181615.1314144361.1316197892.1316480513.20; __utmz=199763511.1314144361.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
I did not even think this was possible.
Any ideas what is going wrong? All XHR requests go to the same context path on the app server.
Thanks.
-Raj
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Launching OpenMPI/pthread apps with slurm On Cray computers such as an XE6, when launching a hybrid MPI/pthreads application via aprun there is a depth parameter which indicates the number of threads each process can spawn. For example,
aprun -N2 -n12 -d5
Each process can spawn 5 threads which the OS will distribute.
Is there a similar option when launching OpenMPI/pthread applications with Slurm's srun? The machine is a generic HP cluster with nehalem processors and IB interconnect. Does it matter if thread support level is only MPI_THREAD_FUNNELED?
A: This is the script I use to launch a mixed MPI-OpenMP job. Here n is the number of nodes and t the number of threads.
sbatch <<EOF
#!/bin/bash
#SBATCH --job-name=whatever
#SBATCH --threads-per-core=1
#SBATCH --nodes=$n
#SBATCH --cpus-per-task=$t
#SBATCH --time=48:00:00
#SBATCH --mail-type=END
#SBATCH --mail-user=blabla@bibi.zz
#SBATCH --output=whatever.o%j
. /etc/profile.d/modules.sh
module load gcc
module unload openmpi
module load mvapich2
export OMP_NUM_THREADS=$t
export LD_LIBRARY_PATH=/apps/eiger/Intel-CPP-11.1/mkl/lib/em64t:${LD_LIBRARY_PATH}
mpiexec -np $n myexe
EOF
Hope it helps
A: You typically select the number of MPI processes with --ntasks and the number of threads per process with --cpu-per-task. If you request --ntasks=2 and --ncpus-per-task=4, then slurm will allocate 8 cpus either on one node, or on two nodes, four cores each, depending on resource availability and cluster configuration.
If you specify --nodes instead of --ntasks, Slurm will allocate one process per node, as if you choose --ntask-per-node=1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python Distance Formula Calculator My assignment is to make a distance calculator that finds the distance between two locations, and I chose to use Python.
I've put all the locations into coordinate points, but I need to know how to pick two of these by name, then apply the distance formula to them:
(sqrt ((x[2]-x[1])**2+(y[2]-[y1])**2)
Anyways, I don't need you to write the whole thing, just point me in the right direction.
fort sullivan= (22.2, 27.2)
Fort william and mary= (20.2, 23.4)
Battle of Bunker II= (20.6, 22)
Battle of Brandywine= (17.3, 18.3)
Battle of Yorktown= (17.2, 15.4)
Jamestown Settlement= (17.2, 14.6)
Fort Hancock=(18.1, 11.9)
Siege of Charleston=(10.2, 8.9)
Battle of Rice Boats=(14.1, 7.5)
Castillo de San Marcos=(14.8, 4.8)
Fort Defiance=(13.9, 12.3)
Lexington=(10.5, 20.2)
A: You just need to put them in a dictionary, like:
points = {
'fort sullivan': (22.2, 27.2),
'Fort william and mary': (20.2, 23.4)
}
and then select from the dictionary and run your thing
x = points['fort sullivan']
y = points['Fort william and mary']
# And then run math code
A: Use a dict to store the tuples:
location = {}
location['fort sullivan'] = (22.2, 27.2)
location['Fort william and mary'] = (20.2, 23.4)
Or you can use the intializer syntax:
location = {
'fort sullivan': (22.2, 27.2),
'Fort william and mary': (20.2, 23.4)
}
Although you may well want to read the data in from a file.
Then you can write a distance function:
def dist(p1, p2):
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
Then you can call it like this:
print dist(
location['fort sullivan'],
location['Fort william and mary']
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Grails tab order I was recently given a project to modify and I know very little about Grails. All I need to do is edit the code to make it so the user does not have to use a mouse, so I need to set the tab order. How do I do that?
Thanks!
A: Set the tabindex property on the fields in the .gsp files, just like an HTML page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net: how do i prevent users from posting the same data multiple times i have a little asp.net web application.
it is a front end to a sql-server-2008 database.
after they fill out all the data, they will press submit and the data will be sent to the database.
after this point if the user refreshes the page, the data is posted again!!! how do i disable this from happening?
A: Send a Location header back to the user that redirects the browser to another page: refresh will then reload that other page rather than resubmit the old form.
A: You need to follow the Post/Redirect/Get pattern which is explained on WikiPedia and alluded to by Femi. In your code after you've done your processing do a Response.Redirect to the desired page.
A: This is caused by the last request being a POST request to the page, what do you need to do is a redirect so the last request becomes a GET.
After you have handled the post data you can just do a redirect to the same page with:
Response.Redirect("~/ThePage.aspx");
This will prevent you from presenting a message to the user straight from the code behind, if you want to present a success message using this method you will need to add a querystring or something similar:
Response.Redirect("~/ThePage.aspx?result=success");
And then check on the page bind if the querystring to present a success message is set, such a check could look something like this:
if (Request.QueryString["result"] != null && Request.QueryString["result"].ToString().ToLower() == "success")
{
//Show success message
}
Another solution which probably is superior but might require some more work is to wrap the form in a updatepanel, you can read more about it here: http://ajax.net-tutorials.com/controls/updatepanel-control/
An updatepanel will make the form submit with AJAX instead of full postback.
A: See this article about the PRG pattern: http://en.wikipedia.org/wiki/Post/Redirect/Get
In short, after the user POSTs (submits) data to your server, you issue a Response.Redirect to have the users browser GET a page. This way, if the user presses the reload button, it is the GET request that is repeated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to remove multiple line breaks from RSS feed? How to remove multiple <br> tags from a RSS feed? I tried those two but it doesn't make any change.
str_replace("<br/><br/>","&",$entry->description);
str_replace("<br><br>","&",$entry->description);
str_replace("<br/><br/>","&",$entry->description);
str_replace("<br /><br />","&",$entry->description); (with space)
Here is a sample
This is copied from feedburn RSS<br /><br />with view page source.
A: It's probably getting escaped, so maybe try:
$formatted = $entry->description
$formatted = str_replace("<br/><br/>","&",$formatted);
$formatted = str_replace("<br /><br />","&",$formatted);
print($formatted)
Make sure you print/echo $formatted. str_replace is not a destructive function, so you need to use its return value.
A: Open it in a DOM Parser and look for br elements of whom their nextSibling (or previousSibling if iterating in reverse) is another br element (you could repeat this for multiple br elements that are direct siblings). Then remove them.
$dom = new DOMDocument;
$dom->loadHTML($html);
$elements = $dom->getElementsByTagName('br');
$length = $elements->length;
while ($length--) {
$elem = $elements->item($length);
$prevSibling = $elem->previousSibling;
if ($prevSibling->nodeType == 1 AND $prevSibling->tagName == 'br') {
$parent = $elem->parentNode;
$parent->removeChild($elem);
$parent->removeChild($prevSibling);
$length--;
}
}
CodePad.
I chose to iterate in reverse to save another variable used for the incremental number.
I had to use a while() { ... } with an index because a foreach() would hold a reference to nodes I would be removing, which would result in errors.
A: If you want to replace more than one in a row, this will do it:
<?php
$entry = "Hello <br><br><br> my <br /><br /> dear <br/><br/><br/> friend";
$formatted = preg_replace('/(<br ?\/?>)+/',"<br />",$entry);
var_dump($formatted);
?>
This will return:
'Hello <br /> my <br /> dear <br /> friend'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SAP cProjects replication: Set task-level WBS When creating a project in cProjects I am using BADI BADI DPR_FIN_GECCO_ATTR to manipulate the external WBS ID that is created in SAP PS.
SAP accepts the ID that I pass for the Phase level, but for the Task level SAP appends a string "/TTO" to the end of my WBS ID. Any idea why this happens and how I can get rid of it. The "/TTO" violates or masking structure in PS?
constants: lc_phase_id_ps type char30 value 'DPR_TV_PROJECT_ELEMENT_ID_PS',
lc_task_id_co type char30 value 'DPR_TV_PROJECT_ELEMENT_ID_CO'.
field-symbols: <project_ext> type dpr_ts_project_ext,
<project_int> type dpr_ts_project_int,
<phase_ext> type dpr_ts_phase_ext,
<phase_int> type dpr_ts_phase_int,
<task_ext> type dpr_ts_task_ext,
<task_int> type dpr_ts_task_int,
<attributes> type dpr_ts_iaom_object_attribute.
case ir_common->get_object_type( ).
when cl_dpr_co=>sc_ot_project.
"not doing anything with this data yet
assign ir_project_ext->* to <project_ext>.
assign ir_project_int->* to <project_int>.
when cl_dpr_co=>sc_ot_phase.
assign ir_attributes_ext->* to <phase_ext>.
assign ir_attributes_int->* to <phase_int>.
read table ct_attributes assigning <attributes>
with key data_element = lc_phase_id_ps.
if sy-subrc = 0.
<attributes>-value = <phase_ext>-phase_id. "something like Z/001-001
endif.
when cl_dpr_co=>sc_ot_task.
assign ir_attributes_ext->* to <task_ext>.
assign ir_attributes_int->* to <task_int>.
read table ct_attributes assigning <attributes>
with key data_element = lc_task_id_co.
if sy-subrc = 0.
<attributes>-value = <task_ext>-search_field. "something like Z/001-001-001
"sometime after this badi call it is changed to Z/001-001-001/TTO
endif.
endcase.
A: I have found the spot where SAP changes the WBS:
In Class CL_IM_CPRO_PROJECT_LABEL method IF_EX_GCC_PS_PROJECT_LABEL~GET_WBS_ELEMENT there is the following logic:
if lv_object_type_co ne 'DPO'.
read table attributes_of_ext_obj
into ls_attribute
with key data_element = 'DPR_TV_PROJECT_ELEMENT_ID_CO'.
if sy-subrc = 0.
if lv_object_type_co eq 'TTO' or "Aufgabe "H860739
lv_object_type_co eq 'ITO'. "Checklistenpunkt "H860739
concatenate ls_attribute-value "H860739
lv_object_type_co "H860739
into ls_value. "<<==Here it is "H860739
wbs_element = ls_value. "H860739
else. "H860739
wbs_element = ls_attribute-value.
endif. "H860739
else.
message e013(iaom_cprojects)
with 'DPR_TV_PROJECT_ELEMENT_ID_CO'
raising error_occurred.
endif.
"...
"... Code removed
endif.
This is part of a standard BAdI implementation for GCC_PS_PROJECT_LABEL.
I have solved the problem by enhancing the method using the implicit enhancement point at the end of the method and resetting the WBS element there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Left Join Hangs I am trying to figure out what could be causing a left join to hang. I've narrowed a problem down to a specific table but I can't for the life of me figure out what might be going on. Basically, I have two tables, lets call them table A and table B. When I left join table A to table B (its a 1 to 1 relationship with table B not always having a related record to table A) the query hangs. When I inner join table A to table B, it runs in about a half second returning about 27,000 records. Why is it when I run a left join, which should take a bit longer but not by much, it hangs? Could I have bad data in table B? The fields I'm joining are bigint's. I'm stumped on this one. Any help would be much appreciated.
Here is my sql:
select
RegMemberTrip.idmember,
RegParent1.idMember_Parent1,
regparent1.idParent1
from
regmembertrip
left join
regparent1 on RegMemberTrip.idmember = regparent1.idMember_Parent1
where
regmembertrip.IDRound = 25
*
*RegParent1 is a view
*If I change the where criteria to '= 24' it works fine. IDRound = 25 is fairly new data. And like I said, if I keep this the way it is (idround = 25) with an inner join it works fine.
Thanks,
Ben
A: Have you tried the execution path tool in the Management Console? Are you sure your left join is not in fact doing a giant cartesian product across A and B?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Problem with closing login form after user is authenticated ,using VB I have a very generic login form created that allows a user to access a application. My problem is getting the log in form to close after the application form is loaded. I have described the specifics in the comments of the code. Any help would be greatly appreciated.
Public Class frmUserLogin
Inherits System.Windows.Forms.Form
Private pass As String
Private username As String
Private attempt As Integer = 0
Private Admin As String
Private Password As String
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
username = "Admin"
pass = "Password"
If (txtUsername.Text = username) And (txtPassword.Text = pass) Then
MsgBox("That is correct")
frmApplicationWindow.Show()
'I am trying to close the login form after the user is able to load the frmapplicationwindow
'frmUserLogin.close() , when I use this it says I can use it because it is referring to the same instance of itself
'me.close , when I use this it closes both the user login form and the application form
Else
MsgBox("wrong username or pass, try again")
attempt += 1
End If
If attempt = 3 Then
MsgBox("You have reached the allowed number of login attempts")
Me.Close()
End If
End Sub
End Class
A: Just use Me.Hide in place of Me.Close.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is the ICMP ECHO data length compared to the size of timeval in the original ping source code? I've been reading through the original ping program code (http://www.ping127001.com/pingpage/ping.text) out of interest, just to see how it was done.
I get most of it, but there is one conditional that I don't understand:
if (datalen >= sizeof(struct timeval)) /* can we time 'em? */
timing = 1;
Where datalen is the length of the echo payload.
I've seen similar predicates in other C ping implementations. Why is it that a data length smaller than the size of a timeval struct prohibits timing?
EDIT: Inevitable late-night derp moment.
A: That's because you need to ensure the packets are big enough to store timing data if you want to actually store timing data in them. In other words, timing works by placing a timeval structure into the payload area.
If, for example, you specified a length of 3 for the ICMP payload area when the size of the timeval structure was 20, it wouldn't be a good idea trying to insert it :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Effects of z-index on drag and drop between two divs I have two container divs and want to drag and drop elements between them. I can drag and drop elements from the second container to the first but not the other way around. The problem is that the elements of the first container seem to have a lower z-index than the second container. When I drag them they slide under the second container. What must I do to have all the the elements be on top and be draggable to any droppable container? This is the fiddle showing the problem.
http://jsfiddle.net/vfAgd/12/
If you drag an element from container 1 to container 2, it goes under container 2. If you drag an element from container 2 you are able to drag it over container 1. This happens because container 2 is added to the document after container 1.
A: To fix this I had to remove the z-index for the containers.
.comdiv {
padding: 0;
margin-top: 20px;
margin-left: 20px;
border: 1px solid DarkKhaki;
border-radius: 3px 3px 0px 0px;
box-shadow: inset 0px 0px 10px DarkKhaki;
/* z-index: 26; */
}
http://jsfiddle.net/vfAgd/17/ .
A: There is a class name that jQuery UI draggable add to elements that are dragging. This class is removed after drag finishes. This class called ui-draggable-dragging. if you add an high z-index to the ui-draggable-dragging class your problem will be solved.
It should solve your problem. It seems your code have bugs. Debug it and add this css. It will work then.
.ui-draggable-dragging{z-index:9999;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android XPath, copy nodes from one document to another Hi I need to copy nodes from one XML into another one:
String _sPathOfrObj = "/response/grp/ofr/obj";
String _sPathHotelData = "/main/hotelData";
String _sPathStatus = "/main/status";
xpath.reset();
NodeList status = (NodeList) xpath.evaluate( _sPathStatus, details, XPathConstants.NODESET );
if(status.item( 0 ).getTextContent().equalsIgnoreCase( "ok" ))
{
NodeList nodes3 = (NodeList) xpath.evaluate( _sPathOfrObj, result, XPathConstants.NODESET );
NodeList nodes4 = (NodeList) xpath.evaluate( _sPathHotelData, details, XPathConstants.NODESET);
minimum = Math.min( nodes3.getLength(), nodes4.getLength() );
Log.i(CLASS_NAME, "obj="+nodes3.getLength());
Log.i(CLASS_NAME, "hdat="+nodes4.getLength());
for (i = 0; i < minimum; i++)
{
try
{
nodes3.item( i ).appendChild( nodes4.item( i ) );
}
catch(DOMException dome)
{
dome.printStackTrace();
Log.e(CLASS_NAME, dome.code+"" );
}
}
}
but it generates an error, DOMException WRONG_DOCUMENT_ERR or when I will do nodes4.item( i ).deepClone(true or false) it will throw DOMException NAMESPACE_ERR
Is there a way to do it?
Many thanks
A: I've managed to have it working, it is a mixture of my solution to overcome deepClone throwing NAMESPACE_ERR and the solution presented in the link.
Basically I wasn't able to make a copy of the given node without an error so I am flattening the XML to string and converting the string to new Node and by using the adoptNode I have my solution:)
I do realise that it is hell of a hack but it works for my tight deadline:)
The converting to string is done by using Transformer class as follows:
private static final String CLASS_NAME = "SendQueryTask";
//...
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
//...
private String transformXmlToString(Node node)
{
Transformer transformer = null;
try
{
transformer = TransformerFactory.newInstance().newTransformer();
}
catch (TransformerConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (TransformerFactoryConfigurationError e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if ( transformer != null )
{
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult( new StringWriter() );
DOMSource source = new DOMSource( node );
try
{
transformer.transform( source, result );
}
catch (TransformerException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String xmlString = result.getWriter().toString();
Log.i( CLASS_NAME, "flattened=" + (xmlString) );
return xmlString;
}
return null;
}
and to convert it back to Node
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.protocol.HTTP;
import java.io.UnsupportedEncodingException;
private Node dumbNodeCopy(Node item)
{
String xmlString = transformXmlToString( item );
if ( xmlString != null )
{
InputStream is = null;
try
{
is = new ByteArrayInputStream( xmlString.getBytes( HTTP.UTF_8 ) );
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if ( is != null )
{
Document doc = null;
dbf = DocumentBuilderFactory.newInstance();
try
{
db = dbf.newDocumentBuilder();
doc = db.parse( is );
doc.getDocumentElement().normalize();
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
if ( doc != null ) return doc.getFirstChild();
}
return null;
}
return null;
and finally the copying
NodeList nodes3 = (NodeList) xpath.evaluate( _sPathOfrObj, result,
XPathConstants.NODESET );
NodeList nodes4 = (NodeList) xpath.evaluate( _sPathHotelData, details,
XPathConstants.NODESET );
minimum = Math.min( nodes3.getLength(), nodes4.getLength() );
Log.i( CLASS_NAME, "obj=" + nodes3.getLength() );
Log.i( CLASS_NAME, "hdat=" + nodes4.getLength() );
for (i = 0; i < minimum; i++)
{
try
{
Node copy = dumbNodeCopy( nodes4.item( i ) );
if ( copy != null )
{
// nodes3.item( i ).appendChild( copy );
nodes3.item( i ).appendChild(
nodes3.item( i ).getOwnerDocument().adoptNode( copy ) );
}
else
Log.e( CLASS_NAME, "Copy of nodes4#" + i + ", failed." );
}
catch (DOMException dome)
{
dome.printStackTrace();
Log.e( CLASS_NAME, dome.code + "" );
}
}
btw. don't laugh at the code:-) I know that it looks terrible but my imperative ATM is to meet deadlines, and if anyone will propose neat solution I will happily adhere:)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: handle SMS- onReceive to trigger event in another activity/class so, what i'm trying to do is change some ui elements which are expanded in my main activity- and i want the changes to be triggered by the onReceive, which is from broadcastreceiver extended in a different separate class.
I'd like to do something like this
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(context, intent){
MainActivity main = new MainActivity(); //this is my... main activity :)
main.button.setBackgroundColor(Color.green);
}//end onReceive
}//end class
in my MainActivity, i've set values to the GUI button element like this:
public class mainactivity extends activity... implements onclick... bla bla (){
Button button;
onCreate....{
button = (Button)findViewById(R.id.button);
so i'd like to know if when onReceive is activated, can i edit the state of a widget in ANOTHER activity by instantiating that activity and calling a setter method on it?
A: Your method will not work because you are creating a new instance of MainActivity. This will not reference your currently active main activity. One solution you may try is sending another intent to your activity and implementing onNewIntent(Intent newIntent) in your activity. That way you can update your main activity in that function, try passing extras in with the new information you have received.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having a problem with external .js file and using google loader? This code works PERFECTLY fine when I include the jQuery within the html document; however, it stops working completely if I put it into an external javascript file. I referenced the jQuery library before referencing the external js file, so I'm not sure what the problem is. I'm a beginner with jQuery already.
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Stuff</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="/html5.js"></script>
<head>
<body>
<figure>
<img src="http://www.yalibnan.com/wp-content/uploads/2011/02/steve-jobs1.jpg" alt="Steve Jobs" />
<figcaption>
<p>Steve Jobs before giving up his title as CEO of Apple Inc.</p>
</figcaption>
</figure>
<section>
<ul id="edit" contenteditable="true">
<li>List item one</li>
</ul>
</section>
</body>
</html>
And the Javascript:
google.load("jquery", "1.3.2");
google.setOnLoadCallback(function() {
$(function($) {
var edit = document.getElementById('edit');
$(edit).blur(function(){
localStorage.setItem('todoData', this.innerHTML);
});
if(localStorage.getItem('todoData')){
edit.innerHTML = localStorage.getItem('todoData');
}
});
});
A: I take it you want the list item to be editable? If so you are missing a (document).ready
Edit: Whoops, not reading properly. You want the editable list to show any changes if user leaves and returns to page? Well it's working for me locally using both methods.
Maybe stupid question but are you linking to your external .js file properly? I noticed that the src="/html5.js" and not "html5.js" and when I do the former it doesn't work for me...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to force to show and hide virtual Keyboard if no hardware keyboard is available? How can I detect that the telephone does not have hardware keyboard and only in that case to force showing the virtual one? And how can I hide it?
I tried putting the focus like this but it doesn't work:
View exampleView = (View)findViewById(R.id.exampleBox);
exampleView.requestFocus();
If I force like this the virtual keyboard, the keyboard will appear also when a hardware keyboard is available, which doesn't make sense.
InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);
And last but not least, how can I show directly the numerical or phone keyboard? (Not the normal keyboard)
Any idea?
Thanks!
A: I would say use the Configuration class hardKeyboardHidden to see if the hard keyboard is out and if not then open the soft keyboard
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What is causing my CSS to behave this way? I have the following html for a simple navigation:
<header>
<div class="login">
<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>
</header>
I have the following css:
header {
height: 145px;
border: 1px solid #f00;
}
.login {
float: right;
}
.login ul {
list-style: none;
margin: 0;
padding: 0;
}
.login li {
display: inline;
}
.login li a {
color: #fff;
background-color: #666;
padding: 5px 10px;
}
I am using HTML5 boilerplate so my header is displayed as a block element. When I view the page in a modern browser the result looks like:
Why is the anchor padding extending outside of the red border/header element? What is causing this behavior?
Furthermore, when I view the same page in IE compatibility view, it now looks like:
Here it seems like the padding is not applied at all or cut off by the containing div. I tried setting a height for the div but the result was still the same. What is causing this behavior?
Thanks
A: Try putting a display:block on .login li a and put a float:left on the .login li
Also you can shorten your code and take out the unnecessary div and just put the class on the ul.
HTML:
<header>
<ul class="login">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</header>
CSS:
header {
height: 145px;
border: 1px solid #f00;
}
.login {
list-style: none;
margin: 0;
padding: 0;
float:right;
}
.login li {
float:left;
}
.login li a {
color: #fff;
background-color: #666;
padding: 5px 10px;
display:block;
}
http://jsfiddle.net/KPzUv/
A: What you are seeing is the body margin or padding. Set the margin to zero and it should go away. This is probably also a follow on problem caused by "margin collapse" between the header and the body causing the padding of the following element to leak through but I don't have time to check right now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to include external files into html with javascript / jquery? I have several files (header.html, nav.html, footer.html). I was wondering if there's a way to include these files into index.html while the page loads (or before) using plain js or jquery library. I know it's better to do it from server-side, but right now I'm working on front-end and don't have access to server-side scripts.
When I try to use $.load('header.html'), it gives me the following error:
Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'load'
A: The load() function has to be called on a matched element.
$('#myDiv').load('test.html');
In this example, the content will be loaded to the myDiv element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HELP: Stopping ruin a HTML design I have some BBCode-like code for my forum:
[quote] opens a table, tr, td...
[/quote] closes the table, tr and td...
But when the user writes another [/quote] it adds another </td></tr></table>, and this closes the table the 'forum body' was in.
I know there is probably a simple solution, but what do I put it in so closing a table will not 'break the layout' so to speak?
Div? Span?
Or is it more complex?
A: It's more complex - there is no way to tell an HTML parser "ignore the spec between these two points" without telling it to treat the interior part as raw text ... which won't work because you are generating HTML from this BBCode. You'll need to validate the user-entered BBCode to make sure it is "well formed".
If that simply is not an option, you can hack it by making sure that your forum body is only wrapped in tags that the BBCode to HTML generator does not generate - but that limits you quite a bit, and it doesn't guarantee that spurious close tags won't break your layout.
A: Try preg_replace/regex:
preg_replace('/\[quote\](.*)\[\/quote\]/', "<table><tr><td>$1</td></tr></table>", $string);
This would match up to the first end-quote tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does this function overloaded for three integer types fail to compile? This attempt to define a function overloaded for three sizes of integers fails. Why?
byte hack(byte x)
{
return x+1;
}
unsigned short hack(unsigned short x)
{
return x+2;
}
unsigned int hack(unsigned int x)
{
return x+3;
}
The compiler tells me:
zzz.cpp:98: error: redefinition of ‘unsigned int hack(unsigned int)’
zzz.cpp:88: error: ‘byte hack(byte)’ previously defined here
A: Your compiler/code thinks that byte and unsigned int are the same thing...
A: Overloaded functions can differ only by their parameters count and/or types and not the return type. So, these are three different functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Right shift and signed integer On my compiler, the following pseudo code (values replaced with binary):
sint32 word = (10000000 00000000 00000000 00000000);
word >>= 16;
produces a word with a bitfield that looks like this:
(11111111 11111111 10000000 00000000)
Can I rely on this behaviour for all platforms and C++ compilers?
A: In C++, no. It is implementation and/or platform dependent.
In some other languages, yes. In Java, for example, the >> operator is precisely defined to always fill using the left most bit (thereby preserving sign). The >>> operator fills using 0s. So if you want reliable behavior, one possible option would be to change to a different language. (Although obviously, this may not be an option depending on your circumstances.)
A: From the following link:
INT34-C. Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand
Noncompliant Code Example (Right Shift)
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation defined and can be either an arithmetic (signed) shift:
Or a logical (unsigned) shift:
This noncompliant code example fails to test whether the right operand is greater than or equal to the width of the promoted left operand, allowing undefined behavior.
unsigned int ui1;
unsigned int ui2;
unsigned int uresult;
/* Initialize ui1 and ui2 */
uresult = ui1 >> ui2;
Making assumptions about whether a right shift is implemented as an arithmetic (signed) shift or a logical (unsigned) shift can also lead to vulnerabilities. See recommendation INT13-C. Use bitwise operators only on unsigned operands.
A: AFAIK integers may be represented as sign-magnitude in C++, in which case sign extension would fill with 0s. So you can't rely on this.
A: From the latest C++20 draft:
Right-shift on signed integral types is an arithmetic right shift, which performs sign-extension.
A: No, you can't rely on this behaviour. Right shifting of negative quantities (which I assume your example is dealing with) is implementation defined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Pointer made from an integer in C on an embedded platform I came across the follow line of code:
#define ADCA (*(volatile ADC_t*)0x200)
It is for embedded C code for an AVR microcontroller. ADC_t is a union.
I know that (volatile ADC_t*)0x200 its a pointer to an absolute memory address but I am still not quite sure what the first * means.
A: That first * dereferences the pointer. In other words ADCA is the contents of the memory at 0x200.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I create a local database inside a Microsoft Visual C++ 2010 Express project? How can I create a local database inside a Microsoft Visual C++ 2010 Express project?
I can't find this simple answer in the web. The only answer I've found is for Visual Studio: using project > add new item > local database. But this option isn't available in Visual c++ 2010 Express edition.
I tried installing "Microsoft SQL Server Compact 4" and "Microsoft SQL Server Denali", and updating "Microsoft Visual C++ 2010 Express" from "Windows Update".
A: Ok, I got a solution at last. Regrettably I must answer my own question...
I used SQLite library (http://www.sqlite.org/). It was a little complicated because the sqlite documentation is a bit vague, but I did as follows:
*
*Download sqlitedll*.zip - extract .def and .dll files somewhere.
*Generate the lib file with a command like "c:\program
files\micros~1\vc98\bin\lib" /def:sqlite3.def". Do that from a command
prompt, in the directory with the .def file in, with the appropriate
path to your lib.exe. You may need to run vcvars32.bat first, which is
also in the bin directory. Copy the resulting .lib to an appropriate
place, and set that as a library directory in VC++. (Or do it on a
per-project basis.)
*Download the sqlite-source*.zip file, and extract the sqlite3.h file
from within to a suitable directory. Set that as an include directory
in VC++. (Again, you could do it on a per-project basis.)
*In your project, #include as required, add sqlite3.lib
to your project, copy the sqlite3.dll to your executable's directory
or working directory, and you should be ready to go.
Then, is easy to use no-out queries, but if you want to use a SQL "SELECT" for example, you could use this code:
std::string queries;
// A prepered statement for fetching tables
sqlite3_stmt *stmt;
// Create a handle for database connection, create a pointer to sqlite3
sqlite3 *handle;
// try to create the database. If it doesnt exist, it would be created
// pass a pointer to the pointer to sqlite3, in short sqlite3**
int retval = sqlite3_open("local.db",&handle);
// If connection failed, handle returns NULL
if(retval){
System::Windows::Forms::MessageBox::Show("Database connection failed");
return;
}
// Create the SQL query for creating a table
char create_table[100] = "CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)";
// Execute the query for creating the table
retval = sqlite3_exec(handle,create_table,0,0,0);
// Insert first row and second row
queries = "INSERT INTO users VALUES('manish','manish',1)";
retval = sqlite3_exec(handle,queries.c_str(),0,0,0);
queries = "INSERT INTO users VALUES('mehul','pulsar',0)";
retval = sqlite3_exec(handle,queries.c_str(),0,0,0);
// select those rows from the table
queries = "SELECT * from users";
retval = sqlite3_prepare_v2(handle,queries.c_str(),-1,&stmt,0);
if(retval){
System::Windows::Forms::MessageBox::Show("Selecting data from DB Failed");
return ;
}
// Read the number of rows fetched
int cols = sqlite3_column_count(stmt);
while(1){
// fetch a row’s status
retval = sqlite3_step(stmt);
if(retval == SQLITE_ROW){
// SQLITE_ROW means fetched a row
// sqlite3_column_text returns a const void* , typecast it to const char*
for(int col=0 ; col<cols;col++){
const char *val = (const char*)sqlite3_column_text(stmt,col);
System::Windows::Forms::MessageBox::Show(stdstr2systemstr(sqlite3_column_name(stmt,col))+" = "+stdstr2systemstr(val));
}
}
else
if(retval == SQLITE_DONE){
// All rows finished
System::Windows::Forms::MessageBox::Show("All rows fetched");
break;
}
else{
// Some error encountered
System::Windows::Forms::MessageBox::Show("Some error encountered");
return ;
}
}
// Close the handle to free memory
sqlite3_close(handle);
I expect this info be useful!
Sources:
*
*http://www.gamedev.net/topic/332251-sqlite3-and-visual-c/page_p_3157685#entry3157685
*http://milky.manishsinha.net/2009/03/30/sqlite-with-c/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: CGContextMoveToPoint before CGContextShowText call Does CGContextMoveToPoint work with CGContextShowText? I'm trying to draw to a PDF. Without any translating of the CTM, if I draw text, I see it in the bottom left side of the screen. Then I try to move to point (100,100), and the text is still there. But if I translate the CTM to position 100, 100, then I see the text at that point. Does CGContextMoveToPoint work with CGContextShowText? Otherwise it seems like I translate my CTM, then I need to make the reverse translation, then move it somewhere else to draw other text (like if I were doing a title, and then starting a paragraph). Thanks!
A: You need to use CGContextSetTextPosition() instead. I don't know why Quartz keeps different positions for text and graphics, but that's the way it is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: yield between different processes I have two C++ codes one called a and one called b. I am running in in a 64 bits Linux, using the Boost threading library.
The a code creates 5 threads which stay in a non-ending loop doing some operation.
The b code creates 5 threads which stay in a non-ending loop invoking yield().
I am on a quadcore machine... When a invoke the a code alone, it gets almost 400% of the CPU usage. When a invoke the b code alone, it gets almost 400% of the CPU usage. I already expected it.
But when running both together, I was expecting that the b code used almost nothing of CPU and a use the 400%. But actually both are using equals slice of the CPU, almost 200%.
My question is, doesn't yield() works between different process? Is there a way to make it work the way I expected?
A: So you have 4 cores running 4 threads that belong to A. There are 6 threads in the queue - 1 A and 5 B. One of running A threads exhausts its timeslice and returns to the queue. The scheduler chooses the next runnable thread from the queue. What is the probability that this tread belongs to B? 5/6. Ok, this thread is started, it calls sched_yield() and returns back to the queue. What is the probability that the next thread will be a B thread again? 5/6 again!
Process B gets CPU time again and again, and also forces the kernel to do expensive context switches.
sched_yield is intended for one particular case - when one thread makes another thread runnable (for example, unlocks a mutex). If you want to make B wait while A is working on something important - use some synchronization mechanism that can put B to sleep until A wakes it up
A: Linux uses dynamic thread priority. The static priority you set with nice is just to limit the dynamic priority.
When a thread use his whole timeslice, the kernel will lower it's priority and when a thread do not use his whole timeslice (by doing IO, calling wait/yield, etc) the kernel will increase it's priority.
So my guess is that process b threads have higher priority, so they execute more often.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Haxe enum assign value I need to port a C-like enum to Haxe:
enum Items
{
item1,
item2=0x00010000,
item3=0x00010001,
item4,
};
But Haxe doesn't allow default value it seems. How can I do this?
My real enum has hundreds of entries and for those with default values I must preserve the values.
A: You would typically use an enum abstract for this:
@:enum abstract Items(Int) {
var Item1 = 0x00000000;
var Item2 = 0x00010000;
var Item3 = 0x00010001;
var Item4 = 0x00010010;
}
With Haxe 4, you can write enum instead of @:enum and also omit values like in C-style enums:
enum abstract Items(Int) {
var Item1;
var Item2 = 0x00010000;
var Item3 = 0x00010001;
var Item4;
}
A: Take a look at Haxe Enum manual, there's no default values. But, maybe you'll describe the problem better? Probably it should be solved by objects not enums?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Programming style from "Game Coding Complete" I have recently read Mike McShaffry's Game Coding Complete and noticed the code style I haven't seen elsewhere yet. The more important things I noticed were the names of base classes defining interfaces starting with an I like IActor, protected member variables' names starting with m_ like m_Type and names of virtual methods like VSetId(). To show a bigger, more readable example:
class BaseActor : public IActor
{
friend class BaseGameLogic;
protected: ActorId m_id;
Mat4×4 m_Mat;
int m_Type;
shared_ptr <ActorParams> m_Params;
virtual void VSetID(ActorId id) { m_id = id; }
virtual void VSetMat(const Mat4×4 &newMat) { m_Mat = newMat; }
public:
BaseActor(Mat4×4 mat, int type, shared_ptr<ActorParams> params)
{ m_Mat=mat; m_Type=type; m_Params=params; }
/* more code here */
};
I pretty much like this style: it seems justified and looks like it helps increase the overall readability of the code. The question is: Is it a more-or-less established standard? Is there any more to it than the things I mentioned?
A: That's called Hungarian Notation. It's encoding information about the variable into the variable name.
For example, m_params means "a member variable called params". IActor means "A class called Actor intended to be used as an ifterface". It is something that is a very hot topic. Most people agree Hungarian Notation is a poor choice, but many will defend what they do as not Hungarian.
A: That looks very similar to Hungarian Notation. It depends on who you ask, but its a rather lets say "aged" style.
A: All of that seems fairly common. I dont recognize anyone else using the V prep for virtual methods. But its more about making the code human followable then anything else. Sounds like a good use to me.
Most of the coding I do is in C# and they use the same conventions for the most part. tho it is uncommon to see m_ for the member variables. Thats more common to C/C++ tho I have seen the same convention used in C# or the variables would start with _ alone. which is also a common convention in Objective-C. Something to separate the Property from the Variable that the property uses as a container.
A: I've seen that, and I'm no game programmer. The 'I' probably indicates that the class is intended to be an interface - all virtual methods and no data members. Using m_ is quite common, but so are other conventions. I think I first saw m_ naming convention in some Microsoft Windows examples in the late 1980s but that's probably not its origin. There are multiple coding standards around that follow these conventions (but differ in other ways) - I can't name any specific ones at the moment, but look around.
A: The initial I to denote interfaces (and A for abstract classes) isn't such a bad practice, however the m_ prefix to denote member variables is horrid. I believe the reasoning behind it is that it allows the parameters to be named nicer by preventing shadowing of member variables. However you will mainly work with member variables in your class, and the m_ prefix really clutters code, hindering readability. It is much better to just rename the parameter, for example id -> pId, id_, identifier, id_p, p_id, etc.
The V to denote virtual methods might be useful if you somehow declared methods virtual in the parent class but not in the child class, and you desperately need to know whether it is virtual or not, however this is easily fixed by declaring them virtual in the child class as well. Otherwise I do not see any advantage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom event does not reach caller I made a custom event that's supposed to be fired when a specific function within a class is executed. I listen for this event from within my main script, frame one of my timeline. See the code to understand my question a bit better.
My CustomEvents.as
package {
import flash.events.Event;
public class CustomEvents extends Event {
public static const PAGE_EMPTY:String = "Page Empty";
public function CustomEvents(type:String) {
super(type);
trace("hello from within the event class!");
}
}
}
The function within FRONT_PAGE.as that dispatches the event
public function exitPage(){
dispatchEvent(new CustomEvents(CustomEvents.PAGE_EMPTY));
var mainLinkExitMove:Tween = new Tween(mainLink, "y", Strong.easeOut, mainLink.y , -150, 3, true);
var gridExitMove:Tween = new Tween(grid, "y", Strong.easeOut, grid.y , -150, 3, true);
}
And finally the code that calls the above function, and listens for the returned event.
frontPage is an object of the FRONT_PAGE.as class, declared earlier in the code.
function gotoSubPage(){
frontPage.exitPage();
frontPage.addEventListener(CustomEvents.PAGE_EMPTY, ef_FrontPageFinishedExiting);
function ef_FrontPageFinishedExiting(event:CustomEvents){
trace("Event has been caught");
}
}
I know I am reaching the CustomEvents constructor, as the trace within it gets printed.
The problem is it seems like the event does not reach the function caller?
I was unable to find good examples of how to use simple custom events, so this is how I think it's supposed to be. What am I doing wrong?
A: It looks like it's not working because you're listening for the event after calling the method that dispatches the event, cart before horse :)
Your're also declaring ef_FrontPageFinishedExiting within gotoSubPage, it should be outside of that method within the class.
Try this instead:
function gotoSubPage() {
frontPage.addEventListener(CustomEvents.PAGE_EMPTY, ef_FrontPageFinishedExiting);
frontPage.exitPage();
}
function ef_FrontPageFinishedExiting(event:CustomEvents) {
trace("Event has been caught");
}
Also when you have a custom event it's a good idea to override the clone method as well:
package
{
import flash.events.Event;
public class MyEvent extends Event
{
public static const SOMETHING_HAPPENED:String = "somethingHappened";
public function MyEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
override public function clone():Event
{
return new MyEvent( type, bubbles, cancelable );
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: use ConfigurationManager to store user values in a file that is separate from the app config Ok, I've just about given up on this.
I would like to be able to record user preferences using a user config file, which would be referenced from the app config file. I am trying to do this with ConfigurationManager and an app config file. I can read just fine from the user settings, but setting them is a whole other problem. I would like to keep the app settings separate from the user settings in two different files.
When I use this:
<appSettings file="user.config">
</appSettings>
and user.config looks like:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="localSetting" value="localVal"/>
</appSettings>
I can use ConfigurationManager to READ the local setting, but not to save to the file.
var oldLocVal = ConfigurationManager.AppSettings["localSetting"];
ConfigurationManager.AppSettings.Set("localSetting", "newLocalValue"); // Doesn't save to file.
If instead my user.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="localSetting" value="localVal"/>
</appSettings>
</configuration>
I would then like to call and save the AppSettings in this way:
var uMap = new ConfigurationFileMap("user.config");
var uConfig = ConfigurationManager.OpenMappedMachineConfiguration(uMap);
var oldLocalVarFromConfig = uConfig.AppSettings.Settings["localSetting"]; // NO
uConfig.AppSettings.Settings.Remove("localSetting"); // NO
uConfig.AppSettings.Settings.Add("localSetting", "newValue");
uConfig.Save();
but it won't let me access the configuration's app settings. (It has a problem casting something as an AppSettings)
I also tried with configSource instead of file attributes in the app config appSettings element.
I was using the examples here for help, but unfortunately it wasn't enough.
Thanks in advance.
A: You can load external config files into a 'Configuration' instance. Here is an example of a singleton class with a static constructor that uses this strategy. You can tweak it a bit to do what you want, I think.
private const string _path = @"E:\WhateverPath\User.config"
static ConfigManager()
{
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
{
ExeConfigFilename = _path
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
// get some custom configuration section
_someConfigSection = config.GetSection("SomeSection") as SomeSection;
// or just get app settings
_appSettingSection = config.AppSettings;
}
Maybe try adding this way, making sure to call Save()
_appSettingSection.Settings.Add("SomeKey", "SomeValue");
//make sure to call save
config.Save();
A: To its credit, this code here works.
Also, I made a simple XML serializable object that saved itself to disk any time Save was called on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to create tables with password fields in mysql? Should I create the password column as a regular varchar and then insert like this:
sha1($pass_string)
Or should I do something extra upon the creation of the table to make sure that password field is secure?
Thanks!
A: You could also use the AES_ENCRYPT() function built into mysql for greater security.
Link here
There is also a good how-to here explaining further: link
A: The manual contains a good explanation of what type of column to use.
A: It's a normal varchar field (40 characters) but if you want to set it more secure you should use salt.
http://highedwebtech.com/2008/04/25/season-your-passwords-with-some-salt/
Update :
WARNING : Hash password without salt is REALLY WEAK ! You should never use it !!
Password salting is the good way for doing it :
password salting
as adviced by pst :
*
*using SHA-1 and salt is the more naive but quite well secure approach.
*using bcrypt :
it's the more secure approach :) because it use speed in order to make it more secure, bfish is a hash function built around the encryption method blowfish. (Seems than twofish exists too and should be the "modern" version of blowfish).
*
*using HMAC-SHA1 :
It's a version using a chain of SHA-1 so it's a intermediate solution, but allowing to set speed to your needs. In fact speed make weaker your security.
A: Most people save the hash as you have suggested. It's safe enough and simple, making it a good choice.
Note that all hashes can be cracked eventually, so any hash is better than none and SHA is strong enough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Cannot bundle in production I recently had to add two gems to my gem file. When I added them to my gemfile, I pushed directly to my production server.
I SSH'd into my production server, and tried running bundle install. This is the error I go:
>> bundle install
.........
>> You are trying to install in deployment mode after changing
your Gemfile. Run `bundle install` elsewhere and add the
updated Gemfile.lock to version control.
If this is a development machine, remove the Gemfile freeze
by running `bundle install --no-deployment`.
You have added to the Gemfile:
* RedCloth
* tanker
A: When you add gems to your Gemfile, you MUST bundle in your dev environment before pushing and deploying.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: push replaces the old value in the array Maybe its because I have been working all day and I can't see the problem. But in the following code the alert only shows the last added value and doesn't push the value in the array. :(
window.sortControl = {
sortControlPanel: $('div.sortControl'),
simpleSortCriteriaList: $('div.sortControl .simple'),
advancedSortCriteriaList: $('div.sortControl .advanced'),
dropDownExpander: $('div.sortControl .dropDownExpand.primary'),
dropDownContent: $('div.sortControl .dropdownContent.primary'),
simpleSortCriteria: $('div.sortControl .sortcriteria.simple a'),
simpleSortCheckboxes: $('.simple .checkbox'),
openAdvancedButton: $('.openAdvanced'),
backtoSimpleButton: $('.backtoSimple'),
advancedDropdownContent: $('div.sortControl .advanced .dropdownContent'),
advancedDropdownExpander: $('div.sortControl .advanced .dropDownExpand')
};
$.each(sortControl.advancedDropdownContent.parent(), function () {
var dropdownContent = $(this).find('.dropdownContent');
var input = $(this).find('input');
$(this).find('.dropDownExpand').live('click', function (event) {
sortControl.advancedDropdownContent.not(dropdownContent).hide('fast');
dropdownContent.toggle('fast');
event.preventDefault();
});
var currentSelectedGroups = [];
$(this).find('li a').bind('click', function (event) {
var criteria = $(this).text();
//if (!currentSelectedGroups.inArray($(this).attr('class'), true)) {
input.attr('value', criteria);
currentSelectedGroups.push($(this).attr('class'));
//}
dropdownContent.toggle('fast');
event.preventDefault();
alert(currentSelectedGroups);
});
});
Some of the html:
<div class='sortcriteria advanced'>
<label>Sort by: </label>
<div class='controlWrapper'>
<input type="text" placeholder='Any' value='Any' class='dropDownExpand'>
<span class='icon dropDownExpand' title='Select property type'></span>
<ul class='dropdownContent'>
<li><a href='#' class='price'>Price ascending</a></li>
<li><a href='#' class='price'>Price descending</a></li>
<li><a href='#' class='party'>Party size ascending</a></li>
<li><a href='#' class='party'>Party size descending</a></li>
<li><a href='#' class='bedrooms'>Number of bedrooms ascending</a></li>
<li><a href='#' class='bedrooms'>Number of bedrooms descending</a></li>
<li><a href='#' class='star'>Star rating ascending</a></li>
<li><a href='#' class='star'>Star rating descending</a></li>
</ul>
</div> ...
*
*There are no JavaScript errors.
*Content and this script get loaded via ajax
*All other statements do what they are supposed to
A: You need to move var currentSelectedGroups = []; outside the each loop. You declare it once for every instance - they all work on their own version of the variable because it lives in the local scope of the each function.
Remember in javascript functions = scope
A: As I asked you (and suspected) in my earlier comment, you need to move:
var currentSelectedGroups = [];
outside the .each() loop. As it is you are re-initializing it to an empty array in each iteration of the loop so it never has more than one value in it. You can do that like this:
var currentSelectedGroups = [];
$.each(sortControl.advancedDropdownContent.parent(), function () {
var dropdownContent = $(this).find('.dropdownContent');
var input = $(this).find('input');
$(this).find('.dropDownExpand').live('click', function (event) {
sortControl.advancedDropdownContent.not(dropdownContent).hide('fast');
dropdownContent.toggle('fast');
event.preventDefault();
});
$(this).find('li a').bind('click', function (event) {
var criteria = $(this).text();
//if (!currentSelectedGroups.inArray($(this).attr('class'), true)) {
input.attr('value', criteria);
currentSelectedGroups.push($(this).attr('class'));
//}
dropdownContent.toggle('fast');
event.preventDefault();
alert(currentSelectedGroups);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Difference between sizeof(struct structname) and sizeof(object) in C Are there scenarios where there can be a difference between sizeof(struct structure_name) and sizeof(object) where object is of type struct structure_name in C?
A: No there is no difference between sizeof(type) and sizeof(o) where the declared type of o is type.
There can be differences if the declared type of the object isn't truly representative of the object. For example
char arrayValue[100];
sizeof(arrayValue); // 100 on most systems
char* pointerValue = arrayValue;
sizeof(pointerValue); // 4 on most 32 bit systems
This difference occurs because sizeof is a compile time construct in C. Hence there is no runtime analysis and the compiler looks instead at the statically declared types.
A: No; sizeof(type) and sizeof(object-of-type) produce the same result at all times.
Well, there's a caveat that with a VLA (variable-length array), the sizeof() might be a run-time operation, but otherwise, they are fixed. And you can make a case that even with a VLA, the result of sizeof(variably-qualified-type) and sizeof(object-of-same-variably-qualified-type) will produce the same result, so VLAs are not really an exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to remove array elements equal to some element in a second array in perl Just wonder if I am given two arrays, A and B, how to remove/delete those elements in A that can also be found in B? What is the most efficient way of doing this?
And also, as a special case, if B is the resulting array after grep on A, how to do this? Of course, in this case, we can do a grep on the negated condition. But is there something like taking a complement of an array with respect to another in perl?
Thank you.
A: Any time you are thinking of found in you are probably looking for a hash. In this case, you would create a hash of your B values. Then you would grep A, checking the hash for each element.
my @A = 1..9;
my @B = (2, 4, 6, 8);
my %B = map {$_ => 1} @B;
say join ' ' => grep {not $B{$_}} @A; # 1 3 5 7 9
As you can see, perl is not normally maintaining any sort of found in table by itself,
so you have to provide one. The above code could easily be wrapped into a function, but for efficiency, it is best done inline.
A: Have a look at the none, all, part, notall methods available via List::MoreUtils. You can perform pretty much any set operation using the methods available in this module.
There's a good tutorial available at Perl Training Australia
A: If you ask for most efficient way:
my @A = 1..9;
my @B = (2, 4, 6, 8);
my %x;
@x{@B} = ();
my @AminusB = grep !exists $x{$_}, @A;
But you will notice difference between mine and Eric Strom's solution only for bigger inputs.
You can find handy this functional approach:
sub complementer {
my %x;
@x{@_} = ();
return sub { grep !exists $x{$_}, @_ };
}
my $c = complementer(2, 4, 6, 8);
print join(',', $c->(@$_)), "\n" for [1..9], [2..10], ...;
# you can use it directly of course
print join(' ', complementer(qw(a c e g))->('a'..'h')), "\n";
A: You're probably better off with the hash, but you could also use smart matching. Stealing Eric Strom's example,
my @A = 1..9;
my @B = (2, 4, 6, 8);
say join ' ' => grep {not $_ ~~ @B } @A; # 1 3 5 7 9
A: Again, you're probably better off with the hash, but you could also use Perl6::Junction. Again stealing Eric Strom's example,
use Perl6::Junction qw(none);
my @A = 1..9;
my @B = (2, 4, 6, 8);
say join ' ' => grep {none(@B) == $_} @A; # 1 3 5 7 9
A: As already mentioned by Eric Strom, whenever you need to search for something specific, it's always easier if you have a hash.
Eric has a nicer solution, but can be difficult to understand. I hope mine is easier to understand.
# Create a B Hash
my %BHash;
foreach my $element (@B) {
$BHash{$element} = 1;
}
# Go through @A element by element and delete duplicates
my $index = 0;
foreach my $element (@A) {
if (exists $BHash{$element}) {
splice @A, $index, 1; #Deletes $A[$index]
$index = $index + 1;
}
}
In the first loop, we simply create a hash that is keyed by the elements in @B.
In the second loop, we go through each element in @A, while keeping track of the index in @A.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: MVC: Is it possible to have one custom ModelBinder AND the default binder on one model? I would like to use my custom binder to deal with the constructor (necessary) and then have the default modelbinder fill in the rest of the properties as normal.
Edit: The custom one would run first of course.
A: Mo.'s answer is correct. Inherit from the DefaultModelBinder then override CreateModel.
I'm just posting to provide sample codes.
The binder:
public class RegistrationViewModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
return new RegistrationViewModel(Guid.NewGuid());
}
}
The model:
public class RegistrationViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Guid Id { get; private set; }
public RegistrationViewModel(Guid id)
{
Id = id;
}
}
If your property will be settable (In this case its the Id), you need to exclude it from the bind:
[Bind(Exclude = "Id")]
public class RegistrationViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Guid Id { get; set; }
}
A: Thanks guys, I think I have found a solution, and that is to override the createmodel method of defaultmodelbinder. I had additional help from here:
http://noahblu.wordpress.com/2009/06/15/modelbinder-for-objects-without-default-constructors/
It needed updating to use modelmetadata instead of setting the modeltype as shown in that link, due to a change they made in mvc.
This is what I have ended up with as a first try that seems to work:
namespace NorthwindMVCApp.CustomBinders{
public class NewShipperBinder<T> : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
Type type1 = typeof(T);
ConstructorInfo[] constructors = type1.GetConstructors();
ConstructorInfo largestConstructor = constructors.OrderByDescending(x => x.GetParameters().Count()).First();
ParameterInfo[] parameters = largestConstructor.GetParameters();
List<object> paramValues = new List<object>();
IModelBinder binder;
string oldModelName = bindingContext.ModelName;
foreach (ParameterInfo param in parameters)
{
string name = CreateSubPropertyName(oldModelName, param.Name);
//bindingContext.ModelType = param.ParameterType;
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, param.ParameterType);
bindingContext.ModelName = name;
if (!System.Web.Mvc.ModelBinders.Binders.TryGetValue(param.ParameterType, out binder))
binder = System.Web.Mvc.ModelBinders.Binders.DefaultBinder;
object model = binder.BindModel(controllerContext, bindingContext);
paramValues.Add(model);
}
// bindingContext.ModelType = typeof(T);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
bindingContext.ModelName = oldModelName;
Debug.WriteLine(Environment.StackTrace);
object obj = Activator.CreateInstance(type1, paramValues.ToArray());
return obj;
}
}
}
The class being bound is as follows. The reason for all of this is that it has no default constructor (to make sure that not-nullables are there):
namespace Core.Entities{
[EntityAttribute()]
public class Shipper
{
protected Shipper() : this("Undefined")
{
}
public Shipper(string CompanyName)
{
this.CompanyName = CompanyName;
Orders = new List<Order>();
}
public virtual int ShipperID { get; set; }
public virtual IList<Order> Orders { get; set; }
public virtual string CompanyName { get; set; }
public virtual string Phone { get; set; }
public override bool Equals(object obj)
{
Shipper obj_Shipper;
obj_Shipper = obj as Shipper;
if (obj_Shipper == null)
{
return false;
}
if (obj_Shipper.CompanyName != this.CompanyName)
{
return false;
}
return true;
}
public override int GetHashCode()
{
return CompanyName.GetHashCode();
}
}
}
And by the way the binder is included in global.asax as follows:
ModelBinders.Binders.Add(typeof(Shipper), new CustomBinders.NewShipperBinder<Shipper>());
So it will be easy to add the whole lot of entity classes (looping through), since I maintain a list of types of entities.
Thus I have been able to update that entity to the database.
Edit: A bit of icing, here is a stack trace:
at NorthwindMVCApp.CustomBinders.NewShipperBinder`1.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) in C:\Users\####\Documents\Visual Studio 2010\Projects\TestFluentNHibernate\NorthwindMVC\NorthwindMVCApp\CustomBinders\NewShipperBinder.cs:line 37
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
A: Have you already inherited from the DefaultModelBinder? I don't think it is possible to do what you intend - if you create a customer model binder and it implements IModelBinder the class must perform all necessary actions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to initialize activeMQ broker with failover I need to send JMS messages to the following provider location:
failover:(tcp://amq.vip.ebay.com:61616,tcp://amqstby.vip.ebay.com:61616)?initialReconnectDelay=100&randomize=false&wireFormat.maxInactivityDuration=0
How to correctly initialize ConnectorFactory for it? Should I just do the follwing?
String url = "failover:(tcp://amq.vip.ebay.com:61616,tcp://amqstby.vip.ebay.com:61616)?initialReconnectDelay=100&randomize=false&wireFormat.maxInactivityDuration=0";
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Or the things are more tricky with this kind of provider urls?
A: That is the correct syntax. Be careful when turning off the inactivity monitor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Batch For Loop Escape Asterisk I am attempting to create a batch for loop (Windows XP and newer command prompts) that iterates through a string containing one or more asterisks. How can I do this? Here is an example:
@FOR %%A IN (A* B) DO @ECHO %%A
The expected output (what I am trying to get) is the following:
A*
B
However, what I am actually getting with the command above is B and only B. For some reason, everything with an asterisk is being ignored by the loop. I have attempted escaping the asterisk with 1-4 carets (^), backslashes (\), percent signs (%), and other asterisks (*), all to no avail. Thanks in advance for illuminating me.
IN CASE YOU WANT MORE INFORMATION:
The purpose of this is to parse a path out of a list of space-separated partial paths. For example, I want to copy C:\Bar\A.txt, C:\Bar\B.txt, and C:\Bar\C*.txt to C:\Foo\ using the following approach:
@SET FILE_LIST=A B C*
@FOR %%A IN (%FILE_LIST%) DO @COPY C:\Bar\%%A.txt C:\Foo\
If there is another alternative way to do this (preferably without typing each and every copy command since there are ~200 files, which is the same reason I don't want to store the full path for every file), I would appreciate the help. Thanks again,
-Jeff
A: the asterisks works the way its intended, in your case,
@FOR %%A IN (A* B) DO @ECHO %%A
expands A* to all the files that begin with A.
A possible way to do what you want, is just to use this expansion
@ECHO off
PUSHD C:\bar
SET FILE_LIST=A.txt B.txt C*.txt
FOR %%A IN (%FILE_LIST%) DO (
IF EXIST %%A COPY %%A C:\Foo\
)
POPD
A: This may help:
@echo off
set "it=a*b .txt-b*.txt-c*.txt-d.txt"
set /a i=0,fn=3
:startLoop
set /a i=i+1
for /f "tokens=%i%delims=-" %%m in ("%it%") do echo %%m
if %i% lss %fn% goto:startLoop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Check if pthread thread is blocking Here's the situation, I have a thread running that is partially controlled by code that I don't own. I started the thread so I have it's thread id but then I passed it off to some other code. I need to be able to tell if that other code has currently caused the thread to block from another thread that I am in control of. Is there are way to do this in pthreads? I think I'm looking for something equivalent to the getState() method in Java's Thread class (http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#getState() ).
--------------Edit-----------------
It's ok if the solution is platform dependent. I've already found a solution for linux using the /proc file system.
A: You could write wrappers for some of the pthreads functions, which would simply update some state information before/after calling the original functions. That would allow you to keep track of which threads are running, when they're acquiring or holding mutexes (and which ones), when they're waiting on which condition variables, and so on.
Of course, this only tells you when they're blocked on pthreads synchronization objects -- it won't tell you when they're blocking on something else.
A: Before you hand the thread off to some other code, set a flag protected by a mutex. When the thread returns from the code you don't control, clear the flag protected by the mutex. You can then check, from wherever you need to, whether the thread is in the code you don't control.
From outside the code, there is no distinction between blocked and not-blocked. If you literally checked the state of the thread, you would get nonsensical results.
For example, consider two library implementations.
A: We do all the work in the calling thread.
B: We dispatch a worker thread to do the work. The calling thread blocks until the worker is done.
In both cases A and B the code you don't control is equally making forward progress. Your 'getstate' idea would provide different results. So it's not what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Help me to understand this code in c# i can not read this line of code
public Wine (decimal price, int year) : this (price) { Year = year; }
what :this keyword do in a constructor
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price)
{
Price = price;
}
public Wine (decimal price, int year) : this (price)
{
Year = year;
}
}
A: This is called constructor chaining. Instead of rewriting the code of the one-argument constructor, you simply call it. C# makes this simple by using this short notation with the colon.
A: this(price) calls another constructor that in this case only takes one parameter of type decimal. As a reference read "Using Constructors".
I'm not a big fan of this particular example since both constructors do initialization work.
In my opinion it is better to pass default values to one constructor that then does all the work - this way initialization is not spread between different constructors and you have a single spot where everything is initialized - a better way would be:
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price): this(price, 0)
public Wine (decimal price, int year)
{
Price = price;
Year = year;
}
}
A: It calls the constructor with the single decimal parameter price first.
A: It calls another constructor in the same class that has that signature passing the values into it that were supplied to the initial constructor call. In you example, the Wine class has (at least) two constructors, one that takes a decimal (price) and a int (year), as well as a second one that only takes a decimal (price).
When you call the one that takes the two parameters, it calls the one that takes only one parameter passing the value of price into the second one. It then executes the constructor body (setting Year to year).
This allows you to reuse common logic that should happen no matter which constructor call was made (in this instance setting the price should always happen, but the more specific constructor also sets the Year).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is APNS cert same as App Store app cert? Our product is white labeled, so while we host the backend, which will include the "provider" in APNS parlance, the App Store submission is not done by us.
Does APNS have to use the same cert as the application's App Store cert?
A: APNS certificate is different from App Store cert. However, both certificates, app store and apns should be generate for same App id. i.e. you will need access to developer account on which app id is created.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IOS Accelerometer/Gyroscope Question I want to write an app that gives the degrees of position from some coordinate (bottom of the phone).
For example... If I'm holding the phone at a 45 degree angle, I want to display: 45 degrees on the screen. If the user holds the phone at 45 degrees and rotates the phone around an axis going from the ear piece to the home button, I want to display that angle (between 0-180degrees).
I've implemented the accelerometer and I get the x, y, z values, however, how do I convert them? I know they are in G's (1G, 0.9G, -0.5G on the respective axis), but what's the conversion? Am I even going on the correct track? Should I be using the gyroscope instead?
Thanks.
A: This question has an example. You can use atan2(y, x) and convert from radians to degrees with * (180/M_PI).
For any real arguments x and y not both equal to zero, atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the coordinates (x, y) on it.
- Wikipedia article on atan2
A: If you can rely on gyroscope support I'd recommend to use it, because you can get the (Euler) angles directly without any calculations. See iOS - gyroscope sample and follow the links inside.
Don't use UIAccelerometer because it will be deprecated soon. The newer CoreMotion framework is always the better choice, even for old devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting image src name javascript I would like to have
album_name = Precious
How do I get that?
<html>
<head>
<title></title>
</head>
<body>
<div id="ps_slider" class="ps_slider">
<div id="ps_albums">
<div class="ps_album">
<div class="ps_image">
<div class="ps_img">
<img src="puppies/Snoopy/primary.jpg" alt="Dachshund Puppy Thumbnail"/>
</div>
</div>
</div>
<div class="ps_album">
<div class="ps_image">
<div class="ps_img">
<img src="puppies/Precious/primary.jpg" alt="Dachshund Puppy Thumbnail"/>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $ps_albums = $('#ps_albums');
$ps_albums.children('div').bind('click',function(){
var $elem = $(this);
var album_name = 'album' + parseInt($elem.index() + 1);
console.log(album_name);
});
});
</script>
</body>
</html>
A: This should do the trick:
$ps_albums.children('div').bind('click',function(){
var album_name = $(this).find('img').attr('src').split('/')[1];
});
A: Try this:
$(function() {
$('#ps_albums .ps_album').click(function() {
var $elem = $(this);
var $img = $elem.find('img');
var album_name = $img.attr('src').split('/')[1];
});
});
A: $(function() {
$(".ps_img").click(function(){
var album = $(this).find("img").attr("src").split("/")[1];
alert(album);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set fancybox width from link rel attribute How would I retrieve a width setting on my a tag (e.g. in the REL attribute) and pass it to my jQuery fancybox function, so I can specify its width? Here is my (pretty standard) Fancybox declaration:
<script type="text/javascript">
$(document).ready(function () {
//TODO - pass width/height value from link somehow
$("a.popup").fancybox({
'autoScale': false,
'height': 500,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'type': 'iframe'
});
});
</script>
A: You really shouldn't be overloading the rel attribute for this, that is not what it's for.
However, the code may look something like...
$(document).ready(function() {
$("a.popup").each(function() {
var width = $(this).attr('rel');
$(this).fancybox({
'autoScale': false,
'width': width,
'height': 500,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'type': 'iframe'
});
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hidden Field in Simple Nested Form Not Being Submitted Environment: Rails 3.1.0, Ruby 1.9.2
I have Portfolio model which has_many Positions which has_one Asset.
This is the schema for the Position model:
create_table "positions", :force => true do |t|
t.integer "portfolio_id"
t.integer "asset_id"
t.decimal "holding_percentage"
end
When the user creates a portfolio he/she should enter the portfolio name and then add positions by adding stock tickers. Jquery does its stuff and shows the full name of the asset and also inserts the asset_id into the hidden field.
I am using both nested_form and simple_form as follows:
<%= simple_nested_form_for @portfolio do |f| %>
<%= f.input :name, :placeholder => 'Your portfolio name' %>
<%= f.fields_for :positions do |position_form| %>
<%= text_field_tag 'asset-ticker', nil, :class => 'asset-ticker' %>
<span class="asset-name"></span>
<%= position_form.text_field :holding_percentage, :class => 'asset-perc' %>
<%= position_form.hidden_field :asset_id, :class => 'asset-num', :as => :hidden %>
<%= position_form.link_to_remove "Remove this position", :class => 'asset-rem-link' %>
<% end %>
<p><%= f.link_to_add "Add a Position", :positions, :class => 'asset-add-link' %></p>
<%= f.button :submit %>
<% end %>
The problem is that the asset_id value in the hidden field is not being submitted. The parameters look as follows:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"hmvoGHF9GzpPsohQQ2MwhWk4FzhVVrf+IqoChHgftEs=",
"portfolio"=>{"name"=>"needhelpnow",
"positions_attributes"=>
{"new_1316730954406"=>{"holding_percentage"=>"11", "asset_id"=>"", "_destroy"=>"false"},
"new_1316730961085"=>{"holding_percentage"=>"22", "asset_id"=>"", "_destroy"=>"false"},
"new_1316730971587"=>{"holding_percentage"=>"33", "asset_id"=>"", "_destroy"=>"false"}}},
"commit"=>"Create Portfolio"}
A: It turns out that the problem was that I was writing in the value of the hidden field with:
('.asset-num').html(data.id)
Instead of:
('.asset-num').val(data.id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: If referencing constant character strings with pointers, is memory permanently occupied? I'm trying to understand where things are stored in memory (stack/heap, are there others?) when running a c program. Compiling this gives warning: function return adress of local variable:
char *giveString (void)
{
char string[] = "Test";
return string;
}
int main (void)
{
char *string = giveString ();
printf ("%s\n", string);
}
Running gives various results, it just prints jibberish. I gather from this that the char array called string in giveString() is stored in the stack frame of the giveString() function while it is running. But if I change the type of string in giveString() from char array to char pointer:
char *string = "Test";
I get no warnings, and the program prints out "Test". So does this mean that the character string "Test" is now located on the heap? It certainly doesn't seem to be in the stack frame of giveString() anymore. What exactly is going on in each of these two cases? And if this character string is located on the heap, so all parts of the program can access it through a pointer, will it never be deallocated before the program terminates? Or would the memory space be freed up if there was no pointers pointing to it, like if I hadn't returned the pointer to main? (But that is only possible with a garbage collector like in Java, right?) Is this a special case of heap allocation that is only applicable to pointers to constant character strings (hardcoded strings)?
A: You seem to be confused about what the following statements do.
char string[] = "Test";
This code means: create an array in the local stack frame of sufficient size and copy the contents of constant string "Test" into it.
char *string = "Test";
This code means: set the pointer to point to constant string "Test".
In both cases, "Test" is in the const or cstring segment of your binary, where non-modifiable data exists. It is neither in the heap nor stack. In the former case, you're making a copy of "Test" that you can modify, but that copy disappears once your function returns. In the latter case, you are merely pointing to it, so you can use it once your function returns, but you can never modify it.
You can think of the actual string "Test" as being global and always there in memory, but the concept of allocation and deallocation is not generally applicable to const data.
A: No. The string "Test" is still on the stack, it's just in the data portion of the stack which basically gets set up before the program runs. It's there, but you can think of it kind of like "global" data.
The following may clear it up a tad for you:
char string[] = "Test"; // declare a local array, and copy "Test" into it
char* string = "Test"; // declare a local pointer and point it at the "Test"
// string in the data section of the stack
A: It's because in the second case you are creating a constant string :
char *string = "Test";
The value pointed by string is a constant and can never change, so it's allocated at compile time like a static variable(but it's still stack not heap).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android - SeparatedListAdapter - How to get accurate item position on onClick? I'm using Sharkey's SeparatedListAdapter class in order to have a ListView that is separated by sections.
The class works great, but the problem I'm having is in my onListItemClick() handler. If I have the following sectioned list:
---------
| A |
---------
| Alex |
| Allan |
---------
| B |
---------
| Barry |
| Bart |
| Billy |
| Brian |
---------
| C |
---------
etc...
When you want to click on an item in the list, you get the position of the item and then do something with it.
In my case, my list is a dynamic list of people's names. The names come from a database that is put into a List<CustomClass> before going into list. It's important for me to know the position of the item that I click on because I use the item position to determine other information about the person in the List object.
Now, the problem is this:
When you click an item in the list, the headers count as items, even though they are unclickable. In the above example, the positions in the list are as follows
Alex = 1
Allan = 2
Barry = 4
Bart = 5
Billy = 6
Brian = 7
But in my original List object the order is like so
Alex = 0
Allan = 1
Barry = 2
Bart = 3
Billy = 4
Brian = 5
So whenever I click on an item, like Alex, my code runs the onClick handler, determines that Alex is at position 1 in the and then retrieves Allans info from the List instead of Alex's.
Do you see the delima here? What is the approach I should take to this problem?
A: You could use setTag() for your every item in the listView. This can be done by adding this tag before you return the view from getView() function in the listAdapter. lets say your list adapter return convertView ,then in the list adapter.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null)
{
convertView = mLayoutInflater.inflate(R.layout.morestores_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// populate holder here, that is what you get in onItemClick.
holder.mNameofItem = "NameofaPerson";
return convertView;
}
static class ViewHolder {
TextView mName;
Button mAction;
ImageView mLogo;
// use this class to store the data you need, and use appropriate data types.
String mNameofItem.
}
when ever you get a click on the list item, use
public void onItemClick(AdapterView<?> arg0, View convertView, int arg2,
long arg3) {
ViewHolder holder = (ViewHolder) convertView.getTag();
// holder has what ever information you have passed.
String nameofItemClicked = holder.mNameofItem;
// access the information like this.
}
This approach doesn't need the position of the item in the list, just wanted to let you know different approach.
HTH.
A: My solution was instead of getting the position in the list and then using that to get the object from the ListArray or Hash, to just get the object in that position in the adapter and then retrieving whatever custom parameter or method from it that I needed. It's kind of obvious now but wasn't making sense at first.
UPDATE
It's a long bit of code so I will just give an overview:
Instead of passing in a String for the list item, pass in a custom object. Lets say this object has two different values it stores. A name (retrievable by public method getName()) and an ID (retrievable by getId()).
You have to override the getView() method for the adapter class and make it use the getName() method of the object and use that text to display in the list item.
Then, when the item is clicked, just get the object from the adapter at that position and then get the ID:
int id = adapter.get(position).getId();
// Then do something with the ID, pass it to an activity/intent or whatever.
Also I ditched the SeparatedListViewAdapter in favor of this. Much better and more flexible imo.
A: int idNo= adapter.get(position).getId();
you can try this code...
A: For anyone else I too recently ran into this problem and ended up here, I solved by:
First altering the Map to take an 'id'
public Map<String,?> createItem(String title, String caption, String id) {
Map<String,String> item = new HashMap<String,String>();
item.put(ITEM_TITLE, title);
item.put(ITEM_CAPTION, caption);
item.put("id", id); // Add a unique id to retrieve later
return item;}
Second when adding a section make sure to include an id:
List<Map<String,?>> GeneralSection = new LinkedList<Map<String,?>>();
GeneralSection.add(createItem(FirstName[GeneralInt] + " " + LastName[GeneralInt], Whatever[GeneralInt], UniqueId[GeneralInt]));
//Unique id could be populated anyway you like, database index 1,2,3,4.. for example like above question.
adapter.addSection("GeneralSection ", new SimpleAdapter(getActivity(), GeneralSection , R.layout.list_complex,
new String[] { ITEM_TITLE, ITEM_CAPTION }, new int[] { R.id.list_complex_title, R.id.list_complex_caption }));
Finally Use a Map in ItemClickListener to retrieve 'id' of the correct position:
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Map<String, String> map = (Map<String, String>) arg0.getItemAtPosition(position);
String UniqueId = map.get("id");
Log.i("Your Unique Id is", UniqueId);
//Can then use Uniqueid for whatever purpose
//or any other mapped data for that matter..eg..String FirstName = map.get("ITEM_TITLE");
}
Hope this helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Rails multi-instances of one model I'm writing simple file upload using Rails 3.1 & Papercip gem.
class Asset < ActiveRecord::Base
belongs_to :assetable, :polymorphic => true
has_attached_file :data
end
How can I load 3 (or more) files in one time. Parent assetable object is already created.
A: be careful with assets name, it will conflict with rails 3.1 asset pipelines...
You should use nested_attributes_for to solve your problem
A: You'll only be able to attach one file with paperclip to each instance of Asset as is. If each Asset has one or more files attached, you can put the has_attached_file in another class called Data, or whatever you like, and add a has_many :data to Asset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Arrays of which size require malloc (or global assignment)? While taking my first steps with C, I quickly noticed that int array[big number] causes my programs to crash when called inside a function. Not quite as quickly, I discovered that I can prevent this from happening by defining the array with global scope (outside the functions) or using malloc.
My question is:
Starting at which size is it necessary to use one of the above methods to make sure my programs won't crash?
I mean, is it safe to use just, e.g., int i; for counters and int chars[256]; for small arrays or should I just use malloc for all local variables?
A: You should understand what the difference is between int chars[256] in a function and using malloc().
In short, the former places the entire array on the stack. The latter allocates the memory you requested from the heap. Generally speaking, the heap is much larger than the stack, but the size of each can be adjusted.
Another key difference is that a variable allocated on the stack will technically be gone after you return from the method. (Oh, your program may function as though it's not gone for a bit if you continue to access that array, but ho ho ho danger lurks.) A hunk of memory allocated with malloc will remain allocated until you explicitly free it or the program exits.
A: You should use malloc for your dynamic memory allocation. For statically sized arrays (or any other object) within functions, if the memory required is to big you will quickly get a segmentation fault. I don't think a 'safe limit' can be defined, its probably implementation specific and other factors come in play too, like the current stack and objects within it created by callers to the current function. I would be tempted to say that anything below the page size (usually 4kb) should be safe as long as there is no recursion involved, but I do not think there are such guarantees.
A: It depends. If you have some guarantee that a line will never be longer than 100 ... 1000 characters you can get away with a fixed size buffer. If you don't: you don't. There is a difference between reading in a neat x KB config file and a x GB XML file (with no CR/LF). It depends.
The next choice is: do you want your program to die gracefully? It is only a design choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Download file while in ssh mode? I use to navigate my remote servers with ssh. Sometimes i would like to download a file to open in my computer.
But the only way i know how to do it is to open a new command line window and use scp from local to remote.
is there a way to do this directly from the ssh server?
like a command that know my current ip so can set up everything automatically?
(wonderful would also be to do the upload in such a way...)
A: There is no easy way to do it - I used ssh & scp many years the way you just described. But, you may configure ssh & scp in such a way that they don't require password each time, which is very comfortable! For this, you need:
*
*generate keys by ssh-keygen - they can be also passphrase (= password) protected
*copy the keys to remote machine to ~/.ssh/authorized_keys
And then, each time you start a session, you run ssh-agent and ssh-add. You just enter the password once. And then you can just run scp/ssh many times, from scripts, etc., without the need to enter the password each time!
I don't remember the exact way how to configure all this, but have a look at manpages of all those useful tools! Many things can be automatized by placing them into ~/.bash_profile or ~/.bashrc files.
A: I found this while trying to answer your question for myself:
https://askubuntu.com/a/13586/137980
Just install zssh and use Ctrl-@ to go into file transfer mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Understanding Big(O) in loops I am trying to get the correct Big-O of the following code snippet:
s = 0
for x in seq:
for y in seq:
s += x*y
for z in seq:
for w in seq:
s += x-w
According to the book I got this example from (Python Algorithms), they explain it like this:
The z-loop is run for a linear number of iterations, and
it contains a linear loop, so the total complexity there is quadratic, or Θ(n2). The y-loop is clearly Θ(n).
This means that the code block inside the x-loop is Θ(n + n2). This entire block is executed for each
round of the x-loop, which is run n times. We use our multiplication rule and get Θ(n(n + n2)) = Θ(n2 + n3)
= Θ(n3), that is, cubic.
What I don't understand is: how could O(n(n+n2)) become O(n3). Is the math correct?
A: The math being done here is as follows. When you say O(n(n + n2)), that's equivalent to saying O(n2 + n3) by simply distributing the n throughout the product.
The reason that O(n2 + n3) = O(n3) follows from the formal definition of big-O notation, which is as follows:
A function f(n) = O(g(n)) iff there exists constants n0 and c such that for any n ≥ n0, |f(n)| ≤ c|g(n)|.
Informally, this says that as n gets arbitrary large, f(n) is bounded from above by a constant multiple of g(n).
To formally prove that n2 + n3 is O(n3), consider any n ≥ 1. Then we have that
n2 + n3 ≤ n3 + n3 = 2n3
So we have that n2 + n3 = O(n3), with n0 = 1 and c = 2. Consequently, we have that
O(n(n + n2)) = O(n2 + n3) = O(n3).
To be truly formal about this, we would need to show that if f(n) = O(g(n)) and g(n) = O(h(n)), then f(n) = O(h(n)). Let's walk through a proof of this. If f(n) = O(g(n)), there are constants n0 and c such that for n ≥ n0, |f(n)| ≤ c|g(n)|. Similarly, since g(n) = O(h(n)), there are constants n'0, c' such that for n ≥ n'0, g(n) ≤ c'|h(n)|. So this means that for any n ≥ max(c, c'), we have that
|f(n)| ≤ c|g(n)| ≤ c|c'h(n)| = c x c' |h(n)|
And so f(n) = O(h(n)).
To be a bit more precise - in the case of the algorithm described here, the authors are saying that the runtime is Θ(n3), which is a stronger result than saying that the runtime is O(n3). Θ notation indicates a tight asymptotic bound, meaning that the runtime grows at the same rate as n3, not just that it is bounded from above by some multiple of n3. To prove this, you would also need to show that n3 is O(n2 + n3). I'll leave this as an exercise to the reader. :-)
More generally, if you have any polynomial of order k, that polynomial is O(nk) using a similar argument. To see this, let P(n) = ∑i=0k(aini). Then, for any n ≥ 1, we have that
∑i=0k(aini) ≤ ∑i=0k(aink) = (∑i=0k(ai))nk
so P(n) = O(nk).
Hope this helps!
A: n(n+n2) == n2 + n3
Big-O notation only cares about the dominant term as n goes to infinity, so the whole algorithm is thought of as Θ(n3).
A: O(n(n+n^2)) = O(n^2 + n^3)
Since the n^3 term dominates the n^2 term, the n^2 term is negligible and thus it is O(n^3).
A: The y loop can be discounted because of the z loop (O(n) + O(n^2) -> O(n^2))
Forget the arithmetic.
Then you're left with three nested loops that all iterate over the full length of 'seq', so it's O(n^3)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spring Roo: use JPA entity as a DAO The code below is what Spring Roo generates by default, the EntityManager is injected in your domain model POJOs with the rest of the methods to manage the entity (save, update, delete, findXXX, ...).
Maybe it is a more object-oriented approach (in contrast to the anemic domain model), but what I don't understand is:
*
*Is there any performance issue when EntityManager is injected in every entity (imagine you retrieve 1000 entities from a database)
*Shouldn't the transactional management (@Transactional annotations) go in a service layer? (imagine you want to operate with two different entities in an atomic way).
*Can you think about other pros/cons of this code against a classical DAO layer?
The code looks like this (some methods are removed for clarity):
@Configurable
@Entity
@RooJavaBean
@RooToString
@RooEntity
public class Answer {
@PersistenceContext
transient EntityManager entityManager;
@Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Answer attached = Answer.findAnswer(this.id);
this.entityManager.remove(attached);
}
}
@Transactional
public Answer merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Answer merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
public static final EntityManager entityManager() {
EntityManager em = new Answer().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long countAnswers() {
return entityManager().createQuery("SELECT COUNT(o) FROM Answer o", Long.class).getSingleResult();
}
public static List<Answer> findAllAnswers() {
return entityManager().createQuery("SELECT o FROM Answer o", Answer.class).getResultList();
}
...
}
A: *
*You will find more on this at the link in the third point.
*You don't get a Service layer in a typical Roo application. Your service methods are contained within the entity itself, hence it is possible to use @Transactional within your entity to ensure the particular method involves in a transaction. However, you will be able to get a separate service layer with the latest 1.2 version of Spring Roo, which will make it possible.
*ADM vs. DDD : A separate question on SO would help on this. Anyways, you can gain a lot of insight with this thread on SpringSource Roo forum. http://forum.springsource.org/showthread.php?77322-Spring-Roo-with-a-services-DAO-architecture
Cheers and all the best with Roo! :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Updating an object that contains a list in Hibernate In my GWT application, I pass an Object to the server for persistence with Hibernate. This Object contains a list of another object. Each element in the list contains a Map which is another Hibernate table.
In order to do this transaction, it is my understanding that I must first:
*
*Do a lookup to get the persistent object from the database via
Hibernate
*Modify the object
*Update the object via Hibernate
Here is some quick code on what I'm doing:
public void saveOrUpdateObject(final Foo foo)
{
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Object lookup = myDAO.getObject(foo.getUniqueValue());
if (lookup != null) {
lookup.getList().clear();
lookup.addAll(foo.getList());
myDAO.update(lookup);
}
else {
myDAO.save(foo);
}
}
Using this method, I occasionally get a HibernateException:
org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: my.Foo.list
What is the proper way to update an Object that contains a collection using Hibernate?
A: The problem has to do with having both managed and unmanaged objects:
*
*lookup is a managed object, as is lookup.list and everything in it
*foo is not a managed object, neither is anything in foo.list
When you call lookup.getList().clear(), you are signalling to Hibernate that everything in that managed list needs to be deleted (due to the all-delete-orphan cascading). However, you then come back and add a bunch of stuff to that (managed) list, including some things that were probably already there. Hibernate gets confused and throws an Exception.
Instead of manually tweaking the managed object's list, use merge(foo) to update the persistent instance's state with the unmanaged instance. From the Hibernate manual:
if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
Merging puts the responsibility of figuring out which state is updated onto Hibernate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get friends of an user An user X joined my application but he is not my friend, so I would like to see his friends, write in their walls, etc. Is it possible using the REST API?
Also, is possible to send a friend request to some user using the API?
A: Apparently, you could using the REST API: target_id.
"This mimics the action of posting on a friend's Wall on Facebook itself."
- http://developers.facebook.com/docs/reference/rest/stream.publish/
However, I think, for new applications, you'd better use not-deprecated methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenGraph API Beta: publish_action vs publish_stream Today, Facebook announced an entirely new way to share user actions on your site on through your app. The documentation is a good attempt at explaining how things work, but if I hadn't already built a sophisticated app off the existing OpenGraph API, I would probably be lost.
What's not made clear, at all, is what happens to the "old" permissions. Facebook wants us to prompt our users for the publish_action permission. I assume I can start (or can I not start yet? not clear here when this is usable on my live site) passing publish_action as a permission in my getLoginUrl (PHP SDK) call immediately.
What happens to the now "old" publish_stream permission? Do I need both? Will publish_stream be fazed out? Can already granted publish_stream permissions be translated in to publish_action so I don't have to prompt all my users for a new permission and scare them away? How do I future proof my app? What about that SPAM algorithm Facebook unleashed on app devs a few months ago, killing people's apps because they were "abusing" the publishing mechanism... does that exist for these new actions? Is there any guidance on how not to upset the algorithm gods and get banned?
I realize the new API was only just announced a few hours ago, but these are important questions and I seriously doubt I'm the only one that has them. I'd love to hear some feedback on this.
A: You can start testing publish_actions today, but shouldn't be asking users for it yet in your production apps until open graph launches more broadly.
publish_stream will continue to exist for more explicit posts, but we encourage apps to use open graph for Timeline apps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compiling source Qt 4.7.4 on windows 7 error qmake is not an internal or external command Edit 2 -
I don't have the application file qmake in the /bin folder and this is the error I am getting.
Path environment variable : C:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-src-4.7.4\bin\
Command Prompt - visual studio 2005
Source folder - C:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-src-4.7.4
Steps -
*
*Downloaded src
*Extracted the files to folder – qt-everywhere-opensource-src-4.7.4(C:\development\referencebuilds\qt\4.7.4)
*configure.exe -opensource -fast -no-accessibility -no-qt3support -no-multimedia -no-audio-backend -no-phonon -no-phonon-backend -no-webkit -no-scripttools -platform win32-msvc2005 -D “_BIND_TO_CURRENT_VCLIBS_VERSION=1”
4.nmake
The error I get is
Microsoft (R) Program Maintenance Utility Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
C:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-src-4.7
.4\bin\qmake C:/development/referencebuilds/qt/4.7.4/qt-everywhere-opensource-sr
c-4.7.4/\projects.pro -o Makefile -spec win32-msvc2005
'C:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-src-4.7.4\bin\
qmake' is not recognized as an internal or external command,
operable program or batch file.
NMAKE : fatal error U1077: 'C:\development\referencebuilds\qt\4.7.4\qt-everywher
e-opensource-src-4.7.4\bin\qmake' : return code '0x1'
Stop.
I know I dont have the app files for qmake and many other appfiles in my \bin folder. How do I get them?
Edit 1
Well, after trying out all the answers, the situation still remains the same. I think i should add more details to what I am doing.
I am copying bin files(.dll , Appplication, Application Extension, Incremental Linker File, Program Debug Database, ) from another machine and the version of Qt was 4.7.2
My questions are -
1. Do you see that as the cause for all the issues here? If yes, how do I get all the above files? If I just congigure as above and then run nmake I get
Microsoft (R) Program Maintenance Utility Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
C:\development\referencebuilds\qt\4.7.4\bin\qmake
C:/development/referen cebuilds/qt/4.7.4/\projects.pro -o Makefile
-spec win32-msvc2008
'C:\development\referencebuilds\qt\4.7.4\bin\qmake' is not recognized
as an inte rnal or external command, operable program or batch file.
NMAKE : fatal error U1077:
'C:\development\referencebuilds\qt\4.7.4\bin\qmake' : return code
'0x1' Stop.
1, Downloaded the source file named
qt-everywhere-opensource-4.7.4 and saved it in folder c:\development\referencebuilds\qt\4.7.4\
2, uncompressed the zip file and the files extracted into folder
c:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-4.7.4
3, Copied back all files from the folder
c:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-4.7.4 to c:\development\referencebuilds\qt\4.7.4\
4, ran
configure.exe -opensource -fast -no-acce ssibility -no-qt3support
-no-multimedia -no-audio-backend -no-phonon -no-phonon- backend
-no-webkit -no-scripttools -platform win32-msvc2008 -D
"_BIND_TO_CURRENT
_VCLIBS_VERSION=1"
5, nmake and now I get the following errors.
C:\development\referencebuilds\qt\4.7.4\bin\qmake
C:/development/referen cebuilds/qt/4.7.4/\projects.pro -o Makefile
-spec win32-msvc2008 Could not find mkspecs for your
QMAKESPEC(win32-msvc2008) after trying:
C:\Qt\4.7.2\mkspecs Error processing project file:
C:/development/referencebuilds/qt/4.7.4//projects .pro NMAKE : fatal
error U1077: 'C:\development\referencebuilds\qt\4.7.4\bin\qmake.EX E'
: return code '0x3' Stop.
I have no clue as to why it is refering to C:\Qt\4.7.2\mkspecs . How do I get over this error? what is exactly happening. How do I prevent such issues in future?
A: Your install directory is:
c:\development\referencebuilds\qt\4.7.4\qt-everywhere-opensource-4.7.4
Let's call it $(QTDIR). Now:
*
*Extend your PATH variable to include $(QTDIR)\bin
*Specify the QMAKESPEC environment variable to be win32-msvc2005
*Open a Visual Studio command prompt to get the Visual Studio environment variables
*Run configure
*Run nmake
This procedure usually gets the Qt build to work for me.
A: Make sure that you don't have any existing QT directories in your path before you call configure and nmake.
A: It looks like you have a previous version of Qt installed. "C:\Qt\4.7.2\". And it would seem you have it setup in your system variables. Look for a variable called QTDIR in your system environment variables. Which is why you are getting an error, basically your 4.7.2 Qt is trying to build the new version.
Two options:
Un-install your old Qt via add/remove software in the control panel.
or
Remove your QTDIR system variable for the time being (will require a re-login) so that when you try to build from source it will use the correct binaries from the source folder.
Then just follow this guide:
http://en.wikibooks.org/wiki/Opticks_Developer_Guide/Getting_Started/Building_Qt_From_Source
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Pulling the last 128 bytes off a binary file with C I am making an id3 tag editor in C. I am having trouble figuring out how to pull the last 128 bytes off the end of the binary file in order to manipulate/printout the area where the id3 tag sits. Heres some code:
struct Tag{
char tagMark[3];
char trackName[30];
char artistName[30];
char albumName[30];
char year[4];
char comment[30];
char genre;
};
int main(int argc, char *argv[]){
struct Tag fileTag;
FILE *fp;
fp=fopen(argv[0], "r+b");
if(!fp){
printf("ERROR: File does not exist.");
}
int bufLength=129;
fseek(fp, 0, SEEK_END);
long fileLength=ftell(fp);
fseek(fp, fileLength-bufLength+1, SEEK_SET);
fread(&fileTag, sizeof(fileTag), 1, fp);
printf("%s\n", fileTag.tagMark);
return 0;
}
I am using a file to test this with that contains a properly formatted id3 tag. In an id3 tag, the first three bytes contain 'T', 'A', and 'G' respectively in order to identify that the tag exists. Does someone know why when I run this program, "_main" is the only thing that prints out?
A: Use fseek() (or lseek() if you're using file descriptors instead of file streams) with a negative offset (-128) bytes from the end of the file. Then read the 128 bytes of information.
Hence:
fseek(fp, -128L, SEEK_END);
lseek(fd, -128L, SEEK_END);
(Interestingly, the SEEK_END, SEEK_SET and SEEK_CUR macros are defined in both <stdio.h> for standard C and in <unistd.h> for POSIX.)
A: Your program does
fp=fopen(argv[0], "r+b");
argv[0] contains the name of the running executable, you want argv[1], the first command line parameter. The next problem you'll probably run into (when starting with ID3v2) is structure field alignment, depending on the datatypes used the compiler may leave "gaps" between the consecutive members of a structure. To avoid this problem the compiler should be instructed to align the structure on byte boundaries with (in most cases, check your compiler's documentation)
#pragma pack(1)
This Structure padding and packing SO answer explains clearly what happens if you don't use the correct packing.
Also, see the ID3V1 layout, there's not always a terminating 0 after the individual fields, so
printf("%s\n", fileTag.tagMark);
will print TAG followed by the song title (printf %s only stops when it encounters a \0).
IMHO, given the jungle that ID3 is you're probably better off delegating the raw ID3 manipulation to an existing library like id3lib and focus on the functionality of your editor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I ensure data is written to disk before closing fstream? The following looks sensible, but I've heard that the data could theoretically still be in a buffer rather than on the disk, even after the close() call.
#include <fstream>
int main()
{
ofstream fsi("test.txt");
fsi << "Hello World";
fsi.flush();
fsi.close();
return 0;
}
A: You cannot to this with standard tools and have to rely on OS facilities.
For POSIX fsync should be what you need. As there is no way to a get C file descriptor from a standard stream you would have to resort to C streams in your whole application or just open the file for flushing do disk. Alternatively there is sync but this flushes all buffers, which your users and other applications are going to hate.
A: You could guarantee the data from the buffer is written to disk by flushing the stream. That could be done by calling its flush() member function, the flush manipulator, the endl manipulator.
However, there is no need to do so in your case since close guarantees that any pending output sequence is written to the physical file.
§ 27.9.1.4 / 6:
basic_filebuf< charT, traits >* close();
Effects: If is_open() == false, returns a null pointer. If a put area exists, calls overflow(traits::eof()) to flush characters. (...)
A:
§ 27.9.1.4
basic_filebuf* close();
Effects: If is_open() == false, returns a null pointer. If a put area
exists, calls overflow(traits::eof()) to flush characters. If the last
virtual member function called on *this (between underflow, overflow,
seekoff, and seekpos) was overflow then calls a_codecvt.unshift
(possibly several times) to determine a termination sequence, inserts
those characters and calls overflow(traits::eof()) again. Finally,
regardless of whether any of the preceding calls fails or throws an
exception, the function closes the file (as if by calling
std::fclose(file)). If any of the calls made by the function,
including std::fclose, fails, close fails by returning a null pointer.
If one of these calls throws an exception, the exception is caught and
rethrown after closing the file.
It's guaranteed to flush the file. However, note that the OS might keep it cached, and the OS might not flush it immmediately.
A: Which operating system are you using?
You need to use Direct (non-buffered) I/O to guarantee the data is written directly to the physical device without hitting the filesystem write-cache. Be aware it still has to pass thru the disk cache before getting physically written.
On Windows, you can use the FILE_FLAG_WRITE_THROUGH flag when opening the file.
A: How abt flushing before closing?
A: The close() member function closes the underlying OS file descriptor. At that point, the file should be on disk.
A: I'm pretty sure the whole point of calling close() is to flush the buffer. This site agrees. Although depending on your file system and mount settings, just because you've 'written to the disk' doesn't mean that your file system drivers and disk hardware have actually taken the data and made magnet-y bits on the physical piece of metal. It could probably be in a disk buffer still.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using tcpdump to capture a specific port when UDP message can be fragmented I am running tcpdump to capture UDP messages on a specific port. The UDP traffic being captured contains fragmented UDP packets.
When a fragmented UDP packet is encountered, tcpdump is only capturing the first fragment. (Probably because only the first fragment contains the port information).
Is there a switch on TCP dump that will capture all the fragments of a UDP packet even when messages from a port are being filtered?
A: I could be wrong but I think what you mean is how to extend the snaplen as you're only catching a snippet of the packet with tcpdump. The default snaplen is usually 68 bytes.
Setting snaplen to 0 sets it to the default of 65535 bytes so run tcpdump with "-s 0" to capture everything. Are you running with the '-s' switch?
It's recommended that you limit snaplen to the smallest number that will capture the protocol information you're interested in.
HTH!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NSTimers VS NSThreading I'm working on an iPhone Game where the player tilts the iPhone to make the character move, but unfortunately all of the timers I'm using to animate the scenario are slowing down my game. I've been told to use NSThreads, but I really don't know anything about them. My question is, What are the differences between using NSThreads and NSTimers? Or what are the advantages of using NSThreads? How are they useful?
A: Timers are used for asynchronous, not concurrent, execution of code.
A timer waits until a certain time interval has elapsed and then fires, sending a specified message to a target object. For example, you could create an NSTimer object that sends a message to a window, telling it to update itself after a certain time interval.
Threads are for concurrent execution of code.
An NSThread object controls a thread of execution. Use this class when you want to have an Objective-C method run in its own thread of execution. Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions. Threads can also be used to divide a large job into several smaller jobs, which can lead to performance increases on multi-core computers.
See also:
*
*How do I use NSTimer?
*Timer Programming Topics
*Threaded Programming Guide
A: Timers are objects that simply call methods at a later time. Threads are additional "streams" of stuff to be processed, in psuedo-parallel. It's like comparing apples to oranges—they're not really related. The only relation I can see is if you want to do some processing in the background, but you shouldn't be doing UI calls in background threads, Why are you using timers to make your character move? Knowing that, we might be able to supply an alternate solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Limit on the number of columns in cassandra Is there any limit on the number of columns in cassandra? I am thinking of using a unix timestamp (converted to TimeUUID) as the column key. In the worst case, I will end up having 86400 columns per row. Is this a good idea?
A: Assuming you're doing that for a good reason, it's totally fine.
A: Having 86.400 columns per row is piece of cake for cassandra as long your columns are not too big and you don't retrieve all of them.
The maximum of column per row is 2 billion.
See http://wiki.apache.org/cassandra/CassandraLimitations
A suggestion: For column name you should use Integer data serialization, which would take just 4 bytes for 1 second precision instead of using UUID (16 bytes); as long as your timestamps are all unique and 1s precision is enough.
Column names are sorted and you can use unix time as Integer. With this you can have fast lookups on columns.
There is also timestamp associated with each column, which can be useful to set in some cases. You cannot query on it, but may provide you additional information if needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Balancing account while selecting MySQL rows in descending order - Code Update Working on a finance tracker and have run into a bit of a snag with displaying transactions in descending order (most recent to oldest) with a correct running balance.
Here is the SQL I am using:
SELECT amount, payee, cat, date FROM transactions ORDER BY id DESC, date DESC
I am using a class to handle the other aspects of this app and the function to display the transactions is part of it. If I were displaying the transactions in ascending order, the following code works as expected:
//Fetch the transactions
public function fetchTransactions() {
global $db;
$this->getStartingBalance();
$runningTotal = $this->startingBalance;
$fetchTransactionsSQL = $db->query("SELECT amount, payee, cat, date FROM transactions ORDER BY id, date");
while ($transactionDetails = $fetchTransactionsSQL->fetch()) {
$payee = stripslashes($transactionDetails[payee]);
$category = $transactionDetails['cat'];
$amount = money_format("%n", $transactionDetails[amount]);
$runningTotal = $runningTotal + $transactionDetails['amount'];
$runningTotalOutput = money_format("%n", $runningTotal);
echo "
<tr>
<td class=\"payee\">$payee</td>
<td>$category</td>
<td>$amount</td>
<td class=\"runningTotal\">$runningTotalOutput</td>
</tr>";
}
}
Stuck on trying to display in desc order with the correct running balance - for example, if the value of $this->startingBalance was $354.00 and the first (therefore the last displayed in desc order) transaction was for $4.00, the last entry's running balance would be $350.00. The numbers are signed.
Many thanks!
UPDATED CODE
Following along the lines of drew010's advice, I remembered a handy little function - array_reverse. I updated the function to include an array for transactions, reversed it, and then iterated through the array to display the transactions in ascending order with the correct running balance.
Another problem that I just ran into is the issue of indexing the transactions - for example, displaying only the current month's transactions while maintaining the correct running balance. The updated code below solves the issue of displaying ALL of the transactions in the right order with the correct balance but does not help with the matter of limiting the returned rows.
Here is the updated code, suggestions are appreciated.
public function fetchTransactions() {
global $db;
$this->getStartingBalance();
$runningTotal = $this->startingBalance;
//Array to contain the transactions
$transactions = array();
//Counter for transactions array key
$i = 0;
$fetchTransactionsSQL = $db->query("SELECT amount, payee, cat, date FROM transactions ORDER BY id, date");
while ($transactionDetails = $fetchTransactionsSQL->fetch()) {
$payee = stripslashes($transactionDetails[payee]);
$category = $transactionDetails['cat'];
$amount = money_format("%n", $transactionDetails[amount]);
$runningTotal = $runningTotal + $transactionDetails['amount'];
$runningTotalOutput = money_format("%n", $runningTotal);
$transactions[$i] = array("payee" => $payee, "category" => $category, "amount" => $amount, "runningTotal" => $runningTotalOutput);
$i++; //Increment the array key
}
$transactions = array_reverse($transactions); //Reverse the transactions array to display in ascending order
//Iterate over transactions array
foreach ($transactions as $transaction) {
$payee = $transaction['payee'];
$category = $transaction['category'];
$amount = $transaction['amount'];
$runningTotal = $transaction['runningTotal'];
echo "
<tr>\n
<td>$payee</td>\n
<td>$category</td>\n
<td>$amount</td>\n
<td>$runningTotal</td>\n
</tr>\n
";
}
}
A: *
*run SUM(amount) FROM transactions
*Remember result and add it to your $startingBalance and remember that as $endingBalance
*Run your query to select all transactions in DESC order like you want
*For each transaction instead of adding $amount to $running balance, substract the $amount from $endingBalance...
Example:
5 Transactions selected in DESC order (amounts only):
1. -7
2. 10
3. 22
4. -17
5. -2
SUM of transactions: $tSum = -7 + 10 + 22 - 17 - 2 = 6
$startingBalance= 300
$endingBalance = $startingBalance + tSum = 300 + 6 = 306
Transactions displayed in desc order:
(AMOUNT | RUNNING BALLANCE)
END BALANCE: 306
-7 | 306 ($endingBalance)
10 | 313 ($endingBalanse -= -7)
22 | 303 ($endingBalance -= 10)
-17 | 281 ($endingBalance -= 22)
-2 | 298 ($endingBalance -= -17)
START BALANCE: 300 ($endingBalance -= -2)
Your code updated:
//Fetch the transactions public
function fetchTransactions()
{
global $db;
$this->getStartingBalance();
$endingBalance = $this->startingBalance + $this->getTransactionsSum();
$runningTotal = $endingBalance;
$prevAmount = 0;
$fetchTransactionsSQL = $db->query("SELECT amount, payee, cat, date FROM transactions ORDER BY id DESC, date DESC");
while ($transactionDetails = $fetchTransactionsSQL->fetch())
{
$payee = stripslashes($transactionDetails[payee]);
$category = $transactionDetails['cat'];
$amount = money_format("%n", $transactionDetails[amount]);
$runningTotal -= $prevAmount;
$prevAmount = $amount;
$runningTotalOutput = money_format("%n", $runningTotal);
echo "<tr>
<td class=\"payee\">$payee</td>
<td>$category</td>
<td>$amount</td>
<td class=\"runningTotal\">$runningTotalOutput</td>
</tr>";
}
}
function getTransactionsSum()
{
$sql = $db->query("SELECT SUM(amount) AS mySum FROM transactions");
if( $sumFields = $sql->fetch() )
{
return money_format("%n", $sumFields[mySum]);
}
else
{
return 0;
}
}
I hope you have found that helpful...
A: I would read the values in ascending order from the point where the starting balance matches up with the first transaction in your query.
Add everything to an array that contains payee, amount, category etc and calculate your balance there. Then add that array to another array $transactions[] = $transaction.
Then when you are ready to output, read backwards from $transactions and output them.
for ($i = sizeof($transactions) - 1; $i >= 0; ++$i) {
$txn = $transactions[$i];
// output data
}
It is a good idea to separate database access from other logic, and separate database and controller logic from your html output for a number of reasons. See MVC on wikipedia.
A: Why don't you start from the current balance and work backwards? So the first transaction's running balance would be the start balance, then you subtract the current transaction amount from the start balance and that is the running balance of the next transaction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to install and use a gem inside an rails engine I use refinery-cms to create a webshop in ruby-on-rails and refinery is largely based on engines. I have therefore made a "webshop" engine with all my models, and i want to install the gem "activeadmin" inside this engine, so when i run "rails g active_admin:install" it will create the model and config files inside my engine dir. I can only get it to install in the root app
Hope you can help me
/Johan
A: The solution to this was just to cd in to the engine folder, and run the generator command from there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: foreach linq2sql string problem Hi all when I am trying to match a letter O in my database I get string format errors. I have tried a few things now and googles alot but still cant resolve this error
const string st1 = ("O");
var docketcheck = from q in db.Dockets
where q.DocketNum == txtDisplay.Text && q.Status.Equals(st1)
select q;
foreach (Docket d in docketcheck)
{
if (d.EngName.Equals("NULL"))
{
isEngNameNull = true;
break;
}
}
if (isEngNameNull)
{
txtDisplay.Clear();
txtDisplay.ReadOnly = false;
var engs = new EngStart();
engs.ShowDialog(this);
}
else
{
var sub = new machinesel();
txtDisplay.Clear();
sub.ShowDialog(this);
}
What is the correct way to check if my mssql database contains the letter O in the above code
Thanks
A: The way you are doing it is fine provided that q.Status is a string type column.
Here is the lambda way to do it if you are interested.
db.Dockets.Where(q => q.DocketNum == txtDisplay && q.Status == "O")
A: Your code looks fine and when I tested an equivalent query on my machine it worked without issue.
You could tidy your code up a bit so that it only pulls back the count of matching records like this:
const string st1 = "O";
var docketcheck =
from q in db.Dockets
where q.DocketNum == txtDisplay.Text
where q.Status == st1
where d.EngName == "NULL"
select q;
if (docketcheck.Any())
{
txtDisplay.Clear();
txtDisplay.ReadOnly = false;
var engs = new EngStart();
engs.ShowDialog(this);
}
else
{
var sub = new machinesel();
txtDisplay.Clear();
sub.ShowDialog(this);
}
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to write a DirectX audio push source I want to create a DirectX 'filter' that sources a single channel of audio. I have seen the Platform SDK sample projects, but the downside there is that those require the ATL library.
Is there a way to create DirectX filters without resorting to ATL or MFC? I.e., some way using only gcc (e.g., MinGW) and other actually free tools?
A: If I understand right, the filter has to be a COM component. You can, sort of, write those from most compilers, if need be.
However, the boilerplate that would involve would be incredible, I had a 18kloc codebase that turned into 25kloc when turned into COM components (ended up turning it back just because there was more boilerplate COM than actual code for small plugins).
MFC isn't necessary or always involved in writing COM components, that I know of.
ATL helps simplify that greatly, by providing templates and functions to handle a lot of the details at compile-time. You may be able to use it from GCC, but I'm not sure what would happen; I doubt it would work well, though it might work.
Without ATL, you need MIDL and to generate the code from there. That is possible with free tools, it's done in a few places in the Wine project; you may check the code and toolchains there.
No matter where you do it, it'll be a pain, and a serious pain if you insist on using "actually free" tools for it (as they're not particularly designed to work with COM).
A: If you had DirectShow filter in mind, the best starting point would be PushSource Windows SDK Sample, which generates video and making it generate audio.
Also note that DirectShow bases classes are one of the earliest COM bases and they do not use ATL/MFC. The base classses themselves are also included with Windows SDK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create an AppleScript to loop through a BBEdit document and move a "-" from the end of a number to the beginning? I have a dirty report file that contains improperly formatted negative numbers. The ultimate goal is to import these to Excel for analysis. I am using BBEdit to clean the report before importing into Excel. I would like to create an apple script to loop through the report and move the "-" from the back of the number to the front.
Dirty Report Example Rows:
B-EXCAL 02 3684 2.0000- 49.02- 108.00- 58.98- 54.6-
B-MISMH 09-3300 33.0000 722.91 1353.00 630.09 46.6
Desired output:
B-EXCAL 02 3684 -2.0000 -49.02 -108.00 -58.98 -54.6
B-MISMH 09-3300 33.0000 722.91 1353.00 630.09 46.6
I have JavaScript and VBScript experience so I imaging the script working something like this psudo script:
Get contents of current window from BBEdit
for each word in contents
if char(len(word)) = "-"
newWord = "-" + rightTrim(word, 1)
replace(word, newWord)
end if
end for
end
This is my first experience with AppleScript and I am at a complete loss.
Thanks for the help/
A: I'm not sure you need AppleScript. Will BBEdit's find/replace window work for this? Try the following:
Find: ([0-9\.]+)\-
Replace: \-\1
"Grep" and "Wrap around" should be the only things selected below the "Replace" text area. Then click "Replace All."
If you need to do it to a bunch of reports at once, use the same find/replace patterns with multi file search. If I'm not understanding your question correctly, let me know, but I think you can get this done without AppleScript.
A: Try this. I'm assuming you can get the text from bbedit (or wherever) into applescript as the variable "originalText". Then you'll have to put the "fixedText" back wherever it belongs. NOTE: in my code I assume the "tab" character separates the words/columns in each line of the origText as Michael J. Barber has it currently formatted. If it is another character (like a space character) then you will have to change the word tab in the code to space.
set originalText to "B-EXCAL 02 3684 2.0000- 49.02- 108.00- 58.98- 54.6-
B-MISMH 09-3300 33.0000 722.91 1353.00 630.09 46.6"
set fixedText to fixNegativeSigns(originalText)
on fixNegativeSigns(theText)
set listText to paragraphs of theText
set fixedText to ""
set {tids, text item delimiters} to {text item delimiters, tab}
repeat with i from 1 to count of listText
set listItems to {}
set thisList to text items of (item i of listText)
repeat with j from 1 to count of thisList
set thisItem to item j of thisList
if text -1 of thisItem is "-" then
set thisItem to "-" & text 1 thru -2 of thisItem
end if
set end of listItems to thisItem
end repeat
set fixedText to fixedText & (listItems as text) & character id 10
end repeat
set text item delimiters to tids
return text 1 thru -2 of fixedText
end fixNegativeSigns
NOTE: when testing my code above you should copy/paste it into Applescript Editor. You will have to fix the tab characters in originalText because they do not survive the copy/paste. So remove the spaces between the words/columns and insert a tab. Then the code will work correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 2D Particle System - Performance I have implemented a 2D Particle System based on the ideas and concepts outlined in "Bulding an Advanced Particle System" (John van der Burg, Game Developer Magazine, March 2000).
Now I am wondering what performance I should expect from this system. I am currently testing it within the context of my simple (unfinished) SDL/OpenGL platformer, where all particles are updated every frame. Drawing is done as follows
// Bind Texture
glBindTexture(GL_TEXTURE_2D, *texture);
// for all particles
glBegin(GL_QUADS);
glTexCoord2d(0,0); glVertex2f(x,y);
glTexCoord2d(1,0); glVertex2f(x+w,y);
glTexCoord2d(1,1); glVertex2f(x+w,y+h);
glTexCoord2d(0,1); glVertex2f(x,y+h);
glEnd();
where one texture is used for all particles.
It runs smoothly up to about 3000 particles. To be honest I was expecting a lot more, particularly since this is meant to be used with more than one system on screen. What number of particles should I expect to be displayed smoothly?
PS: I am relatively new to C++ and OpenGL likewise, so it might well be that I messed up somewhere!?
EDIT Using POINT_SPRITE
glEnable(GL_POINT_SPRITE);
glBindTexture(GL_TEXTURE_2D, *texture);
glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
// for all particles
glBegin(GL_POINTS);
glPointSize(size);
glVertex2f(x,y);
glEnd();
glDisable( GL_POINT_SPRITE );
Can't see any performance difference to using GL_QUADS at all!?
EDIT Using VERTEX_ARRAY
// Setup
glEnable (GL_POINT_SPRITE);
glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
glPointSize(20);
// A big array to hold all the points
const int NumPoints = 2000;
Vector2 ArrayOfPoints[NumPoints];
for (int i = 0; i < NumPoints; i++) {
ArrayOfPoints[i].x = 350 + rand()%201;
ArrayOfPoints[i].y = 350 + rand()%201;
}
// Rendering
glEnableClientState(GL_VERTEX_ARRAY); // Enable vertex arrays
glVertexPointer(2, GL_FLOAT, 0, ArrayOfPoints); // Specify data
glDrawArrays(GL_POINTS, 0, NumPoints); // ddraw with points, starting from the 0'th point in my array and draw exactly NumPoints
Using VAs made a performance difference to the above. I've then tried VBOs, but don't really see a performance difference there?
A: I can't say how much you can expect from that solution, but there are some ways to improve it.
Firstly, by using glBegin() and glEnd() you are using immediate mode, which is, as far as I know, the slowest way of doing things. Furthermore, it isn't even present in the current OpenGL standard anymore.
For OpenGL 2.1
Point Sprites:
You might want to use point sprites. I implemented a particle system using them and came up with a nice performance (for my knowledge back then, at least). Using point sprites you are doing less OpenGL calls per frame and you send less data to the graphic card (or even have the data stored at the graphic card, not sure about that). A short google search should even give you some implementations of that to look at.
Vertex Arrays:
If using point sprites doesn't help, you should consider using vertex arrays in combination with point sprites (to save a bit of memory). Basically, you have to store the vertex data of the particles in an array. You then enable vertex array support by calling glEnableClientState() with GL_VERTEX_ARRAY as parameter. After that, you call glVertexPointer() (the parameters are explained in the OpenGL documentation) and call glDrawArrays() to draw the particles. This will reduce your OpenGL calls to only a handfull instead of 3000 calls per frame.
For OpenGL 3.3 and above
Instancing:
If you are programming against OpenGL 3.3 or above, you can even consider using instancing to draw your particles, which should speed that up even further. Again, a short google search will let you look at some code about that.
In General:
Using SSE:
In addition, some time might be lost while updating your vertex positions. So, if you want to speed that up, you can take a look at using SSE for updating them. If done correctly, you will gain a lot of performance (at a large amount of particles at least)
Data Layout:
Finally, I recently found a link (divergentcoder.com/programming/aos-soa-explorations-part-1, thanks Ben) about structures of arrays (SoA) and arrays of structures (AoS). They were compared on how they affect the performance with an example of a particle system.
A: Consider using vertex arrays instead of immediate mode (glBegin/End): http://www.songho.ca/opengl/gl_vertexarray.html
If you are willing to get into shaders, you could also search for "vertex shader" and consider using that approach for your project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Codeigniter 2.x - Authentication + ACL library I need a Codeigniter 2.x ACL + Authentication library.
I need to give have 3 different admin users and 2 different front end users and want to set everything dynamically through database.
Please help.
A: The two most popular authentication libraries for CI (at least as of early this year) seemed to be Ion_auth and Tank_auth. Neither handle your ACL needs, though Ion_auth provides single group functionality.
I started with Tank_auth on a project several months ago, but switched to Ion_auth when I needed more flexibility. With it's included functionality, I added a user_groups table and the necessary library and model functions to allow multiple group memberships for each user.
The data structure:
mysql> describe auth_users_groups;
+------------+-----------------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------------------+------+-----+-------------------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| user_id | mediumint(8) unsigned | NO | | NULL | |
| group_id | mediumint(8) unsigned | NO | | NULL | |
| dt_updated | timestamp | NO | | CURRENT_TIMESTAMP | |
+------------+-----------------------+------+-----+-------------------+----------------+
4 rows in set (0.00 sec)
Some of the code added in the library:
public function get_user_groups($user_id = NULL)
{
if ($user_id === NULL) $user_id = $this->get_user()->id;
return $this->ci->ion_auth_model->get_user_groups($user_id)->result();
}
/**
* is_member - checks for group membership via user_groups table
*
* @param string $group_name
* @return bool
**/
public function is_member($group_name)
{
$user_groups = $this->ci->session->userdata('groups');
if ($user_groups)
{
// Go through the groups to see if we have a match..
foreach ($user_groups as $group)
{
if ($group->name == $group_name)
{
return true;
}
}
}
// No match was found:
return false;
}
Some of the model code:
public function get_user_groups($user_id = NULL)
{
if ($user_id === NULL) return false;
return $this->db->select('group_id, name, description, dt_updated')
->join($this->tables['groups'], 'group_id = '.$this->tables['groups'].'.id', 'left')
->where('user_id', $user_id)
->get($this->tables['users_groups']);
}
public function set_group($user_id, $group_id)
{
$values = array('user_id'=>$user_id, 'group_id'=>$group_id);
$hits = $this->db->where($values)->count_all_results($this->tables['users_groups']);
if ($hits > 0)
{
return NULL;
}
return $this->db->insert($this->tables['users_groups'], $values);
}
public function remove_groups($user_id, $group_ids)
{
$this->db->where('user_id', $user_id);
$this->db->where_in('group_id', $group_ids);
return $this->db->delete($this->tables['users_groups']);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Internet bots - Filling forms How do Internet bots fill up forms randomly on websites? I am guessing they download the HTML source code and figure out the presence of forms. But then how exactly do they fill them up and actually submit the information?
I know many Forms use Captcha, but a number of systems also use techniques like detecting mouse movements, keyboard events to differentiate humans from bots. Can bots defeat them as well.
Basically, I want to know if there is any way a bot can track the Javascript changes in the code i.e the dynamic changes to the page ?
P.S: I am using this information for a grad project on techniques to defeat bots.
A: You don't particular need to always download the source. You can do it manually to find out the form fields, then build something (almost anything, Python script for example) that submits.
<form action="submit.php" method="post">
<input name="url" />
<input name="name" />
<input type="submit" />
</form>
Then use whatever language to send a POST request to site.com/submit.php. Generally with the data "url=xxx&name=xxx".
Based on the tags though its unlikely you can do it with JS or HTML.
A: Take a look at stateful browsers for scripting languages. Python has this module called mechanize
A: Some testing platforms like Watir actually perform mouse and keyboard actions instead of just HTTP requests (so any bot-prevention methods you do in Javascript could be avoided). This means it is basically impossible to differentiate between a bot and a human. Things like Captcha rely on bots being unable to correctly identify a word or words in an image, but even this can be broken some of the time with OCR.
Basically there are many measures you can put in place to discourage bots, but it's pretty much impossible to stop them if they are diligent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Am I writing procedural code with objects or OOP? So basically I'm making a leap from procedural coding to OOP.
I'm trying to implement the principles of OOP but I have a nagging feeling I'm actually just writing procedural style with Objects.
So say I have a list of pipes/chairs/printers/whatever, they are all all listed as products in my single table database. I need to build a webapp that displays the whole list and items depending on their type, emphasis is on 'correct' use of OOP and its paradigm.
Is there anything wrong about just doing it like:
CLass Show
{
public function showALL(){
$prep = "SELECT * FROM myProducts";
$q = $this->db-> prepare($prep);
$q->execute();
while ($row = $q->fetch())
{
echo "bla bla bla some arranged display".$row['something']
}
}
and then simply
$sth = new show();
$sth->showAll();
I would also implement more specific display methods like:
showSpecificProduct($id)->($id would be passed trough $_GET when user say clicks on one of the links and we would have seperate product.php file that would basically just contain
include('show.class.php');
$sth = new show();
$sth->showSpecificProduct($id);
showSpecificProduct() would be doing both select query and outputing html for display.
So to cut it short, am I going about it allright or I'm just doing procedural coding with classes and objects. Also any ideas/hints etc. on resolving it if I'm doing it wrong?
A: A better fit would be to implement a repository pattern. An example interface might be
interface ProductRepository
{
public function find($id);
public function fetchAll();
}
You would then create a concrete implementation of this interface
class DbProductRepository implements ProductRepsoitory
{
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function find($id)
{
// prepare execute SQL statement
// Fetch result
// return result
}
public function fetchAll()
{
// etc
}
}
It's generally a bad idea to echo directly from a method or function. Have your methods return the appropriate objects / arrays / whatever and consume those results.
A: As well as the model practices described by @Phil and @Drew, I would urge you to separate your business, data and view layers.
I've included a very simple version which will need to be expanded upon in your implementation, but the idea is to keep your Db selects separate from your output and almost "joining" the two together in the controller.
class ProductController
{
public $view;
public function __construct() {
$this->view = new View;
}
public function indexAction() {
$model = new DbProductRepository;
$products = $model->fetchAll();
$this->view->products = $products;
$this->view->render('index', 'product');
}
}
class View
{
protected $_variables = array();
public function __get($name) {
return isset($this->_variables['get']) ? $this->_variables['get'] : null;
}
public function __set($name, $value) {
$this->_variables[$name] = $value;
}
public function render($action, $controller) {
require_once '/path/to/views/' . $controller . '/' . $action . '.php';
}
}
// in /path/to/views/product/index.php
foreach ($this->products as $product) {
echo "Product ID {$product['id']} - {$product['name']} - {$product['cost']}<br />\n";
}
A: The scenario you are describing above seems like a good candidate for MVC.
In your case, I would create a class strictly for accessing the data (doing selects of product categories or specific products) and then have a different file (your view) take the output and display it.
It could look something like this:
class Product_Model {
public function find($prodId) { ... }
public function fetchAll($category = '') { ... }
public function search($string) { ... }
}
Then somewhere else you can do:
$products = new Product_Model();
$list = $products->fetchAll(37); // get all from category 37
// in true MVC, you would have a view that you would assign the list to
// $view->list = $list;
foreach($ilst as $product) {
echo "Product ID {$product['id']} - {$product['name']} - {$product['cost']}<br />\n";
}
The basic principle of MVC is that you have model classes that are simply objects representing data from some data source (e.g. database). You might have a mapper that maps data from the database to and from your data objects. The controller would then fetch the data from your model classes, and send the information to the view, where the actual presentation is handled. Having view logic (html/javascript) in controllers is not desirable, and interacting directly with your data from the controller is the same.
A: first, you will want to look into class autoloading. This way you do not have to include each class you use, you just use it and the autoloader will find the right file to include for you.
http://php.net/manual/en/language.oop5.autoload.php
each class should have a single responsibility. you wouldn't have a single class that connects to the database, and changes some user data. instead you would have a database class that you would pass into the user class, and the user class would use the database class to access the database. each function should also have a single responsibility. you should never have an urge to put an "and" in a function name.
You wouldn't want one object to be aware of the properties of another object. this would cause making changes in one class to force you to make changes in another and it eventually gets difficult to make changes. properties should be for internal use by the object.
before you start writing a class, you should first think about how you would want to be able to use it (see test driven development). How would you want the code to look while using it?
$user = new User($db_object);
$user->load($id);
$user->setName($new_name);
$user->save();
Now that you know how you want to be able to use it, it's much easier to code it the right way.
research agile principles when you get a chance.
A: One rule of thumb is that class names should usually be nouns, because OOP is about having software objects that correspond to real conceptual objects. Class member functions are usually the verbs, that is, the actions you can do with an object.
In your example, show is a strange class name. A more typical way to do it would be to have a class called something like ProductViewer with a member function called show() or list(). Also, you could use subclasses as a way to get specialized capabilities such as custom views for particular product types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: converting a two dimensional javascript array to JSON i've tried a few different json methods (stringify, toJSON, and probably some totally irrelevant others out of desperation) but can't seem to figure out how to stringify this so i can pass it to a php script. i am able to create a two dimensional array that which could be represented something like this:
array(
'image'=>array(
0=>'hello.jpeg',
1=>'goodbye.jpeg',
2=>'etc.jpeg'),
'resume'=>array(
0=>'resume.doc'),
'reel'=>array(
0=>'reel.mov')
)
the array looks okay when i print it to console using this dump function. i tried figuring out how to get this to work with objects because i thought i read something that said objects were already JSON friendly, but since i'm not super familiar with javascript i was pretty much floundering about.
edit: some more details... the declaration of my array (when i had it working) was something like this, although i may have messed up:
var fileArray = [];
fileArray['image'] = [];
fileArray['resume'] = [];
fileArray['reel'] = [];
var type;
var name;
var divs = $("#upload-container").children('div');
$.each(divs, function() {
type = $(this).attr('id');
name = $(this).html();
fileArray[type].push(name);
});
A: The object for that array structure might look like this in JavaScript:
var objects =
[
{
'image': [
{ '0': 'hello.jpeg' },
{ '1': 'goodbye.jpeg' },
{ '2': 'etc.jpeg' }
]
},
{
'resume': [
{ '0': 'resume.doc' }
]
},
{
'reel': [
{ '0': 'reel.mov' }
]
}
]
So now you've got an array of three objects, each of which contains a property (image, resume, reel) that is another array of objects with basically key:value pairs ('0':'hello.jpeg'). Maybe you could simplify it by not bothering to use the indexes:
var objects =
[
{
'image': [ 'hello.jpeg', 'goodbye.jpeg', 'etc.jpeg' ]
},
{
'resume': [ 'resume.doc' ],
},
{
'reel': [ 'reel.mov' ]
}
]
Then you can use JSON.stringify(objects) to pass to your PHP action.
A: Your sample expected output on the PHP side has an associative array containing numeric arrays. JavaScript arrays have numeric indexes: if you want strings as keys use a plain object rather than an array because JavaScript objects act like the associative arrays you are thinking of from PHP. The corresponding JavaScript object should look like this:
var fileArray = {
'image' : [ 'hello.jpeg',
'goodbye.jpeg',
'etc.jpeg'],
'resume' : [ 'resume.doc' ],
'reel' : [ 'reel.mov' ]
};
In the arrays defined with square brackets the numeric indexes are implied. Note that fileArray is defined with curly braces not square brackets and so is not an array (in spite of its name). This still allows you to use the fileArray['image'] = ... syntax if you want to set the properties one at a time:
var fileArray = {}; // an object, not an array
fileArray['image'] = [];
fileArray['resume'] = [];
fileArray['reel'] = [];
Note that the curly brackets in the initial declaration make it an object but properties are still accessed with square bracket syntax.
The way you were defining fileArray as a JavaScript array with square brackets still allows you to add string-based key properties because arrays are objects, but JSON stringify routines may ignore those properties and only serialise the numerically indexed properties.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.