问:
Storing Results of queries into one table
I have multiple different queries and I want to store their results into one table. Results of this queries may have different number of rows and columns.

e.g.
I have three queries:

Q1. select name,id from employee;  (Result has 2 columns and 2 rows)

Q2. select salary from emp_table     (Result has 1 column and 4 rows)

Q3. select country_name,Country_id,count(id) from players group by country_name,Country_id (result has 3 columns and 3 rows)

Now, I want to store these results into one table which has structure like :

```<code>Query_ID | col1  | col2 | col3
-------------------------------
</code>```

In this table query_id is unique id to queries like A1,A2,A3...

When queries have less than three columns as result, remaining column should be filled with null (for first query col3 should be null and for second query col2 and col 3 should be null).

desired output:

```<code>Query_ID | col1   | col2 | col3
----------
A1       | John   | 1356 | NULL
A1       | Mathew | 1667 | NULL
A2       | 1500   | NULL | NULL
A2       | 2000   | NULL | NULL
A2       | 3000   | NULL | NULL
A2       | 3500   | NULL | NULL
A3       | US     | 010  | 25
A3       | UK     | 012  | 26
A3       | GER    | 016  | 16
</code>```

答:
You can use alias to your fields to have a uniform result set for your different queries.

For Q1 select name as col1,id as col2, '' as col3 from employee;

For Q2 select salary as col1, '' as col2, '' as col3 from emp_table

For Q3 select country_name as col1,Country_id as col2,count(id) as col3 from players group by country_name,Country_id

Then you can use your insert statement to save those queries. example:

INSERT INTO table (col1,col2,col3)
select name as col1,id as col2, '' as col3 from employee;

Then you can use any of the above queries as you want to your insert statement.

Body:
I have multiple different queries and I want to store their results into one table. Results of this queries may have different number of rows and columns.

e.g.
I have three queries:

Q1. select name,id from employee;  (Result has 2 columns and 2 rows)

Q2. select salary from emp_table     (Result has 1 column and 4 rows)

Q3. select country_name,Country_id,count(id) from players group by country_name,Country_id (result has 3 columns and 3 rows)

Now, I want to store these results into one table which has structure like :

Query_ID | col1  | col2 | col3
-------------------------------

In this table query_id is unique id to queries like A1,A2,A3...

When queries have less than three columns as result, remaining column should be filled with null (for first query col3 should be null and for second query col2 and col 3 should be null).

desired output:

Query_ID | col1   | col2 | col3
----------
A1       | John   | 1356 | NULL
A1       | Mathew | 1667 | NULL
A2       | 1500   | NULL | NULL
A2       | 2000   | NULL | NULL
A2       | 3000   | NULL | NULL
A2       | 3500   | NULL | NULL
A3       | US     | 010  | 25
A3       | UK     | 012  | 26
A3       | GER    | 016  | 16


来源: stackexchange

问:
Delete multiple sheets at once
I have multiple sheets with data on each sheet. I want to delete sheets from sheet number 4 to unlimited. I have tried below code:

```<code>Sub Delete_Sheets()
    Application.ScreenUpdating = False
    Dim j As Integer
    j = Worksheets.Count
    For k = 4 To j
        With Sheets(k).Delete
        End With
    Next k
    Application.ScreenUpdating = True
End Sub
</code>```

The problem is, every time the code ask my permission to delete sheet and finally saw deletes only few sheets. Someone help.

答:
Turn off displayed alerts. Delete backwards from the last sheet.</p>

```<code>Sub Delete_Sheets()
Dim j as long
Dim k As Long
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    j = Worksheets.Count
    For k = j To 4 Step -1
        Sheets(k).Delete
    Next k
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Delete multiple sheets at once

Body:
I have multiple sheets with data on each sheet. I want to delete sheets from sheet number 4 to unlimited. I have tried below code:

Sub Delete_Sheets()
    Application.ScreenUpdating = False
    Dim j As Integer
    j = Worksheets.Count
    For k = 4 To j
        With Sheets(k).Delete
        End With
    Next k
    Application.ScreenUpdating = True
End Sub

The problem is, every time the code ask my permission to delete sheet and finally saw deletes only few sheets. Someone help.

Body:
Turn off displayed alerts. Delete backwards from the last sheet.

Sub Delete_Sheets()
Dim j as long
Dim k As Long
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    j = Worksheets.Count
    For k = j To 4 Step -1
        Sheets(k).Delete
    Next k
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub


问:
Which function does WP use to format the output?
I pulling a post's content using database query and printing it out.
Unfortunately, I am loosing all the formatting that WP puts in when outputting content.  Such as the additional br tags.  Which function does WP use to format the output? I would like to put the content through that function before printing it.  Many thanks in advance for your help.</p>

答:
If you have the WordPress environment loaded, you should use

```<code>$formatted_content = apply_filters( 'the_content', $raw_content );
</code>```

That will apply every function WP normally uses on the_content

Otherwise, have a look at the functions wptexturize, wpautop, and others at http://core.trac.wordpress.org/browser/tags/3.0.4/wp-includes/formatting.php

ContentLicense: CC BY-SA 2.5

Body:
If you have the WordPress environment loaded, you should use

$formatted_content = apply_filters( 'the_content', $raw_content );

That will apply every function WP normally uses on the_content

Otherwise, have a look at the functions wptexturize, wpautop, and others at http://core.trac.wordpress.org/browser/tags/3.0.4/wp-includes/formatting.php


问:
Cost doesn't converge on tensorflow regression- python
I just recently learned tensorflow. I tried to run a simple regression example, but I got a bad result.

My input X is a matrix of 10x10000, that is, each data is a vector of 10x1, a total of 10000 pieces of data.

Desired output Y is just first row of X.

My code is as follows:

```<code>import tensorflow as tf
import numpy as np
from numpy.random import RandomState
rdm=RandomState(1)
data_size=10000
xdim=10
X=rdm.rand(data_size,xdim)
Y = [x1[0] for x1 in X]

x=tf.placeholder(tf.float32,shape=(None,xdim))
y=tf.placeholder(tf.float32,shape=(None))
#logits = modelFun(x)
Weights = tf.Variable(tf.random_normal([xdim, 1]))
biases = tf.Variable(0.1)
logits = tf.matmul(x, Weights) + biases
loss = tf.reduce_mean(tf.square(logits - y))
optimizer = tf.train.GradientDescentOptimizer(0.005).minimize(loss)

batch_size=50
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    steps=20001
    for i in range(steps):
        start = i * batch_size % data_size
        end = min(start + batch_size,data_size)
        sess.run(optimizer,feed_dict={x:X[start:end],y:Y[start:end]})
        if i % 5000 == 0:
            ypred,training_loss= sess.run([logits,loss],feed_dict={x:X,y:Y})
            print("Epoch %d: loss=%g"%(i,training_loss))
</code>```

The output results are as follows:

```<code>Epoch 0: loss=6.31555
Epoch 5000: loss=0.0798763
Epoch 10000: loss=0.0797333
Epoch 15000: loss=0.0797259
Epoch 20000: loss=0.079724
</code>```

It can't go down to 0.0797.
I checked part of the output. They are far from the correct answer.

```<code>>>>print(ypred[:10].T[0])
[ 0.49342471  0.49475971  0.50192004  0.48912409  0.50592101  0.48473218   0.48652697  0.50261581  0.50218904  0.48906678]

