I only want the first occurrence of a node in XML/XSLT document. XPath is returning all even with [1]

I need to select only the first occurrence of the <fo:table ...> node in the following XSL-FO templace, but xPath is returning all of them.  Here is the XPath statement I'm using after creating a wrapper element with all the namespaces:

<fo:wrapper xmlns:fo="http://www.w3.org/1999/XSL/Format"
    xmlns:j4luserext="xalan://com.java4less.xreport.fop.XLSTDummyExtension"
    xmlns:j4lext="xalan://com.java4less.xreport.fop.XLSTExtension"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:j4lif="http://java4less.com/fop/iform">

    {xsl:stylesheet/xsl:template/fo:root/fo:page-sequence/fo:flow/fo:table/
        fo:table-body/fo:table-row/fo:table-cell/fo:block/fo:table[1]}
</fo:wrapper>

And here is the XSL-FO input:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:j4lif="http://java4less.com/fop/iform"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:j4lext="xalan://com.java4less.xreport.fop.XLSTExtension"
extension-element-prefixes="j4lext j4luserext"
xmlns:j4luserext="xalan://com.java4less.xreport.fop.XLSTDummyExtension">
<xsl:template match="/">
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
        <fo:layout-master-set>
            <fo:simple-page-master master-name="master0"
                page-width="21.0cm" page-height="29.7cm" margin-top="2.0cm"
                margin-bottom="2.0cm" margin-left="2.0cm" margin-right="2.0cm">
                <fo:region-body region-name="body0" margin-top="1.5cm"
                    margin-bottom="1.5cm" />
                <fo:region-before region-name="header0" extent="1.5cm" />
                <fo:region-after region-name="footer0" extent="1.5cm" />
            </fo:simple-page-master>
        </fo:layout-master-set>
        <fo:page-sequence master-reference="master0">
            <fo:static-content flow-name="header0">
                <!-- 846098b14a344ae29ebeb7d3c3ae73c0 -->
                <fo:table width="17.0cm">
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="1.5cm">
                            <fo:table-cell>
                                <fo:table>
                                    <fo:table-column column-width="17.0cm" />
                                    <fo:table-body>
                                        <fo:table-row background-color="#ffffff" height="1.5cm">
                                            <fo:table-cell number-columns-spanned="1">
                                                <fo:block></fo:block>
                                            </fo:table-cell>
                                        </fo:table-row>
                                    </fo:table-body>
                                </fo:table>
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:static-content>
            <fo:static-content flow-name="footer0">
                <!-- b468381816be4ef8bb31f448a8bf5b09 -->
                <fo:table width="17.0cm">
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="1.5cm">
                            <fo:table-cell>
                                <fo:table>
                                    <fo:table-column column-width="17.0cm" />
                                    <fo:table-body>
                                        <fo:table-row background-color="#ffffff" height="1.5cm">
                                            <fo:table-cell number-columns-spanned="1">
                                                <fo:block></fo:block>
                                            </fo:table-cell>
                                        </fo:table-row>
                                    </fo:table-body>
                                </fo:table>
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:static-content>
            <fo:flow flow-name="body0">

                <!-- START Area Header -->
                <!-- 4ce697eac861472391f5eac35a51db48 -->
                <fo:table width="17.0cm">
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="1.5cm">
                            <fo:table-cell>
                                <fo:table>
                                    <fo:table-column column-width="17.0cm" />
                                    <fo:table-body>
                                        <fo:table-row background-color="#ffffff" height="1.5cm">
                                            <fo:table-cell number-columns-spanned="1">
                                                <fo:block></fo:block>
                                            </fo:table-cell>
                                        </fo:table-row>
                                    </fo:table-body>
                                </fo:table>
                            </fo:table-cell>
                        </fo:table-row>
                        <fo:table-row>
                            <fo:table-cell number-columns-spanned="1">
                                <fo:block>

                                    <!-- START Area Detail -->
                                    <!-- 7f22844da7e94220b5877bf7593e1dcb -->
                                    <fo:table width="17.0cm">
                                        <fo:table-column column-width="17.0cm" />
                                        <!-- 63bbf10b61f44321913cffd695225a53 -->
                                        <fo:table-header>
                                            <fo:table-row background-color="#ffffff"
                                                height="2.0cm">
                                                <fo:table-cell>
                                                    <fo:table>
                                                        <fo:table-column column-width="17.0cm" />
                                                        <fo:table-body>
                                                            <fo:table-row background-color="#ffffff"
                                                                height="2.0cm">
                                                                <fo:table-cell number-columns-spanned="1">
                                                                    <fo:block></fo:block>
                                                                </fo:table-cell>
                                                            </fo:table-row>
                                                        </fo:table-body>
                                                    </fo:table>
                                                </fo:table-cell>
                                            </fo:table-row>
                                        </fo:table-header>
                                        <fo:table-body>
                                            <fo:table-row background-color="#ffffff"
                                                height="4.0cm">
                                                <fo:table-cell>
                                                    <fo:table>
                                                        <fo:table-column column-width="17.0cm" />
                                                        <fo:table-body>
                                                            <fo:table-row background-color="#ffffff"
                                                                height="4.0cm">
                                                                <fo:table-cell number-columns-spanned="1">
                                                                    <fo:block></fo:block>
                                                                </fo:table-cell>
                                                            </fo:table-row>
                                                        </fo:table-body>
                                                    </fo:table>
                                                </fo:table-cell>
                                            </fo:table-row>
                                        </fo:table-body>
                                    </fo:table>

                                    <!-- END Area Detail -->
                                </fo:block>
                            </fo:table-cell>
                        </fo:table-row>
                        <fo:table-row>
                            <fo:table-cell number-columns-spanned="1">
                                <fo:block>

                                    <!-- START Area Footer -->
                                    <!-- ae182bb24f5648da9653ed5b997121c4 -->
                                    <fo:table width="17.0cm">
                                        <fo:table-column column-width="17.0cm" />
                                        <fo:table-body>
                                            <fo:table-row background-color="#ffffff"
                                                height="1.5cm">
                                                <fo:table-cell>
                                                    <fo:table>
                                                        <fo:table-column column-width="17.0cm" />
                                                        <fo:table-body>
                                                            <fo:table-row background-color="#ffffff"
                                                                height="1.5cm">
                                                                <fo:table-cell number-columns-spanned="1">
                                                                    <fo:block></fo:block>
                                                                </fo:table-cell>
                                                            </fo:table-row>
                                                        </fo:table-body>
                                                    </fo:table>
                                                </fo:table-cell>
                                            </fo:table-row>
                                        </fo:table-body>
                                    </fo:table>

                                    <!-- END Area Footer -->
                                </fo:block>
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>

                <!-- END Area Header -->
                <fo:block id="last-page" />
            </fo:flow>
        </fo:page-sequence>
    </fo:root>
</xsl:template>
</xsl:stylesheet>

This is what I expect as output:

<fo:wrapper xmlns:j4lif="http://java4less.com/fop/iform"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:j4lext="xalan://com.java4less.xreport.fop.XLSTExtension"
xmlns:j4luserext="xalan://com.java4less.xreport.fop.XLSTDummyExtension"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:table width="17.0cm">
    <fo:table-column column-width="17.0cm" />
    <!-- 63bbf10b61f44321913cffd695225a53 -->
    <fo:table-header>
        <fo:table-row background-color="#ffffff" height="2.0cm">
            <fo:table-cell>
                <fo:table>
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="2.0cm">
                            <fo:table-cell number-columns-spanned="1">
                                <fo:block />
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:table-cell>
        </fo:table-row>
    </fo:table-header>
</fo:table>
</fo:wrapper>

This is what BaseX and Camel xQuery component actually outputs:

<fo:wrapper xmlns:j4lif="http://java4less.com/fop/iform"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:j4lext="xalan://com.java4less.xreport.fop.XLSTExtension"
xmlns:j4luserext="xalan://com.java4less.xreport.fop.XLSTDummyExtension"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:table width="17.0cm">
    <fo:table-column column-width="17.0cm" />
    <!-- 63bbf10b61f44321913cffd695225a53 -->
    <fo:table-header>
        <fo:table-row background-color="#ffffff" height="2.0cm">
            <fo:table-cell>
                <fo:table>
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="2.0cm">
                            <fo:table-cell number-columns-spanned="1">
                                <fo:block />
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:table-cell>
        </fo:table-row>
    </fo:table-header>
    <fo:table-body>
        <fo:table-row background-color="#ffffff" height="4.0cm">
            <fo:table-cell>
                <fo:table>
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="4.0cm">
                            <fo:table-cell number-columns-spanned="1">
                                <fo:block />
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:table-cell>
        </fo:table-row>
    </fo:table-body>
</fo:table>
<fo:table width="17.0cm">
    <fo:table-column column-width="17.0cm" />
    <fo:table-body>
        <fo:table-row background-color="#ffffff" height="1.5cm">
            <fo:table-cell>
                <fo:table>
                    <fo:table-column column-width="17.0cm" />
                    <fo:table-body>
                        <fo:table-row background-color="#ffffff" height="1.5cm">
                            <fo:table-cell number-columns-spanned="1">
                                <fo:block />
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:table-cell>
        </fo:table-row>
    </fo:table-body>
</fo:table>
</fo:wrapper>

I don't want that second table node.  Since /fo:table[1] doesn't work, I've tried putting predicates in there such as /fo:table[fo:table-column/fo:table-row[2]] and nothing is returned.  Oddly, even /fo:table[fo:table-column/fo:table-row] returns nothing, but /fo:table[fo:table-column] returns the same unwanted 2nd table node. Anyone have any idea what's going on here?


Error in importing a csv file in mongoDB2.4

I have installed mongoDB2.4 installed in my windows 7 os. I am new to mongoDB. I would like to import data from a csv file into the database. I have used the mongoimport command but it shows:
Javascript execution failed: Syntax error: Unexpected identifier

my command in mongo shell was:

mongoimport --db mentalhealth --collection bidyut --type csv --file \Users\Adrian\Desktop\Data_sorted.csv

PLEASE kindly provide an answer.


Brew gettext on Mac OS X Terminal

I installed gettext with brew and the path to gettext is

/usr/local/Cellar/gettext/0.18.3.1/bin

my PHP-Project is located under /Applications/XAMPP/xamppfiles/htdocs/projectMine

The files I want to translate are in /Applications/XAMPP/xamppfiles/htdochs/projectMine/public_html

When I'm now in the bin folder I type

