Wednesday, April 18, 2012

Cast exception when marshalling

I'm currently working with a struct which is written into a buffer. When reading the struct back into my Application i get the following exception:




Unable to cast object of type 'System.Windows.Documents.TextStore' to type 'System.Version'.




Code



The exception is thrown when casting the result back ( (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); ).



protected static T ReadStruct<T>(Stream input)
where T : struct
{
Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
input.Read(buffer, 0, buffer.Length);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return result;
}


Used data-structure



/// <summary>
/// The header for all binary files
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet=CharSet.Ansi)]
public unsafe struct BinaryHeader
{
public const String MAGIC_KEY = "TABF";

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
String _Magic;
Version _Version;
DateTime _Timestamp;
Guid _Format;
Int64 _Reserved0;
Int64 _Reserved1;
/// <summary>
/// The magic value for the test automation binary
/// </summary>
public String Magic
{
get
{
return _Magic;
}
}
/// <summary>
/// The version of the assembly ( used for debugging )
/// </summary>
public Version AssemblyVersion { get { return _Version; } }
/// <summary>
/// The formatGuid of the current binary
/// </summary>
public Guid FormatGuid { get { return _Format; } }
/// <summary>
/// The timestamp of the file
/// </summary>
public DateTime Timestamp { get { return _Timestamp; } }

public BinaryHeader(Guid formatGuid)
{
_Reserved0 = 0;
_Reserved1 = 0;

_Version = BinaryBase.AssemblyVersion;
_Format = formatGuid;
_Timestamp = DateTime.Now;
_Magic = MAGIC_KEY;
}
}




Lock free atomic state class - is it correct?

I am just looking for feedback (obvious flaws/ways to improve it) on my attempt to implement atomic read/writes on a structure.



There will be one writing thread and multiple reading threads. The aim is to prevent a reader from getting an inconsistent view of the structure whilst not impeding the writer too much.



I am using the fetch-and-add atomic primitive, in this case provided by the Qt framework.



For example:



/* global */
OneWriterAtomicState<Point> atomicState;

/* Writer */
while(true) {
MyStruct s = atomicState.getState()
s.x += 2; s.y += 2;
atomicState.setState(s);
}

/* Reader */
while(true) {
MyStruct s = atomicState.getState()
drawBox(s.x,s.y);
}


OneWriterAtomicState Implementation:



template <class T>
class OneWriterAtomicState
{
public:
OneWriterAtomicState()
: seqNumber(0)
{
}

void setState(T& state) {
/* Due to the QAtomicInt memory ordering semantics, if the reader
ever encounters an ODD sequence number it can be assumed
that state is inconsistent.

After the state mutation has finished, the sequence number
is made EVEN again and can be safely read.
*/

this->seqNumber.fetchAndAddOrdered(1);
this->state = state;
this->seqNumber.fetchAndAddOrdered(1);
}

T getState(){
T result;
int seq;
bool seq_changed = true;

/* repeat while seq is ODD or if seq changes during read operation */
while( (seq=this->seqNumber.fetchAndAddOrdered(0)) & 0x01 || seq_changed ) {

result = this->state;

seq_changed = (this->seqNumber.fetchAndAddOrdered(0)!=seq);
}
return result;
}


private:
QAtomicInt seqNumber;
T state;
}




mod_rewrite different languages part of url

Here is my current .htaccess:



RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f [NC,OR]
RewriteCond %{REQUEST_FILENAME} !-d [NC]

RewriteRule ^$ /launcher/index.html [L]

RewriteRule ^en/admin$ /main/index.php?lang=en&action=acp [L]
RewriteRule ^sp/admin$ /main/index.php?lang=sp&action=acp [L]

RewriteRule ^en/(.*)$ /main/$1?lang=en [L]
RewriteRule ^sp/(.*)$ /main/$1?lang=sp [L]


I have a launcher screen (which is working fine), and my site PHP files which is main/index.php. I use $_GET to pass information about what page to my index.php ie: index.php?action=download&file=123. There are two root levels I'm going to use /en/ for english, and /sp/ for spanish. These are passed to index.php as ?lang=en or ?lang=sp.