>>>print(np.array(Y[:10]))
[ 0.417022    0.41919451  0.80074457  0.09834683  0.98886109  0.01936696  0.10233443  0.90340192  0.88330609  0.11474597]
</code>```

What is the reason for this? How to solve it?
So thanks for your help!

答:
You're asking for too much from your model.  You're generating 10000 points of ten-dimensional random data, so there's no structure to learn, and then doing linear regression with a single neuron; your model doesn't have the capacity to even begin to memorize your input, so guessing that every y is about 0.5 is the best it can do.

The biggest issue is the random input.  Most types of machine learning models make strong assumptions about the structure of what they're trying to learn, and random data doesn't have that structure.  A large enough neural network could memorize you input data and give you a low training error, but it would completely fail to generalize (the test error would be high), and generalizing is usually the goal.

Body:
I just recently learned tensorflow. I tried to run a simple regression example, but I got a bad result.

My input X is a matrix of 10x10000, that is, each data is a vector of 10x1, a total of 10000 pieces of data.

Desired output Y is just first row of X.

My code is as follows:

import tensorflow as tf
import numpy as np
from numpy.random import RandomState
rdm=RandomState(1)
data_size=10000
xdim=10
X=rdm.rand(data_size,xdim)
Y = [x1[0] for x1 in X]

x=tf.placeholder(tf.float32,shape=(None,xdim))
y=tf.placeholder(tf.float32,shape=(None))
#logits = modelFun(x)
Weights = tf.Variable(tf.random_normal([xdim, 1]))
biases = tf.Variable(0.1)
logits = tf.matmul(x, Weights) + biases
loss = tf.reduce_mean(tf.square(logits - y))
optimizer = tf.train.GradientDescentOptimizer(0.005).minimize(loss)

batch_size=50
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    steps=20001
    for i in range(steps):
        start = i * batch_size % data_size
        end = min(start + batch_size,data_size)
        sess.run(optimizer,feed_dict={x:X[start:end],y:Y[start:end]})
        if i % 5000 == 0:
            ypred,training_loss= sess.run([logits,loss],feed_dict={x:X,y:Y})
            print("Epoch %d: loss=%g"%(i,training_loss))

The output results are as follows:

Epoch 0: loss=6.31555
Epoch 5000: loss=0.0798763
Epoch 10000: loss=0.0797333
Epoch 15000: loss=0.0797259
Epoch 20000: loss=0.079724

It can't go down to 0.0797.
I checked part of the output. They are far from the correct answer.

>>>print(ypred[:10].T[0])
[ 0.49342471  0.49475971  0.50192004  0.48912409  0.50592101  0.48473218   0.48652697  0.50261581  0.50218904  0.48906678]

>>>print(np.array(Y[:10]))
[ 0.417022    0.41919451  0.80074457  0.09834683  0.98886109  0.01936696  0.10233443  0.90340192  0.88330609  0.11474597]

What is the reason for this? How to solve it?
So thanks for your help!


问:
how to release localhost from Error: listen EADDRINUSE
i am testing a server written in nodejs on windows 7
and when i try to run the tester in the command line i get the following error

```<code>Error: listen EADDRINUSE
at errnoException (net.js:614:11)
at Array.0 (net.js:704:26)
at EventEmitter._tickCallback (node.js:192:40)
</code>```

how can I fix it without rebooting?

答:
ps -ef |grep node
find app.js ,
kill pid of app.js</p>

Body:
i am testing a server written in nodejs on windows 7
and when i try to run the tester in the command line i get the following error

Error: listen EADDRINUSE
at errnoException (net.js:614:11)
at Array.0 (net.js:704:26)
at EventEmitter._tickCallback (node.js:192:40)

how can I fix it without rebooting?


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答:
For me it depends on who's going to be using the .h file.  If it's a file largely internal to a module, then I tend to put the tiny methods in the header.  If it's a more external header file that presents a more fixed API, then I'll put everything in the .cpp files.  In this case, I'll often use the PIMPL Idiom for a full compilation firewall.

The trade-offs I see with putting them in the headers are:

Less typing

Easier inlining for the compiler (although compilers can sometimes do inlining between multiple translation units now anyway.)

More compilation dependencies

LastEditorDisplayName: Eddie Parker

OwnerDisplayName: Josh


问:
only returns one column when use the pandas read_csv
Here is my csv file

```<code>Country         2010    2011    2012    2013    2014
Albania         5.5     19.1    6.9     15.4    8
Algeria         18.2    6       8.1     20      9.5
American Samoa  14.1    13.8    3       14.7    2.3
Andorra         16      3       13.6    12.4    8.3
Angola          17.8    9.8     8.8     6.5     5.5
</code>```

my code:

```<code>import pandas as pd

test = pd.read_csv('C:\\Users\\Wing\\Desktop\\TEST.csv',sep='\t')

print(test.head())
print(test.shape)
print(test.columns)
print(test.dtypes)
</code>```

output:

```<code>the print test.shape command will output (14,1)
the print test.columns command will output(Index(['Country,2010,2011,2012,2013,2014'], dtype='object')
</code>```

so how can I separate them to 6 columns

Body:
Here is my csv file

Country         2010    2011    2012    2013    2014
Albania         5.5     19.1    6.9     15.4    8
Algeria         18.2    6       8.1     20      9.5
American Samoa  14.1    13.8    3       14.7    2.3
Andorra         16      3       13.6    12.4    8.3
Angola          17.8    9.8     8.8     6.5     5.5

my code:

import pandas as pd

test = pd.read_csv('C:\\Users\\Wing\\Desktop\\TEST.csv',sep='\t')

print(test.head())
print(test.shape)
print(test.columns)
print(test.dtypes)

output:

the print test.shape command will output (14,1)
the print test.columns command will output(Index(['Country,2010,2011,2012,2013,2014'], dtype='object')

so how can I separate them to 6 columns

Body:
Your csv file seems fine:

In [ ]: from io import StringIO
   ...: import pandas as pd
   ...: TESTDATA = StringIO("""Country         2010    2011    2012    2013    2014
   ...: Albania         5.5     19.1    6.9     15.4    8
   ...: Algeria         18.2    6       8.1     20      9.5
   ...: American Samoa  14.1    13.8    3       14.7    2.3
   ...: Andorra         16      3       13.6    12.4    8.3
   ...: Angola          17.8    9.8     8.8     6.5     5.5""")
   ...: test = pd.read_csv(TESTDATA,sep='\t')
   ...: print(test)
  Country         2010    2011    2012    2013    2014
0  Albania         5.5     19.1    6.9     15.4    8
1  Algeria         18.2    6       8.1     20    ...
2  American Samoa  14.1    13.8    3       14.7  ...
3  Andorra         16      3       13.6    12.4  ...
4  Angola          17.8    9.8     8.8     6.5   ...


问:
BottomNavigationView Does not work
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

```<code>setContentView(R.layout.activity_main);
</code>```

this is my code ( I did not do anything yet )

Main.java

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

xml file :

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">
</code>```

And Menu :

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />
</code>```

and finally dependacies :

```<code> implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'
</code>```

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

答:
make new layout .....(yourBottomNavLayoutName)
{sandroid.support.design.widget.BottomNavigationView} sandroid is invalid because of misspell use android.

```<code> <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dem60"
        android:layout_alignParentBottom="true"
        android:background="@color/appblue"
        app:itemTextColor="@color/colortextlightblue"
        app:itemIconTint="@color/white"
        android:elevation="@dimen/dem10"
        app:menu="@menu/bottomnavitems"/>
</code>```

and include this layout in your main activity like this

```<code><include
            layout="@layout/yourBottomNavLayoutName"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</code>```

Title: BottomNavigationView Does not work

Body:
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

setContentView(R.layout.activity_main);

this is my code ( I did not do anything yet )

Main.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

xml file :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">

And Menu :

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />

and finally dependacies :

 implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

Body:
make new layout .....(yourBottomNavLayoutName)
{sandroid.support.design.widget.BottomNavigationView} sandroid is invalid because of misspell use android.

 <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dem60"
        android:layout_alignParentBottom="true"
        android:background="@color/appblue"
        app:itemTextColor="@color/colortextlightblue"
        app:itemIconTint="@color/white"
        android:elevation="@dimen/dem10"
        app:menu="@menu/bottomnavitems"/>

and include this layout in your main activity like this

<include
            layout="@layout/yourBottomNavLayoutName"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />


问:
TypeError: The element or ID supplied is not valid. (videojs) Angular Ionic
I am trying to control a video player via videojs with in my ionic app. The code I have inside of my controller is:

```<code>        $scope.$on('$ionicView.loaded', function() {
            console.log('view loaded!!!');
            if ($scope.post.media.length > 0) {
                var myPlayer = null;
                for (var i = 0; i < $scope.post.media.length; i++) {
                    videojs("bc-video-0").ready(function () {
                        myPlayer = this;
                    });

                    myPlayer.on('loadstart', function () {
                        console.log('well something happened');
                    })
                }
            }
        });
</code>```

where I use the life cycle event $ionicView.loaded to wait for all of the template code to be loaded onto the page. Then in my template file I have:

```<code>            <div ng-repeat = "video in post.media | limitTo:videoLimit" class="video-box">
                <!--limitTo:videoLimit |-->
                <h3 class="video-title">{{video.title}}</h3>
                <p ng-bind-html = "video.info"></p>
                <!-- BRIGHTCOVE -->
                <div style="display: block; position: relative; width: 100%;" >
                    <div style="display: block; position: relative; width: 100%;">
                        <div style="display: block; padding-top: 56.25%;" data-tap-disable="true">
                            <video
                                    id="{{'bc-video-' + $index}}"
                                    style="width: 100%; height: 100%; position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px;"
                                    data-video-id=" {{video.file}}"
                                    data-account="XXXXXXXXXX"
                                    data-player="XXXXXXXXXX"
                                    data-embed="default"
                                    class="video-js"
                                    controls="">
                                <source ng-src = "{{video.src | trusted}}">
                            </video>

                        </div>
                    </div>
                </div>
                <p style="display: none;">source: {{video.src}}</p>
            </div>
</code>```

but I keep getting the error:

```<code>TypeError: The element or ID supplied is not valid. (videojs)
</code>```

When I inspect I see that the first video id is indeed bc-video-0, any idea on what I am missing?

答: Try enclosing your script inside the $timeout(). had the same issue.</p>

Body:
I am trying to control a video player via videojs with in my ionic app. The code I have inside of my controller is:

        $scope.$on('$ionicView.loaded', function() {
            console.log('view loaded!!!');
            if ($scope.post.media.length > 0) {
                var myPlayer = null;
                for (var i = 0; i < $scope.post.media.length; i++) {
                    videojs("bc-video-0").ready(function () {
                        myPlayer = this;
                    });

                    myPlayer.on('loadstart', function () {
                        console.log('well something happened');
                    })
                }
            }
        });

where I use the life cycle event $ionicView.loaded to wait for all of the template code to be loaded onto the page. Then in my template file I have:

{{video.title}}

                            <video
                                    id="{{'bc-video-' + $index}}"
                                    style="width: 100%; height: 100%; position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px;"
                                    data-video-id=" {{video.file}}"
                                    data-account="XXXXXXXXXX"
                                    data-player="XXXXXXXXXX"
                                    data-embed="default"
                                    class="video-js"
                                    controls="">
                                <source ng-src = "{{video.src | trusted}}">
                            </video>

source: {{video.src}}

but I keep getting the error:

TypeError: The element or ID supplied is not valid. (videojs)

When I inspect I see that the first video id is indeed bc-video-0, any idea on what I am missing?


问:
How to enable Panning on left mouse button in PanAndZoom WPF
I am using WPF.PanAndZoom library for pan and zooming but by default it has panning enabled on right mouse button click but i need it on left mouse button click but found no documentation for this. Anyone can help please?

If you have suggestion for any other similar library, that will also be acceptable.

答:
The latest version on Github has this implemented due to this issue:

https://github.com/wieslawsoltes/PanAndZoom/issues/14

In fact this issue appears to have been opened by you! Within the XAML you can use the PanButton="Left" property to set this.

The NuGET packaged version 0.5.1 does not appear to have this code implemented yet.


问:
Is it possible to get the number of facebook likes for a url?
Ideally I would like to do this using javascript client side scripting only.  If that is not possible then I'd like to do this in such a way as to have the server do the least amount of work.

Any help is appreciated.

答:
It's pretty simple, several other anwsers on SO already showed good examples. Basically use the Graph API: http://developers.facebook.com/docs/api
to query info on your URL, for example: https://graph.facebook.com/?ids=http://www.stackloverflow.com . The API retuns a JSON object which should be easy to use with Javascript.</p>


问:
how can i use pagination in recyclerview when data comes from youtube API.
I am unable to get an idea how can I use pagination when I reached the last item(if 20 items per page) All data comes from youtube server using Youtube API. I use pagination and hit server to get next 20 item data.I use recyclerView.</p>

答:
Use below code snippet in your app.</p>

```<code>private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy)
    {
        if(dy > 0) //check for scroll down
        {
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading)
            {
                if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
                {
                    loading = false;
                    Log.v("...", "Last Item Wow !");
                    //Do pagination.. i.e. fetch new data
                }
            }
        }
    }
});
</code>```

Body:
Use below code snippet in your app.

private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy)
    {
        if(dy > 0) //check for scroll down
        {
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading)
            {
                if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
                {
                    loading = false;
                    Log.v("...", "Last Item Wow !");
                    //Do pagination.. i.e. fetch new data
                }
            }
        }
    }
});


问:
Confusion on Ruby symbols in to_json
im working through a Rails udemy course and were touching on the part of just ruby right now (Which I have NO experience with so this is all new to me).

In this portion were basically taking "permissions" from a permissions file and putting it into a "user json".

```<code>require 'json'