./gettext /Applications/XAMPP/xamppfiles/htdocs/projectMine/public_html

I also tried this one here, but this didn't seem to work either.

/usr/local/Cellar/gettext/0.18.3.1/bin/gettext -n /Applications/PATHTOFOLDER

but this results in nothing. What is the exact command to achieve this. I'm new to Mac and Terminal, because I'm normally a Windows user.


Adding multile row in the girdview

Adding the row one by one in the button click..
(i tried but its overwirting the same row)


How to run sql scripts serially in bash script?

I have 2 DB2 sql scripts that I need to run. I have tried to put both of them in bash script and execute them.

here is script.sh:

#!/bin/bash
db2 -tf firstscript.sql;
db2 -tf secondscript.sql;

When I run this, I get the following error:

DB21034E  The command was processed as an SQL statement because it was
  not a valid Command Line Processor command.  During SQL processing it
  returned: SQL1024N  A database connection does not exist.
  SQLSTATE=08003

But I have made sure that the database connection already exists.

I think that the commands inside the sql scripts are not executed sequentially.
Because when I run each command individually, there is no error.
Also, when I run both the commands inline i.e. db2 -tf firstscript.sql;db2 -tf firstscript.sql, even then the code works.

I thought that it could have something to do with #!/bin/bash, so I removed it from the script.sh file and then executed it. Even then, it returned the same error.

What would be the possible problem and its solution?


CIBIL api integration

I am facing a problem in CIBIL api integration, When we hit CIBIL api we get response in machine readable TUEF format and that is very difficult to parse, So is their a way to get response in XML format.
CIBIL = Credit Information Bureau (INDIA) Limited.


userControl repeated with Form tag disappearing

I have a Contact userControl that have "save contact" as submit button and fields inside form tag we repeat this userControl with Code 20 times in one page

My problem is the Form Tag in the first userControl is hiding somehow --- i checked the userControl with developer Tool IE9 , firebug Firefox7 and the Form is not appearing in the first userControl and its appearing with the rest 19 Controls

I tried to View Source and take html copy in new html file in VS -- i found form is exist

i dont know if iam clear enough but please advice if you need more info


Nested Cell to string

I have the following problem:

Objective (high-level):
I would like to convert ESRI Shapefiles into SQL spatial data. For that purpose, I need to adapt the synthax.

Current status / problem:
I constructed a the following cell array:

'MULTIPOLYGON('    {1x2332 cell}    ','    {1x916 cell}    ','    {1x391 cell}    ','    {1x265 cell}    ')'

with in total 9 fields. This cell array contains the following 'nested' cell arrays: {1x2332 cell}, {1x916 cell}, {1x391 cell}, {1x265 cell}. As an example, 'nested' cell {1x2332 cell} has the following form:

'(('    [12.714606000000000]    [42.155628000000000]    ','    [12.702529999999999]    [42.152873999999997]    ',' ... ','    [12.714606000000000]    [42.155628000000000]    '))'

However, I would like to have the entire cell array (including all 'nested cells') as one string without any spaces (except the space between the numbers (coordinates)). Would you have an idea how I could get to a solution?

Thank you in advance.


How to increase the space (Data Space Total) used by Docker ? That value is less than half on the disk size

Many times, I have this error when building Dockerfile :

devmapper: Thin Pool has 157168 free data blocks which is less than minimum required 163840 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior

My disk has at all 250Go and when I execute docker version, I can see in storage part :

Storage Driver: devicemapper
 Pool Name: docker-253:0-19468577-pool
 Pool Blocksize: 65.54kB
 Base Device Size: 21.47GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 97.03GB
 Data Space Total: 107.4GB
 Data Space Available: 10.35GB
 Metadata Space Used: 83.67MB
 Metadata Space Total: 2.147GB
 Metadata Space Available: 2.064GB
 Thin Pool Minimum Free Space: 10.74GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)

I tried after stopping docker service :
I tried :

dockerd --storage-opt dm.thinpooldev dm.min_free_space=3%
dockerd --storage-opt  dm.thinp_autoextend_percent

But those command doesn't succed.

How to increase the Data Space Total (the free space on the disk is more than 2 times 107.4GB) ?
Or How to decrease the Thin Pool Minimum Free Space: 10.74GB ?


PostgreSQL. Slow Prepare Transaction and Commit Prepared

I've just encountered a strange problem. I've made a report in pgfourine, and found out that  my XA transactions started to work really slow. Prepare transaction and commit prepared combined took 12.55s out of 13.2s. But why?

#####  Overall statistics  #####

Number of unique normalized queries: 175
Number of queries:     268,772
Total query duration:  13m2s

#####  Queries by type  #####

SELECT:    116493     43.3%
INSERT:     15926      5.9%
UPDATE:      7935      3.0%
DELETE:      4923      1.8%

#####  Queries that took up the most time (N)  #####

1) 6m32s - 26,338 - COMMIT PREPARED ''
--
2) 6m23s - 25,972 - PREPARE TRANSACTION ''
--
3) 0.6s - 3,848 - update avatar set lfa_position=NULL where Id=0
.....
7) 0.3s - 21,514 - COMMIT
.....

I have a theory but don't have a proof.. I have slow discs and I turned off synchronous_commit. Maybe PostgreSQL has to make an fsync during "prepare transaction" even if  synchronous_commit is off?

fsync = on
synchronous_commit = off

Any ideas?

UPDATE

Same tests with

fsync = off
synchronous_commit = off

#####  Overall statistics  #####

Number of unique normalized queries: 155
Number of queries:     186,838
Total query duration:  6.6s

#####  Queries by type  #####

SELECT:     84367     45.2%
INSERT:      9197      4.9%
UPDATE:      5486      2.9%
DELETE:      2996      1.6%

#####  Queries that took up the most time (N)  #####

1) 1.8s - 16,972 - PREPARE TRANSACTION ''
--
2) 1.1s - 16,965 - COMMIT PREPARED ''
--
3) 0.4s - 2,904 - update avatar set lfa_position=NULL where Id=0
--
4) 0.2s - 16,031 - COMMIT

Looks like fsync took vast amount of time, but not all the time. 16k commits - 0.2sec, 17k prepare+commit 2.9sec.

Sad story. Looks like XA commit tooks 15 times more time than local commit and doesn't take in account synchronous_commit setting. fsync=off is not safe for production use. So if I want to use XA transactions I have to use it carefully and use a good SSD drive with high IOPS.


why my javascript for loop will not work? for (var i=1; i<5; i++;) { document.write ("A statement has run "); }

I have tried using alert and document.write. It is from the following youtube video. It works for him but not for me.

for (var i=1; i<5; i++;) {
    document.write ("A statement has run ");
}


Egit fetch & pull connection refused

I've installed Egit plugin for eclipse on two ubuntu systems and created two new project on two sytems and shared(team>share) it. What's the proper way to do fetch & pull projects with other users with Egit?

Error connection refused


How can I invoke default model binding within a custom binder in MVC4 Web API?

I recently posed a question here on Stack Overflow about finding the right extensibility point for model binding in the Web API beta.  Using a custom provider / IModelBinder gives me full control of model binding and access to the value providers.

However, it's really too much control.  I just want to control how a couple of values are mapped, and don't want to hand-code model binding that would've otherwise worked just fine.

Ultimately, this is what I'd like to be able to do:

public class MyCustomModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        // Invoke default model binding

        // Pull out custom values
        var value1 = bindingContext.ValueProvider.GetValue("value1");
        var value2 = bindingContext.ValueProvider.GetValue("value2");

        bindingContext.Model.Value1 = DoCustomStuff(value1);
        bindingContext.Model.Value2 = DoCustomStuff(value2);

        return true;
    }

    ... // Define DoCustomStuff
}

It looks like it's pretty hard to get ahold of a default provider for the WebAPI.  Does anyone know if it's accessible and how it should be accessed here in a custom model binder?


SQL query with concat some fields . (MySql)

I using MySQL.
I will explain my question by example.. I have those 2 records:

Id       Name        Role
3004     Jason       x
3004     Jason       y

I want to make a query that make Group by the Id , and concat all the Roles of this Id to one field with ',' between them.

Id    Name     Roles
3004  Jason    x,y

Is it possible?


How do I access the 'mx' or 'fl' namespaces in a Flex Builder Actionscript Project?

How do I access the mx or  fl  namespaces in a Flex Builder Actionscript Project?

Do I need to include a certain .swc file?

I can't seem to find which one.


Copy EventHandler in inherited class

I'm developing an application in c# WPF.

I use a class PropertyChangedNotifier to manage INotifyPropertyChanged (see that link).

I use a classical ViewModelBase :

public class ViewModelBase : INotifyPropertyChanged, IRequestClose
{
    public PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = _propertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

In my MainViewModel : ViewModelBase I have a PropertyChangedNotifier<MainViewModel> working like this :

class MainViewModel : ViewModelBase
{
    private PropertyChangedNotifier<MainViewModel> _notifier;
    public new event PropertyChangedEventHandler PropertyChanged
    {
        add { _notifier.PropertyChanged += value; }
        remove { _notifier.PropertyChanged -= value; }
    }

    public MainViewModel()
    {
        _notifier = new PropertyChangedNotifier<MainViewModel>(this);
    }

    protected new void OnPropertyChanged(string propertyName)
    {
        _notifier.OnPropertyChanged(propertyName);
    }
}

But changes are not detected, when a value changes, my MainWindows doesn't refresh (without using PropertyChangedNotifier it works). I saw that system initiates windows by using WindowsBase.dll!System.ComponentModel.PropertyChangedEventManager.StartListening(object source) and then I saw that my ViewModelBase.PropertyChanged is not null when the constructor for MainViewModel is called.

Is it possible to make something like this :

public MainViewModel()
{
    _notifier = new PropertyChangedNotifier<MainViewModel>(this);
    _notifier.PropertyChanged = base.PropertyChanged;
}

And will that fix my bug ?

Edit:

PropertyChangeNotifier from link :

[AttributeUsage( AttributeTargets.Property )]
public class DepondsOnAttribute : Attribute
{
    public DepondsOnAttribute( string name )
    {
        Name = name;
    }

    public string Name { get; }
}

public class PropertyChangedNotifier<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public PropertyChangedNotifier( T owner )
    {
        mOwner = owner;
    }