I have 2 problems that I cannot fix;




  • My rules have a strange inconsistency of failing. There's probably a better way of doing what I'm trying to do. I'd highly appreciate if someone can show me how. I'm a complete noob at mod_rewrite


  • When I add more things to the end of the URL using a ?variable=value, it occurs after ?lang=en or ?lang=sp. This means that the second question mark causes $_GET to glitch, and those $_GET passed variables are lost. I need a way to append two $_GET together with mod_rewrite?






Crystal Report multi table failure

I'm still new to C# and reports, and in order to take baby steps, I started with a Crystal Report using one table.



Eventually I figured it out and it worked brilliantly.



Then I added another table to the report. I haven't changed anything in my code. Adding a field from the second table to the report, results in a blank report.



Removing that field again (so no columns form the second table is on the report), the report produces data again.



So I get the impression that the problem is on the report side. But I have included the code anyway:



private void Load_Ord_Rep()
{
using (MySqlConnection conn = new MySqlConnection(OTW.Properties.Settings.Default.wcdbConnectionString))
{
conn.Open();

String sql = "SELECT * FROM wcdb.order_table, wcdb.mat_table WHERE order_no = '13661' and order_table.mat_code = mat_table.mat_code";

using (MySqlCommand cmdSel = new MySqlCommand(sql, conn))
{

DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmdSel);

da.Fill(ds);

ReportDocument rpt = new ReportDocument();
rpt.Load("C:\\Visual Studio 2008\\Projects\\OTW\\OTW\\CrystalReport3.rpt");

dataView1.Table = ds.Tables[0];
rpt.SetDataSource(dataView1);


crystalReportViewer1.ReportSource = rpt;
crystalReportViewer1.Refresh();
}
conn.Close();
}
}


With further investigation I have come to the conclusion the problem is not the code or the link, but rather the loading of the second table. I did a outer join with the values being equal or greater. Only the first table's results are displayed on the report. So because the second table's values are not read, no join can be established between the two tables and thus no data on the report. Now the question: why is the second table not being read by Crystal Report!?





Clojure, merging two array of maps

I have two arrays of maps



1st is [{:a 1 :b 2 :d 6} {:a 2 :b 2} {:a 7 :b 7}]



2nd is [{:a 3 :c 3 :e 9 :y 7} {:a 2 :b 6 :c 8}]



depending on the value of a i.e. if its matches in 2nd array the '2nd map' should be merged with '1st map' and the resultant array of maps should be



Res should be [{:a 1 :b 2 :d 6} {:a 2 :b 6 :c 8} {:a 7 :b 7} {:a 3 :c 3 :e 9 :y 7}]



Can anyone help me on this. Thanks in advance.





Java Collection compare generic class that extends interface that extends comparable

I have this interface



public interface IDataPoint<T> extends Comparable<T>  {
public T getValue();
}


and this implementation...



public class IntegerDataPoint implements IDataPoint<Integer> {

// ... some code omitted for this example

public int compareTo(Integer another) {
// ... some code
}
}


and another class...



public class HeatMap<X extends IDataPoint<?> {
private List<X> xPoints;
}


Now I would like to use Collections.max (and similar) on the xPoints list, but that does not work, probably because I got my generics all messed up.



Any suggestions how this could be solved (without a Comparator)?



Collections.max(xPoints);


gives me this error:



Bound mismatch: The generic method max(Collection<? extends T>) of type Collections is not applicable for the arguments (List<X>). The inferred type X is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>




Parsing php manual docbook xml-files

I want to parse the php manual source files (xml docbook format) and convert them into a MySQL database. I am currently trying to do this using simpleXML extension but when I do all the entitites like &reftitle.description; and $false; raise a warning (undefined) and the script stops with "Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML'"
When I remove all entities form the file it parses fine, but then the information is no longer complete. I am no xml expert but I assume I need to include some reference to these entities so the parser recognizes them? I failed to find how to do this?





Formatting line breaks in python strings

I have a string:



f = open("file.txt", r)
message = f.read()

print message
>>> "To: email\ntitle: add title here\nDescription: whatever here\n"


I can split the string by doing:



f_email, f_title, f_description, blank = message.split('\n')


But the problem arises when I have the message like this:



"To: email\ntitle: add title here\nDescription: first line\nSecond line\nthirdline\n"


When I split the string it splits the description as well. I have tried:



f_email, f_title, f_description, blank = message.split('\n',4)


But that obviously returns ValueError because it is splitting more 4 \n's.



Any suggestions?





How can I identify unused i18n keys?

