Year: 2011
Number of Unanswered Questions With Comment: 106275
Sampled Question List: 100

Id: 10684102
title: How to get information on mobile through bluetooth, send information by my notebook
tags: delphi, java-me, bluetooth, communication, delphi-xe2
view_count: 125
body:

I want mobile phones to communicate with the my notebook. I am using Delphi for Windows programming and component nrComm Lib that methods for sending and receiving Char, String there.

  nrBT1.SendString();
  nrBT1.SendString();
  nrBT1.SendData();

But my problem is on the phone how can I get information.I'm not a professional Java programming.I have read the article but will not do it with component nrComm Lib:(

jsr-82-sample-spp-server-and-client. I think the following code can not be implemented in Delphi:

//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
comments:

1 : My main goal is to control the device via Bluetooth.

2 : if you want to do this "pain-free", stick with Java, there are quite a few demos out there


---------------------------------------------------------------------------------------------------------------
Id: 9172758
title: Error when running JMFINIT
tags: java, linux, ubuntu, jmf
view_count: 111
body:

i have problem when itegrate my webcam with JMF. I have got this following error, when i running JMFINIT or running jmfregistry and detect capture device.

JavaSound Capture Supported = true
JavaSoundAuto: Committed ok
Name = v4l:p?p??:0
Trying 4 320 240
Trying 3 160 120
Trying 3 320 240
Trying 3 640 480
Trying 3 176 144
Trying 3 352 288
Trying 3 768 576
Trying 4 160 120
Trying 4 320 240
Trying 4 640 480
Trying 4 176 144
Trying 4 352 288
Trying 4 768 576
Trying 5 160 120
Trying 5 320 240
Trying 5 640 480
Trying 5 176 144
Trying 5 352 288
Trying 5 768 576
Trying 6 160 120
Trying 6 320 240
Trying 6 640 480
Trying 6 176 144
Trying 6 352 288
Trying 6 768 576
Trying 7 160 120
Trying 7 320 240
Trying 7 640 480
Trying 7 176 144
Trying 7 352 288
Trying 7 768 576
Trying 8 160 120
Trying 8 320 240
Trying 8 640 480
Trying 8 176 144
Trying 8 352 288
Trying 8 768 576
Trying 9 160 120
Trying 9 320 240
Trying 9 640 480
Trying 9 176 144
Trying 9 352 288
Trying 9 768 576
Trying 10 160 120
Trying 10 320 240
Trying 10 640 480
Trying 10 176 144
Trying 10 352 288
Trying 10 768 576
Trying 11 160 120
Trying 11 320 240
Trying 11 640 480
Trying 11 176 144
Trying 11 352 288
Trying 11 768 576
Trying 12 160 120
Trying 12 320 240
Trying 12 640 480
Trying 12 176 144
Trying 12 352 288
Trying 12 768 576
Trying 13 160 120
Trying 13 320 240
Trying 13 640 480
Trying 13 176 144
Trying 13 352 288
Trying 13 768 576
Trying 14 160 120
Trying 14 320 240
Trying 14 640 480
Trying 14 176 144
Trying 14 352 288
Trying 14 768 576
Trying 15 160 120
Trying 15 320 240
Trying 15 640 480
Trying 15 176 144
Trying 15 352 288
Trying 15 768 576
java.lang.Error: Can't open video card 1
java.lang.Error: Can't open video card 2
java.lang.Error: Can't open video card 3
java.lang.Error: Can't open video card 4
java.lang.Error: Can't open video card 5
java.lang.Error: Can't open video card 6
java.lang.Error: Can't open video card 7
java.lang.Error: Can't open video card 8
java.lang.Error: Can't open video card 9

This result when i type command lsusb

Bus 002 Device 005: ID 067b:2528 Prolific Technology, Inc. 
Bus 002 Device 004: ID 12d1:140c Huawei Technologies Co., Ltd. 
Bus 002 Device 003: ID 0458:003a KYE Systems Corp. (Mouse Systems) NetScroll+ Mini Traveler
Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 006: ID 413c:8162 Dell Computer Corp. 
Bus 001 Device 005: ID 413c:8161 Dell Computer Corp. 
Bus 001 Device 003: ID 0a5c:4500 Broadcom Corp. BCM2046B1 USB 2.0 Hub (part of BCM2046 Bluetooth)
Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

And when i run dmesg i got my webcam