    public void OnPropertyChanged( string propertyName )
    {
        var handler = PropertyChanged;
        if( handler != null ) handler( mOwner, new PropertyChangedEventArgs( propertyName ) );

        List<string> dependents;
        if( smPropertyDependencies.TryGetValue( propertyName, out dependents ) )
        {
            foreach( var dependent in dependents ) OnPropertyChanged( dependent );
        }
    }

    static PropertyChangedNotifier()
    {
        foreach( var property in typeof( T ).GetProperties() )
        {
            var dependsOn = property.GetCustomAttributes( true )
                                    .OfType<DepondsOnAttribute>()
                                    .Select( attribute => attribute.Name );

            foreach( var dependency in dependsOn )
            {
                List<string> list;
                if( !smPropertyDependencies.TryGetValue( dependency, out list ) )
                {
                    list = new List<string>();
                    smPropertyDependencies.Add( dependency, list );
                }

                if (property.Name == dependency)
                    throw new ApplicationException(String.Format("Property {0} of {1} cannot depends of itself", dependency, typeof(T).ToString()));

                list.Add( property.Name );
            }
        }
    }

    private static readonly Dictionary<string, List<string>> smPropertyDependencies = new Dictionary<string, List<string>>();

    private readonly T mOwner;
}


SpatialLines with determined distance

I have spatial point coordinates in a matrix, and I need create (n) spatial lines with 100km of distance from the point coordinate using intervals of 1°.

How do I determine distance in kilometer using SpatialLines function from sp package? How do I determine regular intervals with 1°?


Is there a way to test Chrome Custom Tabs with Espresso?

Here is the stub of the code.

Click data item on ListView .  Works as designed and opens Chrome Custom Tab :

onData(anything()).inAdapterView(withId(R.id.listView))
                                       .atPosition(0).perform(click());

Pause(5000);
Espresso.pressBack();

Cannot seem to evaluate anything in the tab or even hit device back button.
Getting this error

Error : android.support.test.espresso.NoActivityResumedException: No
activities  in stage RESUMED.

Did you forget to launch the activity. (test.getActivity()  or similar)?


Helptexts lost when referencing a COM DLL

I barely have any knowledge of COM, but I will try to make the question as clear as possible.

I have a .NET 4.0 project and am referencing an older COM DLL written in VBScript.

When I use this DLL in the code, I don't get any custom helptexts in VS2010 describing the methods and classes. They are also not available in the object browser.

I guess this has something to do with the automatic wrapper that is applied by .NET to the COM library. The help texts seem to get lost in the process.

When I view the dll directly in the object browser of VS, I can see the texts for methods etc.

Is there a way to keep the describing texts for coding with the referenced COM dll?


TagName in Kendo ListView in Asp.Net Core

I have simple kendo listview:

@(Html.Kendo().ListView<SomeViewModel>()
    //...
    .TagName("div")
    //...
)

The question is, what TagName method does? Documentation says:

The TagName of Kendo ListView for ASP.NET MVC used to create an
  element which will contain all listivew items once the listview is
  bound.

But when I'm changing it, absolutely nothing happens in output html, for example, I've changed it to ul and template was in li but it didn't create list of items.

So, why do we need TagName method, if it didn't work?


How to calculate sum of path's weight in N allowable moves defined in graph but the destination node is not fixed using Python

gr = {'0': {'4': 4, '6': 6},
      '4': {'3': 7, '9': 13, '0':4},
      '6': {'1': 7, '7':13,'0':6},
      '3': {'4': 7, '8': 11},
      '9': {'4': 13, '2': 11},
      '1': {'6': 7, '8': 9},
      '7': {'2': 9, '6': 13},
      '8': {'1': 9, '3': 11},
      '2': {'9': 11, '7': 9}}

This is the graph, I have made for the allowable moves and defined the weights in moves as I need to calculate sum of the weight of the path after certain number of moves(n) starting from '0'. The path can be random but from within those paths defined in graph, given the destination is not defined.

I have tried the functions like this where the parameters given are starting and ending point. This works to find the path and calculate the weight traveled. But I need to be able to have the parameters as starting point and the number of moves but not the destination and find the sum of path's weight. Also the nodes can be visited as many number of times. Please help me to edit this function or may be my approach should be different.

def paths(gr, frm, to, path_len = 0, visited = None):
   if frm == to:
        return [[to, path_len]]

   visited = visited or []
   result = []
   for point, length in gr[frm].items():
       if point in visited:
           continue
       visited.append(point)
       for sub_path in paths(gr, point, to, path_len + length, visited[:]):
           result.append([frm] + sub_path)

   return result

print (paths(gr, '0', '9'))

My Desired Output is:

Path: 0->4->3->8>1->6->7->2->9->4, Sum: 44

Path: 0->6->7->2->9->4->3->8->1->6, Sum: 46

From the comments:

The problem statement is "It chooses amongst the allowable moves uniformly at random and keeps track of the running sum S of nodes on which it lands." So my problem is to find the sum S of all the nodes on which it lands in K moves.


Handling lots of id's in HTML

I'm new to web design and have a problem I don't really know how to solve in the most eloquent way. I have 7 weekday elements, each 2 dropdowns. A dropdown has 24 options, 1 for each hour of the day. That means 336 possible options a user can click on in total.

I need to assign a function to each of those 336 elements that will update the text in the corresponding box the dropdown menu came from.

I know how to do what I'm trying to achieve, but I'm not sure how to do it 'properly'. I could write my function that updates the text based on what you clicked on. Then I could go through and manually assign a unique ID to each of my 336 elements, then write a function that loops through and assigns my first function to all of them. Although this would mean manually assigning 336 unique ID's in my HTML. Something feels wrong about this? is there any better way?

I feel like I'm missing something very obvious that would make this much easier - maybe I'm taking a completely wrong approach?


separation betwen normal array and associative array

i have a tree processing function which returns, for example such data:

Array
(
[0] => Array
    (
        [efw] => Array
            (
                [0] => ewe
                [sdfe] => Array
                    (
                        [dfe] => Array
                            (
                                [fef] => value
                            )

                        [wefwf] => Array
                            (
                                [0] => qefq
                                [1] => efew
                            )

                    )

            )

i wish that data would look like

                        [wefwf] => Array
                            (
                                qefq
                                efew
                            )

instead of

                        [wefwf] => Array
                            (
                                [0] => qefq
                                [1] => efew
                            )

so i can suggest is values in array is a key=>value or only values, which appended with surrogate keys(keys may be 0,1... like surrogate keys too, it's the problem why i can't suggest after processing is this a predefined key or surrogate)

any suggestions? i just can think about objects. maybe objects from SPL can do this?

or maybe a simpler solution is to use this feature:

A key may be either an integer or a
  string. If a key is the standard
  representation of an integer, it will
  be interpreted as such (i.e. "8"  will
  be interpreted as 8, while "08" will
  be interpreted as "08")

and save numeric predefined keys as strings with lead zero, and surrogate keys will be integers?

lol, i think i will use this solution, but answers appreciated


Show subtitle in HTML5 video player using json

We need to create a video player the same as the reference site below:

http://www.vagalume.com.br/selena-gomez/love-you-like-a-love-song.html

What we need to achieve is to create a HTML5 player which plays youtube video with subtitle dynamically.

I have added one link above which is our reference link and we need to make the same functionality given in reference site.

Here is our HTML page code:

<code>
$(document).ready(function() {
    $('audio, video').mediaelementplayer({
        alwaysShowControls: true,
        videoVolume: 'horizontal',
        features: ['playpause','progress','volume','fullscreen'],
        startLanguage: 'en'
    });
});
</code>

Our video player code:

<code>
video id="video" preload="metadata" controls="controls">
            source type="video/youtube" src="https://www.youtube.com/watch?v=FV4cwmM79NY">
        /video>
</code>

Here is our JavaScript code for adding subtitles dynamically.

<code>
(function() {
    var video = document.getElementById("video"), i, track,     loadcues = document.getElementById("loadcues"), hideTracks = function() {
            for (i = 0; i < video.textTracks.length; i++) {
                video.textTracks[i].mode = "hidden";
            }
        };
    trackdisplay();
    function trackdisplay(){
    hideTracks();
        track = video.addTextTrack("captions", "English", "en");
        track.mode = "showing";
        track.addCue(new VTTCue(0, 12, "Loaded Cues"));
        track.addCue(new VTTCue(18.7, 21.5, "This blade has a dark past."));
        track.addCue(new VTTCue(22.8, 26.8, "It has shed much innocent blood."));
        track.addCue(new VTTCue(29, 32.45, "You're a fool for traveling alone, so completely unprepared."));
        track.addCue(new VTTCue(32.75, 35.8, "You're lucky your blood's still flowing."));
        track.addCue(new VTTCue(36.25, 37.3, "Thank you."));
        track.addCue(new VTTCue(38.5, 40, "So..."));
        track.addCue(new VTTCue(40.4, 44.8, "What brings you to the land of the gatekeepers?"));
        track.addCue(new VTTCue(46, 48.5, "I'm searching for someone."));
        track.addCue(new VTTCue(49, 53.2, "Someone very dear? A kindred spirit?"));
        track.addCue(new VTTCue(54.4, 56, "A dragon."));
        track.addCue(new VTTCue(58.85, 61.75, "A dangerous quest for a lone hunter."));
        track.addCue(new VTTCue(62.95, 65.87, "I've been alone for as long as I can remember."));
        track.addCue(new VTTCue(118.25, 119.5, "We're almost done. Shhh..."));
}
    //loadcues.addEventListener("click", function() {

    //});
}());
</code>

Thanks in advance


PHP Website - Loading Stylesheets in Sub Directories

I'm building a PHP based site with this directory structure

index.php

css

style.css

bootstrap.css

includes

header.php

footer.php

bikes

road.php

mountain.php

The Problem

So I'm working on road.php and I obviously need to be able to link to both style.css and bootstrap.css, but when I declare at the start of road.php to include the header.php and footer.php it is like as if it cannot find the stylesheets and the site reverts back to the default 1990s look.

I have also found that any form of link on the page loads a 404. I'm only just starting out with PHP because I need some more power in my sites, but I just can't seem to get my head around the super basic things.

I just don't know what to do and I'm finding myself turning my back on the whole PHP language.

Thanking you in advance,

Stu :)


Skip a line line in a tabWidget

Is it possible to skip a line in a tabWidget? So far I've tried \r and \n but nothing...Here is a sample code:

this.tabSpec = tabHost.newTabSpec("deux").setIndicator("Alarme\n volontaire",
getResources().getDrawable(R.drawable.ic_tab_alert)).setContent(alarme);
this.tabHost.addTab(this.tabSpec);

Thanks in advance !


Can We Calculate The DOM Length of Each Steps in jQuery UI Slider

Using jquery UI Slider I just wonder if there is a way to calculate the CSS length(width) of between steps in UI Slider? For example at following code I need to calculate the actual width between step1 (min) and step2 and so on!

 $( function() {
 $('#slider').slider({
      min: 1,
      max: 5,
      range: "min",
      animate:"slow",
      value: 0
    });
  } );


Data from MySQL CHARSET problems, please look the image!

If ISO-8859-1 then (HTML Text: GOOD, MySQL Data: BAD)
if UTF-8 then (HTML Text: BAD, MySQL Data: GOOD)

What can I do to solve it?


update only rows with max(id) with condition

I can't find a solution for my problem..

Let's say we have a simple table like this :

id

group_id

flag

For the moment, the flag column is set to 0.

I want to update this table and set the flag to 1 only for rows that have the greatest (newest)id when grouped by group_id.

I have been testing a lot of things, without success.

Example:

id: 1, group_id: 1, flag: 0
id: 2, group_id: 1, flag: 0
id: 3, group_id: 1, flag: 0
id: 4, group_id: 2, flag: 0
id: 5, group_id: 2, flag: 0

Will become :

id: 1, group_id: 1, flag: 0
id: 2, group_id: 1, flag: 0
id: 3, group_id: 1, flag: 1
id: 4, group_id: 2, flag: 0
id: 5, group_id: 2, flag: 1


Put a shape on pictureBox, c#

I have a pictureBox, I need to put some ovalshapes on different places over the pictureBox..

In some reason the shapes are behind the picture and they unseen..

Can I do something that the shapes will be over the picture and not behind it..?

What property change this?


Android image scaling

I'm making an app for 1.6 and I'm having a problem with android image scaling, I have a picture that's 480x295.

On a medium screen this appears correctly, but on a large screen (480x800 or 480x854) it doesn't fill the screen, it android makes the image 1.5x bigger, which is only 720x442.

As 800 is actually 1.67 and 854 is 1.78, I can obviously just include large images for the drawable-hdpi folder, but the image is already 1.5mb, which is larger than people seem to like, and I can't use app2sd as I want to support 1.6.

Any suggestions?

I can only think of three options:
1) Include the larger images (but that limits sales probably, and obviously increases the apk size)