class User

  attr_accessor :email, :name, :permissions

  def initialize(*args)
    @email = args[0]
    @name = args[1]
    @permissions = User.permissions_from_template

  end

  def self.permissions_from_template
    file = File.read 'user_permissions_template.json'
    JSON.load(file, nil, symbolize_names: true)
  end

  def save
   self_json = {email: @email, name: @name, permissions: @permissions}.to_json
   open('users.json', 'a') do |file|
     file.puts self_json
   end
  end
end
</code>```

There is a simple runner.rb file which creates the user and initializes it, thats not my question though. Basically my question is the self_json = {email: @email, name: @name, permissions: @permissions}.to_json

Ive read the to_json API and it's simple enough, but every example of a ruby object i've seen looks like this: {:email => @email, :name => @name, :permissions => @permissions} except replace the @ symbols with "strings"

Im getting confused between the variable types of @variable and :variable.

Are we not using :var => @whatever since were using @ variables or?

答:
It has nothing to do with values being taken from instance variables instead of strings; all it has to do with is keys being symbols.

Old Ruby had only one object literal syntax, with each key/value pair

```<code>key => value
</code>```

e.g.

```<code>{ "foo" => "bar", 2 => 4, :name => "value" }
</code>```

where "foo" is a string key, 2 an integer key, and :name a symbol key.

However, it was found that symbol keys were used very, very often, especially as an alternative to (then missing from language) keyword parameters to functions:

```<code>link_to "Delete", thing, :method => :delete, :data => { :confirm => "Sure?" }
</code>```

which is actually a shortcut for

```<code>link_to("Delete", thing, { :method => :delete, :data => { :confirm => "Sure?" } })
</code>```

To make this kind of construction less verbose, and more intuitive as using keywords, a new syntax was developed as a shortcut, specifically for keys that are symbols, where

```<code>key: value
</code>```

is an alternative to the older but identical

```<code>:key => value
</code>```

So the above hash could have been written as

```<code>{ "foo" => "bar", 2 => 4, name: "value" }
</code>```

(although I don't recommend it in this case, because mixing the two styles is kind of icky.)

Using this new syntax, the above command could be written so:

```<code>link_to "Delete", thing, method: :delete, data: { confirm: "Sure?" }
</code>```

Thus, there is absolutely no difference if you write

```<code>{ :email => @email, :name => @name, :permissions => @permissions }
</code>```

or

```<code>{ email: @email, name: @name, permissions: @permissions }
</code>```

Currently, the latter one is preferred, as it is shorter and more readable. However, in many cases if the code has been around since pre-Ruby-1.9, one can still find the old syntax floating around.

Title: Confusion on Ruby symbols in to_json

Body:
im working through a Rails udemy course and were touching on the part of just ruby right now (Which I have NO experience with so this is all new to me).

In this portion were basically taking "permissions" from a permissions file and putting it into a "user json".

require 'json'

class User

  attr_accessor :email, :name, :permissions

  def initialize(*args)
    @email = args[0]
    @name = args[1]
    @permissions = User.permissions_from_template

  end

  def self.permissions_from_template
    file = File.read 'user_permissions_template.json'
    JSON.load(file, nil, symbolize_names: true)
  end

  def save
   self_json = {email: @email, name: @name, permissions: @permissions}.to_json
   open('users.json', 'a') do |file|
     file.puts self_json
   end
  end
end

There is a simple runner.rb file which creates the user and initializes it, thats not my question though. Basically my question is the self_json = {email: @email, name: @name, permissions: @permissions}.to_json

Ive read the to_json API and it's simple enough, but every example of a ruby object i've seen looks like this: {:email => @email, :name => @name, :permissions => @permissions} except replace the @ symbols with "strings"

Im getting confused between the variable types of @variable and :variable.

Are we not using :var => @whatever since were using @ variables or?

Body:
It has nothing to do with values being taken from instance variables instead of strings; all it has to do with is keys being symbols.

Old Ruby had only one object literal syntax, with each key/value pair

key => value

e.g.

{ "foo" => "bar", 2 => 4, :name => "value" }

where "foo" is a string key, 2 an integer key, and :name a symbol key.

However, it was found that symbol keys were used very, very often, especially as an alternative to (then missing from language) keyword parameters to functions:

link_to "Delete", thing, :method => :delete, :data => { :confirm => "Sure?" }

which is actually a shortcut for

link_to("Delete", thing, { :method => :delete, :data => { :confirm => "Sure?" } })

To make this kind of construction less verbose, and more intuitive as using keywords, a new syntax was developed as a shortcut, specifically for keys that are symbols, where

key: value

is an alternative to the older but identical

:key => value

So the above hash could have been written as

{ "foo" => "bar", 2 => 4, name: "value" }

(although I don't recommend it in this case, because mixing the two styles is kind of icky.)

Using this new syntax, the above command could be written so:

link_to "Delete", thing, method: :delete, data: { confirm: "Sure?" }

Thus, there is absolutely no difference if you write

{ :email => @email, :name => @name, :permissions => @permissions }

or

{ email: @email, name: @name, permissions: @permissions }

Currently, the latter one is preferred, as it is shorter and more readable. However, in many cases if the code has been around since pre-Ruby-1.9, one can still find the old syntax floating around.


问:
15 Puzzle Program, stuck on up left right down commands
```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main (void){

//Function used to set up your game board
   int disp[4][4];
   int i, j;
   int game_over = 0;
   for(i = 0; i < 4; i++) {
      for(j = 0;j < 4; j++) {
         printf("Enter a value from 1 - 15 for %d %d: ", i, j);
         scanf("%d", &disp[i][j]);
      }
   }
//Function used to display the game board
    for(i = 0; i < 4; i++){
        printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                printf(" _    ");
            else if (disp[i][j] < 10)
                printf(" %d    ",disp[i][j]);
            else
                printf("%d    ",disp[i][j]);
        }
    }