I'm working on an existing Rails app and am using a localization file, en.yml, to hold most of the app's text. At the moment, we aren't localizing into any other languages, so there's just the one file, but the fact that we're putting translate('some.key') into our views means that adding another language will be as simple as adding another file - say, sp.yml



The problem is, en.yml has grown to the point that I doubt all the keys are being used.



Apart from git grepping for translate calls using each key, is there a quick way to identify localization keys that aren't being explicitly called by the app?





App sounds cause iPod music, Pandora or Pod cast sound to stop

we have different sounds for actions and buttons within our app. We've heard a number of complaints where users background music stops as soon as one of our sounds is played. We're not quite sure why this is happening. Here is the code we're using to toggle our sounds.



- (void)playSound:(NSString *)sound {

if ( playSoundPath == nil ) {
playSoundPath = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:playSoundPath] error:NULL];
playSound.delegate = self;
}else{
playSoundPath = nil;
[playSound release];
playSoundPath = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:playSoundPath] error:NULL];
playSound.delegate = self;
}
BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"sounds_key"];
if ( enabled ){
[playSound stop];
[playSound play];
}
}


Update: We've actually ended up changing the above to the following per a few users suggestions. This allows iPod music or pod casts to continue and our sounds to play without stopping this background sound. This is possible by setting our sounds as "ambient" sound. This requires that you add the "AudioToolBox" framework and import this framework into your class using the following,



#import <AudioToolbox/AudioToolbox.h>


Here is the code we're using now,



BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"sounds_key"];
if ( enabled ){

AudioSessionInitialize(NULL, NULL, NULL, self);
UInt32 category = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
AudioSessionSetActive(YES);

NSString *path = [NSString stringWithFormat:@"%@/%@.wav",[[NSBundle mainBundle] resourcePath], sound];

SystemSoundID soundID;

NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];

AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);

AudioServicesPlaySystemSound(soundID);

}




Zend Framework "Invalid parameter number: no parameters were bound" get offending sql

I have a massive site I inherited built using Zend Framework. It's a internal company site and many employees have been complaining of errors. The last guy only ever gave a response of "It's working fine for me", hence why he was fired.



I went through and did some research and found I could make a error handle controller. So I created one that captured all the errors and I have been fixing them as they come up (and I now see why the guy as saying it works fine for me, cause the employee's were screwing up on somethings and the guy just didn't have the logic programmed in to handle those screw ups).



Right now I'm done to just a few "Invalid parameter number: no parameters were bound" errors, I have the stack trace's so I do know what line is causing the error. I also have the GET and POST values. Some of the points where it's causing a throwing this error have a lot of logic leading up to it. So I'm wondering if there is a way From the Zend_Controller_Plugin_ErrorHandler if I can retrieve the SQL statement that was being run.



I know I could wrap the calls and catch them independently, but that wont help future problems that come up. Any insight into this would be greatly appreciated.





How do i change IPv4 to Domain Name in intranet application

How do i change IPv4 (192.168.1.58) to Domain Name(Abc.com) in intranet application(IIS 7.5)





Segmentation Fault on MySQL2 / Ruby 1.9.3 / Rails 3.2

I've been having a hard time getting rails 3.2 to work with mysql2.

I'm running OSX 10.6, MySQL 5.1.37



I'm getting this lovely stack trace.



HunterMBP:v hunter$ bundle exec rake db:create
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/mysql2-0.3.2/lib/mysql2/mysql2.bundle: [BUG] Segmentation fault
ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin10.8.0]