2) Make 2 versions, seems a good solution, just harder to implement.

3) Change to 1.5, and handle all my scaling myself.

EDIT:
More details:
I'm drawing using canvas and surfaceview
Image loading code:

backgroundBMP = BitmapFactory.decodeResource(getResources(), R.drawable.background, null);

And the drawing code:

canvas.drawBitmap(backgroundBMP, 0, 0, null);


database atomic operations implementation

The question is about queries that are not wrapped in 'begin-commit' block, but about plain inserts and updates that are atomic in postgres, mysql (innodb engine at least). So how is this implemented internally?


Is there any benifit in using DataContract and DataMember attributes while working with Asp.net Web API?

Many time i saw that developer are using DataContract and DataMember Attributes for their Asp.net Web API model?

What are the differences and best practices?


Spring & neo4j: Previous relationships are deleted when adding new ones

Here is my User class:

@NodeEntity
public class User {

    @GraphId
    private Long id;

    @Property
    private String name;

    @Property
    private String email;

    @Property
    private String password;

    @Property
    private String photoLink;

    @Property
    private Integer age;

    @Property
    private Country country;

    @Property
    private Gender gender;

    @Property
    private String about;

    @Property
    private boolean online;

    private Collection<UserHasLanguage> hasLanguage;

    @Relationship(type="HAS_ROLE", direction=Relationship.OUTGOING)
    private Collection<Role> roles;

    @Relationship(type="HAS_IN_FRIENDLIST", direction=Relationship.OUTGOING)
    private Collection<User> friendList;

    @Relationship(type="HAS_IN_BLACKLIST", direction=Relationship.OUTGOING)
    private Collection<User> blackList;

So I want users to have one-side relationships HAS_IN_FRIENDLIST to other users.
At the service level I have a method for adding friends to user:

public void addToFriendList (User whoAdds, User whoIsAdded)
        throws UserNotFoundException{
    if (whoIsAdded == null)
        throw new UserNotFoundException("User not found");
    Collection<User> friendList = whoAdds.getFriendList();
    if (friendList == null)
        friendList = new HashSet<>();
    friendList.add(whoIsAdded);
    whoAdds.setFriendList(friendList);
    userRepository.save(whoAdds);
}

However, when I use this method, some previous relationships "HAS_IN_FRIENDLIST" of this user are removed.
I have noticed, that whoAdds.getFriendList() method always returns only 1 User.

How can I fix this?


Cant find PasswordValidator property in UserManager, AspNet.Identity 3

I want to change the password requirements for my registration form but I cant find the PasswordValidator property in the UserManager class.

I'm using AspNet.Identity.EntityFramework 3.0.0-beta5

private readonly UserManager<AppUser> _userManager;
        private readonly SignInManager<AppUser> _signInManager;

        public AccountController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
        {

            _userManager = userManager;
            _signInManager = signInManager;

            // UserManager does not contain a definition for PasswordValidator
            //_userManager.PasswordValidator

        }

(For comparison, in Microsoft ASP.NET Identity 2.0, documentation for UserManager<TUser, TKey>.PasswordValidator is here.)


How do I precisely specify the CRM Solution for CRMPackage Plugins deployment?

Having trouble getting MSBuild/Visual Studio 2012 to deploy a CRM 2011 Plugin Assembly to a named CRM Solution.

I've 2 project/SLNs.  In one, I can precisely control which CRM Solution the build deploys a Plugin Assembly into; my msbuild (call this build-1) creates a CRM Solution with my custom entities/forms and Plugins.  In another, despite specifying the exact values via msbuild /p for CRMOrganization, CRMSolutionName, CRMDiscoveryServer, 'CRMDiscoveryServerScheme, the resulting CRM Solution contains only the entities/forms.  The Plugins are deployed but placed incorrectly into the Default Solution (call this build-2).

I've created build-2 from copy/pasting the values (except SLN and Project names) from build-1...and am at a loss to understand why build-1 deploys the plugins to my named CRM Solution, but build-2 deploys them to the Organization's Default CRM Solution.

Any ideas?


Javascript homework

<!DOCTYPE html>
<html>

  <body>
    <script type="text/javascript">
      var images1 = new Array("strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg");
      var images2 = new Array("strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg");
      var images3 = new Array("strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg");
      var length = images1.length;
      var randImg = Math.round(Math.random() * (length - 1));
      document.write('<img src="' + images1[randImg] + '" >');
      var length = images2.length;
      var randImg = Math.round(Math.random() * (length - 1));
      document.write('<img src="' + images2[randImg] + '" >');
      var length = images3.length;
      var randImg = Math.round(Math.random() * (length - 1));
      document.write('<img src="' + images3[randImg] + '" >');

    </script>
  </body>

</html>

I want to compare the images of the arrays if 3 images are strawberry I want to create an alert message like 'congrats you won' but I couldn't do that, how can I do that ?


How to properly read a TCP stream without blocking

I have a TCP server (async) and TCP client (sync).

The TCP server is sending data to the client like so:

private async Task Send(TcpClient client, CancellationToken ct, string message) {
            Console.WriteLine("Sending Message " + message);
            message += "<EOF>";
            NetworkStream stream = client.GetStream();
            byte[] msg = Encoding.ASCII.GetBytes(message);
            await stream.WriteAsync(msg, 0, msg.Length, ct).ConfigureAwait(false);
        }

My client is calling this read every update

private string ReadStream(){
   if(stream.DataAvailable)
        return reader.ReadLine();
}

This results in my client blocking. In my code I do have some string building techniques to accumulate the read stream, so that I can search for "<EOF>" to know when this message is done. But it seems that if I do not disconnect the client from the server, the client will hang forever.

What is a better way to continually read a TCP socket from the client's perspective?


Kivy properties not automatically updating

I'm having trouble with binding properties across different rules using kivy language.

In particular, I'm trying to use a color picker to change the background color a few labels; I'm using a ScreenManager to handle two different Screens, a main screen with just a MyButton instance (a subclass of Label, as can be seen in the code) and another screen with a ColorPicker and another MyButton.

Here's the code I'm working on:

picker.py

from kivy.app import App
from kivy.properties import BoundedNumericProperty, ReferenceListProperty, \
    ObjectProperty
from kivy.uix.behaviors.button import ButtonBehavior
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen

class MyScreen(Screen):
    my_picker = ObjectProperty(None)

class MyButton(ButtonBehavior, Label):
    my_r = BoundedNumericProperty(1, min=0, max=1)
    my_g = BoundedNumericProperty(1, min=0, max=1)
    my_b = BoundedNumericProperty(1, min=0, max=1)
    my_a = BoundedNumericProperty(1, min=0, max=1)
    my_rgba = ReferenceListProperty(my_r, my_g, my_b, my_a)

class PickerApp(App):
    pass

def main():
    PickerApp().run()

if __name__ == '__main__':
    main()

picker.kv

<MyButton@Label>:
    color: 0, 0, 0, 1
    canvas.before:
        Color:
            rgba: self.my_rgba
        Rectangle:
            pos: self.pos
            size: self.size

<PickerScreen@MyScreen>:
    my_picker: picker
    BoxLayout:
        orientation: 'vertical'
        MyButton:
            my_rgba: picker.color
            text: "Back"
            size_hint: 1, .2
            on_press:
                root.manager.current = 'main'
        ColorPicker:
            id: picker

<MainScreen@MyScreen>:
    MyButton:
        my_rgba: root.my_picker.color if root.my_picker is not None else .5, .5, .5, 1
        text: "Picker"
        on_press:
            root.manager.current = 'picker'

ScreenManager:
    MainScreen:
        name: 'main'
        my_picker: picker_screen.my_picker
    PickerScreen:
        name: 'picker'
        id: picker_screen

When I select a color on the ColorPicker, I want both buttons to change their background; but while the button in the PickerScreen changes on color selection, apparently the my_rgba of the button in the main screen isn't bound to root.my_picker.color, as I expected.

I thought the issue could be because of the if-then-else expression; but I tried initializing the ObjectProperty in MyScreen with a dummy value, removing the if-then-else expression, and the behaviour seems identical.

What am I doing wrong? I'm just starting with Kivy, but I thought that properties were automatically bound so that if root.my_picker.color changed, so should both the buttons my_rgba properties.


Facebook SDK for iOS: FBSDKShareDialog is not shown

I am a newbie in iOS, and I would like  to share a link using the Facebook SDK for iOS. My code's as follows:

@IBAction func shareVoucherUsingFacebook(sender: UIButton) {
    print("Facebook")
    let content : FBSDKShareLinkContent = FBSDKShareLinkContent()
    content.contentURL = NSURL(string: "www.google.com")
    content.contentTitle = "Content Title"
    content.contentDescription = "This is the description"

    let shareDialog: FBSDKShareDialog = FBSDKShareDialog()

    shareDialog.shareContent = content
    shareDialog.delegate = self
    shareDialog.fromViewController = self
    shareDialog.show()

}

I have also implemented the FBSDKSharingDelegate methods, but I am not able to receive the share dialog when I press this button, and the method func sharer(sharer: FBSDKSharing!, didFailWithError error: NSError!) is being executed, which means something is going wrong, but I can't figure it out.

Thanks in advance.


Table Column Styling using CSS

I have the following HTML table. I need to give a background color to each column (first column = red, second column = yellow, third column = blue). How can I do this using CSS?

Note: This need to work in IE6 onwards.

http://jsfiddle.net/Lijo/kw4yU/