// Function to show where cursor is
    for(i = 0; i < 4; i++){
        printf("\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                printf("");
        }
    }
//Skeleton to function to controller
    do{
    char move[10];
    printf("Enter a move: ");
    scanf("%s", move);

    if (strcmp("up", move) == 0){
        for(i = 0; i < 4; i++){
            printf("");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i >= 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i - 1][j];
                    disp[i - 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Up", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i - 1][j];
                    disp[i - 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("UP", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i - 1][j];
                    disp[i - 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else if (strcmp("down", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i < 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Down", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i < 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("DOWN", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i < 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else if (strcmp("left", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (j >= 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j - 1];
                    disp[i][j - 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Left", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("LEFT", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else if (strcmp("right", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (j <= 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Right", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j - 1];
                    disp[i][j - 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("RIGHT", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j - 1];
                    disp[i][j - 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else
        printf("Invalid Move!");

//Update the board function
    for(i = 0; i < 4; i++){
        printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                printf(" _    ");
            else if (disp[i][j] < 10)
                printf(" %d    ",disp[i][j]);
            else
                printf("%d    ",disp[i][j]);
        }
    }
}
    while (game_over == 0);

return 0;
}
</code>```

I am having trouble making the cursor go right or down? I can go left and up, but not the other two. I'm not looking for someone to answer the entire program its just I have been stuck on this for hours and every other code I look at sees similar to mine.I can get it to correctly do up and left but right and down cause a problem and not sure why.

答:
The bug is the checking logic is wrong and the bad practice you followed is lots of repetitive code.

Well I have boiled the code to something simple.

```<code>    ...
else if (strcmp("down", move) == 0 || strcmp("Down", move) == 0 || strcmp("DOWN", move) == 0){
        int d = 0;
        for(i = 0; i < 4; i++){

        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i+1 < 4){  // <--- notice the change
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                    d = 1;
                    break;     // <-- and this
                }
                else {
                    printf("%s","Invalid move!");
                }
            }
            if( d == 1)
                break;
        }
    }
    else if (strcmp("right", move) == 0 || strcmp("Right", move) == 0 || strcmp("RIGHT", move) == 0){
        for(i = 0; i < 4; i++){

        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if ( j+1 < 4){    // <--- notice the change
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                    break;        // <-- and this
                }
                else {
                    printf("%s","Invalid move!");
                }
            }

        }
    }
    ...
</code>```

You can check that there is a break statement in case of down and right. The reason is, when you swap -1 to the right or down then you will meet up again in the loop iteration.

So without the break the result would be

```<code>_ 1 2 3
4 5 6 7
8 9 1 2
3 4 5 6

>>> right

1 2 3 _
4 5 6 7
8 9 1 2
3 4 5 6
</code>```

Another thing is don't repeat code. The readability is worse when you do that. Maintaining the code is even harder. Even better here you can write swap() logic and use it. And also the movement of the tiles can also be done with another function.

Tricky downlogic (Edit-1).

In case of downlogic the simple breaking up the loop wont work because in case you do that there will be a chance that in next iteration it will again get -1 and try to swap it with next number.

Body:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main (void){

//Function used to set up your game board
   int disp[4][4];
   int i, j;
   int game_over = 0;
   for(i = 0; i < 4; i++) {
      for(j = 0;j < 4; j++) {
         printf("Enter a value from 1 - 15 for %d %d: ", i, j);
         scanf("%d", &disp[i][j]);
      }
   }
//Function used to display the game board
    for(i = 0; i < 4; i++){
        printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                printf(" _    ");
            else if (disp[i][j] < 10)
                printf(" %d    ",disp[i][j]);
            else
                printf("%d    ",disp[i][j]);
        }
    }
// Function to show where cursor is
    for(i = 0; i < 4; i++){
        printf("\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                printf("");
        }
    }
//Skeleton to function to controller
    do{
    char move[10];
    printf("Enter a move: ");
    scanf("%s", move);

    if (strcmp("up", move) == 0){
        for(i = 0; i < 4; i++){
            printf("");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i >= 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i - 1][j];
                    disp[i - 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Up", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i - 1][j];
                    disp[i - 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("UP", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i - 1][j];
                    disp[i - 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else if (strcmp("down", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i < 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Down", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i < 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("DOWN", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i < 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else if (strcmp("left", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (j >= 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j - 1];
                    disp[i][j - 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Left", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("LEFT", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 1){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else if (strcmp("right", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (j <= 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("Right", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j - 1];
                    disp[i][j - 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }
    else if (strcmp("RIGHT", move) == 0){
        for(i = 0; i < 4; i++){
            printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i > 4){
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j - 1];
                    disp[i][j - 1] = temp;
                }
                else {
                    printf("Invalid move!");
                }
            }
        }
    }

    else
        printf("Invalid Move!");

//Update the board function
    for(i = 0; i < 4; i++){
        printf("\n\n");
        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                printf(" _    ");
            else if (disp[i][j] < 10)
                printf(" %d    ",disp[i][j]);
            else
                printf("%d    ",disp[i][j]);
        }
    }
}
    while (game_over == 0);

return 0;
}

I am having trouble making the cursor go right or down? I can go left and up, but not the other two. I'm not looking for someone to answer the entire program its just I have been stuck on this for hours and every other code I look at sees similar to mine.I can get it to correctly do up and left but right and down cause a problem and not sure why.

Body:
The bug is the checking logic is wrong and the bad practice you followed is lots of repetitive code.

Well I have boiled the code to something simple.

    ...
else if (strcmp("down", move) == 0 || strcmp("Down", move) == 0 || strcmp("DOWN", move) == 0){
        int d = 0;
        for(i = 0; i < 4; i++){

        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if (i+1 < 4){  // <--- notice the change
                    int temp = disp[i][j];
                    disp[i][j] = disp[i + 1][j];
                    disp[i + 1][j] = temp;
                    d = 1;
                    break;     // <-- and this
                }
                else {
                    printf("%s","Invalid move!");
                }
            }
            if( d == 1)
                break;
        }
    }
    else if (strcmp("right", move) == 0 || strcmp("Right", move) == 0 || strcmp("RIGHT", move) == 0){
        for(i = 0; i < 4; i++){

        for(j = 0; j < 4; j++){
            if (disp[i][j] == -1)
                if ( j+1 < 4){    // <--- notice the change
                    int temp = disp[i][j];
                    disp[i][j] = disp[i][j + 1];
                    disp[i][j + 1] = temp;
                    break;        // <-- and this
                }
                else {
                    printf("%s","Invalid move!");
                }
            }

        }
    }
    ...

You can check that there is a break statement in case of down and right. The reason is, when you swap -1 to the right or down then you will meet up again in the loop iteration.

So without the break the result would be

_ 1 2 3
4 5 6 7
8 9 1 2
3 4 5 6

>>> right

1 2 3 _
4 5 6 7
8 9 1 2
3 4 5 6

Another thing is don't repeat code. The readability is worse when you do that. Maintaining the code is even harder. Even better here you can write swap() logic and use it. And also the movement of the tiles can also be done with another function.

Tricky downlogic (Edit-1).

In case of downlogic the simple breaking up the loop wont work because in case you do that there will be a chance that in next iteration it will again get -1 and try to swap it with next number.


问:
Android Studio - AVD Manager is not visible
I have installed Android Studio 2.3.2 and
The AVD Manager (which should be under the tools menu is not visible).

Is there any way that i could make it available?

Tools menu in Android Studio

Menus and Toolbars

答:
Make sure you have installed  Android emulator from sdk manager

Then go to tools -->android-->avd manager

if it doesn't work check settings-->plugins-->android support that
  it(android support) is installed or not


问:
JS Array.every alway return false on comparing strings
I'm trying to complete an assignment using every, I tried everything and after and after 1 hour I decided to ask your help.

This function should return true if all the words in the array start with a case-insensitive but always return false, no matter what.

Thank you

var allStartingWithA = function(words){
  return words.length !== 0? words.every((word) => {word[0] === /"a"/i }) : true;
};

allStartingWithA(["abbb","aee", "aee", "avvv"]);```

答:
Someone before posted this and then delete it, I like this solution and thank you whoever you are.

var allStartingWithA = function(words){
  return words.length !== 0? words.every(word => word[0].toLowerCase()=='a') : true;
};
console.log(allStartingWithA(["abbb","aee", "aee", "avvv"]));```


问:
Conflicting dependencies in Androidstudio
How can I solve this problem?

It seems that different versions of android support and firebase are troublesome. But I didn't write the dependencies: there were there once I created the project and linked it to firebase.

答:
Change these two dependencies to the versions shown:

```<code>compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.firebaseui:firebase-ui:3.0.0'
</code>```

In future questions, please post text instead of an image. That allows the text to be copied, used for evaluation and answering.

There are three version numbers that must be made consistent:

Firebase and Google Play libraries

Android Support libraries

FirebaseUI

The FirebaseUI documentation contains a table of compatible Firebase SDK versions.  To determine the needed Support library version, you need to run a Gradle task to see the dependencies, or deduce the version by looking at the warnings Android Studio reports with red underlines on the dependencies in the app build.gradle file.

The latest version of Firebase is listed in the release notes.  To keep this answer simple, I used 11.4.2.  The latest is 11.6.2, but IIRC would require more extensive changes to your build setup for repos and classpaths.

Body:
Change these two dependencies to the versions shown:

compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.firebaseui:firebase-ui:3.0.0'

In future questions, please post text instead of an image. That allows the text to be copied, used for evaluation and answering.

There are three version numbers that must be made consistent:

Firebase and Google Play libraries

Android Support libraries

FirebaseUI

The FirebaseUI documentation contains a table of compatible Firebase SDK versions.  To determine the needed Support library version, you need to run a Gradle task to see the dependencies, or deduce the version by looking at the warnings Android Studio reports with red underlines on the dependencies in the app build.gradle file.

The latest version of Firebase is listed in the release notes.  To keep this answer simple, I used 11.4.2.  The latest is 11.6.2, but IIRC would require more extensive changes to your build setup for repos and classpaths.


问:
How to auto-update multiple sheets in Excel workbook?
I have an Excel workbook with two worksheets - "Upcoming Orders" and "Completed Orders". I used "Upcoming Orders" sheet for upcoming orders, and "Completed Orders" for completed orders.

Once the order is completed, I delete it from "Upcoming Orders" sheet and paste it into "Completed Orders".

Is there a way to automate it by creating a macro that would do it it automatically for me, once I mark order as completed in the "Upcoming Orders" sheet it will be automatically add into the " Completed Orders" sheet.

I went over a few tutorial on macros, but I couldn't find the right method. Please help.

答:
I'm new to this website, so this is my first "answer"
I am also new to VBA coding, but I am hitting it hard xD

I simply made a macro that opens an "inputbox" to enter a sale ID#, "OK" then moves it from it's location in the "Upcoming Orders" table to the first row of the "Completed Orders" table on the second sheet... I think this is nice because it allows you to verify the data which you are transferring by having to actually type the ID#; also makes it easier for longer tables since you wouldn't have to search for the entry.
(tomorrow I will try to make one that returns records to the "Upcoming" page... in case a mistake was made.
-Enjoy! (.Reverus.)

```<code>Sub Record_Transfer()
  Dim Rcrd, Rcrd2, Rng, tbl1, Tbl2 As Range
  Dim IDnum As String
  Dim x, x2, y, n As Integer

Worksheets(1).Activate

Set tbl1 = ActiveSheet.ListObjects("Table1")

IDnum = InputBox("Input ID to transfer: ", ["Transfer"], 17)
    If vbOKCancel = vbCancel Then
        Exit Sub
    End If

    If vbOKCancel = vbOK Then
        Set Rng = ActiveSheet.ListObjects("Table1").ListColumns(1).Range
        Set Rcrd = Rng.Find(IDnum, LookIn:=xlValues)
     End If

     If Rcrd Is Nothing Then
         MsgBox "ID not found."
             Exit Sub
     End If

 y = Rcrd.Row
 Set Rcrd = Worksheets(1).Range(Rcrd, Rcrd.End(xlToRight))
 x2 = ActiveSheet.ListObjects("Table1").ListColumns.Count

 Worksheets(2).Activate
 ActiveSheet.ListObjects("Table2").ListRows.Add (1)
 Set Rcrd2 = ActiveSheet.ListObjects("Table2").ListRows(1).Range
     For x = 1 To x2
         Rcrd2.Cells(x).Value = Rcrd.Cells(x).Value
         If x > x2 Then GoTo Del
     Next x
 Del:
     Sheets("Sheet1").Activate
     ActiveSheet.Rows(y).Delete

 End Sub
</code>```

Body:
I'm new to this website, so this is my first "answer"
I am also new to VBA coding, but I am hitting it hard xD

I simply made a macro that opens an "inputbox" to enter a sale ID#, "OK" then moves it from it's location in the "Upcoming Orders" table to the first row of the "Completed Orders" table on the second sheet... I think this is nice because it allows you to verify the data which you are transferring by having to actually type the ID#; also makes it easier for longer tables since you wouldn't have to search for the entry.
(tomorrow I will try to make one that returns records to the "Upcoming" page... in case a mistake was made.
-Enjoy! (.Reverus.)

Sub Record_Transfer()
  Dim Rcrd, Rcrd2, Rng, tbl1, Tbl2 As Range
  Dim IDnum As String
  Dim x, x2, y, n As Integer

Worksheets(1).Activate

Set tbl1 = ActiveSheet.ListObjects("Table1")

IDnum = InputBox("Input ID to transfer: ", ["Transfer"], 17)
    If vbOKCancel = vbCancel Then
        Exit Sub
    End If

    If vbOKCancel = vbOK Then
        Set Rng = ActiveSheet.ListObjects("Table1").ListColumns(1).Range
        Set Rcrd = Rng.Find(IDnum, LookIn:=xlValues)
     End If

     If Rcrd Is Nothing Then
         MsgBox "ID not found."
             Exit Sub
     End If

 y = Rcrd.Row
 Set Rcrd = Worksheets(1).Range(Rcrd, Rcrd.End(xlToRight))
 x2 = ActiveSheet.ListObjects("Table1").ListColumns.Count

 Worksheets(2).Activate
 ActiveSheet.ListObjects("Table2").ListRows.Add (1)
 Set Rcrd2 = ActiveSheet.ListObjects("Table2").ListRows(1).Range
     For x = 1 To x2
         Rcrd2.Cells(x).Value = Rcrd.Cells(x).Value
         If x > x2 Then GoTo Del
     Next x
 Del:
     Sheets("Sheet1").Activate
     ActiveSheet.Rows(y).Delete

 End Sub


问:
Special Copy Paste in VBA
This is a Copy Paste question using VBA. I basically want to grab a number from many different workbooks. My problem is this number is contantly updating so I don't think I can have the last vesion of the number without opening the workbooks.
The workbooks are big and take time to open and load data (taking data from an external source (bloomberg)).
My first clue was to open the workbooks, then let them charge then taking the data from it. My problem is, I need to set up a timer to do so(and let my workbook load) and during this timer my workbook cannot upload the datas so I end up with my old datas...

So the only solution I found was to do two different macros. One open all the workbook, then the second close and save it and grab the data from it...

Do you guys have any better idea?

My problem is, the workbooks are so big I need to open them 5 by 5 maximum and do it every time...

I copy paste you my code, I know it is very basic, if you think of any better code or way to make it work, please let me know.

```<code>Sub OpenWorkbooks()
workbooks.Open Filename :="C/.../file1.xlsx"
workbooks.Open Filename :="C/.../file2.xlsx"
workbooks.Open Filename :="C/.../file3.xlsx"
.
.
End sub
</code>```

Now the one to close and then copy paste the value as written by someone else.

```<code>Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String

Workbooks("file1").Close SaveChanges:=True

wbPath = "C:/etc...."

WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"

arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)

End sub
</code>```

As said do you think there is a better way to do it? I wanted to do the whole steps for each file but I cannot since the timer stop the refresh of my spreadhseet and I need a timer since my worksheets needs time to load.
So 1 - Open all , 2- close all and save all and copy the numbers... But I need to do it by batch cause if I open all it crashes...

My other question is, how could I make the code better? Ultimately I would like to have in my open workbook a spreadsheet where I would have all the paths for each worbook to open and copy/paste. then I would like a macro which loop the path, open the workbook wait (but timer not working...) then copy paste and close.

The altrnative is always looping the paths but by blocks. I will put all my paths on cells A1:A10 and I could have a loops opening the path present in A1:A10, then a second macro closing and saving the workbook with the path in A1:A10

Any ideas are welcome,

Thank you

答:
```<code>Sub testopenRefreshClose()
    Call openRefreshClose("C/.../file1.xlsx")
    Call openRefreshClose("C/.../file1.xlsx")
End Sub
Sub openRefreshClose(wbPathName As String)
    Dim wb As Workbook

    Set wb = Workbooks.Open(wbPathName) ' open and assign to workbook object
    wb.RefreshAll ' refresh the data
    wb.Close SaveChanges:=True ' close the workbook
End Sub
</code>```

This appears to finish running the query before closing, but you can also try unchecking enable background refresh which will ensure the data is updated before other actions are taken.

Title: Special Copy Paste in VBA

Body:
This is a Copy Paste question using VBA. I basically want to grab a number from many different workbooks. My problem is this number is contantly updating so I don't think I can have the last vesion of the number without opening the workbooks.
The workbooks are big and take time to open and load data (taking data from an external source (bloomberg)).
My first clue was to open the workbooks, then let them charge then taking the data from it. My problem is, I need to set up a timer to do so(and let my workbook load) and during this timer my workbook cannot upload the datas so I end up with my old datas...

So the only solution I found was to do two different macros. One open all the workbook, then the second close and save it and grab the data from it...

Do you guys have any better idea?

My problem is, the workbooks are so big I need to open them 5 by 5 maximum and do it every time...

I copy paste you my code, I know it is very basic, if you think of any better code or way to make it work, please let me know.

Sub OpenWorkbooks()
workbooks.Open Filename :="C/.../file1.xlsx"
workbooks.Open Filename :="C/.../file2.xlsx"
workbooks.Open Filename :="C/.../file3.xlsx"
.
.
End sub

Now the one to close and then copy paste the value as written by someone else.

Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String

Workbooks("file1").Close SaveChanges:=True

wbPath = "C:/etc...."

WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"

arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)

End sub

As said do you think there is a better way to do it? I wanted to do the whole steps for each file but I cannot since the timer stop the refresh of my spreadhseet and I need a timer since my worksheets needs time to load.
So 1 - Open all , 2- close all and save all and copy the numbers... But I need to do it by batch cause if I open all it crashes...

My other question is, how could I make the code better? Ultimately I would like to have in my open workbook a spreadsheet where I would have all the paths for each worbook to open and copy/paste. then I would like a macro which loop the path, open the workbook wait (but timer not working...) then copy paste and close.

The altrnative is always looping the paths but by blocks. I will put all my paths on cells A1:A10 and I could have a loops opening the path present in A1:A10, then a second macro closing and saving the workbook with the path in A1:A10

Any ideas are welcome,

Thank you

Body:
Sub testopenRefreshClose()
    Call openRefreshClose("C/.../file1.xlsx")
    Call openRefreshClose("C/.../file1.xlsx")
End Sub
Sub openRefreshClose(wbPathName As String)
    Dim wb As Workbook

    Set wb = Workbooks.Open(wbPathName) ' open and assign to workbook object
    wb.RefreshAll ' refresh the data
    wb.Close SaveChanges:=True ' close the workbook
End Sub

This appears to finish running the query before closing, but you can also try unchecking enable background refresh which will ensure the data is updated before other actions are taken.


问:
possible all combinations of list of length n in python without itertools
How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

```<code>def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))
</code>```

above code is to get the combinations of string it gives correct output:

```<code>['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
</code>```

答:
Are you looking for this :

```<code>import itertools

def combinations(list_1):
    split_list=[item for item in list_1[0]]
    return [''.join(sub_item) for sub_item in itertools.combinations(split_list,r=2)]

print(combinations(['12345']))
</code>```

output:

```<code>['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
</code>```

Body:
How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))

above code is to get the combinations of string it gives correct output:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']

Body:
Are you looking for this :

import itertools

def combinations(list_1):
    split_list=[item for item in list_1[0]]
    return [''.join(sub_item) for sub_item in itertools.combinations(split_list,r=2)]

print(combinations(['12345']))

output:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']


问:
PCL App Development - Button not clickable following splash screen transition
I am working on an app with a group of friends for a Twitch project.  I have recently integrated a splash animation when the app starts up. The only issue is, this splash animation renders my login button on the main page useless.  Now, if I move the button code, the button appears before the transition is complete (undesired result), but the button will work.  If I keep the code in place where the button shows up post transition (desired result), it isn't clickable (undesired result).  I'm sure you can see my frustration. The code is pasted below.  Please keep in mind I am very new to coding in general, so if this seems like a no-brainer, please have mercy.

XAML for LoginPage:

```<code>  <Grid>
    <Image x:Name="image" Aspect="AspectFit"/>
    <Button     HorizontalOptions="Center"
                VerticalOptions="Center"
                BackgroundColor="#008b8b"
                Image="twitchtwo.png"
                Text="  Login using Twitch!"
                FontSize="14"
                TextColor="White"
                Clicked="Button_Clicked"/>
    <Grid x:Name="SplashGrid" BackgroundColor="#007272">
      <Image  x:Name="Logo"
              Source="logo"
              HorizontalOptions="Center"
              VerticalOptions="Center">
        <Image.TranslationY>
          <OnPlatform x:TypeArguments="x:Double">
            <On Platform="iOS">0</On>
            <On Platform="Android">-12</On>
          </OnPlatform>
        </Image.TranslationY>
      </Image>
    </Grid>
  </Grid>
</code>```

C# code behind for LoginPage:

```<code>{
  [XamlCompilation(XamlCompilationOptions.Compile)]
  public partial class LoginPage : ContentPage
  {
    public LoginPage()
    {
      InitializeComponent();
      image.Source = ImageSource.FromResource("CCG.Images.ccgtext.png");
    }
    protected override async void OnAppearing()
    {
      base.OnAppearing();
      await Task.Delay(2000);
      await Task.WhenAll(
        SplashGrid.FadeTo(0, 2000),
        Logo.ScaleTo(0, 250)
        );
    }
    private async void Button_Clicked(object sender, EventArgs e)
    {
      await Navigation.PushModalAsync(new TwitchAuth());
    }
  }
}
</code>```

答:
I was able to fix it using the 'IsVisible' property set to false.  Thanks Roger Leblanc for pointing me in the right direction. </p>

```<code>protected override async void OnAppearing()
    {
      base.OnAppearing();

      await Task.Delay(2000);

      await Task.WhenAll(
        SplashGrid.FadeTo(0, 500),
        Logo.ScaleTo(0, 250)
        );
      SplashGrid.IsVisible = false;
    }
</code>```

Body:
I am working on an app with a group of friends for a Twitch project.  I have recently integrated a splash animation when the app starts up. The only issue is, this splash animation renders my login button on the main page useless.  Now, if I move the button code, the button appears before the transition is complete (undesired result), but the button will work.  If I keep the code in place where the button shows up post transition (desired result), it isn't clickable (undesired result).  I'm sure you can see my frustration. The code is pasted below.  Please keep in mind I am very new to coding in general, so if this seems like a no-brainer, please have mercy.

XAML for LoginPage:

  <Grid>
    <Image x:Name="image" Aspect="AspectFit"/>
    <Button     HorizontalOptions="Center"
                VerticalOptions="Center"
                BackgroundColor="#008b8b"
                Image="twitchtwo.png"
                Text="  Login using Twitch!"
                FontSize="14"
                TextColor="White"
                Clicked="Button_Clicked"/>
    <Grid x:Name="SplashGrid" BackgroundColor="#007272">
      <Image  x:Name="Logo"
              Source="logo"
              HorizontalOptions="Center"
              VerticalOptions="Center">
        <Image.TranslationY>
          <OnPlatform x:TypeArguments="x:Double">
            <On Platform="iOS">0</On>
            <On Platform="Android">-12</On>
          </OnPlatform>
        </Image.TranslationY>
      </Image>
    </Grid>
  </Grid>

C# code behind for LoginPage:

{
  [XamlCompilation(XamlCompilationOptions.Compile)]
  public partial class LoginPage : ContentPage
  {
    public LoginPage()
    {
      InitializeComponent();
      image.Source = ImageSource.FromResource("CCG.Images.ccgtext.png");
    }
    protected override async void OnAppearing()
    {
      base.OnAppearing();
      await Task.Delay(2000);
      await Task.WhenAll(
        SplashGrid.FadeTo(0, 2000),
        Logo.ScaleTo(0, 250)
        );
    }
    private async void Button_Clicked(object sender, EventArgs e)
    {
      await Navigation.PushModalAsync(new TwitchAuth());
    }
  }
}

Body:
I was able to fix it using the 'IsVisible' property set to false.  Thanks Roger Leblanc for pointing me in the right direction.

protected override async void OnAppearing()
    {
      base.OnAppearing();

      await Task.Delay(2000);

      await Task.WhenAll(
        SplashGrid.FadeTo(0, 500),
        Logo.ScaleTo(0, 250)
        );
      SplashGrid.IsVisible = false;
    }


问:
Including header files more than once
```<code>#include <stdio.h>
#include <stdio.h>

int main ()
{
   printf ("hello world");
   return 0;
}
</code>```

when I compile this, the compiler doesn't give any warning/error for including stdio.h twice.  Why is it so? Aren't the functions scanf, printf etc. declared and defined twice now?

Thanks, in advance

答:
As an aside, doing the "#ifndef" trick is appropriate for headers used by other people (like the standard headers).

If you need the #ifndef for a "private" program, then you are doing it "wrong". That is, you can and should organize headers within a project so they are not included more than once.

One reason that this is helpful is that keeps headers you think you have deleted from popping up again.

Since you can't control how public headers are used, this trick is reasonable for public headers. This trick is completely unnecessary for private headers.

Title: Including header files more than once

Body:
#include <stdio.h>
#include <stdio.h>

int main ()
{
   printf ("hello world");
   return 0;
}

when I compile this, the compiler doesn't give any warning/error for including stdio.h twice.  Why is it so? Aren't the functions scanf, printf etc. declared and defined twice now?

Thanks, in advance


问:
Can't get the value passed in any way to the entry index.js
I am learning redux with react and hit a mental roadblock, I have the following entry index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import {Provider} from 'react-redux';
import store from './store';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import Main from './components/front/Main';
import Login from './components/front/Login';
import Home from './components/front/Home';
import Register from './components/front/Register';
import Forgot from './components/front/Forgot';
import Verify from './components/front/Verify';
import Dashboard from './components/back/Dashboard';
import './css/app.css';

import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.isLogged ? ( //<-need to get props here
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

const App = () => (<BrowserRouter>
  <div>
    {/* PUBLIC */}
      <Route path={'/'} exact component={Home}/>
      <Route path={'/login'} component={Login}/>
      <Route path={'/register'} component={Register}/>
      <Route path={'/forgot'} component={Forgot}/>
      <Route path={'/verify'} component={Verify}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

  </div>
</BrowserRouter>);

ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));
</code>```

Overall redux works, the only problem is in this file, as I am not exporting anything, I can't get connect to work.

Ideally Auth.isLogged should be either true or false based on isAuthenticated prop, but I can't get the value passed in any way to the entry index.js

```<code>import React from 'react';
import { connect } from 'react-redux';

@connect((store) => {
  return {isAuthenticated: store.auth.isAuthenticated, authenticating: store.auth.authenticating};
})

export default class Auth extends React.Component {
  //Can't get anything from here to index.js
}
</code>```

Please any help would be greatly appreciated!

答:
If I understand correctly, you’re trying to provide context of store.auth.isAuthenticated to PrivateRoute.

If you declare App in its' own file you can connect it to the store and then pass the value of isAutenticated to your PrivateRoute component

```<code>//App.js

import React, { Component } from 'react'
import { withRouter, Switch, Route } from 'react-router-dom'
import { connect } from 'react-redux'

import PrivateRoute from 'components/PrivateRoute'

@withRouter
@connect(store => ({
  isAuthenticated: store.auth.isAuthenticated,
  authenticating: store.auth.authenticating
}))
class App extends Component {

  render() {
    const { isAuthenticated } = this.props

    return (
      <span>
        {/* PUBLIC */}
        { !isAuthenticated &&
          <Switch>
            <Route path={'/'} exact component={Home}/>
            <Route path={'/login'} component={Login}/>
            <Route path={'/register'} component={Register}/>
            <Route path={'/forgot'} component={Forgot}/>
            <Route path={'/verify'} component={Verify}/>
          </Switch>
         }

         {/* PRIVATE */}
         { isAuthenticated &&
           <PrivateRoute
             isAuthenticated={isAuthenticated}
             path="/dashboard"
             component={Dashboard}
           />
         }
       </span>
    )
  }
}

export default App
</code>```

For readability sake you could make this change in index.js

```<code>ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
)
</code>```

You may or may not need to wrap connect(App) inside of withRouter, but the way I was handling my routing made this part necessary.

Body:
I am learning redux with react and hit a mental roadblock, I have the following entry index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import {Provider} from 'react-redux';
import store from './store';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import Main from './components/front/Main';
import Login from './components/front/Login';
import Home from './components/front/Home';
import Register from './components/front/Register';
import Forgot from './components/front/Forgot';
import Verify from './components/front/Verify';
import Dashboard from './components/back/Dashboard';
import './css/app.css';

import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.isLogged ? ( //<-need to get props here
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

const App = () => (<BrowserRouter>

    {/* PUBLIC */}
      <Route path={'/'} exact component={Home}/>
      <Route path={'/login'} component={Login}/>
      <Route path={'/register'} component={Register}/>
      <Route path={'/forgot'} component={Forgot}/>
      <Route path={'/verify'} component={Verify}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

</BrowserRouter>);

ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));

Overall redux works, the only problem is in this file, as I am not exporting anything, I can't get connect to work.

Ideally Auth.isLogged should be either true or false based on isAuthenticated prop, but I can't get the value passed in any way to the entry index.js

import React from 'react';
import { connect } from 'react-redux';

@connect((store) => {
  return {isAuthenticated: store.auth.isAuthenticated, authenticating: store.auth.authenticating};
})

export default class Auth extends React.Component {
  //Can't get anything from here to index.js
}

Please any help would be greatly appreciated!

Body:
If I understand correctly, you’re trying to provide context of store.auth.isAuthenticated to PrivateRoute.

If you declare App in its' own file you can connect it to the store and then pass the value of isAutenticated to your PrivateRoute component

//App.js

import React, { Component } from 'react'
import { withRouter, Switch, Route } from 'react-router-dom'
import { connect } from 'react-redux'

import PrivateRoute from 'components/PrivateRoute'

@withRouter
@connect(store => ({
  isAuthenticated: store.auth.isAuthenticated,
  authenticating: store.auth.authenticating
}))
class App extends Component {

  render() {
    const { isAuthenticated } = this.props

    return (
      <span>
        {/* PUBLIC */}
        { !isAuthenticated &&
          <Switch>
            <Route path={'/'} exact component={Home}/>
            <Route path={'/login'} component={Login}/>
            <Route path={'/register'} component={Register}/>
            <Route path={'/forgot'} component={Forgot}/>
            <Route path={'/verify'} component={Verify}/>
          </Switch>
         }

         {/* PRIVATE */}
         { isAuthenticated &&
           <PrivateRoute
             isAuthenticated={isAuthenticated}
             path="/dashboard"
             component={Dashboard}
           />
         }
       </span>
    )
  }
}

export default App

For readability sake you could make this change in index.js

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
)