-- Control frame information -----------------------------------------------
c:0033 p:-543968548 s:0099 b:0099 l:000098 d:000098 TOP
c:0032 p:---- s:0097 b:0097 l:000096 d:000096 CFUNC :require
c:0031 p:0107 s:0093 b:0093 l:000092 d:000092 TOP /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/mysql2-0.3.2/lib/mysql2.rb:8
c:0030 p:---- s:0091 b:0091 l:000090 d:000090 FINISH
c:0029 p:---- s:0089 b:0089 l:000088 d:000088 CFUNC :require
c:0028 p:0026 s:0085 b:0085 l:000065 d:000084 BLOCK /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:68
c:0027 p:---- s:0082 b:0082 l:000081 d:000081 FINISH
c:0026 p:---- s:0080 b:0080 l:000079 d:000079 CFUNC :each
c:0025 p:0091 s:0077 b:0077 l:000065 d:000076 BLOCK /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:66
c:0024 p:---- s:0071 b:0071 l:000070 d:000070 FINISH
c:0023 p:---- s:0069 b:0069 l:000068 d:000068 CFUNC :each
c:0022 p:0046 s:0066 b:0066 l:000065 d:000065 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:55
c:0021 p:0021 s:0062 b:0062 l:000061 d:000061 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler.rb:118
c:0020 p:0137 s:0058 b:0058 l:000057 d:000057 TOP /Users/hunter/Workspace/Projects/Visionare/config/application.rb:13
c:0019 p:---- s:0056 b:0056 l:000055 d:000055 FINISH
c:0018 p:---- s:0054 b:0054 l:000053 d:000053 CFUNC :require
c:0017 p:0026 s:0050 b:0050 l:000049 d:000049 TOP /Users/hunter/Workspace/Projects/Visionare/Rakefile:5
c:0016 p:---- s:0048 b:0048 l:000047 d:000047 FINISH
c:0015 p:---- s:0046 b:0046 l:000045 d:000045 CFUNC :load
c:0014 p:0013 s:0042 b:0042 l:000041 d:000041 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25
c:0013 p:0274 s:0038 b:0038 l:000037 d:000037 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:501
c:0012 p:0009 s:0033 b:0033 l:000026 d:000032 BLOCK /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:82
c:0011 p:0009 s:0031 b:0031 l:000030 d:000030 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:133
c:0010 p:0011 s:0027 b:0027 l:000026 d:000026 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:81
c:0009 p:0019 s:0024 b:0024 l:000017 d:000023 BLOCK /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:65
c:0008 p:0009 s:0022 b:0022 l:000021 d:000021 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:133
c:0007 p:0011 s:0018 b:0018 l:000017 d:000017 METHOD /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:63
c:0006 p:0060 s:0015 b:0015 l:000014 d:000014 TOP /Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/bin/rake:33
c:0005 p:---- s:0013 b:0013 l:000012 d:000012 FINISH
c:0004 p:---- s:0011 b:0011 l:000010 d:000010 CFUNC :load
c:0003 p:0127 s:0007 b:0007 l:002398 d:001e70 EVAL /Users/hunter/.rvm/gems/ruby-1.9.3-p125/bin/rake:19
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
c:0001 p:0000 s:0002 b:0002 l:002398 d:002398 TOP