  <table id = "myTable">
    <thead>
        <tr>
            <th>
                 Name
            </th>
            <th>
                Address
            </th>
            <th>
                Age
            </th>
        </tr>
    </thead>
    <tr>
        <td>
            Lijo
        </td>
        <td>
            India
        </td>
        <td>
            27
        </td>
    </tr>
</table>

EDIT:

I got it working by putting the js code inside document.ready. Thanks to @Jose Rui Santos http://jsfiddle.net/Lijo/kw4yU/11/

Another solution is http://jsfiddle.net/Lijo/kw4yU/12/

Yet another approach: Column width setting - HTML table


Resharper 6.0 tab instead of spaces

How to force resharper 6.0 to use tab instead of spaces during code clearup ?


how to use .csv file in android?

I'm doing a sample Quiz application in Android. I used array to store the Questions and Answers, now I wish to store the questions and answers in a .csv file.
it is possible to parse .csv file in Android?


How to make child span collapse with parent

I am teaching myself about animations using simple rectangles and I have so far managed a bit of progress with this simple project:

html:

<!DOCTYPE html>
<html>
    <head>
        <title>test slider</title>

        <link rel="stylesheet" type="text/css" href="styles.css">
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>

    <body>
        <span class="rect">
            <span class="otherrect"></span>
        </span>
        <p id="button"> click here </p>
    </body>
</html>

css

.rect{
    float: left;
    height: 400px;
    width: 550px;
    background-color: blue;

    transition-property: all;
    transition-duration: 2s;
    transition-timing-function: ease-in-out;
}

.otherrect {
    float: left;
    height: 200px;
    width: 250px;
    background-color: red;
}

.closed {
    height: 0;
    background-color: white;
}

#button {
    float: right;
    margin-top: 200px;
    margin-right: 500px;
}

js

$(document).ready(function(){

    $("#button").click(function(){

        if ($( ".rect" ).hasClass( "closed" )){

            $(".rect").removeClass("closed");

        } else {

        $(".rect").addClass("closed");
    }

    });
});

And it looks like this:

So, what I was aiming at, was that the red rectangle (class: otherrect) should also collapse and fade like its parent rectangle. How can I do this without using javascript and preferably not having to use the display property. Thanks for your time. P

---------------------------------EDIT AFTER RECEIVING ANSWERS-----------------------------------

Thank you all for your answers. These are all good in one way or another, but I guess I sould have mentioned that the red rectangle is going to be a video in the finished project so I need it to be a child of the other element because if the class that collapses it is applied to it directly, it affects the way it looks. Please refer to this other question to see a gif of what I mean:
slideDown() function behaving oddly


Soot plugin and command line - windows - jdk1.7

I've created a simple plugin following the instructions found here and here.

However, when I launch Soot from command line I get an error (I also get a similar error when using the full path of the jars)

C:\..\folder>java -cp soot-2.5.0.jar;plugin.jar soot.Main --plugin plugin.xml -p jap.foo opt:true java.lang.Object

Invalid option -plugin Exception in thread "main" soot.CompilationDeathException: Option parse error
    at soot.Main.processCmdLine(Main.java:85)
    at soot.Main.run(Main.java:161)
    at soot.Main.main(Main.java:141)

What am I missing? Any help is welcome


How to create a custom keyboard that looks like the standard one

I am experimenting with custom ime on android. The sample SoftKeyboard app seems to show everything I need except how to make the keyboard look like the standard one (colors, hover effects, sizes etc.).
It seems like reusing resources from the standard keyboard sources could work, but I receive errors when trying to compile them like:

error: Error: No resource found that matches the given name: attr android:layout_alignParentStart'.

Commenting these errors produce lots of other XML errors, like:

error: No resource identifier found for attribute 'additionalMoreKeys' in package 'com.android.inputmethod.latin' key_f1.xml

Is there some semi automatic a way to fix these errors and make them compile?

I have got the sources from here: https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/android-4.4.2_r2

Thanks in advance.


Understanding Failure Hits reports

I have a MonoGame based game up on the Store with gamers playing it. Under Failure Hits, I get a stack trace. I'm having trouble making sense of these stack traces.


Does memory address change after new declaration?

After executing "0th sentence" memory address of n1, n2 and *pn were ADDR:0061FF2C, 0061FF28, 0061FF24. Do they change after executing 1), 2) and 3)? I put printf for every code but they do not seem to change. theoretically, shouldn't they change because variables were assigned new values?

#include <stdio.h>
int main(void)
{
    int n1=3, * pn = &n1;
    int n2=0;

    printf("%p, %p, %p\n", &n1, &n2, &pn);  // 0)
    n2 = *pn;                           // 1)
    *pn = n2 + 1;                   // 2)
    n1 = *pn + *(&n2);                      // 3)
    printf("%d, %d, %d\n",n1,n2,*pn);           // 4)
    return 0;
}


Passing an array of integers from JavaScript to a controller action of List<int>

I am using javascript code to postdata to a controller action coded in C#. I am getting a null value when attempting to pass an array of integers in javascript created as follows:

var answers = [];
answers.push(1);
answers.push(2);
answers.push(3);

I can see from javascript alert that the values are going into array as when I try answers.tostring I am getting the value "1,2,3" as expected, I am then trying the following postdata

var postData = {
                'surveyID': surveyID,
                'questionID': questionID,
                'answers': answers,
                'answerText': null,
                'comment': comment,
                'questionType': questionType
            };

This is targetting the following controller action but the array of integers does not seem to be carrying across to the controller action as my List is always null

[HttpPost]
public PartialViewResult GoForward(int surveyID, int questionID, List<int> answers, string answerText, string comment, string questionType)
{}

Any know how I can get the postdata array to translate to a List that is not null?


Animating strings fading in/out in Swift

I'm new to programming - but I've made strides learning Swift for iOS in the last two months. I'm making a simple typing game - and the way I've structured my project is that I have a hidden UITextView that detects the character pressed by the player, and I match that character string with a visible UITextView's character string.

What I'm looking to do now is to add some sort of animation - I'd like the individual letters to fade in/out

I've created an attributed string, added it to a UITextView, and I just can't figure out a way to animate a specific range in the string. I've tried using something along the lines of this:

            UIView.animateWithDuration(1, delay: 0.5, options: .CurveEaseOut, animations: {
                self.stringForPlayer.addAttribute(
                    NSForegroundColorAttributeName,
                    value: UIColor.greenColor(),
                    range: NSRange(location: self.rangeOfText, length: 1))
                self.textViewForPlayer.attributedText = self.textForPlayer
                }, completion: { finished in
                    println("FINISHED")}
            )

with no luck. I figure maybe UIView animations are only on the view object itself and can't be used on the attributed string. Any ideas or even workarounds to make this happen? Any help is appreciated, thanks a lot!


Same plugin to be used twice in a page without error

I have a page that uses "Mac style bouncing menus" once on the left side panel and then again in the footer. Basically it's just the same plugin with different images.

Either one only works, even I tried jQuery.noConflict(true) , doesn't help.

My question is if we were to repeat the same plugin in a page ,what need to be done to avoid the conflict? from my understanding if various plugin to be used,jQuery.noConflict can solve it but for the same type of plugin?

test4.php

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>Test4</title>
        <link rel="stylesheet" href="css/style1.css" type="text/css">
        <link rel="stylesheet" href="css/side_style.css" type="text/css">
        <script src="js/menuv2.js" type="text/javascript"></script>
        <!--<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />-->
        <link href="css/bootstrap.css" rel="stylesheet" />
        <link href="http://getbootstrap.com/2.3.2/assets/js/google-code-prettify/prettify.css" rel="stylesheet" />

        <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap-responsive.css" rel="stylesheet" />

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://getbootstrap.com/2.3.2/assets/js/google-code-prettify/prettify.js"></script>
        <script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>
        <script src="js/bootstrap-modalmanager.js"></script>
        <script src="js/bootstrap-modal.js"></script>

        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/interface.js"></script>

    </head>
    <body id='superstar'>
        <div class='left'>
            <aside>
                <img src="hooha_images/logo_small.png" class="expand">
            </aside>
            <aside  class="ontop">
                <?php
                 include ('sidebar.php');

                ?>

            </aside>
            <aside>

             <aside>

                   <?php include('bottom_left.php');?>//1st Mac styled menu
             </aside>
        </div>
        <div class="wrap">
        <div class='middle'>
           <font color='#fff'><center>This is the Shop With Us Page of Indonesia</center></font>

        </div>

        <div class="footer">

            <?php
          include ('footer.php');//2nd Mac styled menu
           ?>
        </div>
        </div>
        <div class='right'>

          <?php
              include 'top-right.php';
              include 'side-ad.php';
          ?>

        </div>

    </body>
</html>

bottom-left.php

<div class="dock" id="dock1">
  <div class="dock-container1">
      <a class="dock-item2" href="index.php"><span>Home</span><img src="images/home.png" alt="home" /></a>
      <a class="dock-item2" href="about-intro.php"><span>About Us</span><img src="images/portfolio.png" alt="contact" /></a>
      <a class="dock-item2" href="contact-us.php"><span>Contact Us</span><img src="images/email.png" alt="portfolio" /></a>

  </div>