You may or may not need to wrap connect(App) inside of withRouter, but the way I was handling my routing made this part necessary.


问:
jQuery sum of textbox
Below is my HTML

I want a script like this
in one Textbox I want to add all the amount total and display it
and in one more textbox I want it like this

```<code>"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]
</code>```

My Updated Question

```<code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">
</div>
<div class="main">
  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">
</div>
<div class="main">
  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">
</div>
<button>Click Me!!!</button>
</code>```

My Updated code not working in this js core js is working fine

答:
Try the following way:

$('input[name="qty"]').change(function(){
  var name = [];
  $('.main').each(function(index,item){
    var obj={};
    obj.id = $(item).find('input[name="id"]').val();
    obj.qty = $(item).find('input[name="qty"]').val();
    name.push(obj)
  });
  console.log(name);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input{
  width:100px;
}</code>```

    <input type="text" name="name">
    <input type="text" name="id">
    <input type="text" name="qty">
    <input type="text" name="amount">

    <input type="text" name="name">
    <input type="text" name="id">
    <input type="text" name="qty">
    <input type="text" name="amount">

    <input type="text" name="name">
    <input type="text" name="id">
    <input type="text" name="qty">
    <input type="text" name="amount">

```

Title: jQuery sum of textbox

Body:
Below is my HTML

I want a script like this
in one Textbox I want to add all the amount total and display it
and in one more textbox I want it like this

"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]

My Updated Question

  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">

  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">

  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">

<button>Click Me!!!</button>

My Updated code not working in this js core js is working fine

Body:
Try the following way:

$('input[name="qty"]').change(function(){
  var name = [];
  $('.main').each(function(index,item){
    var obj={};
    obj.id = $(item).find('input[name="id"]').val();
    obj.qty = $(item).find('input[name="qty"]').val();
    name.push(obj)
  });
  console.log(name);
});

input{
  width:100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
    <input type="text" name="name">
    <input type="text" name="id">
    <input type="text" name="qty">
    <input type="text" name="amount">
</div>
<div class="main">
    <input type="text" name="name">
    <input type="text" name="id">
    <input type="text" name="qty">
    <input type="text" name="amount">
</div>
<div class="main">
    <input type="text" name="name">
    <input type="text" name="id">
    <input type="text" name="qty">
    <input type="text" name="amount">
</div>


问:
OpenGL depth test not working as expected
I have a simple program to use depth test.   It is not working as expected.   The program draws X, Y axis and a sphere near the origin.
If I don't turn on the GL_DEPTH_TEST, the sphere is drawn over the axis.   If I turn on the GL_DEPTH_TEST, the axis are drawn over the sphere which I was not expecting.   Can someone tell me what I did
wrong ?</p>

```<code>void
glwid::initializeGL()
{
    glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
}

void
glwid::resizeGL(int width, int height)
{
    glViewport( 0, 0, (GLint)width, (GLint)height );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glEnable (GL_DEPTH_TEST);
}

void
glwid::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt (0, 0, 100, 0, 0, 0, 0, 1, 0);

    //
    // X axis
    //
    glBegin( GL_LINES );
    qglColor( green );
    glVertex3f (-100.0,  0, 0. );
    glVertex3f (100.0, 0, 0. );
    glEnd();

    //
    // Y axis
    //
    glBegin( GL_LINES );
    qglColor( red );
    glVertex3f (0.0, 100.0, 0. );
    glVertex3f (0.0, -100, 0. );
    glEnd();

    //
    // sun
    //
    glTranslated (5, 0, 20);
    GLUquadricObj *sphere_quadric = gluNewQuadric();
    glColor3ub (255, 255, 0);
    gluQuadricDrawStyle(sphere_quadric, (GLenum)GLU_SMOOTH);
    gluSphere(sphere_quadric, 10, 36, 36);
}
</code>```

答:
I've tried your code. The problem is in resizeGL() function.
The problem was your putting to

```<code>gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
</code>```

0.0 value as a third argument. Put 0.01 for example - and everything will be ok. that's because this parameter should always be positive:
http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml

Also change (GLint)width/ (GLint)height to (GLfloat)width/ (GLfloat)height otherwise the result will be strange.

And it's better to put glEnable(GL_DEPTH_TEST) into initializeGL() function

Body:
I have a simple program to use depth test.   It is not working as expected.   The program draws X, Y axis and a sphere near the origin.
If I don't turn on the GL_DEPTH_TEST, the sphere is drawn over the axis.   If I turn on the GL_DEPTH_TEST, the axis are drawn over the sphere which I was not expecting.   Can someone tell me what I did
wrong ?

void
glwid::initializeGL()
{
    glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
}

void
glwid::resizeGL(int width, int height)
{
    glViewport( 0, 0, (GLint)width, (GLint)height );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glEnable (GL_DEPTH_TEST);
}

void
glwid::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt (0, 0, 100, 0, 0, 0, 0, 1, 0);

    //
    // X axis
    //
    glBegin( GL_LINES );
    qglColor( green );
    glVertex3f (-100.0,  0, 0. );
    glVertex3f (100.0, 0, 0. );
    glEnd();

    //
    // Y axis
    //
    glBegin( GL_LINES );
    qglColor( red );
    glVertex3f (0.0, 100.0, 0. );
    glVertex3f (0.0, -100, 0. );
    glEnd();

    //
    // sun
    //
    glTranslated (5, 0, 20);
    GLUquadricObj *sphere_quadric = gluNewQuadric();
    glColor3ub (255, 255, 0);
    gluQuadricDrawStyle(sphere_quadric, (GLenum)GLU_SMOOTH);
    gluSphere(sphere_quadric, 10, 36, 36);
}

Body:
I've tried your code. The problem is in resizeGL() function.
The problem was your putting to

gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );

0.0 value as a third argument. Put 0.01 for example - and everything will be ok. that's because this parameter should always be positive:
http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml

Also change (GLint)width/ (GLint)height to (GLfloat)width/ (GLfloat)height otherwise the result will be strange.

And it's better to put glEnable(GL_DEPTH_TEST) into initializeGL() function


问:
Calling fopen with an output from fgets
I am trying to open files with an output from fgets from another text file.

Specifically, my "./list.txt" contains all of the relative paths to the files I want to open.

For example, this is what list.txt looks like:

```<code>./tst/f/ak/1237743.txt
./tst/f/ak/1393387.txt
./tst/f/ak/276317o.txt
./tst/f/ak/44z5938.txt
.
.
.
</code>```

and so on.

What I tried to do was get one line from this "list.txt" and use that output as a parameter for another fopen call, thereby resulting in opening of "./tst/f/ak/1237743.txt" and so on.

I made a very simple code to see whether or not this could be done.

This is how my code looks like:

```<code>int main()
{
    FILE *f;
    f = fopen("./list.txt", "r");
    if(f==NULL){

        printf("failed\n");
        return 1;
    }

    char tmp[255];
    char *addr;
    addr = fgets(tmp, sizeof(tmp), f);
    addr[strlen(addr)-1] = '\0';
    fclose(f);
    printf("%s\n", addr);

    FILE *x;
    x = fopen(addr, "r");
    if(x==NULL){

        printf("failure\n");
        return 1;
    }

    printf("Success\n");

    fclose(x);
}
</code>```

This is what I got:

./tst/f/ak/1237743.txt

failure

Any help on where I'm doing it wrong?

I also tried

```<code>fopen("./tst/f/ak/1237743.txt", "r)
</code>```

and it worked fine, so I am sure there is nothing wrong with relative paths here...

答:
Copying comments into an answer.

The basic problem is that your data file has CRLF (DOS-style) line endings but you're working on a Unix machine that doesn't map CRLF to newline, unlike a Windows machine.

You could improve the printing by enclosing the name in, for example, square brackets:

```<code>printf("[%s]\n", addr);
</code>```

This would show whether there is a newline, or perhaps a carriage return, in the string addr. And that, I suspect, is the cause of your problem. You'd probably see the ] on a different line from the [. Alternatively, you might see the ] at the start of the line and not see the [ at all.

Also, are you compiling and running on a Unix derivative or on Windows? Was the data file ever on a Windows machine? (I guess you're using Linux and the data file came from Windows.)

To which the response was:

Wow, you are right. [%s]\n shows "]./tst/f/ak/1237743.txt". And yes, I am using Ubuntu but the list.txt file was created from a Windows machine. Is this the source of the problem?

And the answer is:

That's a carriage return before the newline that you zap. […] Yes — the configuration information you give is the source of your trouble; Windows data on a Unix (Linux, Ubuntu) machine.

The trick of surrounding text strings with marker characters can often diagnose problems like this quite quickly. It's worth remembering.

And again:

Thank you! So I guess I have to create a whole new list.txt file?

To which the response is:

You have a couple of options.  One would be to create a new file.  You could use a conversion utility such as dos2unix to convert the file.  Or you could strip newlines or CRLF by using strcspn() instead of strlen(), like this:

```<code>addr[strcspn(addr, "\r\n")] = '\0';`
</code>```

That will put the null byte at the first CR or LF it encounters, or overwrite the null byte with a null byte if there are no CR or LF characters (so it is safe, even with degenerate data).

Title: Calling fopen with an output from fgets

Body:
I am trying to open files with an output from fgets from another text file.

Specifically, my "./list.txt" contains all of the relative paths to the files I want to open.

For example, this is what list.txt looks like:

./tst/f/ak/1237743.txt
./tst/f/ak/1393387.txt
./tst/f/ak/276317o.txt
./tst/f/ak/44z5938.txt
.
.
.

and so on.

What I tried to do was get one line from this "list.txt" and use that output as a parameter for another fopen call, thereby resulting in opening of "./tst/f/ak/1237743.txt" and so on.

I made a very simple code to see whether or not this could be done.

This is how my code looks like:

int main()
{
    FILE *f;
    f = fopen("./list.txt", "r");
    if(f==NULL){

        printf("failed\n");
        return 1;
    }

    char tmp[255];
    char *addr;
    addr = fgets(tmp, sizeof(tmp), f);
    addr[strlen(addr)-1] = '\0';
    fclose(f);
    printf("%s\n", addr);

    FILE *x;
    x = fopen(addr, "r");
    if(x==NULL){

        printf("failure\n");
        return 1;
    }

    printf("Success\n");

    fclose(x);
}

This is what I got:

./tst/f/ak/1237743.txt

failure

Any help on where I'm doing it wrong?

I also tried

fopen("./tst/f/ak/1237743.txt", "r)

and it worked fine, so I am sure there is nothing wrong with relative paths here...

Body:
Copying comments into an answer.

The basic problem is that your data file has CRLF (DOS-style) line endings but you're working on a Unix machine that doesn't map CRLF to newline, unlike a Windows machine.

You could improve the printing by enclosing the name in, for example, square brackets:

printf("[%s]\n", addr);

This would show whether there is a newline, or perhaps a carriage return, in the string addr. And that, I suspect, is the cause of your problem. You'd probably see the ] on a different line from the [. Alternatively, you might see the ] at the start of the line and not see the [ at all.

Also, are you compiling and running on a Unix derivative or on Windows? Was the data file ever on a Windows machine? (I guess you're using Linux and the data file came from Windows.)

To which the response was:

Wow, you are right. [%s]\n shows "]./tst/f/ak/1237743.txt". And yes, I am using Ubuntu but the list.txt file was created from a Windows machine. Is this the source of the problem?

And the answer is:

That's a carriage return before the newline that you zap. […] Yes — the configuration information you give is the source of your trouble; Windows data on a Unix (Linux, Ubuntu) machine.

The trick of surrounding text strings with marker characters can often diagnose problems like this quite quickly. It's worth remembering.

And again:

Thank you! So I guess I have to create a whole new list.txt file?

To which the response is:

You have a couple of options.  One would be to create a new file.  You could use a conversion utility such as dos2unix to convert the file.  Or you could strip newlines or CRLF by using strcspn() instead of strlen(), like this:

addr[strcspn(addr, "\r\n")] = '\0';`

That will put the null byte at the first CR or LF it encounters, or overwrite the null byte with a null byte if there are no CR or LF characters (so it is safe, even with degenerate data).