-- Ruby level backtrace information ----------------------------------------
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/bin/rake:19:in `<main>'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/bin/rake:19:in `load'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:65:in `block in run'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:81:in `load_rakefile'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:82:in `block in load_rakefile'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/application.rb:501:in `raw_load_rakefile'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in `load_rakefile'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in `load'
/Users/hunter/Workspace/Projects/Visionare/Rakefile:5:in `<top (required)>'
/Users/hunter/Workspace/Projects/Visionare/Rakefile:5:in `require'
/Users/hunter/Workspace/Projects/Visionare/config/application.rb:13:in `<top (required)>'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler.rb:118:in `require'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:55:in `require'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:55:in `each'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:66:in `block in require'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:66:in `each'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.0/lib/bundler/runtime.rb:68:in `require'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/mysql2-0.3.2/lib/mysql2.rb:8:in `<top (required)>'
/Users/hunter/.rvm/gems/ruby-1.9.3-p125/gems/mysql2-0.3.2/lib/mysql2.rb:8:in `require'


Gemfile looks like this:



    source 'https://rubygems.org'
gem 'rails', '3.2.2'
#gem 'json'
gem "mysql2"
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem "rspec-rails", ">= 2.8.1", :group => [:development, :test]
gem "factory_girl_rails", ">= 1.7.0", :group => :test
gem "email_spec", ">= 1.2.1", :group => :test
gem "cucumber-rails", ">= 1.3.0", :group => :test
gem "capybara", ">= 1.1.2", :group => :test
gem "database_cleaner", ">= 0.7.1", :group => :test
gem "launchy", ">= 2.0.5", :group => :test
gem "devise", ">= 2.0.4"


I have rails 3.2 and ruby 1.9.3



bundle install produces this list successfully.



Using rake (0.9.2.2) 
Using i18n (0.6.0)
Using multi_json (1.1.0)
Using activesupport (3.2.2)
Using builder (3.0.0)
Using activemodel (3.2.2)
Using erubis (2.7.0)
Using journey (1.0.3)
Using rack (1.4.1)
Using rack-cache (1.2)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.1.2)
Using actionpack (3.2.2)
Using mime-types (1.17.2)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.4.3)
Using actionmailer (3.2.2)
Using arel (3.0.2)
Using tzinfo (0.3.32)
Using activerecord (3.2.2)
Using activeresource (3.2.2)
Using addressable (2.2.7)
Using bcrypt-ruby (3.0.1)
Using nokogiri (1.5.2)
Using ffi (1.0.11)
Using childprocess (0.3.1)
Using rubyzip (0.9.6.1)
Using selenium-webdriver (2.20.0)
Using xpath (0.1.4)
Using capybara (1.1.2)
Using coffee-script-source (1.2.0)
Using execjs (1.3.0)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Using json (1.6.5)
Using rdoc (3.12)
Using thor (0.14.6)
Using railties (3.2.2)
Using coffee-rails (3.2.2)
Using diff-lcs (1.1.3)
Using gherkin (2.9.0)
Using term-ansicolor (1.0.7)
Using cucumber (1.1.9)
Using cucumber-rails (1.3.0)
Using database_cleaner (0.7.1)
Using orm_adapter (0.0.6)
Using warden (1.1.1)
Using devise (2.0.4)
Using rspec-core (2.8.0)
Using rspec-expectations (2.8.0)
Using rspec-mocks (2.8.0)
Using rspec (2.8.0)
Using email_spec (1.2.1)
Using factory_girl (2.6.3)
Using factory_girl_rails (1.7.0)
Using jquery-rails (2.0.1)
Using launchy (2.0.5)
Using mysql2 (0.3.2)
Using bundler (1.1.0)
Using rails (3.2.2)
Using rspec-rails (2.8.1)
Using sass (3.1.15)
Using sass-rails (3.2.4)
Using uglifier (1.2.3)




How can I order a List<string>?

I have this List :



IList<string> ListaServizi = new List<string>() { };


how can I order it due to the strings inside it? Alphabetic and ascending.





Postgresql: Calculate rank by number of true OR clauses

I need to order/rank the results of a PostgreSQL query by the number of OR-clauses that are true. For example, given a query like



SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC


should rank results based on the number of fulfilled conditions. Also approaches that solve this issue with views/stored procedures are very welcome!





python bindings, how does it work?

I am exploring python. I curious about python bindings. Could anybody explain, how it is possible that you can have access to C libraries from Python.





Tooltips for a Google Visualization API stacked chart?

I'd like to add some custom text to the tooltips on a Google Visualization API. I'm using a stacked chart for percentages, and I'd like to add some extra values for raw numbers that will only be displayed in the tooltips, without affecting the chart itself.



This is my current code:



  var dt = new google.visualization.DataTable(
{
cols: [{id: 'Year', label: 'year', type: 'string'},
{id: 'Golf', label: '% time on golf', type: 'number'},
{id: 'Soccer', label: '% time on soccer', type: 'number'},
],
rows: [{c:[{v: '1996'}, {v: 11}, { v: 10} ]},
{c:[{v: '1997'}, {v: 2}, { v: 10} ]},
{c:[{v: '1998'}, {v: 2}, { v: 10} ]},
{c:[{v: '1999'}, {v:2}, { v: 10} ]},
{c:[{v: '2000'}, {v:7, f:'7.000'}, { v: 10} ]}
]
},
0.6
)
var ac = new google.visualization.AreaChart(document.getElementById('visualization'));
ac.draw(dt, {
isStacked: true,
width: 600,
height: 400,
vAxis: {title: "% of time"},
hAxis: {title: "Year"}
});


How can I add raw data numbers and extra tooltips, so that when I mouseover golf for 1996 (say), it will show me another number as well?



I was hoping I could change the rows to be something like this:



rows: [{c:[{v: '1996'}, {v: 11, raw_value: 17}, { v: 10, raw_value: 16} ]},


And then specify the content of the tooltip to include raw_value as well.





Persistently setting the default name on an Android project in Eclipse

I have an Android project. The name is correctly set in the Android manifest (android:label), the package name is also set correctly (package="com.etc..."). Now, when I add this project to Eclipse the name picked up by the package explorer is actually the name of my launch activity. As you may imagine this is not what I want.



I can rename the project by selecting it in the package explorer, pressing F2 and changing the name. However, once I remove this project from Eclipse and re-add it then the name that is picked up is again that of my first activity.



Does anybody know how to tell Eclipse to pick the manifest's application name and not the launch activity name?



Thanks!





Mock only a subset of all calls to a method.

I would like to mock only a sub set of calls to a method using the Mock module. So,



fubar = Fubar()
fubar.myMethod = Mock()
funar.myMethod.return_value = [fubar.myMethod(), 'MyMOck', fubar.MyMethod]


would call the read method myMethod the first and third time but would call the mocked method on the second call.



Is this possible? If so, how? If not, why not?





How to include header and footer of error document found in apache's custom error response package?

I have this line in my PHP script that includes a "file not found" 404 custom error provided by apache:



include('/var/www/error/HTTP_NOT_FOUND.html.var');


What is shown on my browser is just the body of the custom error page:




Content-language: cs Content-type: text/html; charset=ISO-8859-2
Body:----------cs-- Po?adovan? URL nebylo na tomto serveru nalezeno.
Zd? se, ?e odkaz na ">odkazuj?c? str?nce je chybn? nebo zastaral?.
Informujte, pros?m, autora




The error page contains the following comments:



<!--#include virtual="include/top.html" -->


and



<!--#include virtual="include/bottom.html" -->


which are supposed to be the header and footer found in the include folder. But this is outside of my document root, /var/www/html.



How do I include the header and footer without moving the error folder into the document root?





api to connect to conmanclient2/cmaccept

I'm writing programs in C# & C++ that run on a custom Windows CE 5 and 6 device. I have followed the instructions on how to connect to a CE device on Microsoft's site (http://msdn.microsoft.com/en-us/library/ms228708(v=vs.80).aspx), and things work fine with DevStudio and with the remote tools.



I am dissatisfied with the remote tools, however. So I would like to write some better ones. For sample, a command-line tool to copy *.dll to a directory on the device, which doesn't say "are you sure you want to overwrite that file?" for each one.



Does anyone know what protocol / API one uses to connect to the device using TCP/IP, here? And/or can point me to a code example?





C#, Using Interface

I'm trying to use Interface class and I have a question about Interface method parameters.



I have an Interface class to make child class use specific method.
but the child classes need different number of parameters for the method.



Example,



public interface IPayment
{
void MakePayment();
}


and define the MakePayment method in child classes.



public class PayPay : IPayment
{
public void MakePayment(string a); // it needs only one parameter
}

public class Google : IPayment
{
public void MakePayment(string a, int b); // it needs two parameters.
}


Like above case, How can I modify my interface class?



Thank you!





Augment data frame missed values by another data frame

I have following data frames:



> df1 = data.frame(ind = 1:4, x=c('a', 'b', NA, 'd'))
> df2 = data.frame(ind = 1:4, x=c(NA, NA, 'c', NA))
> df1
ind x
1 1 a
2 2 b
3 3 <NA>
4 4 d
> df2
ind x
1 1 <NA>
2 2 <NA>
3 3 c
4 4 <NA>


I want combine them filling missing values in df1 by numeric values from df2. How can I do that? I cannot do that neither with merge nor with join commands:



> merge(df1, df2, by='ind', all=T)
ind x.x x.y
1 1 a <NA>
2 2 b <NA>
3 3 <NA> c
4 4 d <NA>




MAVEN Archetype choosing

Hi i am just new to maven.
My requirement is to build a ear with 2 wars and also create a jar.
I tried using some archetypes but few folder structure are missing.
My maven folder structure should contain
src/main/
java
resource
webapp
test/java
test/resource.
Which archetype will be a suitable?





Weird PHP behaviour - What's going on?

Just came across this bug recently in a PHP app. Not sure what's going on.



Basically, it shows up when using a combination of two foreach (one with &, one without).



Here's a test code that reproduce the problem:



$items = array(

array('id'=>1, 'name'=>'foo', 'value'=>150),

array('id'=>2, 'name'=>'bar', 'value'=>190)
);


foreach($items as &$item)
{

$item['percentage'] = $item['value'] * 0.75;

}

var_dump($items); // All Good

foreach($items as $item)
{

var_dump($item); // Shows 1st item twice
}


The second foreach loop runs the block twice, as expected, but $item remains stuck on the first item.



I understand this is likely caused by the use of the reference & in the first loop but I don't see why it should behave like this..



Any idea? is that a bug?



Getting the same result on 5.3.8, 5.3.10 & 5.4





Only some projects in a solution targeting Client Profile of .NET framework 4

In case most projects inside a WPF app solution target .NET Framework 4, can some class library projects of the same solution target .NET Framework 4 Client Profile?

Is it totally okay, or could there be something wrong with such a combination?





Acceptable mysql select speed as per documentation?

Is there an acceptable speed as in this many records per second for MySQL SELECT? I know it depends on how complex the query is and my machine spec. But can I have a vague/approximate speed estimation of a standard SELECT query? May be for something like this:



SELECT a, b, c, d, e, f FROM my_table;


I use .NET connector to access MySQL; from my code I do something like this:



MySqlCommand cmd = new MySqlCommand(query, _conn);
MySqlDataReader r = cmd.ExecuteReader();

List<int> lst = new List<int>();
while (r.Read())
{
lst.Add(.....
}

r.Close();


Currently I can SELECT 25000 records under 150 ms. But when I run it under phpmyadmin it takes about 75 ms. From MySQL console it neeed 110 ms. Is there a need not be worried about limit that documentation recommends be it via connector, console or anything? I am running on an Intel Core2 Duo (2 GHz) with 2 Gb RAM. Speed is critical for my need.



I remember reading one such somewhere..





How do Repositories fit with CQRS?

According to Fowler (here), a repository "mediates between the domain and data mapping layers, acting like an in-memory domain object collection." So, for example, in my Courier Service application, when a new run is submitted, my application service creates a new Run aggregate root object, populates it with values from the request then adds it to the RunRepository before calling the Unit of Work to save the changes to the database. When a user wants to view the list of current runs, I query the same repository and return a denormalized DTO representing the information.



However, when looking at CQRS, the query would not hit the same repository. Instead, it would perhaps go directly against the data store and always be denormalized. And my command side would evolve to a NewRunCommand and Handler that would create and populate a NewRun domain object then persist the information to the data store.



So the first question is where do repositories fit into the CQRS model if we aren't maintaining an in-memory collection (cache, if you will) of domain objects?



Consider the case where the information submitted to my application service contains nothing but a series of ID values that the service must resolve in order to build the domain object. For example, the request contains the ID # of the courier assigned to the run. The service must lookup the actual Courier object based on the ID value and assign the object to the NewRun using the AssignCourier method (which validates the courier and performs other business logic).



The other question is, given the separation for queries and potential absence of repositories, how does the application service perform the lookup to find the Courier domain object?



UPDATE



Based on some additional reading and thought after Dennis' comment, I'll rephrase my questions.



It appears to me that CQRS encourages repositories that are merely facades over the data access and data storage mechanisms. They give the "appearance" of a collection (like Fowler describes) but are not managing the entities in-memory (as Dennis pointed out). This means that every operation on the repository is pass-through, yes?



How does a Unit of Work fit into this approach? Typically a UoW is used to commit changes made to a repository (right?) but if the repository isn't maintaining the entities in-memory, then what role does a UoW have?



With regards to a 'write' operation, would the command handler have a reference to the same repository, a different repository or perhaps a UoW instead of a repository?





How to delete all lines from a CSV file containing an exact match of a search term?

I have a CSV file like this:



text,0
more text,2
some more text,100


I need to delete any line containing only 0 in the second column, e.g., the output of the above would be:



more text,2
some more text,100


How can I delete all lines from a CSV with an exact match?





itext filling table

I need to fill a table with in the first column a number and in the second column certain data from a array.



So it will look like :



1 | Data1



2 | Data2



3 | Data3



What is the best way to add this data.



Usualy you do something like :



 Table table = new Table(3); 
table.setWidth(100);
table.setDefaultVerticalAlignment(Element.ALIGN_TOP);
table.setCellsFitPage(true);
table.setPadding(2);
table.setSpacing(0);
for (int i = 1; i <= 6; i++) {
Cell cell = new Cell("Data " + i);
table.addCell(cell); }


Then you get something like :



Data 1 | Data 2 | Data 3



Data 4 | Data 5 | Data 6



Is there a specific way to fill selected cells or do I see it wrong.