</div>

<!--dock menu JS options -->
<script type="text/javascript">

    $(document).ready(
        function()
        {
            $('#dock2').Fisheye(
                {
                    maxWidth: 60,
                    items: 'a',
                    itemsText: 'span',
                    container: '.dock-container2',
                    itemWidth: 40,
                    proximity: 80,
                    alignment : 'left',
                    valign: 'bottom',
                    halign : 'center'
                }
            )
        }
    );

</script>

footer.php

<div class="dock" id="dock2">
  <div class="dock-container2">
      <a class="dock-item2" href="index.php"><span>Home</span><img src="images/home.png" alt="home" /></a>
      <a class="dock-item2" href="about-intro.php"><span>About Us</span><img src="images/portfolio.png" alt="contact" /></a>
      <a class="dock-item2" href="contact-us.php"><span>Contact Us</span><img src="images/email.png" alt="portfolio" /></a>
      <a class="dock-item2" href="index.php"><span>Home</span><img src="images/home.png" alt="home" /></a>
      <a class="dock-item2" href="about-intro.php"><span>About Us</span><img src="images/portfolio.png" alt="contact" /></a>
      <a class="dock-item2" href="contact-us.php"><span>Contact Us</span><img src="images/email.png" alt="portfolio" /></a>

  </div>

</div>

<!--dock menu JS options -->
<script type="text/javascript">
    //var $=jQuery.noConflict(true);

    $(document).ready(
        function()
        {
            $('#dock2').Fisheye(
                {
                    maxWidth: 60,
                    items: 'a',
                    itemsText: 'span',
                    container: '.dock-container2',
                    itemWidth: 40,
                    proximity: 80,
                    alignment : 'left',
                    valign: 'bottom',
                    halign : 'center'
                }
            );
        }
    );

</script>


System.NullReferenceException: Object reference not set to an instance of an object.. what should i do?

here is my code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

private void BindData()
{
    DataTable dt = new DataTable();
    string connStr = @"Data Source=DESKTOP-IP1FFN6\MSSQLSERVER2;Initial Catalog=OCEP2;Integrated Security=True";
    using (SqlConnection cn = new SqlConnection(connStr))
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from Question_Table where QuestionId = 1 ", cn);
        adp.Fill(dt);

    }
    if (dt.Rows.Count > 0)
    {
        DataList2.DataSource = dt;
        DataList2.DataBind();

    }
    foreach (DataListItem dli in DataList2.Items)
    {
        RadioButtonList RadioButtonList2 = (RadioButtonList)DataList2.FindControl("RadioButtonList2");
        //RadioButtonList2.Items.Clear();

        RadioButtonList2.Items.Insert(0, new ListItem("QuestionOptions".ToString(), "QuestionOptions".ToString()));

    }
}

then i keep geting Object reference not set to an instance of an object on

RadioButtonList2.Items.Insert(0, new ListItem("QuestionOptions".ToString(), "QuestionOptions".ToString()));

there is table Question_Table on my database can any one help me?


Is it possible to bypass sorting of localdata when using grouping in jqgrid?

I have client-side data (local data) always sorted, and I don't want jqgrid to re-sort the data for grouping (like server-side sorted data behaviour-- groupDataSorted = true).

Is it possible to bypass/disable sorting of data before grouping in jqGrid? In other words, are there any way to use groupDataSorted = true, for editurl= "clientArray"?

datatype: 'local',
data: mydata,
rowNum: 10,
rowList: [10, 20,30,40],
pager: '#pager',
gridview: true,
sortname: 'invdate',
viewrecords: true,
grouping: true,
groupingView: {
    groupField: ['name'],
    groupSummary: [true],
    groupColumnShow: false,
    groupText: ['<b>{0}-{1} items</b>'],
},
editurl: 'clientArray'


jquery.kyco.googleplusfeed.min.js Unminified Source code

Where is the unminified jquery.kyco.googleplusfeed.min.js source code?

All source files are minified at the GitHub repo.


Styling/ Theming Google Maps using API V3

I'm trying to style Google Maps for my website like here: http://www.sidewalkprophets.com/shows
They only show the USA and unfortunately the site uses API V2.

Is the same possible using Google Maps API V3? Can someone help me?


How to prevent horizontal scrolling of text in input field with blackberry5

I am creating a html form that needs to work for users of older mobile devices.

The problem I have is when using an older Blackberry device, such as a 2 year old 9300, if you use the trackpad to move to the right of the text field, then the text scrolls off to the left and becomes hidden.

Is there any way to prevent this behaviour, or even to realign the text after the input has lost focus?

The problem is apparent even with a form as simple as this.

<form>
<input type="text" name="testit" />
</form>


Android bind service with intent filter

I have two separate applications and ideally I would like to use an IntentFilter to bind to the service on the second application. Is this possible?

In app 1 Manifest:

    <service
        android:name=".ServiceName"
        android:exported="true"
        android:icon="@drawable/ic_launcher"
        android:label="Bound Service" >
        <intent-filter>
            <action android:name="IntentFilterName" />
        </intent-filter>
    </service>

In app 2 Activity:

It is currently :

@Override
protected void onResume() {
    super.onResume();
    Intent i = new Intent();
    i.setComponent(new ComponentName("com.test.application1", "com.test.application1.ServiceName"));
    bindService(i, mConnection, Context.BIND_AUTO_CREATE);
}

Is it possible to work like this :

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter1 = new IntentFilter("IntentFilterName");
    bindService(filter1, mConnection, Context.BIND_AUTO_CREATE);
}

I get the following error:

The method bindService(Intent, ServiceConnection, int) in the type ContextWrapper is not applicable for the arguments (IntentFilter, ServiceConnection, int)


Interfacing zlib with ActiveTcl 8.5?

I'm trying to use the zlib extension in ActiveTcl 8.5 in order to save out a compressed blob to a file.  Both ActiveTcl 8.5.5 and 8.5.6 on win32 have a zlibtcl 1.2.3 extension.  I've tried both:

package require zlibtcl

and

load zlibtcl123.dll

Which both seem to indicate that the extension is properly loaded.  However, I can't seem to figure out what command is necessary to access the extension.  I am aware that ActiveTcl 8.6b1 onwards has the zlib functionality built in (http://wiki.tcl.tk/4610), however I need to deploy to existing systems that must use 8.5.x.

As far as I can tell, loading the extension does not add any new commands to the interpreter, which is quite confusing.  Running a strings on the dll does not seem to reveal any additional information.

Note: my backup plan is to SWIG zlib, but I'd prefer to use the existing extension if possible.


how to make images responsive in a bootstrap template

I know this had been asked a lot and I did research and try a lot before posting this question, but nothing seems to work. I have two images and a text which I want to display all in one line. However, when I decrease my window size the images are displayed below and above the text instead of next to it.
I have the following code and here's a fiddle:

<div class="row">
   <div class="col-md-4">
     <img src="image.jpg" class="images">
   </div>
   <div class="col-md-4">
     <div class="text">
       <h2 class="featurette-heading">What's Included with HTML?</h2>
          <p class="lead">Tags to make words. And tons of CSS properties to style your page:</p>
    </div>
</div>
  <div class="col-md-4">
    <img src="image.jpg" alt="Chrome Browser" class="images"></div>
</div>

How do I make the images resize according to the window size so that images and text are all displayed in one line?

I tried width:100%;height auto; and max-width:100%; and all sorts of combinations in order to make them responsive but it nothing worked so far.

Thanks in advance!


running a java project from command line using classpath issue?

I am trying to run a java project from the command line in linux, my project uses two external jar files. The command that i am givin is

java -classpath -jar bin:common-cli-1.2.jar:BuildFrameworkLibrary.jar com.kpit.goa.common.tools.kivibuild.KIVIBuild

where KIVIBuild is the class that contains the main function. But the error that am getting is:

baibhav@baibhav:~/git/KiviBuild/Infra/RepoManagement/BuildManagement/KIVIBuild$ java -classpath bin:common-cli-1.2.jar:BuildFrameworkLibrary.jar com.kpit.goa.common.tools.kivibuild.KIVIBuild

Gives

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException
Caused by: java.lang.ClassNotFoundException: org.apache.commons.cli.ParseException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: com.kpit.goa.common.tools.kivibuild.KIVIBuild. Program will exit.


Unable to analyse dictionary validate expression for field Drawing?

I got "Unable to analyse dictionary validate expression for field Drawing. "this error when compling below program how to resolve this?

/*Sample Item master Maintenance Program*/
/* DISPLAY TITLE */
{us/mf/mfdtitle.i "3+ "}
form
    pt_part colon 25
    with frame a side-labels width 80.
/* SET EXTERNAL LABELS */
setFrameLabels(frame a:handle).

form
   "Enter the Value of" pt__qad13 colon 30 skip(1)
   "Enter the Value of" pt_draw   colon 30 skip(1)
   "Enter the Value of" pt_group  colon 30
    with frame b side-labels width 80.
setFrameLabels(frame b:handle).
view frame a.
repeat with frame a:
   prompt-for pt_part
    editing:
   /* FIND NEXT/PREVIOUS RECORD */
     {us/mf/mfnp.i pt_mstr pt_part "pt_mstr.pt_domain = global_domain and pt_part" pt_part pt_part pt_part }
     if recno <> ? then
          do:
           display pt_part.
          end.
    end.
        find pt_mstr exclusive-lock where pt_domain = global_domain and pt_part = input pt_part .
               disp pt__qad13 pt_draw pt_group with frame b.
               update pt__qad13 pt_draw pt_group with frame b.

end.


How to make HTML buttons responsive

Here is the code for a basic website I'm making. I'm doing it for a school project.

.html-button {
  font-family: 'Hammersmith One', sans-serif;
  font-size: 20px;
  color: white;
  position: absolute;
  top: 55%;
  left: 45%;
  text-align: center;
  -webkit-transform: translate3d(-50%, -50%, 0);
  -o-transform: translate3d(-50%, -50%, 0);
  -webkit-border-radius: 8;
  border-radius: 8px;
  font-size: 21px;
  background: #42A5F6;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
  -webkit-transition-duration: 0.7s;
  /* Safari */
  transition-duration: 0.7s;
  border: none;
  cursor: pointer;
}
.html-button:hover {
  background: #0090FF;
  text-decoration: none;
  color: black;
}
.css-button {
  font-family: 'Hammersmith One', sans-serif;
  font-size: 20px;
  color: white;
  position: absolute;
  top: 55%;
  left: 55.3%;
  text-align: center;
  -webkit-transform: translate3d(-50%, -50%, 0);
  -o-transform: translate3d(-50%, -50%, 0);
  -webkit-border-radius: 8;
  border-radius: 8px;
  font-size: 21px;
  background: #42A5F6;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
  -webkit-transition-duration: 0.7s;
  /* Safari */
  transition-duration: 0.7s;
  border: none;
  cursor: pointer;
}
.css-button:hover {
  background: #0090FF;
  text-decoration: none;
  color: black;
}