[   25.074507] Linux video capture interface: v2.00
[   25.086563] uvcvideo: Found UVC 1.00 device Laptop_Integrated_Webcam_1.3M (0c

Please help me, it's immediately

comments:

1 : *"Please help me, it's immediately"* My advice for any urgent inquiry is to hire a consultant (and pay them a rate that reflects your urgency).


---------------------------------------------------------------------------------------------------------------
Id: 11271811
title: Chat functionality in windows phone 7?
tags: windows-phone-7.1
view_count: 22
body:

I need to implement chat functionality in my app.for that i saw socket programming by using that we can make the conversations.But how to identify the user to user conversations.i.e 1,2,3 are the users in my app i need to chat with 1st user only how to possible that? any other alternatives to implement chat functionality in windows phone 7?

Please let me know... thanks in advance.

comments:

1 : possible duplicate of [How to implement chat functionality in windows phone 7.5?](http://stackoverflow.com/questions/11288174/how-to-implement-chat-functionality-in-windows-phone-7-5)


---------------------------------------------------------------------------------------------------------------
Id: 10230649
title: macro to fetch specific column data from other sheets to a mainsheet
tags: excel, excel-vba
view_count: 94
body:

Need help with a macro which Creates a new Sheet named "MainSheet" and should fetch data from column's P, Q & R from the other existing sheets into the columns B , C & D of the MainSheet

comments:

1 : What have you tried?

2 : I did manual process of writing the formulae in each cell and fetch the data, since I am new to macros I have less idea about the process

3 : Here is a good start on how to record macros. http://msdn.microsoft.com/en-us/library/ee264224%28v=office.12%29.aspx Post the code that you try :) We will take it from there.


---------------------------------------------------------------------------------------------------------------
Id: 9013809
title: How to put an index page with login credentials, yet the files in the folder can be hotlinked?
tags: login, index, page, credentials, hotlinking
view_count: 36
body:

I'm trying to hide my folder on my hosting account, so I was thinking of using an Index Page, but an Index Page will not let me see my files. So, I am thinking of having an index page with basic login credentials.

If I use password protect directory from my hosting account, then I cannot hotlink my files, which are mainly images, which I wish to hotlink to my blog.

Is there a way out for me?

Is there a script which will allow me to preview my images once I have login to view the directory?

Can a script randomize the image filename when it is hotlinked? So that the directory path is not revealed to anyone, making it more difficult for anyone to know where the images are stored on my host?

comments:

1 : No matter how you protect your images, they can always do a "Save as"... you know it ... right?


---------------------------------------------------------------------------------------------------------------
Id: 9390138
title: Android apk can't handle exception after using ProGuard
tags: java, android, exception, apk, proguard
view_count: 78
body:

I have write an android apk. If I don't use proguard, even an exception happened, my apk can catch and handle it. apk won't crash. After I use proguard, apk will crash after an exception happened.

comments:

1 : You probably have configured proguard incorrectly. Please post your proguard config file. For a recommended config file see here http://blog.androidquery.com/2011/06/android-optimization-with-proper.html


---------------------------------------------------------------------------------------------------------------
Id: 8251768
title: Why is Firefox claiming a reset connection
tags: firefox, iframe, ssl, https, cgi
view_count: 190
body:

I'm working on a password maker page at http://JonathansCorner.com/passwords/. Because that page is not encrypted (and the site does not have an SSL certificate), I have a skeleton page that loads https://haywardfamily.org/password.cgi in an iframe.

Works great on every browser I've tested except Firefox--even IE6! In Firefox it usually says that the connection was reset:

The connection was reset

The connection to the server was reset while the page was loading.

The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.

This happens most of the time; occasionally Firefox loads it. If I load the iframe contents, Firefox handles it without a hitch.

What is going on, and is there any way I can implement things so Firefox will load the iframe correctly?

comments:

1 : You do realize that framing an https page in an http page is insecure, right? In particular someone can MITM the outer page and stick whatever page they want in the subframe....

2 : Well enough; thank you.


---------------------------------------------------------------------------------------------------------------
Id: 7827288
title: Using DDD with C# 4.0, should the model raise change events to be handled by the repository / UnitOfWork?
tags: c#, domain-driven-design, repository, unit-of-work
view_count: 149
body:

I'm trying to get my head around DDD and for now I have some domain classes and repositories.

public class Entity1
{
    public int SomeValue {get;set;}
    public ICollection<Entity2> SomeEntities {get;}

    public void SomeMethod ();
}

public class Entity1Repository
{
    public void Add (Entity1 entity) {...}
    ...
}

I also have a unit of work interface

public interface IUnitOfWork
{
    void Commit ();
    void Rollback ();
}

Not entirely convinced that the IUnitOfWork should be passed to the repository constructor as it seems, to me at least, that it makes the repository not so ignorant on persistence.

So, what I thought would be nice is perhaps having domain events sent from the domain objects to indicate they are changed. The unit of work implementation and, why not, the repository would listen to those events and act accordingly.

Also, I was thinking of having the collection implementation of ICollection send some event too.

This scheme would decouple the need of the user of the domain layer for fiddling with a repository.

Is this sound?

comments:

1 : Take a look at [this article](http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84). Although it's not written in the context of DDD, it might give you some ideas.

2 : 2 things I don't understand: why do you want your repository to handle events, what do you mean by "act accordingly"? And why do you want the domain user to not use the repository? That's what the repository is for.


---------------------------------------------------------------------------------------------------------------
Id: 8186276
title: php: remove html entities
tags: php, special-characters, htmlentities, html-entity-decode
view_count: 246
body:

Possible Duplicate:
How to remove html special chars?

What is the best way to remove all html entities from a string? I do not want to decode them, I simply want them removed.

Similar functions include:

If I have an input string

the&nbsp;brown dog jumped over&gt;the fence.

then the output should be

thebrown dog jumped overthe fence.

Update: link provided answered the question with this preg_replace

$Content = preg_replace("/&#?[a-z0-9]{2,8};/i","",$Content);
comments:

1 : Look at this question http://stackoverflow.com/questions/657643/how-to-remove-html-special-chars-in-php

2 : Thank you Frank!


---------------------------------------------------------------------------------------------------------------
Id: 10747069
title: Android MultiPartEntity File Upload using HTTP Post
tags: android, multipartform-data
view_count: 422
body:

I tried using the ByteArrayBody method to convert my file into bytearray to upload to server via HTTP Post. I am required to Post a document via MultiPart/Form-Data.

Here is what I am doing:

FileBody bin = new FileBody(file);
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", bin);
post.setEntity(multipartEntity);

I keep getting this response: request failed: error reading the headers. Bad request, Status is 400.

What am I doing wrong?

comments:

1 : Does the server accepts your document type?


---------------------------------------------------------------------------------------------------------------
Id: 10331503
title: Google Analytics CodeIgniter fetching data distributed monthly over year
tags: codeigniter, google-api, analytics
view_count: 206
body:

I am using this library (modification of this library) for google analytics.

What I need to do is get the data for 2 years, distributed over months and then weekly.

Given image will make it clear.

The script given here takes too much execution time. Is there a way I can get all these data in one query and then get (somehow parse) individual pieces of data per months or per weeks? Giving start date and end date for one year period gives cumulative result. I need data distributed over week and month.

Any suggestions...

image.

for ($startYear = 2011; $startYear <= 2012; $startYear++) {
        foreach ($this->months as $months) {// months is array ('Jan','Feb'...)
            $timestamp = strtotime($months . " " . $startYear);
            $start_date = date('01 F Y', $timestamp);
            $end_date = date('t F Y', $timestamp);
            $today = strtotime(date('F Y'));
            if ($timestamp <= $today) {
                // refferers
                $this->analytic_data['refferers'][$startYear][$months] = $this->ga_api
                        ->dimension('source')
                        ->metric($metrics)
                        ->when($start_date, $end_date)
                        ->limit(1)
                        ->get_object();
                $this->ga_api->clear();
                // mobile
            $this->analytic_data['mobile_traffic'][$startYear][$months] = $this->ga_api
                    ->segment(-11)
                    ->dimension('source')
                    ->metric('visits')
                    ->when($start_date, $end_date)
                    ->limit(1)
                    ->get_object();
            $this->ga_api->clear();
            //direct
            $this->analytic_data['direct_traffic'][$startYear][$months] = $this->ga_api
                    ->segment(-7)
                    ->dimension('source')
                    ->metric('visits')
                    ->when($start_date, $end_date)
                    ->limit(1)
                    ->get_object();
            $this->ga_api->clear();
            //referral search
            $this->analytic_data['ref_traffic'][$startYear][$months] = $this->ga_api
                    ->segment(-8)
                    ->dimension('source')
                    ->metric('visits')
                    ->when($start_date, $end_date)
                    ->limit(1)
                    ->get_object();
            $this->ga_api->clear();
            //search traffic
            $this->analytic_data['search_traffic'][$startYear][$months] = $this->ga_api
                    ->segment(-6)
                    ->dimension('source')
                    ->metric('visits')
                    ->when($start_date, $end_date)
                    ->limit(1)
                    ->get_object();
            $this->ga_api->clear();
            }
        }
comments:

1 : Why are you pulling data for the last two years? Seems like alot of overhead. Are you using google charts to output the data? If so How many, ie: one chart to show all metrics or multiple charts? If the former you could just build a form of dropdowns for days/month/year and pass that to your query on request and cache the results for later use. If you have multi charts and use this approach then building one query becomes more difficult. ->dimension and ->metric I believe also take arrays as parameters.

2 : Hi, Philip. thanx 4 response(& sorry for late response). I need data for two years. I am using google charts but that will display yearly data so won't be problem. It would have been nice if one could query a single year or even a month and get weekly data. But thats not for now i guess. Dimension and metric do take arrays but segments don't. Else I would have made my query a lot smaller (above i am making separate queries to access separate segments). Anyway, I am sticking with cache for now...


---------------------------------------------------------------------------------------------------------------
Id: 10111320
title: Extjs4 radiogroup in tabpanel, loads fine on first tab, but not others
tags: extjs4, tabpanel, radio-group
view_count: 135
body:

I have a tabpanel with a grid in the first tab - called main-grid. I double-click on a row in main-grid and it loads a new tab, with a form-grid. In the form-grid I have set a column layout. I have a grid in the left column and a form with the radiogroup in the right column.

When a new tab opens, the grid from the form-grid loads fine, and when I select a record in the form-grid grid, it loads into the form fine and the radiogroup loads as well with my convert function. The values I am working with from the grid are "Yes" and "No", so I am converting them with my 'convert' function to an INT and then returning them.

Here is a snippet of my code:

Ext.define('ValueRadioGroup',({
    extend: 'Ext.form.RadioGroup',
    alias: 'widget.valueradiogroup',

    fieldLabel: 'Value',
    columns: 2,
    defaults: {
        name: 'rating' //Radio has the same name so the browser will make sure only one is checked at once
    },
    items: [{
        inputValue: '2',
        boxLabel: 'Yey'
    }, {
        inputValue: '1',
        boxLabel: 'Nay'
    }]
}));

Ext.define('TargetViewModel', {
    extend: 'Ext.data.Model',
    fields  : [
        {name: 'ID'},
        {name: 'FAMILYNAME'},
        {name: 'TABLENAME'},
        {name: 'TARGETNAME'},
        {name: 'TARGETLABEL'},
        {name: 'TARGETVALUE'},
        {name: 'ITEMREL'},
        {name: 'ITEMREF'},
        {name: 'ITEMNAME'},
        {name: 'ITEMMNEMONIC'},
        {name: 'ALLOWED'},

        {name: 'rating', type: 'int', convert: convertTARGETVALUE}
    ]
}); 

... and here is where it is being called:

this.items = [{ 

            // GRID
            columnWidth: .65, // GRID width                        
            xtype: 'ggtargetviewgrid',
            store: this.store,
            listeners: {
                selectionchange: function(model, records) {
                    if (records[0]) {
                        var value = this.up('form').getForm().loadRecord(records[0]);

                    }
                } 
            }                       
        }
        ,
        {
            // FORM
            columnWidth: 0.3, // FORM width
            margin: '0 0 0 10',
            xtype: 'fieldset',
            title:'Target Details',
            defaults: {
                width: 280,
                labelWidth: 50
            },
            defaultType: 'textfield',
            items: [
                {
                    fieldLabel: 'Name',
                    name: 'ITEMNAME'
                }, {

                    xtype: 'valueradiogroup' 
            }]
}]

This is my convert function:

var convertTARGETVALUE = function(value, record) {
    var tval = record.get('TARGETVALUE'), val = 0;

    if (tval === 'Yes') return val+2;
    if (tval === 'No') return val+1;
    return val;
};

The problem is that the radiogroup works fine for the FIRST form-grid opened, but NOT for the second, or ANY subsequent tabs opened.

comments:

1 : does selectionchange gets fired?

2 : I am not calling it, but could.


---------------------------------------------------------------------------------------------------------------
Id: 10518841
title: Access ModelAndView object in a JSP with jQuery
tags: java, jquery, spring, modelandview
view_count: 177
body:

I have a Spring 2.5 Controller:

    ModelAndView mav = new ModelAndView();

    JSONObject ret = new JSONObject();
    ret = obtainJson();

    mav.addObject("JSON", ret.toString()); // JSON like "{'param':'hello'}"
    mav.setViewName("test");

    return mav; 

In test.jsp, I want to access to the actual JSON, instead it alerts the string ${JSON}.

    <script type="text/javascript">
    var data = '${JSON}';
    alert (data);
    </script>

Any help? Thanks

comments:

1 : *How* doesn't it work?

2 : The alert prints the string: "${JSON}", not the value of JSON in ModelAndView

3 : Then JSP EL isn't enabled; make sure your web.xml is using the correct servlet spec level, and nothing in your container or JSP disallows EL. You also need to JavaScript-escape the value of `JSON`.

4 : JSP EL isn't enabled!!! With: <%@ page isELIgnored="false" %> now works! Thanks Dave!


---------------------------------------------------------------------------------------------------------------
Id: 11090634
title: File upload issue depending on URL
tags: python, django, google-app-engine
view_count: 52
body:

I have a client using Google App Engine, Django, SQL and the blobstore and a curious issue dependent on witch URL they are using. All files are being saved on the GAE blobstore. The client at location X and myself cannot upload files to the Django admin using the clients domain. We receive a 404 from Google when the upload is attempted (See screenshot). However another client from the same company at location Y can upload files whenever they like with no issues. If I or the client from location X upload files from the xxxx.appspot.com domain then everything works fine. Saving standard data that uses the SQL store works fine from both domains from any location. Any help would be greatly appreciated.

Django version 1.3.0 Screen shot - http://tinypic.com/r/2n2ij8/6

comments:

1 : Your question is so cryptic i cannot understand it.

2 : Are you saying that trying to upload to the blobstore via a URL on your custom domain doesn't work, but via your appid.appspot.com domain it does? Maybe this is because of stale DNS caching or something?

3 : Sorry about the cryptic question Stuart. Moishe is correct that uploading via appid.appspot.com works for everyone but uploading with the custom domain only works for the location Y user. I was wondering if it might have something to do with the users being associated with a specific Google App and permissions associated with that, but have been unable to verify if that is actually the issue.


---------------------------------------------------------------------------------------------------------------
Id: 8386012
title: Connection in SQL Developer to iSQLPlus
tags: sql, oracle, database-connection, sql-developer
view_count: 169
body:

i have problem to connect to school db using SQL Developer. I can connect using browser to isqlplus on port 7778, but when i want to connect by SQL Developer i have error : Error in/out. Socket read timed out. It is possible to do to something ?

comments:

1 : Most likely something to do with your firewall, turn it off and check if it still giving the same error.

2 : My firewall is off all time :/

3 : What port are you using in SQL Developer? It is not 7778. The default is 1521 inorder to connect to the listener. Are you sure the school does not have a firewall blocking direct access to the database?

4 : @mientus - Does the school's firewall allow direct connections to the Oracle listener? Normally, for security reasons, you wouldn't allow connections to an Oracle database over the public internet.

5 : Propably school wouldn't allow connections to Oracle database directly, remains to use onyl iSQL Plus.


---------------------------------------------------------------------------------------------------------------
Id: 7932032
title: Adding alias to column name breaks createSQLQuery in Hibernate
tags: sql, hibernate
view_count: 280
body:

I have a following query that works:

String sql = "SELECT heirarchyID FROM menu_heirarchy "

List res2 = getSession().createSQLQuery(sql) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) .list();

but when i just ad alias to the column name it gives me an error

SELECT heirarchyID as hid FROM menu_heirarchy

Caused by: java.sql.SQLException: Column 'heirarchyID' not found.

I am using Hibernate 3.5 and can't figure out why the query wouldn't work. Hibernate is configured to use MySQL dialect and both queries work when I run them against the database.

Presensce of Transformer is irrelevant. It will throw exception even if I don't use it.

Thanks!

Update:

The issue went away when I upgraded Hibernate from 3.5 to 3.6.

comments:

1 : So what is it: `when i just ad alias to the column name it gives me an error` or `Presensce of Transformer is irrelevant. It will throw exception even if I don't use it`?


---------------------------------------------------------------------------------------------------------------
Id: 7767985
title: Filesystem paths for ANT
tags: tomcat, deployment, ant
view_count: 53
body:

When attempting to customize a project's ant build script there has been what must be a very stupid mistake. The command line interface is attempting to build and deploy the files is some strange combination of the configured paths. The directory of the project is X:\SourceCode\Project\Layer. I would like the deploy command to move the files to the Tomcat server root at X:\Tomcat\TomcatVersion\Project.

However, what I actual get is that the build command fails trying to find X:\SourceCode\Project\Layer\X:TomcatTomcatVersion\lib. Even when building. Note that it is looking for the lib folder in a combination of the project filepath and deployment path without the '\' character. What should I change in the build file to get the project to look for the lib folder in the correct directory?

Build.xml of Web

<property file="build.properties"/>
<property name="src.dir" value="src"/>
<property name="web.dir" value="dist"/>
<property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
<property name="name" value="Project"/>

<path id="master-classpath">
    <fileset dir="${web.dir}/WEB-INF/lib">
        <include name="*.jar"/>
    </fileset>
    <!-- We need the servlet API classes: -->
    <fileset dir="${appserver.lib}">
        <include name="servlet*.jar"/>
    </fileset>
    <pathelement path="${build.dir}"/>
</path>
<!--Other Items -->
    <target name="deploy" depends="build" description="Deploy application">
    <copy todir="${deploy.path}/${name}" preservelastmodified="true">
        <fileset dir="${web.dir}">
            <include name="**/*.*"/>
        </fileset>
    </copy>
</target>

Build.properties of Web

appserver.home="X:\Tomcat\TomcatVerson"
appserver.lib=${appserver.home}/lib
comments:

1 : Where exactly does the error occurs? Write now I can't tell by seeing your build file. Also your error means that a somewhere a path is resolved relative therefore you have this crazy path.

2 : Try just using forward slashes in all your paths. \ is an escape character in properties files, and ant uses / for paths. And remove the quotes around the appserver.home property value.

3 : JB Nizet +1. Ant has the ability to automatically find the right path both on Windows and Linux with just "/" in the build file. And also, the values in a properties file should not contain quotes. Only XML needs it.

4 : JB Nizet has the source of the problem. The strange deployment path was because of the \ characters. JB if you can put your comment as an answer I'll mark it this one closed. Thank you also to FailedDev there was a relative path involved that generated the combination of the two directories.


---------------------------------------------------------------------------------------------------------------
Id: 10262422
title: Count from a list query
tags: ruby-on-rails, activerecord
view_count: 34
body:

How can i do to generate all the count based on the query off the find method?

pools = Serverpool.find(
    :all,
    :order => "#{params[:sidx]} #{params[:sord]}",
    :limit => rows,
    :offset => 0
)

Pools returns the list of pool, but in my table has 200 entries but I limited the results in 10. In grails i do just use pools.getTotalCount() and gorm remake the query removing the limit and offset.

Somebody knows the better way do it in rails?

thanks

edit: if I do like this:

pools_query = Serverpool.order("#{params[:sidx]} #{params[:sord]}")
pools = pools_query.limit(2).offset(0).all
pools_results = pools_query.count

it works. but this is the correct approach?

comments:

1 : what version of Rails are you using, the syntax doesn't look like Rails3

2 : hi! i'm using Rails 3. What is the better way to do it? This link: [link] http://apidock.com/rails/ActiveRecord/Base/find/class [/link] i'm used to build this fragment

3 : `"#{params[:sidx]} #{params[:sord]}"` -- congrats with SQL-injection vulnerability!

4 : @jdoe what is the correct way to do?

5 : @PedroGon?alves: there are several ways to go, check out the [guides](http://guides.rubyonrails.org/active_record_querying.html#conditions)


---------------------------------------------------------------------------------------------------------------
Id: 8401144
title: does -webkit-animation-fill-mode: forwards wont work with opacity
tags: css3
view_count: 212
body:

This fiddle http://jsfiddle.net/hfJLQ/1/ shows a fading text. I want the animation to end in the final keyframe. I have added the fill mode to forwards after seeing http://css3animator.com/2010/12/how-to-control-your-css3-animations/. But the opacity of the text returns to the value of 1.

Also this fiddle http://jsfiddle.net/hfJLQ/5/ contains a color changing demo. But here the fill mode works fine and the text maintains the final keyframe.

Please calrify

comments:

1 : I do not observe this problem in the latest version of Safari nor Chrome for OSX. What browser are you using?

2 : tested on safari 5.0.3 on windows

3 : rajkamal the grammar could be better here - it's not so clear if it's a question of a statement because you say 'does' as if it's a question, and 'wont' as if it's a statement.


---------------------------------------------------------------------------------------------------------------
Id: 7400354
title: Rails I18n always taking default locale for custom field
tags: ruby-on-rails, internationalization
view_count: 109
body:

I am using our own defined helper field, in that I need the label to be localized. But no luck those label are visible with default locale. That custom field is defined in the controller.

So in controller when I call I18n.t('some.method'), I get only :en locale which is default locale for mine.

Remaining places this is working fine. How do I use internationalization for this.

comments:

1 : I got to know, controller strings are loaded before I18n configuration so its starts with default locale. But I still didnt find the solution for the same.


---------------------------------------------------------------------------------------------------------------
Id: 8162587
title: Google Map Script Fails when Opening Map in Lightbox
tags: google-maps-api-3, lightbox
view_count: 120
body:

The following code works correctly when inserted on a regular page.

<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);

    var myOptions = {
      zoom: 8,
      center: latlng,

      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

  }

</script>

<div class="maplink_show" style="padding-bottom:10px;"><a href="#" onClick="initialize()">[+] map</a></div>

  <div id="map_canvas" style="width:300px; height:300px">

  </div>

If the same code is placed in a lightbox (I am using lightbox_me) it doesn't get past var latlng = new google.maps.LatLng(-34.397, 150.644); Just to clarify the link to open the map is inside a lightbox and I want the map to become visible inside that same lightbox.

comments:

1 : Maybe calling the initialize function at page load would solve the issue. Initializing the map during/after loading the lightbox may be an issue.


---------------------------------------------------------------------------------------------------------------
Id: 9861587
title: Xcode 4.3.2: Can not add files outside the project folder
tags: xcode4.3
view_count: 436
body:

I have just upgraded to XCode 4.3.2 and now my old projects are not correctly loaded. All files outside the project folder are displayed in red color. The folder structure is like this:

So I can't add "mylibfile.h" to the project. It's simply impossible. It's also impossible to add the file via an alias ("alias of mylibfile.h").

Currently the only way is to make a copy of "MyLibFiles" into "MyProject". But that can not be the way, it's silly.

comments:

1 : Same problem here. Xcode does not want to include aliased files. As you said, it's silly.


---------------------------------------------------------------------------------------------------------------
Id: 11245204
title: Is possible to create a singleton c++ to authenticate and post in the wall using HTTP request to Facebook API?
tags: c++, facebook-graph-api, cocos2d-x
view_count: 93
body:

I'm working on linux.

I have been looking for a method to post in facebook from a c++ app (that run in Android and Iphone using cocos2d-x). I have found some code on c++ to post on facebook and twitter, but it not compile on linux. This or this.

In theory, I think, using http request, it could be easy to do, but i'm not sure.

The same question on cocosd2-x forum.

Some idea about this theory?

comments:

1 : You should be aware that Facebook officially supports only PHP, and that their API changes often enough that you probably want a third-party platform which is popular enough to be reliably supported and/or simple enough that you can fix it. Are you already using Qt for other networking operations?

2 : I'm not using Qt, the facebook-cpp-graph-api work using qt, but I use cocos2d-x libraries

3 : if you are familiar with low level codes, you can try to use libcurl to send http request. libcurl is included in cocos2d-x.


---------------------------------------------------------------------------------------------------------------
Id: 9576056
title: Using RJB or plain Javascript?
tags: javascript, ruby-on-rails, rjb
view_count: 48
body:

What do you think? Which one is the best in Rails framework? Using plain javascript or RJB? Can you explain pros and cons of the usage each?

Thanks in advance for the ideas...

comments:

1 : Using apples or screwdrivers? What do you think? Which one is the best? Can you explain pros and cons of the usage each?

2 : Use RJB, use Coffeescript, use jQuery. Use anything that makes your code better and your job easier.


---------------------------------------------------------------------------------------------------------------
Id: 7117702
title: Search Platform for C# + Sql Server Website
tags: lucene, solr, full-text-search, sphinx, full-text-indexing
view_count: 136
body:

We have developed and are maintaining a Newspaper website. The content of the website is updated every night from a bunch of XML files which goes into the website's database (MS SQL Server 2008).

Our current search mechanism is not sufficient at all due to the large amount of data (around 5 years and increasing).

So we have decided to use a custom text indexing and search platform. Our candidate tools are:

Can you give us an explanation of which one will suit our need the best and why. Your suggestion could be a tool that we have not considered in our list.

Please consider our technology stack and needs. We need also a tool that could be used as soon as possible with a steep learning curve.

If we need to program in a language except than C#, we prefer Java over C++.

comments:

1 : This is a duplicate of approximately three billion questions. E.g. [this one](http://stackoverflow.com/questions/737275/pros-cons-of-full-text-search-engine-lucene-sphinx-postgresql-full-text-searc), [this one](http://stackoverflow.com/questions/1284083/choosing-a-stand-alone-full-text-search-server-sphinx-or-solr), ... if you have a specific question then we might be able to help.

2 : Using stackoverflow to decide for you what's best for your projects is always a big mistake. You already have options and the information to compare them, so you should take a decision on your own based on that.


---------------------------------------------------------------------------------------------------------------
Id: 10251580
title: Flare 3D Scene Environment panning
tags: flash, stage3d, 3dgame
view_count: 126
body:

I am using Flare3D to load a small city modeled for a game. I have a problem when creating and panning the game environment.

I am going to create a small model city by using 3ds Max and exporting it to f3d format. I am currently using a Viewer3D to load the model created. But the problem is by using a Viewer3D, the user is able to pan the view and he can view the downside of the city also (the ground plane) by dragging the mouse. Also when zooming out,the city becomes small and the dark grey area also comes into the scene which looks ugly. So what can I do for it. Should I use Scene3D(which cannot be panned) instead of Viewer3D and use a custom camera and code to render the scene out? (for an example a model walks in the city and camera follows him) please help me. thanks here is the code I am using

        scene = new Viewer3D(this.parent);

        scene.registerClass(Flare3DLoader1);

        var city:Pivot3D = scene.addChildFromFile("./resources/city.f3d");

        scene.addChild(city);

        scene.addEventListener( Scene3D.COMPLETE_EVENT, completeEvent );

        this.addEventListener(Event.ENTER_FRAME, updateScene);

for above reply please follow the link alcity

Finally I created a Scene3D (which does not allow the panning) and control the character movement at the scene Update Event. Then the last 2 lines allow to camera to follow the character. This works fine for now and Still I want to write a Custom code to pan the Scene3D camera. thanks.refer Building a 3D Flash game with Flare3D and Stage3D

 protected function gameLogics():void
     {
         _model.translateZ(1.2);

         if(Input3D.keyDown(Input3D.LEFT)) _model.rotateY(-2);

         if(Input3D.keyDown(Input3D.RIGHT)) _model.rotateY(+2);

         Pivot3DUtils.setPositionWithReference(_scene.camera,0,20,-100,_model,0.1);

         Pivot3DUtils.lookAtWithReference(_scene.camera,0,10,0,_model,_model.getDir(),0.05);
     }
comments:

1 : Doesn't Flare3D offer a wide variety of camera's to choose from? Follow cams, cams with constraints, etc.

2 : Thanks Torious and Basically what I want is create a skybox like thing So that we can hide the empty area in the model. Thank you so much for the answer.


---------------------------------------------------------------------------------------------------------------
Id: 8507805
title: Scaling a group of images together iOS using a transformation Matrix
tags: iphone, objective-c, ios
view_count: 103
body:

I have a menu with images that the user can choose. Once an image is selected it appears in the middle of the screen. Every image is a UIImageView. I was able to manage the translation, rotation, and scale of every selected image. My problem now is to allow the user to scale the whole group of images.

The image views were added to a superview, used as a canvas. If I resize the canvas, all the images inside get resized as well and proportionally. The problem is when I add a new image, it fits under the new canvas transform matrix and appears as small as the others.

Is there a way to scale the images at the same time, without touching the superview transform? I tried this with no luck: iterating through all the images in the canvas view, applying the same scale factor, for every single image view. Each of them get scaled independently and the resulting image was just wrong.

Thanks

comments:

1 : How about adding the images that you want to resize as a group to a `UIView` that you apply transform to and put that into your `canvas`


---------------------------------------------------------------------------------------------------------------
Id: 7482649
title: How to call python functions and pass parameters to them from my Java app
tags: java, function, methods, parameters, jython
view_count: 125
body:

I have a fully developed web app in Java. I recently started coding a little in python and liked it.

I have written some simple functions in python that look something like :

def doSomething(something)
perform some logic using something...
return the_answer

I'd like to call these methods from my java app (and pass a string param) but couldn't find out how.

I'm particularly interested in using Jython standalone alongside my app so, if it makes any difference. All of the other related questions I found either say use Jepp or don't deal with parameter passing.

comments:

1 : How about this answer? http://stackoverflow.com/q/6467407/407651


---------------------------------------------------------------------------------------------------------------
Id: 7513794
title: Sending data via HTTP GET method
tags: iphone, objective-c, cocoa-touch, http
view_count: 157
body:

I want to send data via the HTTP GET method in Cocoa Touch.

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",loginURL,@"?CurrCode=GBP"]]];
[request setHTTPMethod:@"GET"];
[request setTimeoutInterval:60];

This gives some weird response:

currency code not set correctly

while it works fine from a Web browser.

comments:

1 : In mean time also go thru this apple doc, :-http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i

2 : I tried ..I want to send data via query string..but I don't know ..How to send.. :'(

3 : You haven't shown it here, so I can only assume... You're feeding this NSMutableURLRequest to a NSURLConnection and then you're actually starting that connect, right? If not, you're configuring a request but not actually *making* it.


---------------------------------------------------------------------------------------------------------------
Id: 7239276
title: What's the best way to add progressbar to cxGrid column
tags: devexpress, c++builder, c++builder-2010
view_count: 309
body:

I am adding progressbar to each row of my first grid's banded tableview column ! The way I do it => I put 4 progressbars on my form and on btvArrProgGetProperties(TcxCustomGridTableItem *Sender, TcxCustomGridRecord *ARecord, TcxCustomEditProperties *&AProperties) assigning properties to a specific row by changing putted progressbar properties. here is my code

void __fastcall TfMain::btvArrProgGetProperties(TcxCustomGridTableItem *Sender, TcxCustomGridRecord *ARecord,
          TcxCustomEditProperties *&AProperties)
    {
          if ( StrToInt(ARecord->Values[ARecord->RecordIndex,1])==4 ){
            ARecord->Values[ARecord->RecordIndex,0]=100;
            AProperties=pCancel->Properties;
          }
          else
            if ( StrToInt(ARecord->Values[ARecord->RecordIndex,1])==2) {
                ARecord->Values[ARecord->RecordIndex,0]=100;
                AProperties=pDep->Properties;
          }
              else  {

                  if (StrToInt(ARecord->Values[ARecord->RecordIndex,1])==1) {
                        if ((ARecord->Values[ARecord->RecordIndex,7])!=0 && (ARecord->Values[ARecord->RecordIndex,12])!=0) {
                            //now time
                            nwTm=Now().FormatString("hh:mm:ss");
                            //get dep time
                            dpTm=StrToDateTime(ARecord->Values[ARecord->RecordIndex,7]);
                            dpTm.DecodeTime(&dpH,&dpM,&dpS,&dpMS);
                            //get reg time
                            rgTm=StrToDateTime(ARecord->Values[ARecord->RecordIndex,12]);
                            //find difference between dep and reg
                            dif=(1.0 + Double(dpTm)-Double(rgTm));
                            //get difference hours and mins
                            dif.DecodeTime(&difH,&difM,&difS,&difMS);
                            //diff between dep and reg in seconds
                            pReg->Properties->Max=difH*3600+difM*60+difS;
                            nwTm=Now().FormatString("hh:mm:ss");
                            nwTm.DecodeTime(&nwH,&nwM,&nwS,&nwMS);

                            if ((dpH>nwH) || ((dpH>nwH) && (dpM>=nwM ||dpM<=nwM)) || (dpH==nwH && dpM>nwM)  ) {
                                fltRem =(1.0 + Double(dpTm)-Double(nwTm));
                                fltRem.DecodeTime(&remH,&remM,&remS,&remMS);
                                _result=remH*3600+remM*60+remS;


                                pReg->Properties->Text=getTimeBySecs(_result);
                                ARecord->Values[ARecord->RecordIndex,0]=pReg->Properties->Max-_result;
                                pReg->Position=- _result;
                            }
                            else
                            {
                                    pReg->Properties->Max=100;
                                    ARecord->Values[ARecord->RecordIndex,0]=100;
                                    pReg->Properties->Text="??????";

    /*
                                        ARecord->Values[ARecord->RecordIndex,0]=pReg->Properties->Max;

                                        pReg->Position=pReg->Properties->Max;

    */
                            }
                            AProperties=pReg->Properties;

                        }
                  }

            }

    }

I think that this not a good approach to solve my problem (adding progressbar to a column which it's position get's changed dynamically), because when I click to each's row progressbar's position gets changed due to a last value set to progressbar!!

I prefer to dynamically create progressbar set name and other properties to it during runtime and assign to specific row on GetProperties event. What approach is the best one ? Is there any demo on this issue? If yes could you share please! Thanks in advance !

comments:

1 : and also calling `btvDep->LayoutChanged(true);` on `btvDepFocusedRecordChanged` event!

2 : when I click a row it's property(position,text) get's changed..


---------------------------------------------------------------------------------------------------------------
Id: 10003847
title: Given multiplicity constraints, a corresponding 'xxx_yyy_Source' must also in the 'Added' state
tags: c#, asp.net-mvc-3, entity-framework
view_count: 90
body:

Struggling with adding to a collection property of an entity class. I keep getting the error below:

A relationship from the 'User_ProfilePic' AssociationSet is in the 'Added' state. Given multiplicity constraints, a corresponding 'User_ProfilePic_Source' must also in the 'Added' state.

Below is the method used to save the image to the database:

 public void SaveImage(Library library, Image image)
     {
        image.PostedBy = new User { Id = image.PostedBy.Id, ProfilePic = new ProfilePic { Id = image.PostedBy.ProfilePic.Id} };

           var lib = Libraries.FirstOrDefault(l => l.Id == library.Id);
        lib.Images.Add(image);
   //     context.Entry(lib).State = EntityState.Unchanged;
        context.Entry(image.PostedBy).State = EntityState.Unchanged;
    //    context.Entry(image.PostedBy.ProfilePic).State = EntityState.Unchanged;
        context.SaveChanges();
    }

(I've been working this method for awhile now trying to get it to work, so you can see it looks a bit 'played with')

And here are the relevant classes if helpful:

public class Image : EntityBase
    {
        public string Url { get; set; }
        public User PostedBy { get; set; }
    }

 public class User 
    {
        public Guid UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
     public ProfilePic ProfilePic { get; set; }
   }

 public class Library
    {
        public List<Image> Images { get; set; }
     }

    public class ProfilePic : Image
        {
       // public int ProfilePicId { get; set; }
        public string Test { get; set; }
    }

 public class Image : EntityBase
    {
        public string Url { get; set; }
        public User PostedBy { get; set; }
        public List<Thumbnail> Thumbnails { get; set; }
    }

 public abstract class EntityBase
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateAdded { get; set; }

        public EntityBase()
        {
            DateAdded = DateTime.Now;
        }
    }

edit:

Mappings

 public IQueryable<Image> Images
        {
            get { return context.Images; }
        }

  public IQueryable<Library> Libraries
        {
            get { return context.Libraries.Include("Images").Include("Documents"); }
        }

  public IQueryable<User> Users
        {
            get { return context.Users
                .Include("ProfilePic");
              }
        }

Can anyone recommend how to get past this? Thank you in advance.

comments:

1 : Are you using EF code-first? If so, what do your mappings look like?

2 : Yes, using code-first. Have added relevant mappings. Thanks.

3 : Why are you assigning `ProfilePic` in your `SaveImage` method? It is not needed for rest of your code and it is a cause of your problem.

4 : Yea, that was it @LadislavMrnka. I could've sworn that I tried not setting that, but apparently I did not. Thanks.


---------------------------------------------------------------------------------------------------------------
Id: 10609023
title: clipsToBounds isn't working with my UIButton
tags: ios, xcode, cocoa, uibutton, bounds
view_count: 84
body:

guys, I wann to make light under button, but light is bigger then button size and it should be displayed out of buttons bounds. I we tried to use:

[btn setClipsToBounds:NO];

but it isn't working. My image drawing code:

[[UIImage imageNamed:@"light.png"] drawAtPoint:point];

Have you any ideas?

comments:

1 : are you setting btn = [[UIImage imageNamed:@"light.png"] drawAtPoint:point];

2 : I'm drawing image inside custom button.

3 : Are you opposed to creating an image view and either adding it as a subview of the button or just using a frame derived from the buttons frame instead?

4 : Thank you for suggestion, I will try it.


---------------------------------------------------------------------------------------------------------------
Id: 7341434
title: Keep external object same width as container in Masonry
tags: jquery, html, css, jquery-masonry
view_count: 194
body:

I'm using the great jQuery Masonry script, but am having a small problem with getting everything to line up right. Basically, I have an array of objects I float which are centered on the page with the following:

<script> 
$(function(){
  var $container = $('.category-matrix');
  $container.imagesLoaded( function(){
    $container.masonry({
      isAnimated: true,
      isFitWidth: true
    });
  );
});
</script>

Above the div.category-matrix , however, I also have a header of the page that I would like to remain centered regardless of how wide div.category-matrix is.

div.category-matrix has a min-width set but no max-width, as I want it to stretch to as wide as the browser window.

Is there a way to bind the width of the header to .category-matrix?

Thanks!

comments:

1 : I think this is doable in pure css using `margin: 0 auto`.

2 : Alxandr, That would work if I knew what the width of the container was going to be. However, since the width changes dynamically as the user resizes their browser, I need to figure out a way to duplicate what Masonry sets the width to be. Thanks!

3 : I don't see the problem at all. By setting the margin to `0 auto`, you tell the browser to center-position the div inside the cointainer, and when the container-size changes, the position of the div is updated too.

4 : Maybe to better illustrate, here's an example of how my code looks: `

Title

Content
` Masonry changes the width of the div dynamically based on the width of the browser window. I want it to also change the width of the header element to match that width. If I set the margin to `0 auto`, I need to set a fixed width for the element, but that changes depending on user action.

5 : Oh. That's simple. Just register for the resize-event of the document/window (don't remember which one, think both of the work actually), then just resize the header using jQuery.


---------------------------------------------------------------------------------------------------------------
Id: 10843603
title: MPI transport for zeromq sockets
tags: c++, mpi, amqp, zeromq
view_count: 66
body:

i read on the web

"?MQ is much higher-level than MPI, at least in theory you can implement MPI transport for ?MQ sockets"

I wanted to to see if any one else has tried to implement this

I also wanted to see if any one could offer some advice or consulting on implementing this before i blindly start

thanks

comments:

1 : What would be the benefit of such an implementation? The commonly used MPI libraries can already work over TCP sockets. You could argue that 0MQ's programming model is easier (being somewhat higher level and having fewer features), but you'd be replacing it with MPI's anyway.

2 : I doubt that anyone did that - MPI is mainly used in tightly coupled High Performance Computing applications while Message Queuing is suitable for loosely coupled and more general distributed systems.

3 : The quoted statement is seems backwards to me, anyway. I would think that if A is much higher level than B, it would be *hard* to implement B on top of A, and *easier* to implement A on top of B, rather than vice-versa, right?

4 : @JonathanDursi, I read that as "in theory one can use MPI to transport 0MQ messages", i.e. 0MQ presents abstraction on higher level than MPI.

5 : so it wouldn't make much sense? I'm just looking for something opensource in which I can contribute i.e I sort of know mpi very well..


---------------------------------------------------------------------------------------------------------------
Id: 9264867
title: Manipulate radio button set in javascript when you know the name, without using eval
tags: javascript, radio-button, eval, name
view_count: 68
body:

I have a function that gets passed the name of a radio button set, and needs to do stuff to it. It's easy to do like this:

function ClearRBs(rbsName) {
    var rbs = eval('document.formname.' + rbsName);
    if (rbs.length) { etc...
}

But lots of coders say eval is evil, like kicking a puppy. The orthodox way to select an element is getElementById(id) but a radio button set does not have an id, I don't think. Each individual radio button has an id, but I can't know a priori what the ids will be. Just the name of the set.

What is the preferred way to do this?

comments:

1 : `var rbs = document.formname[rbsName];`.

2 : possible duplicate of [Access dynamically named JavaScript Objects?](http://stackoverflow.com/questions/2232851/access-dynamically-named-javascript-objects)

3 : ok -- I thought of [] as only containing integers, and never tried putting a text string


---------------------------------------------------------------------------------------------------------------
Id: 7519967
title: Unable to read camera feed from my Lenovo Y500's built in camera (OpenCV)
tags: opencv
view_count: 102
body:

CvCapture* capture; capture = cvCreateCameraCapture(0); assert( capture != NULL );

It gives me two options, trivid capture and USB camera 2.0 Trivid capture opens a black screen as expected, but on selecting USB camera 2.0, it shows following error(I use my camera everyday) : assertion "capture != NULL" failed: file "main.cpp", line 31, function: int main(int, char**)

And my project partner executed the same code but it worked(He has attached a camera).

I'm new to OpenCV. Suggest any modifications I should make in the questions to make it more understandable, thanks.

comments:

1 : It seems unlikely to get an answer on application question about opencv...:(


---------------------------------------------------------------------------------------------------------------
Id: 9680801
title: Graph library for PyCUDA
tags: graph, pycuda
view_count: 38
body:

Can anyone please suggest graph theory library which can be used with PyCUDA?I looked at Thrust,but that can be used simple C based CUDA

comments:

1 : What kind of functions are you looking for ?

2 : First of all is there any such library?I'm looking for BFS,DFS and similar algos for graph

3 : I don't think I know of any CUDA based libraries that do similar things. These are quite hard problems to do in parallel ( effeciently anyway )


---------------------------------------------------------------------------------------------------------------
Id: 10921926
title: DRUPAL - How can I force a block not to be cached for unauthenticated users?
tags: drupal, caching, block
view_count: 64
body:

I have a php block which I would like to be refreshed on every page load/reload. Although I have disabled all caching under Site Configuration -> Performance the block is still being cached. Although I've googled a great deal on this I haven't found any definitive answers. Surely there must be a way to properly disable caching of content for unauthenticated users!

I'm using Drupal 6.20 and the site address is www.cygnet-rcDOTorg.uk (The block in question is the Twitter feed on the left sidebar 'Latest Tweets'...

BTW - The PHP in is using the Twitter Pull module. I have changed the configuration for the module for a 1 minute cache so I don't think the problem is there.

Tia, Tom

comments:

1 : Could your hosting company be providing some caching? I know, for example, that if you host with Acquia they additionally cache pages for anonymous users using Varnish... Or could it be browser caching? Did you test to see whether when you open the site on a different browser whether new tweets are reflected?

2 : Good thought Boriana, thanks, but that's not it.

3 : Go for http://twitter.com/about/resources/widgets/widget_profile and use the javascript api instead of the twitter pull module.


---------------------------------------------------------------------------------------------------------------
Id: 10770529
title: In controller validation Cakephp
tags: database, validation, cakephp
view_count: 59
body:

Im trying to create a message system where a person can only send another person a message when they have a relationship, in the relationship table that is active. I'm also doing the validation in my messages controller but it needs to check the relationships table to make sure that the relationship exists. The code I have at the moment cake does not like and I was hoping someone could lend a hand

here is the code from my current function from the controller

 public function addinvoice(){

 if($this->request->is('post')){
 $this->Invoice->set($this->request->data);
 if(this->Invoice->validates(array('fieldList'=>array('Relationship.partyone','Relationship.active')){
  $this->Invoice->create(); 
 if ($this->Invoice->saveAll($this->request->data,array('validate'=>false))) 
 { 
  $this->Session->setFlash('The invoice has been saved');  
} else { 
      $this->Session->setFlash('The invoice could not be saved. Please, try again.');
      $errors=$this->Invoice->validationErrors;
    }

  } 

  }



first attempt at my function from the conntroller

if($this->request->is('post')){
 $this->Invoices->set($this->request->data);
 if(this->Request->validates(array('fieldList'=>array('Relationship.partyone','Relationship.active')){
  $this->Invoice->create();
 if ($this->Invoice->save($this->request->data))
 {
  $this->Session->setFlash('The invoice has been saved');  
} else { $this->Session->setFlash('The invoice could not be saved. Please, try again.'); }
 else{
        $errors=$this->Invoices->validationErrors;
        }

  }

  }

my relationship table has the following structure id, partyone, partytwo, active, expirydate

partyone will always be the person sending the request.

comments:

1 : your indentation is a mess u_U if you put everything in place you'll see that you have two "else" for the same if. That's not the solution to your problem, but at least your code will be easier to read (even for you)

2 : what do you mean by "the code I have at the moment cake does not like"? A description about the exact error you are getting will be very helpful. Also, you have a typo in the fieldList "relationship" has 2 t's

3 : I got rid of the extra else, unfortunatly it's throwing an error with the validation - Parse error: syntax error, unexpected T_OBJECT_OPERATOR

4 : you can tell ive spent way too much time behind a computer screen. When I say it doesnt like it - i mean cake throws an error. @ Toote

5 : That's a php error, not a cake error.

6 : All you have to do is format your code to catch your missing brace. I can't understand what you're doing here though. Calling save() already does validation, why are you manually calling validates?

7 : solved the issue will update with answer shortly


---------------------------------------------------------------------------------------------------------------
Id: 8082605
title: mysql: Mining for keywords and phrases
tags: php, mysql, search, sphinx, phrases
view_count: 189
body:

I would like to get popular words and phrases (up to 3 words) from my products database table.

I tried using sphinxsearch service for that which was great, except..

  1. The result it give are plain txt words - without slovenian special chars (???) that ARE in the products table

  2. the results are only single words, and no phrases

sphinx builds this from an index... all together (including building the index) tooks about 2 minutes for 100,000 products...

this is impressive.. since I need this only once in a while (1/month)...

but as said before, unusable in my case....

what are other alternatives?

I need about 5,000 words and phrases

edit my products db source

source products_src
{
    type            = mysql

    sql_host        = localhost
    sql_user        = root
    sql_pass        = xxxxxxxxxx
    sql_db          = xxxxxxxxx

    sql_query_pre = SET CHARACTER_SET_RESULTS=utf8
    sql_query_pre = SET NAMES utf8

    sql_query       = \
        SELECT id, title, summary, keywords, text, category_id, company_id, created \
        FROM products WHERE status='A'

    sql_attr_uint = category_id
    sql_attr_uint = company_id
    sql_attr_timestamp = created
    sql_attr_string = title
    sql_attr_string = text

    sql_query_info      = SELECT id, category_id, title FROM products WHERE id=$id
}
comments:

1 : I suspect it's possible to overcome both of these issues with Sphinx. While this probably isn't very helpful, I would suggest reviewing the manual to see if your issues are addressed.

2 : I did. I would hope that it woild be possible with sphinx... but I cannot find any settings to get those special chars out... and in some forum questions I read, that it produces only single words

3 : As far as the special characters, I'm pretty sure you can solve this by specifying the appropriate character set and collation. This [blog post](http://yob.id.au/2008/05/08/thinking-sphinx-and-unicode.html) has some info. Do you want search to consider `? == c`? (while still returning ? in the actual result of course)

4 : I already specified the correct set and all special chars. the searching works perfecly (with or without special chars)... the problem are only these returned stop words, maybe becouse sphinx keep only this version of the word in the index

5 : You could try adding the column you're searching on as a [string attribute](http://sphinxsearch.com/docs/1.10/conf-sql-attr-string.html) so you can access the original data when you retrieve the document.

6 : I tried added title and text and I got nothing... tried only text, or only title... got the same result as without :(


---------------------------------------------------------------------------------------------------------------
Id: 9824401
title: setting datagridview values from another thread - cross thread operation IS valid
tags: c#, thread-safety
view_count: 89
body:

I'm using another thread than the UI thread to access a datagridview like this:

dataGridView1.Rows[5].Cells[5].Value = "hello";

but I don't get an execption of "cross thread operation not valid".

why?

comments:

1 : In Debug mode ?

2 : the mode is Debug but I don't have any breakpoints.

3 : It probably just means you found a maze in the checking net, don't assume this is safe.

4 : ok.. thank you.


---------------------------------------------------------------------------------------------------------------
Id: 10553417
title: ASP.NET website under IIS does not show needed client certificate in choice of certificate popup window
tags: asp.net, ssl, iis7
view_count: 65
body:

I have a web-site under IIS 7 with https binding as shown in pic below.

web-site binding settings

Also, I have installed several root CA certificates in trusted root certificates of local computer account. It can be seen from the pic shown below

root CA certificates

I have installed two different client certificates which were given by two different certificate authorities in firefox. And when I enter to web-site via https, only one certificate appears in list of available client certificates in choice of certificate popup window (shown in pic below), the other one which was given by second CA is not displayed. I have checked thumbprint of CA certificate installed on server and thumbprint of issuer's certificate in certification path, they are same.

only one certificate is available to choose

What could be the reason of not displaying the second certificate? The only answer I have found from internet is that I might not installed CA certificate in trusted root certificates of local computer account in server. But I did. What am I missing? Please help.

comments:

1 : Not sure if this is more server related (serverfault.com) or webmaster (http://webmasters.stackexchange.com/)


---------------------------------------------------------------------------------------------------------------
Id: 9445063
title: iPhone annotations cause app to act slow
tags: iphone, annotations
view_count: 43
body:

When I load 500 annotations on map, app becomes laggy when moving a map, is there a way to solve this problem? It's good when the map is zoomed and show 50 annotations, but when zoomed out to show all annotations, app is slow and it laggs when moving within a map.

Current code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.annotations = [[NSMutableArray alloc] init];

    // Create location manager object
    locationManager = [[CLLocationManager alloc] init];

    // All results from the location manager
    [locationManager setDistanceFilter:kCLDistanceFilterNone];

    // Set accuracy
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

    // Start updating current location
    [mapView setShowsUserLocation:YES];

    self.mapView.mapType = MKMapTypeStandard;   // also MKMapTypeSatellite or MKMapTypeHybrid

    // Start off by default in some city
    MKCoordinateRegion newRegion;
    newRegion.center.latitude = value1;
    newRegion.center.longitude = value2;
    newRegion.span.latitudeDelta = value3;
    newRegion.span.longitudeDelta = value4;

    [self.mapView setRegion:newRegion animated:YES];

    [self.mapView addAnnotations:self.annotations]; // --> self.annotations is array with 500 annotations
}
comments:

1 : 500 annotations on an iPhone screen? How is that even legible? I solved this issue by reducing the number of annotations that show when zoomed out to less than 50.

2 : I've seen apps that show thousand of annotations at once, but it is not laggy

3 : What does your viewForAnnotation look like? Do you have additional code to handle zooming in and out? Are your annotations animated?

4 : http://pastebin.com/yjqMESHh


---------------------------------------------------------------------------------------------------------------
Id: 8309185
title: how libc.a is compiled
tags: compilation, malloc, glibc
view_count: 38
body:

i added some code in glibc in a separate directory and updated Makefiles. My libc.so is build properly but in case of libc.a compilation i am facing undefined reference errors for pthread related functions. What/where I am missing ?

comments:

1 : to be more specific. I am facing the above errors when the said libc.so and libc.a are built and the testes are done.


---------------------------------------------------------------------------------------------------------------
Id: 9207465
title: node --debug-brk doesn't work
tags: debugging, node.js
view_count: 230
body:

I think the --debug-brk CLI options makes node stop at first line of script.

But it doesn't.

$node --debug-brk app.js 

debugger listening on port 5858

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Cannot read property 'port' of null
    at Object.<anonymous> (/home/raincole/nodejs_projects/app.js:35:76)

The line 35 of app.js still be executed. Why the --debug-brk doesn't work?

My node version is 0.6.10.

comments:

1 : WFM on node 0.6.3 (Linux). Looks like you filed a bug with node directly. (https://github.com/joyent/node/issues/2724 ) Generally, if you file a bug, I don't think it's necessary to also create an SO question.


---------------------------------------------------------------------------------------------------------------
Id: 10596552
title: EWS api load() on FileAttachment linux/mono base64 decode gives wrong output
tags: web-services, mono, ews
view_count: 98
body:

EWS 1.2 api, exchange 2007, windows/.net and linux/mono2.10.2

using the EWS 1.2 api to extract attachments from exchange gives different results on .net/windows as on mono/linux.

the files differ at byte 8192, 16384, 20480

So first after 8k block, then again after next 8k block and then 4k block again?!

fileAttachment.Load();

byte[] buffer = fileAttachment.Content;
Console.WriteLine(buffer[8191]); //windows -> 50  | linux -> 50
Console.WriteLine(buffer[8192]); //windows -> 9   | linux -> 59
Console.WriteLine(buffer[8193]); //windows -> 54  | linux -> 44

I put the

service.TraceEnabled = true;

so i can look at the soap message. there i find the content as a base64 string. i converted the base64 string online with this online base64 decoder and the attachment returns perfect.

The size of the buffer on linux is smaller than on windows when using the EWS API.

So there must be something wrong with converting base64 string linux/mono!?

comments:

1 : Did a test with java version of EWS and this works perfect. too bad for c#/mono

2 : Please specify the version of Mono you are using - this might be a bug in a particular release.

3 : version 2.10.2 - I can't find anything related to this issue

4 : made a [bug report](https://bugzilla.novell.com/show_bug.cgi?id=762529)


---------------------------------------------------------------------------------------------------------------
Id: 8431500
title: JBoss Hibernate Library Conflict
tags: oracle, hibernate, tomcat, jboss, oracle11g
view_count: 223
body:

I'm having a problem hitting an Oracle DB when deploying to JBoss. Deploying to Tomcat works fine--No issue. I suspect the problem is related to a conflicting library that ships with JBoss. When I attempt to query the database (using Hibernate), I get the following:

2011-12-08 08:02:53,640 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/xxxx].[xxxx]] (http-0.0.0.0-8080-9) Servlet.service() for servlet xxxx threw exception
java.lang.IllegalStateException: BaseClassLoader@50d81341{vfszip:/opt/jboss/jboss-eap-5.1/jboss-as/server/web/deploy/xxxxx.war/} classLoader is not connected to a domain (probably undeployed?) for class oracle.sql.DATE
        at org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:857)
        at org.jboss.classloader.spi.base.BaseClassLoader.doLoadClass(BaseClassLoader.java:502)
        at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:447)

Again, no such problem when running in Tomcat. I have set up a jboss-classloading file in my webroot the contains this:

<classloading xmlns="urn:jboss:classloading:1.0"
    parent-first="false" domain="DefaultDomain" top-level-classloader="true"
    parent-domain="Ignored" export-all="NON_EMPTY" import-all="true" />

But it doesn't seem to help. Strangely, I am connecting to two different databases with two different hibernate configurations, one Oracle 11i and one Oracle 8i. The Oracle 11 connection never throws a problem... Its only the 8i connection that causes this problem. The 11 connection works just fine.

I have no idea why this happens, but maybe JBoss contains an Oracle 8 Hibernate dialect lib and not the Oracle 11 dialect lib? In any case, how do I tell JBoss to use my packaged libraries and not the ones found on its classpath (assuming this is my problem)?

Thanks!!!

comments:

1 : I need jboss-web.xml (in WEB-INF): com.talecris:archive=flint.war java2ParentDelegation=false

2 : This is what we did on our jboss deployment, We removed all the hibernate jars from JBOSS server that did it. In our case the hibernate version on our app was not matching the jboss version.


---------------------------------------------------------------------------------------------------------------
Id: 7772544
title: 'Specified method is not supported' in System.Web.Helper.Chart
tags: asp.net-mvc-3, data-binding, charts, ienumerable, system.web
view_count: 214
body:

I?m using System.Web.Helper.Chart method in one of my MVC3 application. The method is working fine as far as I am manually giving it values like this:

public ActionResult GetRainfallChart()
    {
        var key = new Chart(width: 600, height: 400)
            .AddSeries(
                chartType: "bar",
                legend: "Rainfall",
                xValue: new[] { "Jan", "Feb", "Mar", "Apr", "May" },
                yValues: new[] { "20", "20", "40", "10", "10" })
            .Write();
       return null;
    }

But when I tried using its DataBindTable method that required an Enumerable object to bind with it gives be this exception: Specified method is not supported.

    public ActionResult GetRainfallChart()
    {
        string uId = ?1?;
        int usrId = int.Parse(uId);
        var usr = new User();
        DataTable chartRecord = usr.getChartRecord(usrId);
        var cr1 = chartRecord.AsEnumerable();
        Chart key = new Chart(width: 1000, height: 400)
            .AddSeries(
                chartType: "column").DataBindTable(cr1)
            .Write();
        return null;
    }

I think am doing some mistake while casting DataTable object as Enumerable object through AsEnumerable, but unable to figure out what actually is the problem as I?m new to it. Kindly help. :)

comments:

1 : Doesn't DateBindTable take two args? http://msdn.microsoft.com/en-us/library/system.web.helpers.chart.databindtable(v=vs.99).aspx

2 : [link](http://www.dotnetcurry.com/ShowArticle.aspx?ID=597) I'm taking reference from here and here it is with only one argument: `.DataBindTable(d.MonthNames)`


---------------------------------------------------------------------------------------------------------------
Id: 11079221
title: Ext plugin for Liferay 6.0.6 is not executed on RHEL 5.2 x86_64
tags: java, jboss, centos, liferay-6
view_count: 120
body:

This is a strange problem . The Ext plugin for Liferay 6.0.6 can be executed on any OS platform but centos or RHEL.

Now I will try my best to explain my experiment.

First, I create a login-hook where a captcha image is added on $LIFERAY_SDK_DIR/hooks/login-hook/docroot/custom-jsps/html/portlet/login/login.jsp:

<portlet:actionURL windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>" var="captchaURL">
                <portlet:param name="struts_action" value="/login/captcha" />
</portlet:actionURL>

<liferay-ui:captcha url="<%= captchaURL %>" />

and also make a modification on /html/taglib/ui/captcha/simplecaptcha.jsp :

<div class="taglib-captcha">
    <table border=0>
        <tr>
            <td>
                <aui:input label="text-verification" name="captchaText" size="10" type="text" value="" />
            </td>
            <td style="padding-left:10px;">
                <img id="captcha_image" alt="captcha" class="captcha" src="<%= url %>"  />
            </td>
            <td>
                <a href="#" id="captcha_change_btn" class="captcha"
                   onclick="return false;"><liferay-ui:message key="change_captcha" />
                </a>
            </td>
        </tr>
    </table>
    <aui:script>
        jQuery.noConflict();
        jQuery(function ($) {
              $('#captcha_change_btn').click(function () {
                 var url = "<%= url %>";
                 $('#captcha_image').attr('src', url + '&random=' + Math.random());
              });
        });
    </aui:script>
</div>

After deploying the login-hook onto liferay, the login window will look like this: enter image description here

Second, I create a login-ext which will check the captcha text provided by user while logging in . So I add the code

    _log.warn("check the captcha ... ");
    CaptchaUtil.check(actionRequest);
    System.out.println("success check captcha");

in protected void login( ThemeDisplay themeDisplay, ActionRequest actionRequest, ActionResponse actionResponse, PortletPreferences preferences) throws Exception of $LIFERAY_EXT_DIR/ext/login-ext/docroot/WEB-INF/ext-impl/src/com/liferay/portlet/login/action/LoginAction.java

Deploy the login-ext, then try to login without providing a captcha text will causes an error which is correct. But when I move the whole liferay system onto centos 5.8, login without a captcha text will be passed.

Could anyone give me a suggestion ? Thx

comments:

1 : Does anyone understand what i mean ?


---------------------------------------------------------------------------------------------------------------
Id: 9239538
title: Modal popup, update progress and jquery animation
tags: javascript, jquery, jquery-ajax, modalpopupextender, updateprogress
view_count: 601
body:

I've got a modal popup displaying an update progress upon AJAX call:

<asp:Panel ID="panelUpdateProgress" runat="server" ClientIDMode="Static">
        <asp:UpdateProgress ID="UpdateProg1" DisplayAfter="2" runat="server" ClientIDMode="Static">
            <ProgressTemplate>
                <div style="position: fixed; bottom:1%; right: 10px; border-width: 1px; border-style: solid; background-color: #FAFAD2;
                    width: 250px; height: 100px;">
                    <div style="position: relative; top: 40%; text-align: center;">
                        <asp:Image ID="Image1" runat="server" Style="border: 0px; vertical-align: middle;
                            padding-bottom: 4px;" ImageUrl="~/Images/Refresh.gif" />
                        <asp:Label ID="Label2" runat="server" Style="border: 0px; vertical-align: middle;
                            margin-left: 7px" Text="Refreshing data, please wait..."></asp:Label>
                    </div>
                </div>
            </ProgressTemplate>
        </asp:UpdateProgress>
    </asp:Panel>
    <ajaxToolkit:ModalPopupExtender ID="ModalProgress" runat="server" TargetControlID="panelUpdateProgress"
        BackgroundCssClass="modalBackground" PopupControlID="panelUpdateProgress">
    </ajaxToolkit:ModalPopupExtender>


<script type="text/javascript" language="javascript">
    var ModalProgress = '<%= ModalProgress.ClientID %>';
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginReq);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endReq);
    function beginReq(sender, args) {
        // shows the Popup 
        $find(ModalProgress).show();
    }

    function endReq(sender, args) {
        //  Hides the Popup
        $find(ModalProgress).hide();
    } 
</script>

I'm trying to get an animated fadeout/or slide down effect on the update progress div.

However, I am clearly out of my depth now as I can't get it to work!!

I tried $find(ModalProgress).fadeOut(); but this throws an error.

Please can someone point me in the error of my ways?

When I use:

 function endReq(sender, args) {
        //  Hides the Popup
        $find(ModalProgress).fadeOut();

    } 

I receive a "Microsoft JScript runtime error: Object doesn't support this property or method" error.

comments:

1 : - What error do you get? - `$find()` looks odd, is that supposed to be jQuery, or have you defined `$find` somewhere?


---------------------------------------------------------------------------------------------------------------
Id: 8362060
title: win32com help translating VBA to python
tags: python, vba, win32com
view_count: 108
body:

I am doing a lot of work with excel and would like to automate some of the more repetitive process. My problem is I can't quite figure out how to translate VBA (from macro's) over to python. I understand the basic idea but run into trouble over how to approach the actual syntax. I have found some useful things on the web but nothing that really explains how to approach VBA syntax to Python syntax. If anyone could give me some general rule of thumb it would be greatly appreciated or at least point me to a good source of info, thank you.

comments:

1 : you can't *convert* VBA to Python, they are very different languages. What you should do is **learn** Python (http://www.diveintopython.net/) and write the needed code.

2 : How about this? http://vb2py.sourceforge.net/

3 : Here's a simple example that might be helpful: [http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/](http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/)


---------------------------------------------------------------------------------------------------------------
Id: 10536388
title: jQuery Slider Doesn't Work in IE
tags: javascript, jquery, html, css, slider
view_count: 213
body:

My code works perfectly with all browsers except IE. I tried every solution I could find on the forums with no luck. I am still learning JavaScript, so I will learn jQuery later. The issue is that in IE the slides appear vertically with no effect. Here is my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org      /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

 <head>
 <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
 <link href="stylesheet...css" rel="stylesheet" type="text/css" />

 <title>div test</title>
 <script src="jquery.js" type="text/javascript"></script>
 <script src="jquery.bxSlider.min.js" type="text/javascript"></script>

 <script type="text/javascript">
 $(function(){
 var slider = $('#slider1').bxSlider({
 controls: false
  });

$('#bx-prev').click(function(){
slider.goToPreviousSlide();
return false;
});

 $('#bx-next').click(function(){
 slider.goToNextSlide();
 return false;
  });
  });</script>
 </head>

  <body>
   <div id="slider1">
    <div>
   <div id="wrapper">

  <div id="head"><img alt="logo" align="left" src="logo.png"/></div>
  <div id="main"> <div id="content">content</div> </div>
  <div id="rash"><img alt="r" align="middle" 
  style=" position:relative;top:-70px;"  src="image1.png"/></div>
 <div style="clear:both"></div>

 </div></div>
 <div>
 <div id="wrapper">

 <div id="head"><img alt="logo" align="left" src="logo.png"/></div>
 <div id="main"> <div id="content">content</div> </div>
 <div id="rash"><img alt="r" align="middle" 
 style=" position:relative;top:-70px;"   src="image1.png"/></div>
 <div style="clear:both"></div>

 </div></div>
 <div>page3</div>
 <div>page4</div>


 </div>
 <div id="bx-next">next</div>
 <div id="bx-prev">prev</div>

 </body>

</html>

And here is my style sheet:

 div#head{
width:100%;
height:100px;
/*background-color:antiquewhite;*/
 margin-bottom:100px;
 }

  div#content{
    border-left: 2px solid #F0F8FF;
border-right: 2px solid #8a815d;
border-top: 2px solid #8a815d;
border-bottom: 2px solid #8a815d;
width:400px;height:300px;
-webkit-border-radius: 0px 28px 20px 0px;
-moz-border-radius: 0px 28px 20px 0px;border-radius: 0px 28px 20px 0px;
font-family:Arial,Helvetica,sans-serif;
color:#8a815d;
padding-left:100px;
    background-color:#F0FFFF;
background-color: rgba(215,227,211,0.3);
position:relative;
top:20px;
left:0px

     }


  div#wrapper {
   width: 100%;
   margin-top: 0px;
   margin-bottom: 0px;
   margin-left: 0px;
   margin-right: 0px;
   padding: 0px;
   }

 div#main{
   /* background-color:black;*/
   width:50%;
   height:360px;
   float:left;


   }
      div#rash{
 float:right;
 /*background-color:blue;*/
 height:360px;
 width:50%;
      }
   body {
background-color: #E8F3F9;
background-image: url('squares layer.png');
background-repeat:no-repeat;
background-size:cover;
background-position:center;


    }
    /*next button*/
     #bx-next {
  position:absolute;
  top:45%;
  right:3px;
  z-index:998;
  width: 30px;
  height: 30px;
  text-indent: -999999px;
  background: url(gray_next.png) no-repeat 0 -30px;
        }

    /*previous button*/
     #bx-prev {
   position:absolute;
   top:45%;
   left:4px;
   z-index:998;
   width: 30px;
   height: 30px;
   text-indent: -999999px;
   background: url(gray_prev.png) no-repeat 0 -30px;
            }
comments:

1 : do you have any errors in the console? can you post your code on jsfiddle.net ?

2 : it says your JS code is valid


---------------------------------------------------------------------------------------------------------------
Id: 7093932
title: asp.net datalist RepeatDirection="vertical" not working
tags: c#, asp.net, datalist
view_count: 248
body:

I have a datalist in my asp.net application that renders out html checkboxes:

<asp:DataList ID="dlCategories" runat="server" RepeatColumns="2" RepeatDirection="Vertical">
    <ItemTemplate>
        <input type="checkbox" id="chk" runat="server" class="myclass" catID='<%# DataBinder.Eval(Container.DataItem,"catID") %>' catName='<%# DataBinder.Eval(Container.DataItem,"catName") %>' colID='<%# DataBinder.Eval(Container.DataItem,"colID") %>' /><img src='<%# DataBinder.Eval(Container.DataItem,"img") %>' alt='<%# DataBinder.Eval(Container.DataItem,"catName") %>' /><%# DataBinder.Eval(Container.DataItem,"catName") %>
    </ItemTemplate>
</asp:DataList>

I can't seem to get the output to render vertically, it always renders horizontally. I want the output to look like:

Result1 Result4

Result2 Result5

Result3 Result6

But no matter what i put in repeatdirection, i always get:

Result1 Result2

Result3 Result4

Result5 Result6

Can anyone see what I'm doing wrong?

comments:

1 : I can't reproduce your problem (.Net 4.0). It renders correctly for me. If you remove the reference to "myclass" does it work?

2 : which version of .net? also show us your collection. BTW, whats `catid`

3 : @Carter 'myclass' is only there so it can be selected with jquery, there aren't any styles being applied to it. I still get the same when it is removed

4 : @naveen this is .net 4. Catid is just a custom attribute that i'm adding to the checkbox for later use.

5 : If you reduce the contents of the itemtemplate to a single label do you still get the same problem?


---------------------------------------------------------------------------------------------------------------
Id: 9443213
title: How to get a transparent image on the edge..only on the edge?
tags: objective-c, xcode, core-graphics, cgimage
view_count: 78
body:

I'm trying to do this with a mask

- (UIImage*) maskImage:(UIImage *)image1 withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image1 CGImage], mask);
    CGImageRelease(mask);
    UIImage* retImage= [UIImage imageWithCGImage:masked];
    CGImageRelease(masked);
    return retImage;
}

But i am not satisfied with the result. Any ideas?

comments:

1 : Can you edit your question and explain what is the result you are trying to get? What do you mean by: *"transparent image on the edge..only on the edge"*?

2 : Can you post some pictures of how this looks with the mask applied and how you'd like it to look instead?

3 : i have an image... in this image i need to set alpha on center 1 and on the edge more transparent

4 : So you basically want something like this (I used a solid black image to demonstrate the alpha)? http://i.imgur.com/xfuAw.png

5 : Sorry, more like this? http://i.imgur.com/caY8l.png

6 : yes something like this


---------------------------------------------------------------------------------------------------------------
Id: 10538071
title: How to Calculate FAT
tags: fat
view_count: 27
body:

I am learning about FAT file system and how to calculate FAT size. Now, I have this question:

Consider a disk size is 32 MB and the block size is 1 KB. Calculate the size of FAT16.

Now, I know that to calculate it, we would multiply the number of bits per entry with the number of blocks. So first step would be to calculate the number of blocks = (32MB)/(1KB) = 2^15 = 32 KB blocks.

Then, we would put that into the first equation to get = 2^16 * 2^15 = 2^19 Now, up to here I understand and I had thought that that is the answer (and that is how I found it to be calculated in http://pcnineoneone.com/howto/fat1/).

However, the answer I was given goes one step further to divide 2^19 by (8*1024) , which would basically give an answer of 64KB. Why is that? I have searched for hours, but could find nothing.

Can someone explain why we would perform the extra step of dividing 2^19 by (8*1024)? oh, and the other question stated that the block size is 2KB and so it divided the end result by(8*1024*1024) ... where is the 8 and 1024 coming from? please help

comments:

1 : Is this homework?

2 : of course it is, but it's not "how do i figure out x" it's "i thought it should have been x, but was y. why"

3 : yes it is, and I have the answer, I am trying to understand it so that if it appears again I can apply it correctly.

4 : Really? No one knows why to get the answer you must also divide by (8*1024)?


---------------------------------------------------------------------------------------------------------------
Id: 10477104
title: ruby on rails multiple file upload as of GMail using javascript or jQuery
tags: javascript, ruby-on-rails
view_count: 96
body:

I have worked for single upload it is working fine. I need an output to upload multiple files as it is in gmail with check box and one browser button.

<%= file_field 'upload', 'attachfile',:onchange=>"addRemoveFile();"%>
<div id="moreUploadsLink">
   <%= link_to "Attach another File", 'javascript:addElement()'%> 
</div>
<%= hidden_field_tag 'theValue', '0'%>
<div id="myDiv">  </div>

function addElement() {
    var ni = document.getElementById('myDiv');
    var numi = document.getElementById('theValue');
    var num = (document.getElementById('theValue').value -1)+ 2;
    numi.value = num;
    var newdiv = document.createElement('div');
    var divIdName = 'my'+num+'Div';
    newdiv.setAttribute('id',divIdName);
    newdiv.innerHTML = '<input type="file" name="upload" id="attachfile"/><a href="#" onclick="removeElement(' + divIdName + ')">Remove </a>';
    ni.appendChild(newdiv);
    var fileInput = document.getElementById('attachfile');

    var files = fileInput.files;
    var file;

    for (var i = 0; i < files.length; i++) {

        file = files.item(i);
        //or
        file = files[i];

        document.getElementById("attachfile").value = file;
    }
}
comments:

1 : so what have you tried?

2 : I don't understand your question. Can you explain what you have working, what you have tried and what the problem you're facing is in more detail?

3 : Too little information to get a good response, at the very least, post your working code in the single file case, especially your view code. I think your problem is easily resolved, but without some more context, any answer would involve a lot of guesses and assumptions.


---------------------------------------------------------------------------------------------------------------
Id: 10937905
title: ibatis unsupported sql type for dates
tags: java, sql, ibatis
view_count: 78
body:

I'm working with a huge SQL proc, calling it from my java code via ibatis. I'm getting this error "Unsupported SQL Type 1111", which appears to be coming from the DATETIME parameters of the parameter map that I'm passing in my sql map to the database.

Here is an example parameter from the ibatis map that I am passing a java.util.Date value to:

<parameter property="userSpecifiedTime" jdbcType="DATETIME" javaType="java.util.Date" mode="IN" />

And then the proc on the database is expecting the input parameter as such:

@TM_DT DATETIME = NULL

Anyone else getting the same issue with Datetimes in ibatis? I tried using java.sql.Date instead of java.util.Date but that didn't fix it either.

comments:

1 : Got it! The correct jdbcTpe should be TIMESTAMP, not DATETIME... you can use DATE too but that will trim off the time value. Just don't use DATETIME as it can't be null for some reason


---------------------------------------------------------------------------------------------------------------
Id: 11237354
title: SSL Certificate not Working on Safari
tags: windows, ssl, safari
view_count: 80
body:

We have our site setup to use SSL through a certificate from GoDaddy.com. On every browser except Safari, there are no issues with SSL. However, on Safari on a PC, we cannot access the site. When you try to browse to the site, you either receive a "Select a Certificate" prompt or, a "No Certificate Available" prompt. If you receive the "Select a Certificate" prompt and you choose a valid certificate, the prompt goes away and it looks like the page begins to load, but it just hangs indefinitely.

I have already spoken at length with GoDaddy and they have confirmed that there is not an issue with SSL or the certificate chain.

The server that hosts the site is running Windows Server 2008 - IIS 7. The issue has been reproduced on the latest version of Safari (5.1.7).

This is working fine on a MAC.

Any help would be greatly appreciated!

The site is https://www.nextcrew.com

comments:

1 : Sounds like you should stop requesting a TLS client certificate.

2 : How do you stop requesting a TLS certificate?


---------------------------------------------------------------------------------------------------------------
Id: 10692195
title: How do I embed an image in an html email, if I can't use data:uri's?
tags: .net, html, gmail, html-email
view_count: 94
body:

Google's Gmail can be frustrating. I need to embed a small icon in an email, but Gmail explicity strips out data:uri from <img src="" />.

(Not only that but Gmail doesn't allow "normal" stylesheet inclusion in <head>, so I've gone through and put all styling explicitly in each element.)

I can't host the image on a web server, which would be the simplest alternative to embedding.

Is there a way to show an image inline and send it as an attachment or part of a multipart MIME message? Or some other way to inline an image that would show up in Gmail?

The image in question is a 32x32 PNG icon. I am using C# .NET 4.0 (Winforms).

Related:

comments:

1 : Use your [first option](http://stackoverflow.com/questions/104177/how-do-i-embed-an-image-in-a-net-html-mail-message); it will work with Gmail.


---------------------------------------------------------------------------------------------------------------
Id: 11030628
title: Splitting XML node based on delimiter 'OR' in SQL server
tags: sql, xml, xml-parsing
view_count: 30
body:

I have a XML which needs to be splitted based on 'OR' . IF i have 2 OR's I would be splitting into 2+1 nodes as shown below in [XML2]
[XML1]

<Rules>
<Rule Text="WHEN FamilyCode = 'ABC' AND (PriceDifferentiatorCode In ('DEF', 'GHI') OR ( PriceDifferentiatorCode = 'JKL' AND NameDifferentiatorCode = 'MNO' ) OR (PriceDifferentiatorCode = 'XYZ' AND NameDifferentiatorCode = 'MNO')) THEN 'DummyValue'" />
</Rules>

[XML2]

<Rules>
<Rule RuleText="WHEN FamilyCode = 'ABC' AND PriceDifferentiatorCode In ('DEF', 'GHI')  THEN 'DummyValue'" />
<Rule RuleText="WHEN FamilyCode = 'ABC' AND PriceDifferentiatorCode = 'JKL' AND NameDifferentiatorCode = 'MNO' THEN 'DummyValue'" />
<Rule RuleText="WHEN FamilyCode = 'ABC' AND PriceDifferentiatorCode = 'XYZ' AND NameDifferentiatorCode = 'MNO' THEN 'DummyValue'" />
</Rules>  
comments:

1 : 1) Review your question after you post it. You'd have seen that your XML is not actually "visible". 2) appart from reading the attribute value itself, that question has nothing to do with XML parsing, and is generally hard to understand.

2 : Yeah thats what I was editing my post as soon as I posted it when I observed that nothing is visible.Any ways thanks for editing my post.


---------------------------------------------------------------------------------------------------------------
Id: 11168905
title: android debug on real device install app error
tags: android, eclipse
view_count: 42
body:

When i run debug mode to install my application to an android machine,the eclipse console shows the following error:

06-23 18:49:27.156: E/NetlinkEvent(94): NetlinkEvent::FindParam(): Parameter 'POWER_SUPPLY_ONLINE' not found

but on the AVD it runs fine.

Could any one help me?Thanks.

comments:

1 : http://stackoverflow.com/questions/10318938/netlinklistener-and-netlinkevent-error-messages


---------------------------------------------------------------------------------------------------------------
Id: 8174357
title: not able to install grails 2.0.0.RC1
tags: grails, grails-2.0
view_count: 82
body:

I upgraded my grails to v 2.0, set grails_home to new grails location and updated the path variable, When I do grails -version in the command prompt I get an error like this

Invalid maximum heap size: -Xmx
Could not create the Java virtual machine.

I tried removing all options from Java, grails in the env variables (JAVA_OPTS, GRAILS_OPTS)and it stil throws this error.

Is this a bug in grails 2.0?

comments:

1 : What platform and what JVM are you using?

2 : I am using windows 7 OS , & for java its jdk1.6.0_27

3 : Can you reproduce if you open a new command prompt (`cmd.exe`) and run grails from the command line? What is the output of `echo %JAVA_OPTS%` and `echo %GRAILS_OPTS%`?

4 : I have removed the those environment variables, I am just doing grails -version in the cmd prompt after setting the grails_home and updating path (I was previously using v1.3.7). I can reproduce it anytime I switch to 2.0 , I had JAVA_OPTS and GRAILS_OPTS setup and I was getting the same error, I removed them and still I get the error. I am just wondering if there is some problem with the startGrails script


---------------------------------------------------------------------------------------------------------------
Id: 9634503
title: how to display wave form visualizer without using Open GLES when playing audio in iPhone?
tags: iphone, objective-c
view_count: 231
body:

In my iphone application, i want to add wave forms visualization.How to write the functionality with out using Open GLES? Could you explain which process have to approach for getting waves form visualization when playing any audio files?

Thanking you in advance

comments:

1 : See the little box in the top right hand corner of the page - it might say something like "search". Have you tried typing something in it like "iphone display waveform"?

2 : @Nari -- saved you the trouble http://stackoverflow.com/questions/896194/rendering-a-waveform-on-an-iphone

3 : thank you..@Jaitsu.


---------------------------------------------------------------------------------------------------------------
Id: 8515437
title: Set HTTP Header During UpdatePanel Postback
tags: http, header, updatepanel, postback, set
view_count: 49
body:

Is this possible? Response.AddHeader() does not seem to work.

comments:

1 : On further investigation, AddHeader() in the click event of an UpdatePanel button works fine. It's when combined with a Response.Redirect() to the same page (i.e., a code-behind page refresh) that AddHeader() does nothing. Does anyone know why this is?


---------------------------------------------------------------------------------------------------------------
Id: 9243764
title: How to increase the stack size in Xcode 4.1?
tags: c++, arrays, xcode, stack-size
view_count: 129
body:

The thing is that i want to increase the stack size because the maximum size of an array in a command line project (c++) is 32767 items, (please don't ask why do I need an array of that size), I've already created a pointer with malloc in order to create an "array" bigger than that, but it's exactly the same, that's why I need to increase the size of my stack. . .

I've also tried to split my array in two to create a matrix (f.e. an array with a size of 10000 into a matrix of [100][100] then set the pointer to the begining of the array to emulate a vector), the problem with this is exactly the same i works fine until I try to go beyond 32768 items.

(P.S. The solution is here -> Increase stack size with XCode <-, but I can't find that options in Xcode 4.1)

Thank's in advance!!!

comments:

1 : malloc does not use stack space, it uses the heap. Also, what does "but it's exactly the same" mean, please edit your question to clarify .

2 : As CocoaFu said, stack has nothing to do with `malloc`. How do you know "it's exactly the same"? Maybe your problem is that you're compiling a 16-bit code (seems likely). If so - there's no conventional way (in the scope of C/C++) to create a larger array. On some processors (such as x86) you may address more memory using processor-specific things...


---------------------------------------------------------------------------------------------------------------
Id: 10728781
title: AVAssetExportSession Error -11820 Cannot Complete Export
tags: ios, avassetexportsession
view_count: 177
body:

I'm using an AVComposition to merge two .m4a audio files together. One has to be inserted in the other one at a specific time. I then use an AVAssetExportSession to save the merge audio.

I'm getting this error during the Export Session Completion Handler:

Error Domain=AVFoundationErrorDomain Code=-11820 "Cannot Complete Export" UserInfo=0x1c3760 {NSLocalizedRecoverySuggestion=Try exporting again., NSLocalizedDescription=Cannot Complete Export}

Code - Merging the two assets:

  AVAsset *originalAsset = [AVAsset assetWithURL:url];
NSURL *recordingAssetUrl = [[NSURL fileURLWithPath: NSTemporaryDirectory()] URLByAppendingPathComponent:kRecordTemp];
AVAsset *recordingAsset = [AVAsset assetWithURL:recordingAssetUrl];

AVMutableComposition *composition = [AVMutableComposition new];

AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio 
                                                                 preferredTrackID:kCMPersistentTrackID_Invalid];

//Add the original audio asset to the composition
AVAssetTrack *sourceAudioTrack = [[originalAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
NSError *error = nil;
CMTimeRange sourceRange = CMTimeRangeMake(CMTimeMakeWithSeconds(0, 1), originalAsset.duration);
[audioTrack insertTimeRange:sourceRange ofTrack:sourceAudioTrack atTime:CMTimeMakeWithSeconds(0, 1) error:&error];
if (error) [self showError:error];

//Remove the portion of the original audio asset that will be replaced by the recording
CMTimeRange overwrittenRange = CMTimeRangeMake(self.currentTime, recordingAsset.duration);
[audioTrack removeTimeRange:overwrittenRange];

//Add the recording asset to the composition
AVAssetTrack *recordAudioTrack = [[recordingAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
error = nil;
CMTimeRange recordRange = CMTimeRangeMake(CMTimeMakeWithSeconds(0, 1), recordingAsset.duration);
[audioTrack insertTimeRange:recordRange ofTrack:recordAudioTrack atTime:self.currentTime error:&error];
if (error) [self showError:error];

//Delete the original asset
if([[NSFileManager defaultManager] fileExistsAtPath:url.path]){
    error = nil;
    [[NSFileManager defaultManager] removeItemAtURL:url error:&error];
    if(error) [self showError:error];
}

//Write the composition
AVAssetExportSession * exportSession = [AVAssetExportSession exportSessionWithAsset:composition 
                                                                         presetName:AVAssetExportPresetAppleM4A]; 
exportSession.outputURL = url;
exportSession.outputFileType = AVFileTypeAppleM4A;

[exportSession exportAsynchronouslyWithCompletionHandler:^{
    if(exportSession.status != AVAssetExportSessionStatusCompleted){
        [self showError:exportSession.error];
    }
}];

//Delete the temporary asset
if([[NSFileManager defaultManager] fileExistsAtPath:recordingAssetUrl.path]){
    error = nil;
    [[NSFileManager defaultManager] removeItemAtURL:recordingAssetUrl error:&error];
    if(error) [self showError:error]; //BOOM it blows up here
}

I'm not sure what other piece of code I should paste since it's such a generic error.

I'm using an AVAssetWriter to write the sample buffer to create the recording asset I receive from the capture session. The capture session successfully records and saves into files into the urls used in the above listing.

comments:

1 : CMTimeMakeWithSeconds(0, 1) ? do you want to start from the asset from 0 seconds ..

2 : Sorry, I wasn't clear in what I wanted to do. I want to take everything from the recordingAsset and overwrite the originalAssset with it at self.currentTime.

3 : tri replacing CMTimeMakeWithSeconds(0, 1) with kCMTimeZero

4 : still the same. but the code is cleaner :)

5 : hmm I commented the code deleting the origin asset and changed the export session's url and it works. I guess I'll have to export in a temporary file then delete the original asset on export completion and move the export temporary file.


---------------------------------------------------------------------------------------------------------------
Id: 7069870
title: Building Android Games
tags: android
view_count: 162
body:

I'm kinda familiar with using flash cs5 and so i wanted to know if building android apps using flash and box2d would be better than using game engines like andEngine or rokon. Could someone pls help me out ? Thanks !!

comments:

1 : I guess it would be a nice blog post to compare both technologies.

2 : This is a fairly broad question, I would consider revising and asking something a bit more specific.

3 : I would always recommend using native code over flash on any platform if possible.


---------------------------------------------------------------------------------------------------------------
Id: 10063602
title: Upload swf files using php?
tags: php, file, upload, swf
view_count: 386
body:

This might sounds basic, but thought I'd ask anyway.

What I want to do is upload swf files into a specific folder so users can upload games, and I can have a look at them to make sure they're safe.

I'm not exactly sure how I'd do this though. Here is a simple code I found on w3schools.com that I tried modifying to no avail.

    <?php
if ((($_FILES["file"]["type"] == "application/swf"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "games/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "games/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }

?>

I changed the uploadable file type to application/swf, but when I actually upload a swf file, it just says "invalid file"

I've searched all over google for a swf file uploading script, haven't found anything, so I thought I'd try my luck here.

Thanks

comments:

1 : Try "application/x-shockwave-flash" [http://www.gsp.com/support/virtual/web/conf/mimetypes.html]

2 : Flash file uploading isn't any different from uploading any kind of file - perhaps except for the checking you will want to do to ensure it _is_ a flash file.

3 : Using application/x-shockwave-flash worked, and also did changing the max file size. thanks!


---------------------------------------------------------------------------------------------------------------
Id: 8668673
title: Concurrently filling in drupal forms on different computers mixes up form_state data of the different computers
tags: forms, drupal, module, corruption, ahah
view_count: 39
body:

I'm having a very difficult problem atm, one that I can not explain... at all. I really hope someone here may be able to shed some light on this predicament.

On my website I have a self-developed module that displays some kind of registration form. The registration form consists of different parts:

  1. Personal information
  2. Educational Information
  3. Linguistic Skills
  4. Local/Exchange Specific information
  5. Some optional additional remarks.

Using AHAH and the AHAH Helper module I have created (read: programmed) this form to be 'multipage'. It has the header on top describing what part of the total registration you are currently in, and which parts you have yet to complete. You have a previous/next button to navigate between the different pages of the form. This is all controlled by AHAH, and I keep track of the pages using a hidden form element with a default value 'current_page'. Anyway that is kind of besides the point.

The important part of the above explanation is that the data of all the different parts persists through the different pages by using the form_state variable. AHAH Helper keeps the previous values entered in the form saved in the 'storage' of the form_state.

Now some of the users seem to be experiencing the following problem upon registering: While they are filling in their information, and some AHAH call is triggered in the form (e.g.: Pressing the next button, Checking the email address for validity, checking birthdate for >= 17) after the AHAH call is finished, the values within the form elements, that had already been filled in, have been replaced by completely different values. A name of a different person, his age, his email address etc. Even though this person, I assume that this is what is happening, is filling out the form on a different, private computer, in obviously a different session.

My users do not have to login on the website in order to register using this page, I'm not sure if that is causing an issue?

Anyway, as far as I can tell, I can only recreate the problem when I try filling out the form with different data from different browsers on my computer, concurrently. In that case I can manage to corrupt the form_state data. But as the users are on different, private computers, which presumable use different sessions/cookies/what-not, how is it ever possible for form_state data to be changed to form_state data of another computer who is also filling out the form??

I don't get this? Is there some kind of inherent flaw in using AHAH (& AHAH Helper) for keeping the form_state? If there is, is there some kind of work around? Am I just making a huge newby mistake somewhere in my module code that prevents the form from working correctly?

Is there please, anybody, that can shed even a little bit of light at all on this problem? I am absolutely, and completely clue-less and I can not begin to imagine what is going wrong and how and even IF I can fix it at all. Please help me! :S

Thanks in advance!

Best Regards,

Tom

comments:

1 : Are you able to post the code that builds your form?

2 : Sorry for the late reply. I actually thought I would get an email notication of this. I'll check my settings later. Sharing the code here would be a bit difficult, but I can link you to my github: It starts here at [link]https://github.com/tompauwaert/Buddylinker/blob/master/buddylinker_v2.module on line 304. Then goes to this file: [link]https://github.com/tompauwaert/Buddylinker/blob/master/managers/registration_manager.php. I've just started wondering, could the problem be that I'm using static methods?


---------------------------------------------------------------------------------------------------------------
Id: 9967350
title: Add a link in jQuery vertical content slider
tags: jquery, hyperlink, anchor
view_count: 406
body:

Hey,
I have a vertical slider using jQuery. The navigation is using ID's to slide to the relevant content block. I need to add a link on the content page to be able to slide to a section of the content block. I have pasted the entire code in pastebin please look at the link for the sample. I want to have user click from the about section to the contact page (line 266 is the contact link). - VIEW CODE

comments:

1 : So many caps in the question title. Was your shift key stuck?

2 : @ThiefMaster **WHAT? CAN YOU REPEAT THAT?**


---------------------------------------------------------------------------------------------------------------
Id: 10273695
title: How to serialize a class (JPanel) and why?
tags: java, serialization, jpanel
view_count: 47
body:

How can I serialize a class (JPanel) and why should I?

Thanks!

comments:

1 : If you don't even know why you should do it, why do you need to know *how*? Anyway the answer is that you shouldn't'. See the statement in the Javadoc in the preamble to the class (indeed to any Swing class).


---------------------------------------------------------------------------------------------------------------
Id: 8654853
title: WPF Ways for fire DataGrid.CurrentCellChanged
tags: wpf, datagrid
view_count: 149
body:

Please call, all the ways in which you can change the WPF DataGrid current cell == fire WPF DataGrid.CurrentCellChanged event.

Best regards!

comments:

1 : Please search stackoverflow **thoroughly** first. You will find all the ways.

2 : I found only a change of focus, tell me, what I missed?


---------------------------------------------------------------------------------------------------------------
Id: 9241491
title: How to pass object with parameters via construct
tags: php, class, constructor
view_count: 236
body:

I have a class that relies on several other classes being present. Therefore, I pass these other classes through my construct function and this all works fine. However, when I pass a class that requires a parameter for its own construct function, I get a error saying 'Missing argument 1 for mysql::__construct()...'. What is the best method for passing objects through a class with required parameters?

If you see any potential flaws in this design, please let me know. I am fairly new to Object Orientation and resultantly am still learning.

An example of what I currently have and is not working:

class mysql{
    function __construct($memcache){
        // Construct the object 
    }
}
class company{
    function __construct($databases,$connections,$mysql,$facebook){
        // Construct the object

        // Make the MySQL class available to all the methods
        $this->mysql = $mysql;
    }
}

// Initialize the objects (Company, MySQL, Memcache and Facebook)
$memcache = new memcache;
$facebook = new Facebook($facebook_config);
$mysql = new mysql($memcache);
$company = new company($_DATABASES,$_CONNECTIONS,$mysql,$facebook);

SOLVED UDPATE

The code above is in fact correct, the problem was because I was calling __construct() at the end of one of my methods and I had forgotten to pass the $memcache parameter

comments:

1 : Your code seems ok, when did you get the error?

2 : I thought so too! I just got the error. It occurs when I try to call a method from the mysql object via the company class. I will double check my code to make sure I havent missed anything but I am definitely passing the parameter where I initiate the class.

3 : please give the code which gave the error.

4 : I sincerely apologise, I have managed to find the error. I was calling __construct() at the end of one of my methods and I had completely forgetten to add the $memcache parameter. Really sorry to waste your time, thank you anyway.

5 : You should add an & in front of the given object instance. This creates a reference to the instance instead of copying it to the method. You have to add the & in the headline of the method: function __construct($databases, $connections, &$mysql, &$facebook) {...};

6 : Yes, I am aware of references but have never really understood the point with them. Will this reduce the resource usage of the script? What are the benefits of using references?

7 : @BenCarey Reference works as a link to another variable or object. We still only have one variable/object, but we may have two or more names for it. Example, if we do `$a = 5; $b = &$a;` then $a is really the only variable we have, $b is only a link to $a and if we change $a then $b is also changed. But also, since $b is a link to $a and $a is the only real value, if we change $b then we also change $a.


---------------------------------------------------------------------------------------------------------------
Id: 8517659
title: Can't get user data through facebook OAuth
tags: c#, asp.net, facebook
view_count: 185
body:

We are moving new facebook auth system, however we had some difficulties. Our software gets access_token perfectly but when it tries to get user data over "https://graph.facebook.com/me/?access_token=2213137650421321321|mPvhgRLuSQ_khfggfhfgs" it fails.

{   "error": {
  "message": "An active access token must be used to query information about the current user.",
  "type": "OAuthException"   } }

When i try to get data through "https://graph.facebook.com/myUserId/?access_token=275374459176504|mPvZq1AAoA0iUzjRLuSQ_kdRWns" it works perfectly again.

The main problem is, does "me" work perfectly or am I doing something wrong, what should I do, any ideas?

comments:

1 : App AccessToken vs. User Access token perhaps ?

2 : Are you requesting a new access token each time your user logs in?

3 : Access Token is ok, i have tried with different users. And yes, everytime user log in, it requests new access token.

4 : It sounds like your code is treating **me** as the username, since your authentication token is invalid for that username, your authentication is failing


---------------------------------------------------------------------------------------------------------------
Id: 10947043
title: Typecast an object to generic
tags: android
view_count: 25
body:

I am developing an application where i need to send an object to another class and back to calling class. My code is....

class Generic{
public static byte[] SerializeObject(Object o) {
        byte[] buffer = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        `enter code here`try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            oos.close();
            buffer = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static HelloWorld DeSerializeObject(byte[] buf) {
        HelloWorld d2 = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(
                    new ByteArrayInputStream(buf));
            d2 = (HelloWorld) ois.readObject();
            ois.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        }
        return d2;
    }
}

And i am calling this methods from a different activity like

HelloWorld helloworld=Generic.DeSerializeObject(bytearray);

Now i want to write a generic method to send this object and typecast in this method generically.Is there any method to achieve genericity in JAVA?

comments:

1 : put your code in your question ? [FAQ ?](http://stackoverflow.com/faq)


---------------------------------------------------------------------------------------------------------------
Id: 7513757
title: Setting Header Search Path
tags: iphone, objective-c, xcode
view_count: 99
body:

I need to set the Header Search Path of a library for my project.

While setting, I gave ${SRCROOT}/../Dicom_Image/DicomImage/ITK_BINARY_DIR

which sets the value as /Users/xx/Workspace/ImgProcessing/Dicom_Img_Demo/../Dicom_Image/DicomImage/ITK_BINARY_DIR

where /Users/xx/Workspace/ImgProcessing/Dicom_Img_Demo is the ${SRCROOT} value.

I need to move to the parent directory of the project to set the path from therin.

So the output should be like this: /Users/xx/Workspace/ImgProcessing/Dicom_Image/DicomImage/ITK_BINARY_DIR

Please help.

comments:

1 : It's much easier to just add the library headers directory to your project and let Xcode take care of the rest.

2 : @PaulR - The library is in parent directory of the project and I dont want to add the library directly to the project directory.

3 : You don't need to add the library itself, just the header(s).


---------------------------------------------------------------------------------------------------------------
Id: 10133421
title: On Android Context.getCacheDir() seems to return a directory I cannot create subdirectories in
tags: android, file, caching, permissions, subdirectories
view_count: 310
body:

Does Android not allow creating subdirectories in the cacheDir? Given that third party (such as advendors) surely will need to cache their own files, it makes lots of sense for me to create a subdirectory for my cached files and let third parties I've integrated manage their own cached files.

Does anyone know how to set the permissions so you can create subdirectories?

comments:

1 : How have you determined that "Context.getCacheDir() seems to return a directory [you] cannot create subdirectories in"?

2 : mkdir(s) returns false and any files I try to create in subdirectories aren't there (despite no IOExceptions getting thrown).

3 : Post some code. AFAIK, there is no restriction on creating subdirectories in `getCacheDir()`.


---------------------------------------------------------------------------------------------------------------
Id: 10314231
title: How to reposition an ImageView
tags: android, android-layout, android-imageview
view_count: 25
body:

I have some ImageViews in my xml file. In my code section I want to move an image according to my wish. For that, I've done event.getx() and event.getY() and then use imageView.layout(). This process is not working. How can i move that image?

comments:

1 : check this question http://stackoverflow.com/questions/7168770/how-to-place-views-in-a-specific-location-x-y-coordinates


---------------------------------------------------------------------------------------------------------------
Id: 7722885
title: asp.net button control not working in update panel with asynchonous file upload
tags: ajax, asp.net-ajax, update-panel
view_count: 136
body:

I am working with ASP.Net and AJAX control toolkit 3.5. I put an update panel and put 5 asp.net buttons in it. Then put 5 asp.net panels in it.The intension behind this was when we click on button then corresponding panel will be show. some panels have asynchornous fileupload provided in controltoolkit 3.5. When click on button which corresponding to panel having asynchonous fileupload then other all buttons stop working.

comments:

1 : Can you provide the update panel code ?


---------------------------------------------------------------------------------------------------------------
Id: 10637082
title: Drop down Menu -> Firefox shows lines when body margin is set to 0
tags: css, firefox
view_count: 46
body:

I am implementing a drop down menu, so far using css only. Everything works as expected, however there is a bug in firefox.

When hovering over a parent element the drop down displays correctly. However when the dropped down element collapses again, firefox shows weird lines all across the body. It may not happen right the first time, but eventually these lines are shown, which drives me nuts.

The weird thing is, that this problem only occurs when the body's margin is set to zero.

There is a Demo here:

http://78.46.130.4:8053/drop_menu_test/

Any ideas?

comments:

1 : What version of Firefox are you using? I've got 12 and it's working just fine

2 : Same with me, 12, on Windows 7. I Will try it on my Ubuntu Box in a bit..

3 : No problem on Ubuntu with firefox 12...


---------------------------------------------------------------------------------------------------------------
Id: 9798296
title: iphone popToRootViewControllerAnimated, its animated paramter setting issue
tags: iphone, pop, animated
view_count: 74
body:

See apple doc as below, does it mean we must set parameter animated as NO if we create navigation controller in advance? Such as the case as following. 1. Creat a navigation controller. 2. Push view controllers in navigation controller. 3. Then invoke popToRootViewControllerAnimated.

Ask this question dues to I have experienced many strange issues (including crash) regarding animated setting in my project. Any discussion will be appreciated, thanks in advance.

popToRootViewControllerAnimated:
Parameters
animated
Set this value to YES to animate the transition. Pass NO if you are setting up a  
navigation controller before its view is displayed.
comments:

1 : How do you guys use this method in your project? Thanks.


---------------------------------------------------------------------------------------------------------------
Id: 8572118
title: Embed mp4 video in site
tags: object, video, embed, mp4
view_count: 245
body:

What is the best way to embed a mp4 video in a webpage? I tried quicktime but if the user doesn't have it it takes a really long time. YouTube is not an option at this point. Any other solutions?

Edit: is there any way to use a flash player without being a swf.

(I dont really know much about video embedding, but a tried googling a lot)

Thanks

comments:

1 : possible duplicate of [How can I link to an .mp4 video in my site?](http://stackoverflow.com/questions/7172386/how-can-i-link-to-an-mp4-video-in-my-site)

2 : nope didnt see that one, i will have a look


---------------------------------------------------------------------------------------------------------------
Id: 10056018
title: Trying to compile with codelite
tags: c++, c, compilation, codelite
view_count: 210
body:

I have just downloaded this tarball...Now I wan to compile it cos I found a readme in trunk/projects/gcc that says this:

The Linux GCC and Windows MinGW builds in this project are supported via a CodeLite project file. Codelite is a very cool open source C++ IDE, it can be found here: http://www.codelite.org/ Other GCC build methods aren't actively supported but contributors and maintainers are welcome to do so! Just drop me a line and I'll see about adding you to the project's svn write access list.

So I installed codelite 3.5 and opened the trunk/projects/gcc/libtheoraplayer.workspace with codelite but when I try to run the project (play button) nothing happens..any idea?

Anyway, if anyone knows how to compile that tarball in other way I will be pleased to use it..I tried it using configure-make but i didnt get it..

Ubuntu 11.10

Javier

comments:

1 : Stupid question, but have you compiled it first? The play button only runs the program; it won't compile automatically before running, unless you change the settings to do so.

2 : Do you have `gcc` installed?

3 : @Blender, yess.


---------------------------------------------------------------------------------------------------------------
Id: 10472517
title: jQuery mobile auto hidden footer
tags: jquery-mobile
view_count: 148
body:

I am using jQueryMobile and using [data-position='fixed'] with headers and footers and it is indeed fixed on desktop but when I load the page on iPad the footer is visible for a second but vanishes after the page is completely loaded....
Note that I am using iScroll and also some of data is loaded in page by JSON objects. Would feel pleasure if any one help with a working solution in short.
Thanks

comments:

1 : Try adding this line - $.mobile.fixedToolbars.show(true) in the pageshow event handler for the page


---------------------------------------------------------------------------------------------------------------
Id: 8398461
title: PHP: ZipArchive::extractTo() doesn't complete unzipping
tags: php, zip, ipa, ziparchive
view_count: 136
body:

I'm using ZipArchive to unzip files. It's working great, except for ONE file so far (it's 10.6MB, if that matters).

The problem is, ZipArchive::extractTo() returns FALSE, and that's correct since if fails.

BUT it doesn't completely fails: half of the file is being unzipped, and then it returns FALSE.

As this method doesn't throw any Exception, FALSE is not really great to understand what happened in the middle of that unzipping journey. If anyone already ran into that problem, i'd love some help :) Thanks!

comments:

1 : check if this file has some special character in name, or if the destination folder already exists with a non write permission.

2 : thank you for your answer, but everything is alright on that side. I believe it wouldn't even extract almost half the archive if that was not the case.


---------------------------------------------------------------------------------------------------------------
Id: 10517195
title: Plugins architecture or framework for database driven application
tags: c#, nhibernate, plugins, architecture, spring.net
view_count: 85
body:

Recently I am trying to develop a plugins framework for database driven application. Where the application is developed using Spring.Net and nHibernate. Spring has it's own DI and IoC support. Normally for accessing data I use HibernateTemplate at DAO layer (Which DAO I use at Service Layer for implementing business logic). Now problem is I want to develop application in a modular fashion. For a large scale ERP I want to keep a main application window where Employee management, Product management, Billing, Accounting and all other modules will load as plugins. But each of those modules are internally depended at database level. So please suggest me a better way to develop this kind of application using Spring.Net/nHibernate.

Thanks

comments:

1 : Does not make sense to me. In a DI context plain classes are your plugins contained in arbitrary assemblies glued together either by xml config files or code. What do you need more?


---------------------------------------------------------------------------------------------------------------
Id: 9487602
title: StreamCorruptedException at ObjectOutputStream::writeObject
tags: java, android, sockets
view_count: 97
body:

The below is my class. It simple write a serialized object to socket output stream. I got a strange error at writeObject line. Why?

W/System.err(  576): java.io.StreamCorruptedException
W/System.err(  576):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1712)
W/System.err(  576):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1665)
W/System.err(  576):    at com.megaclient.activity.ControlActivity.sendDelta(ControlActivity.java:92)
W/System.err(  576):    at com.megaclient.activity.ControlActivity.touchTouchPad(ControlActivity.java:68)
W/System.err(  576):    at com.megaclient.activity.ControlActivity.access$0(ControlActivity.java:48)
W/System.err(  576):    at com.megaclient.activity.ControlActivity$1.onTouch(ControlActivity.java:42)
W/System.err(  576):    at android.view.View.dispatchTouchEvent(View.java:3762)
W/System.err(  576):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
W/System.err(  576):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
W/System.err(  576):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
W/System.err(  576):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
W/System.err(  576):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1671)
W/System.err(  576):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
W/System.err(  576):    at android.app.Activity.dispatchTouchEvent(Activity.java:2086)
W/System.err(  576):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1655)
W/System.err(  576):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1785)
W/System.err(  576):    at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(  576):    at android.os.Looper.loop(Looper.java:123)
W/System.err(  576):    at android.app.ActivityThread.main(ActivityThread.java:4627)
W/System.err(  576):    at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(  576):    at java.lang.reflect.Method.invoke(Method.java:521)
W/System.err(  576):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
W/System.err(  576):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
W/System.err(  576):    at dalvik.system.NativeStart.main(Native Method)

My class

public class ControlActivity extends Activity {
...

    public void somewhere() {
    ...
                    final Socket socket = new Socket(host, port);
                    sendDelta(socket, dx, dy);
    ....
    }

    public void sendDelta(final Socket socket, final int dx, final int dy) {
        try {
            final ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            final MegaPoint point = new MegaPoint(dx, dy);
            oos.writeObject(point);

            oos.close();
            socket.close();
        } catch (final StreamCorruptedException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}



public class MegaPoint implements Serializable {

    private final int x, y;

    public MegaPoint(final int x, final int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
comments:

1 : What does the rest of your stack trace look like?

2 : You can copy the log using a normal terminal, run `adb logcat` (given adb is in your path. If it is not, use `cd /path/to/your/androidsdk/platform-tools` followed by `./adb logcat`)


---------------------------------------------------------------------------------------------------------------
Id: 7995125
title: Is there any free tool out there to simply duplicate a Visual Studio project?
tags: visual-studio, visual-studio-2010, extension, project, code-duplication
view_count: 62
body:

I am aware of the manual procedure presented here and of this commercial product, but I am wondering if you know a (free) Visual Studio extension (e.g. allowing project copy/paste) or standalone tool that can properly duplicate a project (with new assembly IDs, name etc).

Thanks!

comments:

1 : Copy and changing the ID seems simple. Do you have to do it very often where tools and automation are warranted? Maybe that's the problem?

2 : Not often I must say, but I would appreciate a copy/paste shortcut to do it when needed.


---------------------------------------------------------------------------------------------------------------
Id: 7551027
title: Not able to see the Text in QML Application
tags: linux, qt, qml, qt4.7
view_count: 87
body:

I am developing QML+JavaScript application on Linux system.
When i run my application I am not able to see the Texts in the QML screens, Text on Labels, Buttons and Text Input fields are not visible.

I have configured QT-4.7.2 using following configure command:

./configure -webkit -no-openssl -script -scripttools -declarative -prefix /usr/local/Trolltech/Qt-4.7.2

When I run only ./configure command with the default options, I am able to see the Text but QT JavaScript Interpreter engine starts behaving weird, when I use default options I face issues with XMLHTTPRequest object, My application is using XMLHTTPRequests.

Can some one please tell me what all the configuration options we need to provide while configuring QT-4.7.2 for Linux.

Thanks.

comments:

1 : What platform is exactly? Did you build it yourself? Are you working over X11? Have you tried adding -fontconfig to the configure script?


---------------------------------------------------------------------------------------------------------------
Id: 8509472
title: Trouble with vwprintf/vswprintf on OS X
tags: c, osx, printf, vswprintf
view_count: 97
body:

To give more detail I am writing the code using C for OS X using XCode 4.2 and the LLVM GCC 4.2.2 compiler.

I have a variable argument function - I include the entire function for completeness although I /believe/ most of it to be irrelevant, the only problem I have is with how vswprintf behaves in some cases.

void FTFRenderText( const struct FTFFont* const pxFont,
               const int iStartX, const int iStartY,
               const wchar_t* const wszFormatString,
               ... )
{
    if( !pxFont || !( pxFont->mbValid ) )
    {
        return;
    }

    static wchar_t lswszBuffer[ 2048 ];    
    va_list xArguments;
    va_start( xArguments, wszFormatString );
    //
    // SE - TODO: remove
    vwprintf( wszFormatString, xArguments );
    va_end( xArguments );
    va_start( xArguments, wszFormatString );
    //
    vswprintf( lswszBuffer, 2048, wszFormatString, xArguments );
    va_end( xArguments );
    const struct FTFTriList xTriList =
        FTFCreateTriListFromText( pxFont, iStartX, iStartY, lswszBuffer );

    const int iIndexCount = xTriList.miNumIndices;
    if( iIndexCount )
    {
        // SE - TODO: something to allow user selected colour
        glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
        glVertexPointer( 2, GL_FLOAT, 0, xTriList.mpfVertices );
        glDrawElements(
            GL_TRIANGLES, iIndexCount, GL_UNSIGNED_SHORT, xTriList.mpsIndices );
    }
}

Perhaps I am being dim but it seems that if I pass in a simple enough set of parameters like "Test %d", 101 the functions work fine. However if I pass in a string with a unicode character, either as a literal or using \uXXXX the string I get back from vswprintf is completely empty In the debugger I can see the the compiler has done the right thing with the string in memory, and it contains the unicode character - but the string written to by vswprintf is all 0s.

Comparing with wprintf and vwprintf is interesting - because both seem to behave as I expect and produce the expected unicode character from both a literal and the \uXXXX escaping.

I am loathe to suggest the library is buggy because a great number of other libraries and apps have been built on top just fine, so I think I am doing something wrong, but I just can't see what it could possibly be...

Any suggestions or help would be greatly appreciated.

comments:

1 : Is the (variadic) string that you're passing in a `wchar_t` string, or a `char` string using (e.g.) UTF-8 or similar? ? i.e. is the "string in memory" being stored multibyte?

2 : So far I have only used literal wide strings, e.g. L"Test %d" - from inspecting memory the compiler seems to produce the correct wchar_t (32-bit) string of character codes

3 : a copy-pasted example for exactness: FTFRenderText(&gxFont, 100, 500, L"%%" );

4 : So the Unicode chars are in the format string, itself, not params to it (e.g. `FTFRenderText (font, x, y, L"%ls", L"??????")` vs. `FTFRenderText (font, x, y, L"?????%d", 4)` ? ? (apologies if Google Translate stuck anything rude in there?!)

5 : Ouch. Sorry, I'm out of ideas :-) I was hoping for something along the usual lines of `%s` vs. `%ls` vs. bad pointers in the variadic, which would be unlikely here, but plausible. If you're passing in a format string with the content already in it, that line of questioning won't help? sorry. :-/

6 : np. the problem occurs if i use unicode in the format string specifically.


---------------------------------------------------------------------------------------------------------------
Id: 10881551
title: Calling Shell Script function from a perl script
tags: perl, function, shell, dynamic
view_count: 112
body:

There was a related post regarding this issue.

My code in Perl script to call the shell script with functions ..

`. shellScript.sh $var1 $var2 $var3 $var4; shellFunc1 $var5 $var6`

But the problem I am facing is there is an dynamic variable resides in shellScript.sh

Here is a high level coding of shellScript.sh

happy=${var1}hello
holiday=${var2}bye

function shellFunc1 {

         cap1=$1
         cap2=$2

if [[ "$cap1" == "happy" ]] || [[ "$cap2" == "holiday" ]]
then
    echo ${!happy}
    echo ${!holiday}
fi

Error

sh: ${!happy}: 0403-011 The specified substitution is not valid for this command.
sh: "${!holiday}": 0403-011 The specified substitution is not valid for this command.

This is not the real code. Just an example. It was working fine when I am calling this from another shell script. But not working when calling from a Perl script.The dynamic varible creating problem. I would like to know is it possible or do I have to change my code completely.(Before changing the code I wanted to confirm from the Perl Gurus)

If possible can anybody please help me on the same.

comments:

1 : What is your problem, exactly?

2 : Why this is closed?

3 : When I am trying to access to shell function I am getting the error mentioned in my post.

4 : This is a perfectly valid question, and should be re=opened. The problem may be that perl's backtick operator uses `csh`, and your shell script is lacking a proper shebang line to change interpreter.

5 : Thanks William. Is there any other way of calling it? I tried system function its not working either. Do I have to call the script every time I call the function ?

6 : I will re-open this question provided that @avirup can provide a [sscce](http://sscce.org/) that is runnable and demonstrates the problem in hand.


---------------------------------------------------------------------------------------------------------------
Id: 7487799
title: iterating through and changing values in a form
tags: javascript
view_count: 30
body:

I have a html form where the id of each element is labeled like a spreadsheet. (Sheet1_A1). I need to iterate a column of entries and change the values. Those values are loaded from a csv file on the server and placed into an array with javascript and jquery. How would it be possible to change those values in the specific id's upon document load?

comments:

1 : What have you tried? What specifically did not work about your approach?

2 : please provide an example of your html


---------------------------------------------------------------------------------------------------------------
Id: 7550080
title: Getting Resource Urls From Assembly
tags: .net, asp.net, razor, asp.net-webpages
view_count: 48
body:

In ASP.NET web forms, you can use this component to extract a JS file that's embedded in a DLL: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getwebresourceurl.aspx. This would also work in ASP.NET MVC since it used the ASP.NET framework.

Since Razor isn't leveraging the ASP.NET framework, is it even possible to extract a resource out of an assembly? Maybe by dynamically constructing the Page class? Or is it not supported?

Thanks.

comments:

1 : I am guessing you aren't working with ASP.NET Web Pages since that is something different from ASP.NET MVC. It is typically seen as the system used by [WebMatrix](http://www.asp.net/web-pages). Assuming you are actually working in ASP.NET MVC with the Razor view engine, you can probably find an answer here: http://stackoverflow.com/questions/5665279/getwebresourceurl-equivalent-for-asp-net-mvc


---------------------------------------------------------------------------------------------------------------
Id: 10882694
title: Spring's RestTemplate and prefix in JSON body
tags: json, spring, jackson, resttemplate
view_count: 198
body:

I'd like to use RestTemplate to obtain response from server and process that response in my Android app, but server answers with prefix (or variable) in json body, so response looks similar to this:

response={"foo":"bar"}

Is it possible to omit that "response=" part som simple way, or do I need to reimplement MappingJacksonHttpMessageConverter class?

Thanks in advance

Edit: It works now, following code is based on newest SpringAndroid (1.0.0 RELEASE). RestTEplate(true) constructor adds required convertors and request.toMap() builds a MultiValueMap, which is only body type FormHttpMessageConverter accepts.

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application", "x-www-form-urlencoded"));

RestTemplate restTemplate = new RestTemplate(true);
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

final String url = "http://www.dummy.org/herp/getDerp";
String result = restTemplate.postForObject(url, request.toMap(), String.class);

Now I have string on output, from which I can extract JSON and parse that.

comments:

1 : Server side is not mine, so I cant modify it. And yes, response={"foo":"bar"} is whole response body.

2 : What fields are within CheckLoginResponse, does it have a field for...well...foo in this case. When it maps the object, the field names in the json should match the fields in the pojo.

3 : Do you mind posting the code you're using to obtain the response?

4 : Just added piece of code, but I think it's not important.

5 : Wouldn't you just parse the response with a jackson mapper?

6 : I think it can parse messages like {"foo":"bar"}, not response={"foo":"bar"}

7 : Right, I'm just wondering how you know there is a response={"foo":"bar"} is it part of the result in the body, if so, how is it being stored, etc.

8 : Thank you, dardo, it works now - please see edited question. My problem was not resposne, but request - FormHttpMessageConverter does not accept anything, but MultiValueMap.


---------------------------------------------------------------------------------------------------------------
Id: 10474368
title: Element is already the child of another element - wp7
tags: windows-phone-7, parent-child
view_count: 130
body:

Edited

I have a paragraph object attached to a richtextbox. I've created a click event to switch between two paragraphs in the richTextBOx, but I always get this exception even that i'm clearing the richTetxBox. My code

    public bool Collapsed
    {
        set
        {
            _collapsed = value;

            Paragraph p = new Paragraph();
            richTextBox.Blocks.Clear();

            if (_collapsed)
            {
                p = backupParagraph;
                richTextBox.Blocks.Add(p);
            }
            else
            {
                p = paragraph;
                richTextBox.Blocks.Add(p);
            }

        }
        get
        {
            return _collapsed;
        }
    }

I have an event which fired when user tap the object

     void rtb_Tap(object sender, GestureEventArgs e)
    {
        Collapsed = !_collapsed;
    }

And trying this I had this in my mainPage

            p.Title = "Tryout";
        p.Text = "Hello Hello <small>Hello</small> Hello, <b>is it gonna</b> change? <big>why</big> <small>don't</small>";
        p.Collapsed = true;

        ContentPanel2.Children.Add(p.richTextBox);  

Now when I tap the object, I get the error.

Any suggestions?

comments:

1 : Make sure that you have added the rich text box or paragraph text in another control. Or just post your codes fully i will help you

2 : I'm afraid you have to create a copy of either backupParagraph or paragraph before adding them to Blocks property again. As far as I know, this is a known Silverlight bug. reagards,

3 : Well I tried to do so. I have created an inner type paragraph which initialized every time I call collapsed, and it still giving me that exception.


---------------------------------------------------------------------------------------------------------------
Id: 9989435
title: An applet is working on local but not in a server
tags: java, apache, applet, japplet
view_count: 59
body:

I have a problem with an applet on a html.

If I run my applet.html with an address as c :/ wamp / www / test / applet.html, my applet works great.

If I run this with an address as applet.html http://127.0.0.1:8888/test/applet.html, nothing happens. No error in the java console, no error in the applet on the page (still loading).

Do you have an idea?

I said that my JARS are signed .....

Thank you!

comments:

1 : Still loading? I recently written an applet and tested it in Firefox. Sometimes it just gets stuck on loading so I need to restart the browser.

2 : Alternatively, enable the Java console and use the `x:clear classloader cache` command.

3 : Try launching the applet free-floating using [JWS](http://stackoverflow.com/tags/java-web-start/info) & see if the problem persists.


---------------------------------------------------------------------------------------------------------------
Id: 10612129
title: Illegal mix of collations in ejb
tags: mysql, ejb
view_count: 52
body:

On MySQL 5.1 with a database collation of latin1_general_ci, I get this Exception when I UPDATE:

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Illegal mix of collations (latin1_general_ci,IMPLICIT) and (latin1_swedish_ci,IMPLICIT) for operation '='
Error Code: 1267
Call: UPDATE medicaltestdetails, TL_medicaltestdetails SET medicaltestdetails.Status = TL_medicaltestdetails.Status WHERE medicaltestdetails.TestDate = TL_medicaltestdetails.TestDate AND medicaltestdetails.TestSerial = TL_medicaltestdetails.TestSerial AND medicaltestdetails.ConsultantId = TL_medicaltestdetails.ConsultantId AND medicaltestdetails.TestTime = TL_medicaltestdetails.TestTime
Query: UpdateAllQuery(referenceClass=Medicaltestdetails sql="CREATE TEMPORARY TABLE IF NOT EXISTS TL_medicaltestdetails (Chg BIGINT, Remarks VARCHAR(255), Result VARCHAR(255), Status VARCHAR(255), TestDesc VARCHAR(255), TestType VARCHAR(255), TestDate DATE NOT NULL, TestSerial VARCHAR(255) NOT NULL, ConsultantId VARCHAR(255) NOT NULL, TestTime INTEGER NOT NULL, PRIMARY KEY (TestDate, TestSerial, ConsultantId, TestTime))")

Please help me to resolve this problem.

comments:

1 : Please post the output of `SHOW CREATE TABLE` for both `medicaltestdetails` and `TL_medicaltestdetails`.


---------------------------------------------------------------------------------------------------------------
Id: 10509180
title: Paypal recurring payment Api method calls returns the empty transaction ID
tags: c#, paypal, paypal-api
view_count: 102
body:

I am using the recurring payment in my application.There is no error in carrying out the operation.The acknowledgement or status message from the paypal is success when i make the payment in the current date.But the result gives me empty transaction id.I get the profile ID for the transaction however.Please advise if its ok or there is something wrong while carrying out the transaction. Edit:I checked after logging into my test account.I can see that the payment has occurred successfully for the paypal.But not able to figure out why the transaction id is not visible while completing the payment.The transaction id is empty while i debug the payment process using visual studio.

Regards, S.

comments:

1 : Can you post the request and resposne?


---------------------------------------------------------------------------------------------------------------
Id: 9958456
title: Text-bottom in Opera
tags: css
view_count: 30
body:

The following doesn't work in Opera:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<style type="text/css">
p {font:10pt Arial; background:green; height:16px;}
img {width:16px; height:16px; vertical-align:text-bottom;}
</style>
</head>
<body>
<p>An <img src="https://ssl.gstatic.com/images/icons/gplus-16.png" alt=""> image with a text-bottom alignment.</p>
</body>
</html>

Is it a bug or am I missing something?

Thanks!

comments:

1 : Please define "doesn't work".

2 : @JamesMontagne: The image position doesn't look right. I tried it in other browsers with no problem.

3 : doesn't look right? it doesn't vertical align as you want? can you post a screen? here i can't see what could be wrong http://jsfiddle.net/25K9y/1/


---------------------------------------------------------------------------------------------------------------
Id: 7367387
title: Rails, Nested Models, Arrays, Iterating through a "for" loop
tags: ruby-on-rails, arrays, models
view_count: 210
body:

I'm new to Ruby and following this novawave tutorial (a little older) on creating an internal messaging system.

http://www.novawave.net/public/rails_messaging_tutorial.html

I'm currently attempting to list the sent messages, but I am unable to properly link to the message "recipients." Here is the for loop:

 <% for message in @messages %>
  <tr>
  <td><%= message.user.name %></td>

   <td><%= message.subject %></td>
   <td><%= message.recipients.map(&:user).to_sentence %></td>

I'm getting an "unitialized constant" error for "recipients" I have three models: User, Message_Copy, and Message.

Message Model belongs_to User,
has_many :recipients, :through => :message_copies

Message_Copy model belongs_to Message and recipient

User model has_many of the other models.

I've noticed this same problem in other applications. When I iterate through the array, if the primary model "belongs to" another model, I can access that model. For example, I can access the User model because the Message model "belongs_to" the User model. Hence I can use message.user.name. But I cannot access the attributes of a model that "belongs_to" the primary model. So I cannot access the Message_Copy model attributes in this array. So message.recipient.id will return an error. This question may have already been answered, and I may just be making a series of easy mistakes. But I'm confused and was hoping someone could help and possibly explain what I'm missing. Please let me know if more informaiton is required. Thank you

Apologies, here is more code from the models: User Model

class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation

has_many :sent_messages, :class_name => "Message"
has_many :received_messages, :class_name => "MessageCopy", :foreign_key =>"recipient_id"
has_many :folders

class MessageCopy < ActiveRecord::Base
  belongs_to :message
  belongs_to :recipient
  belongs_to :folder

delegate   :user, :created_at, :subject, :body, :recipients, :to => :message
end

class Message < ActiveRecord::Base

 belongs_to :user
 has_many :message_copies 
  has_many :recipients, :through => :message_copies
  before_create :prepare_copies

   attr_accessor  :to # array of people to send to
   attr_accessible :subject, :body, :to  

  def prepare_copies  
   return if to.blank?

     to.each do |recipient|
       recipient = User.find(recipient)
       @recipient=recipient
  message_copies.build(:recipient_id => recipient.id, :folder_id =>   recipient.inbox.id)
     end
   end    
 end

I noticed this worked: <%= message.message_copies %>

Instead of the above code:

<td><%= message.recipients %></td>

I don't understand this because the tutorial can use "recipients" and also because I can reference the Message_Copy model through Recipients in other methods.

But <%= message.message_copies %> also just returns an array, and I'm unclear how I can reach the specific attributes in the message_copy model, since <%= message.message_copies.content %> does not work.

Thank you! I'll post more code if necessary

comments:

1 : Please post the code from your models.

2 : Wow- two hours later I realize that I didn't include this line in the Message_Copy model ":class_name=>"User." So it should've said- belongs_to :recipient, :class_name => "User" That's really frustrating. I'm still not really sure what's going on, but at least it works. I'll stare at it for another two hours in the hope that it starts making sense!

3 : Basically it's saying to use the User model for recipient relationship. When you don't specify class_name it will attempt to infer the proper model, but in your case it couldn't figure out what model to use for the relationship, hence the error.

4 : Thank you, I'm just new to rails and trying to get used to the structure. Any info helps.


---------------------------------------------------------------------------------------------------------------