<button class="html-button" role="button">VIEW HTML</button>
<button class="css-button" role="button">VIEW CSS</button>

That is not my entire code, but that's the main part that I'm focusing on here. This will display 2 separate buttons (decorated with CSS), on my screen, they are the perfect length apart, however currently, when I make my browser smaller, the buttons push closer together as it gets smaller, how might I prevent this?


google app engine get_serving_url() is not defined

It seems like an easy problem yet I cant figure it out:

I call get_serving_url() function in my code and get en error:

NameError: global name 'get_serving_url' is not defined

my import statement currently looks like:
from google.appengine.api import images

before i tried various "from PIL import Image" and got import errors.
i recently installed the PIL library

I have site-packages and PIL folder on my python path

how do I make get_serving_url() work?


Which defaulted methods are needed in purely abstract base classes?

As Scott Meyers points out in "Effective Modern C++", no move constructor is generated if a class defines a destructor.

It is not clear to me what that means for abstract base classes, which need to define a (defaulted) virtual destructor.

I do not want the lack of auto-generated methods in my base class to prevent the auto-generation of methods in any derived class.

The focus is only on derived classes, since the abstract base class does not have any data members, so there is no difference between moving and copying the base class. Yet what does it mean for a derived class if its base can only be copied, but not moved?

Which lines in the following class definition are unnecessary?

struct AbstractBase {
   AbstractBase () = default;
   AbstractBase (AbstractBase const &) = default;
   AbstractBase (AbstractBase &&) = default;
   AbstractBase & operator = (AbstractBase const &) = default;
   AbstractBase & operator = (AbstractBase &&) = default;
   virtual ~AbstractBase () = default;

   virtual void f () = 0;
};


Google Analytics Reporting API (Python) - How can I obtain previous and next page path?

Using the google analytics portal, i can check the previous and next page path for a given path (for an example, see below) [ Behavior > Site Content > All Pages > Navigation Summary)

How can I access path of all pages, and then for each of these pages the previous and next pages path via the API?
The API supports ga:previousPagePath, but nextPagePath is deprecated.

Here is a snippet of my source code (python).

DIMENSIONS =['ga:date','ga:hour', 'ga:minute', ??, ??]
METRICS =['ga:pageviews','ga:uniquePageviews', 'ga:sessions', 'ga:avgTimeOnPage']

def get_api_traffic_query(service):
  start ='2016-08-24'
  end = '2016-08-24'
  metrics =','.join(map(str, METRICS))
  dimensions =','.join(map(str, DIMENSIONS))
  start_index = '1'
segment='sessions::condition::ga:hostname!~mongo|app|help|docs|staging|googleweblight',
  return service.data().ga().get(ids=PROFILE_ID,start_date=start,end_date=end,metrics=metrics,dimensions=dimensions,
                                 start_index=start_index)


Issue with trigger delimiters

I'm running into a problem with creating a trigger on a table using MySQL and phpmyadmin v3.4.5.  After some research, it seems like this is a common problem, but none of the fixes I've found are working for me.  The error I'm getting is:

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 8

The query I'm trying to run is:

 CREATE TRIGGER book_insert
 AFTER INSERT ON `books`
 FOR EACH ROW BEGIN
 INSERT INTO products
      (ProductID,Type,Title,Price)
 VALUES
      (books.ProductID,0,books.Title,0)
 END
 //

I've set the delimiter to // in the text below the query input as I've read that PHPMyAdmin doesn't like you using the delimiter keyword in the query.  I've also played around with the placement of the delimiter, having no spaces between END and '//', having one space, and trying it on a different line.  I've also tried different delimiters like the default semicolon, 2 dollar signs, and 2 pound signs.  This seems like its something really small and stupid, but I can't figure out what it doesn't like about that statement.


what does 'key, ok := k.(*dns.A)' mean in Go?

I am pretty new to Go and trying to write a DNS server by using package  miekg DNS. According its example, I copy & pasted a simple snippet to perform A record request:

package main

import "fmt"
import "github.com/miekg/dns"

func main() {
    config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
    c := new(dns.Client)
    m := new(dns.Msg)
    zone := "miek.nl"
    m.SetQuestion(dns.Fqdn(zone), dns.TypeA)
    m.SetEdns0(4096, true)
    r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port)
    if err != nil {
        return
    }
    if r.Rcode != dns.RcodeSuccess {
        return
    }
    _ = "breakpoint"
    for _, k := range r.Answer {
        if key, ok := k.(*dns.A); ok {
            fmt.Printf("%+v\n", key)
        }
    }
}

Loading by godebug, stopped at _ = "breakpoint":

./godebug run ~/aRequest.go  -d /usr/local/go/
-> _ = "breakpoint"
(godebug) p r.Answer
[]dns.RR{(*dns.A)(0xc8200120c0)}
(godebug) n
-> for _, k := range r.Answer {
(godebug) n
-> if key, ok := k.(*dns.A); ok {
(godebug) p k
&dns.A{Hdr:dns.RR_Header{Name:"miek.nl.", Rrtype:0x1, Class:0x1, Ttl:0x708, Rdlength:0x4}, A:net.IP{0x8b, 0xa2, 0xc4, 0x4e}}
(godebug) n
-> fmt.Printf("%+v\n", key)
(godebug) p key
&dns.A{Hdr:dns.RR_Header{Name:"miek.nl.", Rrtype:0x1, Class:0x1, Ttl:0x708, Rdlength:0x4}, A:net.IP{0x8b, 0xa2, 0xc4, 0x4e}}
(godebug) p ok
true

According godebug, ok == true and key seemed same as k. How could k.(*dns.A) return two variables?


How can I set margin for div inside column div in bootstrap, like in the code I am trying to make margin 5px but it doesnt work!

<div class="container bg_red">
        <h1>Test DIV boxes</h1>
        <div class="row">
            <div class="col-md-3 thin_border bg_green">
                <div class="bg_blue">
                Some content here for panel 1
                </div>
            </div>
            <div class="col-md-9 thin_border">
                Some content here for panel 2
            </div>
        </div>
    </div>


Pass authenticated user from sharepoint to asp mvc application

I have made asp.net mvc application that have custom forms authentication.
Beside that it needs to authenticate user from sharepoint (in other words I need to pass user from sharepoint to asp mvc application). SP and asp mvc app are in the same domain and SP is using AD to authenticate user. I have searched google/so and so far I haven`t got any good solution.

Note: I need secure way of passing user from sp to asp mvc application ... I saw few examples that pass user thought URL parameter and I think that this is not secure thing to do.


Is there an easy way to check the .NET Framework version?

The problem is that I need to know if it's version 3.5 SP 1. Environment.Version() only returns 2.0.50727.3053.

I found this solution, but I think it will take much more time than it's worth, so I'm looking for a simpler one. Is it possible?


Program throwing OperationCanceledException despite catching it

I'm trying to use Tokens to cancel Task started by Task.Run. I took pattern from microsoft site: https://msdn.microsoft.com/pl-pl/library/hh160373(v=vs.110).aspx

This is my code:

public static class Sender
{

    public static async Task sendData(NetworkController nc) {
        await Task.Run(() => {
            IPEndPoint endPoint = new IPEndPoint(nc.serverIp, nc.dataPort);
            byte[] end = Encoding.ASCII.GetBytes("end");
            while (true) {
                if (Painting.pointsQueue.Count > 0 && !nc.paintingSenderToken.IsCancellationRequested) {

                    byte[] sendbuf = Encoding.ASCII.GetBytes(Painting.color.ToString());
                    nc.socket.SendTo(sendbuf, endPoint);

                    do {
                        sendbuf = Painting.pointsQueue.Take();
                        nc.socket.SendTo(sendbuf, endPoint);
                    } while (sendbuf != end && !nc.paintingSenderToken.IsCancellationRequested);

                }
                else if (nc.paintingSenderToken.IsCancellationRequested) {
                    nc.paintingSenderToken.ThrowIfCancellationRequested();
                    return;
                }
            }
        }, nc.paintingSenderToken);
    }
}

And here I start this task:

    public void stopController() {
        try {
            paintingSenderTokenSource.Cancel();
            senderTask.Wait();
        } catch(AggregateException e) {
            string message = "";
            foreach (var ie in e.InnerExceptions)
                message += ie.GetType().Name + ": " + ie.Message + "\n";
            MessageBox.Show(message, "Przerwano wysylanie");
        }
        finally {
            paintingSenderTokenSource.Dispose();
            byte[] message = Encoding.ASCII.GetBytes("disconnect");
            IPEndPoint endPoint = new IPEndPoint(serverIp, serverPort);
            socket.SendTo(message, endPoint);
            socket.Close();
            mw.setStatus("disconnected");
        }

    }

    public async void initialize() {
        Task t = Reciver.waitForRespond(this);
        sendMessage("connect");
        mw.setStatus("connecting");
        if (await Task.WhenAny(t, Task.Delay(5000)) == t) {
            mw.setStatus("connected");
            Painting.pointsQueue = new System.Collections.Concurrent.BlockingCollection<byte[]>();
            senderTask = Sender.sendData(this);
        }
        else {
            mw.setStatus("failed");
        }
    }
}

In initialize() method I'm waiting for the response from the server and if I get it I start new thread in this sendData() method. It is in static class to make code cleaner. If I want to stop this thread I call stopController() method. In microsoft site we can read:

The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.

But my program breaks onnc.paintingSenderToken.ThrowIfCancellationRequested(); which is in 'sendData()' method and the error says that OperationCanceledException was not handled. I started program from microsoft site and it works perfectly. I think I'm doing everything like they did but unfortunately it doesnt't work like it should.


datatables json input multiple tables single page

I originally built this script for another use case - with CSVs.  That project is no longer around and now I need to update it so datatables takes the input from multiple json files rather than CSVs.

The goal is to have an html document when i click on a link in a particular menu it will then render a table based on the link clicked.

Part 1 - Original Use case - input from CSV.

$(document).ready(function() {
var descriptions = {
"clusterconf.csv":
"<h3> Description </h3> <p>Some Information here that will be presented on the webpage on refresh.</p>"
    }
    $('.nav .dropdown-menu a').click(function(event) {
      event.preventDefault();
      location.hash = $(this).attr('href');
      var description = descriptions[$(this).attr('href')];
      $('#description').html(description);
      init_table({
        csv_path: '../output/' + $(this).attr('href'),
        element: 'table-container',
        allow_download: true,
        csv_options: {
          separator: ',',
          delimiter: '"'
        },
        datatables_options: {
          "paging": true,
          "deferRender": true,
          "searching": true
        }
      });
    });
    if (window.location.hash) {
      $('a[href="' + window.location.hash.substring(1) + '"]').click();
    }
});

Part 1.b - The HTML Menu I used originally-

<li><a href="clusterconf.csv">ClusterConf</a></li>
<li><a href="Other1.csv">Other1</a></li>
<li><a href="Other2.csv">Other2</a></li>
<li><a href="Other3.csv">Other3</a></li>
<li><a href="Other4.csv">Other4</a></li>

What this would do is present the datatables and then as the menu items were clicked it would load that CSV associated with it.

Where I am struggling and trying to figure out how to do is modify this so it leverages AJAX input and json files instead of the CSVs. I was able to get the AJAX working on a very generic test.

Ajax working properly:

$(document).ready(function() {
$('#example').DataTable( {
    responsive: true,
    select: {items: 'column'},
    "ajax": {
        "url": "/output/current/clusterconf.json",
        "dataSrc": ""
    },
    "columns": [
        { "data": "SomeData"},
        { "data": "Cluster"},
        { "data": "Name"},
        { "data": "Version"},
        { "data": "Build"},
        { "data": "SomeData6"},
        { "data": "SomeData7"},
        { "data": "SomeData3"},
        { "data": "SomeData2"},
        { "data": "NumCapacity"},
        { "data": "SomeData4"},
        { "data": "SomeData5"}
    ]
} );
} );

If it is relevant here are the js files i was leveraging before.

jquery/1.11.2/jquery.min.js
bootstrap.min.js
jquery.csv.min.js
jquery.dataTables.min.js
dataTables.bootstrap.js
csv_to_html_table.js

any help would be greatly appreciated.


How to get full command from Eclipse external tool configuration

So I've been hit by an Eclipse bug. \o/

Long story short, either I've got to install an old Eclipse and set up a bunch of workspaces from scratch (a laborious process that'll take half a day at least) or I can run a few specific ant commands manually. However I can't seem to find a way to extract the full command from a specific external tool configuration.

Any ideas? Or will I have to build the commands manually (a few properties, a custom ANT_HOME and alternative JRE make them a bit lengthy).


Python to C++ function conversion using Boost.Python

I have a bunch of classes and APIs written in C++ and exposed to Python with help of Boost.Python

I am currently investigating the possibilities of creating the following architecture.

In python:

from boostPythonModule import *
AddFunction( boostPythonObject.Method1, args )
AddFunction( boostPythonObject.Method2, args )
AddFunction( boostPythonObject.Method2, args )
RunAll( ) # running is done by C++

In C++:

void AddFunction( boost::object method,  boost::object args )
{
    /// 1. Here i need to extract a real pointer to a function
    /// 2. Make argument and type checking for a function under method
    /// 3. Unpack all arguments to native types
    /// 4. Store the pointer to a function somewhere in local storage
}

void RunAll( )
{
    /// 1. run all previously stored functions and arguments for them
}

Basically I am trying to put all functions down to the native part of my program.
The thing is that I am not sure if it's possible to extract all required data from Boost metainfo to do this in generic way - at compile time I should not know what functions I'm gonna call and what arguments they accept.

Few questions:

1. Is there any shared Python info tables I can access to check for some of this stuff ?

2. Boost.Python does type arguments checking. Can it be reused separately ?

Let me know your thoughts.

Thanks


Python- Most efficient way to return batches of numbers

Background

I am working on some REST JSON calls via python to get a list of users. Unfortunately, the server can only return a maximum number of 50 users at a time.
e.g.

call "[0:49]" returns the first 50 users

call "[51:99]" returns the next batch of 50 users

The server does return the total number of users therefore, i am able to write some logic to get all users with multiple rest calls.

Problem

I have written a very messy function that prints the data in a dictionary format:

    def get_all_possible_items(max_no_users):
        dict={}
        base=0
        values=max_no_users//50
        if max_no_users>49:
            dict[base]=base+49
            base+=49
        else:
            base-=1
        for i in range(values-1):
            base+=1
            dict[base]=base+49
            base+=49
        dict[base+1]=max_no_users

        print dict

    get_all_possible_items(350)

The output looks like:

If max_no_users is 350:

{0: 49, 100: 149, 200: 249, 300: 349, 50: 99, 150: 199, 250: 299, 350: 350}

if max_no_users is 351:

{0: 49, 100: 149, 200: 249, 300: 349, 50: 99, 150: 199, 250: 299, 350: 351}

Is there a better way of writing this (there must be!)?


where to save the checkpoint while training the neural network

In the example below I train the data x amount of times based on the value of iterations. At first I saved a checkpoint every iteration, but when I place it just below the iterations the training becomes much faster obviously. I'm not really sure if it makes a difference. Is one save in the session enough? And will the iterations use the values(weights) set in the previous iteration?

def train():
"""Trains the neural network
:returns: 0 for now. Why? 42
"""

unique_labels, labels = get_labels(training_data_file, savelabels=True) # get the labels from the training data
randomize_output(unique_labels) # create the correct amount of output neurons

prediction = neural_network_model(p_inputdata)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=p_known_labels)) # calculates the difference between the known labels and the results
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
with tf.Session() as sess:
    sess.run(tf.initialize_all_variables()) # initialize all variables **in** the session
    with open(training_data_file, "r") as file:
        inputdata = [re.split(csvseperatorRE, line.rstrip("\n"))[:-1] for line in file]
    if path.isfile(temp_dir + "\\" + label + ".ckpt.index"):
        saver.restore(sess, temp_dir + "\\" + label + ".ckpt")
    for i in range(iterations):
        _, cost_of_iteration = sess.run([optimizer,cost], feed_dict={
            p_inputdata: np.array(inputdata),
            p_known_labels: np.array(labels)
        })
    saver.save(sess, temp_dir + "\\" + label + ".ckpt")
    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(tf.argmax(p_known_labels, 1)))

    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

    with open(verify_data_file, "r") as file:
        verifydata = [re.split(csvseperatorRE, line.rstrip("\n"))[:-1] for line in file]

    npverifydata = np.array(verifydata )
    nplabels = np.array(get_labels(verify_data_file)[1])
    print("Accuracy: ", accuracy.eval({p_inputdata: npverifydata , p_known_labels: nplabels}))
return 0


Speed and XML Parsing in .NET - Serialization vs XML DOM vs?

I have done XML parsing before but never on a massive scale.
If I'm working with many documents similar to this format:

<?xml version="1.0" ?>
<items comment="something...">
  <uid>6523453</uid>
  <uid>94593453</uid>
</items>

What is the fastest way to parse these documents?

1) XML DOM

2) XML Serialize - Rehydrate to a .NET Object

3) Some other method

UPDATE

I forgot to mention that there would be approx 8000 uid elements on average.


How std::enable_shared_from_this::shared_from_this works

I just cannot understand how std::enable_shared_from_this::shared_from_this returns a shared pinter that shared ownership with existing pointer. In other words you do this:

std::shared_ptr<Foo> getFoo() { return shared_from_this(); }

So when you call getFoo how does exactly it get what is the other shared_ptr to share the ownership with and not to create a separate shared_ptr that owns the same this.

I need to understand this to be able to understand how to create shared_ptr from some object that all increase the same ref count and not initialize separate shared_ptrs.


Setting up dependency lib for android project

I'm very new to android and also to android.

I wish to do build my project if I do ant release.

I'm getting an error like due to the fact that my dependency lib aren't added to path.

But when I add :

android.library.reference.1=lib/android-support-v4.jar

like this local.properties I get an error like this:

 lib/android-support-v4.jar resolve to a path with no project.properties file for project /home/ubuntu/test

Where I'm making the mistake. Thanks in advance.


Build social graph of friends

I need in my application to build a social graph of friends for each user.
Like it is doing the facebook app "Social Graph":
App URL.
As I have seen there is no way to extract the friends of friends besides they are also using the application. So what I was thinking about is to extract the friends and for each pair of friends I can check with friends.areFriends whether they are friends and so build the social graph.
But for a user with 300 friends, I need 45.150 API calls. Which exceeds the API call limit per hour.
So is there a way to cast more queries in an API request. Or any suggestions how I can build this social graph in a better way??

best regards


How to Load an Image on the iPhone

I am using a UIImagePickerController, and once an image is selected, I save it to a PNG.  But for some reason, I can't load the saved image.

Here is my code:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //
// Create a PNG representation of the edited image
//
UIImage *anImage   = [info valueForKey:UIImagePickerControllerEditedImage];
NSData  *imageData = UIImagePNGRepresentation(anImage);

//
// Save the image to the documents directory
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

// Get a unique filename for the file
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
NSString *fileName = [(NSString *)string autorelease];
fileName = [NSString stringWithFormat:@"images/%@", fileName];
fileName = [fileName stringByAppendingString:@".png"];

NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:fileName] ];
[imageData writeToFile:path atomically:YES];
NSLog(@"Wrote the imageData to a file at path: %@", path);

// TEST TO SEE IF THE FILE WAS WRITTEN CORRECTLY
UIImage *testImage = [UIImage imageWithContentsOfFile:path];
NSLog(@"testImage is %@", testImage);

And here is my debugger output:

2010-12-28 16:29:08.676 Appster[6656:207] The imagePath is defined as: images/7ADB104E-DA45-4EE9-88DA-FF71B8D730CA.png
2010-12-28 16:29:08.712 Appster[6656:207] Wrote the imageData to a file at path: /Users/bschiff/Library/Application Support/iPhone Simulator/4.2/Applications/9F6FC2C7-9369-438C-AF8F-D5D25C72D8D7/Documents/images/FC94AA93-02EC-492A-A8FE-7D0C76E2C085.png
2010-12-28 16:29:08.715 Appster[6656:207] testImage is (null)