问:
One page menu on scroll with underline sliding links as active
I have a one page scroll menu with an underline sliding in from left to right when hovering a link. I need help on how to make a link active (meaning the line full) when in specific section such as "About".

Heres a picture that might help to show what I'm talking about (notice the link "Run" being highlighted):

I've seen many examples of a link being active online but its very confusing cause I haven't found one with my specific problem.

The closest example I found online was this http://jsfiddle.net/mdesdev/zkrh7/ but i still can't figure out how to fix the underline active.

I have created a js fiddle to show what I have so far:
    https://jsfiddle.net/rsrsrs/36rtdboh/

HTML:

```<code><div id="nav_Wrapper_dk">
<nav id="dk_Nav" role="navigation" class="cf">

    <div><a href="#home" class="link_Button sliding-u-l-r scroll">Home</a>      </div>
    <div><a href="#about" class="link_Button sliding-u-l-r scroll">About us</a></div>
    <div><a href="#link3" class="link_Button sliding-u-l-r">Gallery</a></div>
    <div><a href="#link4" class="link_Button sliding-u-l-r">Find Us</a></div>
    <div><a href="#link5" class="link_Button sliding-u-l-r">Contact</a></div>
    <div><a href="#link6" class="link_Button sliding-u-l-r">Catering</a></div>
    <div><a href="#link7" class="link_Button sliding-u-l-r">Blog</a></div>

</nav>

</div>

<div id="home"></div>

<div id="about"></div>
</code>```

CSS:

```<code>#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    width: 742.6167px;
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
    background: white;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        margin-right: 44.8px;
    }

#dk_Nav div a {
  text-decoration: none
}

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}
</code>```

Javascript:

```<code>// Scroll Menu
jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
  event.preventDefault();
  $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});
</code>```

Any sort of help would be highly appreciated, thanks!

答:
make a.active class that displays the bar as it looks at the end of the animation.

Toggle it on click between the elements like this:

```<code>$(document).on('click','.scroll',function(e){
    $('.scroll').removeClass('active');
    $(e.target).addClass('active');
});
</code>```

JSFIDDLE Example

https://jsfiddle.net/Panomosh/yu530bpf/

Body:
I have a one page scroll menu with an underline sliding in from left to right when hovering a link. I need help on how to make a link active (meaning the line full) when in specific section such as "About".

Heres a picture that might help to show what I'm talking about (notice the link "Run" being highlighted):

I've seen many examples of a link being active online but its very confusing cause I haven't found one with my specific problem.

The closest example I found online was this http://jsfiddle.net/mdesdev/zkrh7/ but i still can't figure out how to fix the underline active.

I have created a js fiddle to show what I have so far:
    https://jsfiddle.net/rsrsrs/36rtdboh/

HTML:

Home

About us

Gallery

Find Us

Contact

Catering

Blog

CSS:

#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    width: 742.6167px;
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
    background: white;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        margin-right: 44.8px;
    }

#dk_Nav div a {
  text-decoration: none
}

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}

Javascript:

// Scroll Menu
jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
  event.preventDefault();
  $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});

Any sort of help would be highly appreciated, thanks!

Body:
make a.active class that displays the bar as it looks at the end of the animation.

Toggle it on click between the elements like this:

$(document).on('click','.scroll',function(e){
    $('.scroll').removeClass('active');
    $(e.target).addClass('active');
});

JSFIDDLE Example

https://jsfiddle.net/Panomosh/yu530bpf/


来源: stackexchange

问:
string.compare and string for comparison
I have my code like this

```<code>private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }
</code>```

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

答:
I suggest you use:

```<code>// There's no point in casting it in every if statement
string selectedItem = (string) cmbOperations.SelectedItem;

if (selectedItem.Equals("NonPrimaryKeyTables",
                        StringComparison.CurrentCultureIgnoreCase))
{
    ...
}
</code>```

Choosing the right string comparison can be tricky. See this MSDN article for a lot more information.

I wouldn't suggest using Compare as other people have suggested, simply because it's not the right emphasis - Compare is designed to be used for testing which order strings should appear in when they're sorted. That has the by-product of allowing you to test for equality, but it's not the main aim. Using Equals shows that all you care about is equality - if the two strings aren't equal, you don't care which would come first. Using Compare would work, but it doesn't leave your code expressing itself as clearly as it can.

ContentLicense: CC BY-SA 2.5

Body:
I have my code like this

private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

Body:
I suggest you use:

// There's no point in casting it in every if statement
string selectedItem = (string) cmbOperations.SelectedItem;

if (selectedItem.Equals("NonPrimaryKeyTables",
                        StringComparison.CurrentCultureIgnoreCase))
{
    ...
}

Choosing the right string comparison can be tricky. See this MSDN article for a lot more information.

I wouldn't suggest using Compare as other people have suggested, simply because it's not the right emphasis - Compare is designed to be used for testing which order strings should appear in when they're sorted. That has the by-product of allowing you to test for equality, but it's not the main aim. Using Equals shows that all you care about is equality - if the two strings aren't equal, you don't care which would come first. Using Compare would work, but it doesn't leave your code expressing itself as clearly as it can.


问:
Getting 404 error when submitting a form
Routes:

```<code>Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
Route::resource('/orders', 'Admin\OrderController');
</code>```

Controller:

```<code>public function addProduct($id){
  dd($id);
}
</code>```

View:

```<code>{!! Form::open(['route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
{!! Form::label('product_id','Product ID') !!}<br>
{!! Form::input('text','product_id') !!}<br>
{!! Form::label('qty','Quantity') !!}<br>
{!! Form::input('number','qty',1,['min'=>'1'])!!}<br>
{!! Form::submit('Add product',['class'=>'btn btn-info ','id'=>'addProduct']) !!}
{!! Form::close() !!}
</code>```

Why am I getting 404 page? I tried to do it with new controller, but also got 404 error...

答:
You can't chain name() on certain versions, I would recommend defining it explicitly.

```<code>Route::post('orders/edit-order-content/{$id}', [
    'uses'  =>'Admin\OrderController@addProduct',
    'as'=>'addProductToOrder'
]);
</code>```

Also as mentioned in another answer, remove the $

ContentLicense: CC BY-SA 3.0

Body:
Routes:

Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
Route::resource('/orders', 'Admin\OrderController');

Controller:

public function addProduct($id){
  dd($id);
}

View:

{!! Form::open(['route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
{!! Form::label('product_id','Product ID') !!}

{!! Form::input('text','product_id') !!}

{!! Form::label('qty','Quantity') !!}

{!! Form::input('number','qty',1,['min'=>'1'])!!}

{!! Form::submit('Add product',['class'=>'btn btn-info ','id'=>'addProduct']) !!}
{!! Form::close() !!}

Why am I getting 404 page? I tried to do it with new controller, but also got 404 error...

Body:
You can't chain name() on certain versions, I would recommend defining it explicitly.

Route::post('orders/edit-order-content/{$id}', [
    'uses'  =>'Admin\OrderController@addProduct',
    'as'=>'addProductToOrder'
]);

Also as mentioned in another answer, remove the $


问:
How to reset editor for fields in Model View in MVC
I have a web page in which i can input values. For that, i have provided code something like this

```<code><td colspan="2">
    @Html.EditorFor(model => model.Line1, new { id= "txtLine1" })
</td>
</code>```

which creates an editor field in the view in the web page for Address Line1. Now , on click of reset button, i want whatever is filled in the editor for Line1, it should be cleared. For this i am using a reset button and javascript as below

```<code><input type="button" value="reset" id="btnReset" />

<script type="text/javascript">
 $(document).ready(function () {
    $("#btnReset").click(function () {
            $("#txtLine1").val("");
        });
     });
</script>
</code>```

but this is not working for me. Have tried a lot, googled a lot but no solution seems to work. have even tried giving input type= "reset". Please provide the best solution for this

答:
You are referencing the Editorfor control by the id that you've specified in the html attributes. "txtLine1". If you look at the html generated, its "Line1" as per your model binding.

Change to the below and it works fine.

```<code><script>
 $(document).ready(function () {
    $("#btnReset").click(function () {
            $("#Line1").val("");
        });
     });
</script>
</code>```

Body:
I have a web page in which i can input values. For that, i have provided code something like this

    @Html.EditorFor(model => model.Line1, new { id= "txtLine1" })

which creates an editor field in the view in the web page for Address Line1. Now , on click of reset button, i want whatever is filled in the editor for Line1, it should be cleared. For this i am using a reset button and javascript as below

<input type="button" value="reset" id="btnReset" />

but this is not working for me. Have tried a lot, googled a lot but no solution seems to work. have even tried giving input type= "reset". Please provide the best solution for this

Body:
You are referencing the Editorfor control by the id that you've specified in the html attributes. "txtLine1". If you look at the html generated, its "Line1" as per your model binding.

Change to the below and it works fine.

<script>
 $(document).ready(function () {
    $("#btnReset").click(function () {
            $("#Line1").val("");
        });
     });
</script>


问:
Override onSavedInstanceState: savedInstanceState object is always null
I have two activities (A and B). Activity A calls activity B. Activity B has Back (Up) button like this:

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Now when this UP button is pressed, onCreate of activity A is again called. In the activity A, there is a classId variable (which I got from an Intent) which I want to retain. For this I have following code in my onCreate of activity A:

```<code>        if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }
</code>```

I have also overriden the onSavedInstanceState method:

```<code>@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}
</code>```

I am following this SO answer:
onCreate being called on Activity A in up navigation

The problem I am facing is that when I come again to activity A by passing back button in activity B, onCreate gets called and I found savedInstanceState to be NULL.

Edit:

Is there any other way to save my classId variable so that when I return again to activity A, I can use that?

Edit 2

If I set launch mode of my activity A to SingleTop in the manifest file, my issue gets resolved. Is it the right approach?

答:
I changed the launchMode of the activity A to singleTop in the mainfest file like this:

```<code>android:launchMode="singleTop"
</code>```

I followed this question on SO: Setting launchMode="singleTask" vs setting activity launchMode="singleTop"

By using this approach, activity A is not destroyed and when I just finish the activity B or click UP navigation in activity B, the existing instance of activity A is launched again.

Body:
I have two activities (A and B). Activity A calls activity B. Activity B has Back (Up) button like this:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now when this UP button is pressed, onCreate of activity A is again called. In the activity A, there is a classId variable (which I got from an Intent) which I want to retain. For this I have following code in my onCreate of activity A:

        if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }

I have also overriden the onSavedInstanceState method:

@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}

I am following this SO answer:
onCreate being called on Activity A in up navigation

The problem I am facing is that when I come again to activity A by passing back button in activity B, onCreate gets called and I found savedInstanceState to be NULL.

Edit:

Is there any other way to save my classId variable so that when I return again to activity A, I can use that?

Edit 2

If I set launch mode of my activity A to SingleTop in the manifest file, my issue gets resolved. Is it the right approach?

Body:
I changed the launchMode of the activity A to singleTop in the mainfest file like this:

android:launchMode="singleTop"

I followed this question on SO: Setting launchMode="singleTask" vs setting activity launchMode="singleTop"

By using this approach, activity A is not destroyed and when I just finish the activity B or click UP navigation in activity B, the existing instance of activity A is launched again.


问:
Error on lambda operators in android
i want to write a code using Runnable method using lambda operators but i got an error of
Error:(40, 33) error: lambda expressions are not supported in -source 1.7
(use -source 8 or higher to enable lambda expressions)
Here is my code:`</p>

```<code>public void countDownStart(){
    handler= new Handler();
    runnable= (Runnable) () -> {
       handler.postDelayed((Runnable) this, 1000);
        try{
            SimpleDateFormat dateFormat= new SimpleDateFormat("YYYY-MM-DD");
            Date futureDate= dateFormat.parse("2017-03-31");
            Date currentDate= new Date();
            if (!currentDate.after(futureDate)){
                long diff = futureDate.getTime()- currentDate.getTime();
                long days = diff / (24 * 60 * 60 * 1000);
                diff -= days * (24 * 60 * 60 * 1000);
                long hours = diff / (60 * 60 * 1000);
                diff -= hours * (60 * 60 * 1000);
                long minutes = diff / (60 * 1000);
                diff -= minutes * (60* 1000);
                long seconds = diff / 1000;
             txtTimerDay.setText("" + String.format("%02d", days));
             txtTimerHour.setText("" + String.format("%02d", hours));
             txtTimerMinute.setText("" + String.format("%02d", minutes));
             txtTimerSecond.setText("" + String.format("%02d", seconds));
            }else{
                tvEvent.setVisibility(View.VISIBLE);
                tvEvent.setText("The Event Started");
                textViewGone();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    };
    handler.postDelayed(runnable, 1 * 1000);
}
</code>```

答: you are using java 7. lambda expressions are supported since java 8. problem in android is, only android n (7.0) or higher supports java 8. if you still want to use lambdas in lower android versions, you can use libraries like retrolambda, but these libraries often don't support all functionalities of java lambdas. </p>

Title: Error on lambda operators in android

Body:
i want to write a code using Runnable method using lambda operators but i got an error of
Error:(40, 33) error: lambda expressions are not supported in -source 1.7
(use -source 8 or higher to enable lambda expressions)
Here is my code:`

public void countDownStart(){
    handler= new Handler();
    runnable= (Runnable) () -> {
       handler.postDelayed((Runnable) this, 1000);
        try{
            SimpleDateFormat dateFormat= new SimpleDateFormat("YYYY-MM-DD");
            Date futureDate= dateFormat.parse("2017-03-31");
            Date currentDate= new Date();
            if (!currentDate.after(futureDate)){
                long diff = futureDate.getTime()- currentDate.getTime();
                long days = diff / (24 * 60 * 60 * 1000);
                diff -= days * (24 * 60 * 60 * 1000);
                long hours = diff / (60 * 60 * 1000);
                diff -= hours * (60 * 60 * 1000);
                long minutes = diff / (60 * 1000);
                diff -= minutes * (60* 1000);
                long seconds = diff / 1000;
             txtTimerDay.setText("" + String.format("%02d", days));
             txtTimerHour.setText("" + String.format("%02d", hours));
             txtTimerMinute.setText("" + String.format("%02d", minutes));
             txtTimerSecond.setText("" + String.format("%02d", seconds));
            }else{
                tvEvent.setVisibility(View.VISIBLE);
                tvEvent.setText("The Event Started");
                textViewGone();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    };
    handler.postDelayed(runnable, 1 * 1000);
}


问:
C TCP Client sockaddr_in pointer
i would like to creat a simple TCP client with sockaddr_in pointer.

```<code>#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>

#include <errno.h>  /* errno */
#include <string.h> /* strerror() */

using namespace std;

int creeSock();
struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort);

int main(int argc, char *argv[])
{
    if (argc < 3){
        exit(1);
    }

    int dSock = creeSock();
    struct sockaddr_in* aD = configConnect(dSock, argv[1], atoi(argv[2]));

    close(dSock);
    return 0;
}

int creeSock(){
    int dSock;
    if( (dSock = socket(PF_INET, SOCK_STREAM, 0)) == -1){
        perror("Erreur lors de la création de la socket ");
        exit(errno);
    }

    return dSock;
}

struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort){
    struct sockaddr_in* ad = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));

    if(inet_pton(AF_INET, adresseIP, &(ad->sin_addr)) <= 0){
        perror("config error");
        exit(errno);
    }

    ad->sin_port = htons(numPort);

    if (connect(dSock,(struct sockaddr*)ad, sizeof(*ad)) == -1){
        cout<<errno;
        perror("Error connect ");
        exit(errno);
    }

    return ad;
}
</code>```

No compilation error (g++ -std=c++11 client.cpp)
On execution: ./a.out 127.0.0.1 42000

```<code>Error connect : Invalid argument
</code>```

My old code works on same server when sockaddr_in is not a pointer

Thank you in advance.

答:
You're not setting the sin_family element of the structure.

```<code>if(inet_pton(AF_INET, IP, &(ad->sin_addr)) <= 0){
        perror("Error config ");
        exit(errno);
}

ad->sin_port = htons(PORT);

// need to set sin_family, too
ad->sin_family = AF_INET;
</code>```

Title: C TCP Client sockaddr_in pointer

Body:
i would like to creat a simple TCP client with sockaddr_in pointer.

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>

#include <errno.h>  /* errno */
#include <string.h> /* strerror() */

using namespace std;

int creeSock();
struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort);

int main(int argc, char *argv[])
{
    if (argc < 3){
        exit(1);
    }

    int dSock = creeSock();
    struct sockaddr_in* aD = configConnect(dSock, argv[1], atoi(argv[2]));

    close(dSock);
    return 0;
}

int creeSock(){
    int dSock;
    if( (dSock = socket(PF_INET, SOCK_STREAM, 0)) == -1){
        perror("Erreur lors de la création de la socket ");
        exit(errno);
    }

    return dSock;
}

struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort){
    struct sockaddr_in* ad = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));

    if(inet_pton(AF_INET, adresseIP, &(ad->sin_addr)) <= 0){
        perror("config error");
        exit(errno);
    }

    ad->sin_port = htons(numPort);

    if (connect(dSock,(struct sockaddr*)ad, sizeof(*ad)) == -1){
        cout<<errno;
        perror("Error connect ");
        exit(errno);
    }

    return ad;
}

No compilation error (g++ -std=c++11 client.cpp)
On execution: ./a.out 127.0.0.1 42000

Error connect : Invalid argument

My old code works on same server when sockaddr_in is not a pointer

Thank you in advance.

Body:
You're not setting the sin_family element of the structure.

if(inet_pton(AF_INET, IP, &(ad->sin_addr)) <= 0){
        perror("Error config ");
        exit(errno);
}

ad->sin_port = htons(PORT);

// need to set sin_family, too
ad->sin_family = AF_INET;


问:
Issue with description from php to csv
I use php to generate a csv file like this:

```<code><?php
function myfunction() {
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');

    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );

    foreach (rows as $row) {
      $description=$this->FixDescription($row['Description']);
      $id = $row['id'];
      $myrow .= $id . ',' . $description ."\n";
}

      fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
      fclose($output);
}
   public function FixDescription($descr){
    $d = html_entity_decode($descr, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars_decode($d);
    $d = str_replace(' ', ' ', $d);
    $d = strip_tags($d);
    $d = str_replace('&','_',$d);
    return $d;
  }
?>
</code>```

When i download the generated file i get some rows correctly but for some rows description breaks and leaves blank rows and then prints and generally create a mess in my csv file. Any ideas of how not to break the content inside description field?

答:
Replace:

```<code>foreach (rows as $row) {
    $description=$this->FixDescription($row['Description']);
    $id = $row['id'];
    $myrow .= $id . ',' . $description ."\n";
}

fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
</code>```

with

```<code>foreach (rows as $row) {
    $description = $this->FixDescription($row['Description']);
    $description = mb_convert_encoding($description, 'UCS-2LE', 'UTF-8');
    $id = $row['id'];
    $myrow = [$id, $description];
    fputcsv($output, $myrow);
}
</code>```

Title: Issue with description from php to csv

Body:
I use php to generate a csv file like this:

<?php
function myfunction() {
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');

    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );

    foreach (rows as $row) {
      $description=$this->FixDescription($row['Description']);
      $id = $row['id'];
      $myrow .= $id . ',' . $description ."\n";
}

      fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
      fclose($output);
}
   public function FixDescription($descr){
    $d = html_entity_decode($descr, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars_decode($d);
    $d = str_replace(' ', ' ', $d);
    $d = strip_tags($d);
    $d = str_replace('&','_',$d);
    return $d;
  }
?>

When i download the generated file i get some rows correctly but for some rows description breaks and leaves blank rows and then prints and generally create a mess in my csv file. Any ideas of how not to break the content inside description field?

Body:
Replace:

foreach (rows as $row) {
    $description=$this->FixDescription($row['Description']);
    $id = $row['id'];
    $myrow .= $id . ',' . $description ."\n";
}

fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));

with

foreach (rows as $row) {
    $description = $this->FixDescription($row['Description']);
    $description = mb_convert_encoding($description, 'UCS-2LE', 'UTF-8');
    $id = $row['id'];
    $myrow = [$id, $description];
    fputcsv($output, $myrow);
}


问:
SQL if/case statement - returning value from db
I have trouble with sql command in MS Sql server .....
I would like to  check names in table. in Column are e.g. Carl, Loius, Manfred, Jenny ....
Is there any way, to create case or if statement :

```<code>Case  when name = 'Carl' then 'Man'
else Return original value(name) from table?
</code>```

(Louis, Manfred, Jenny) ?

If yes, how can i achieve that ? Case statement? If statement?
Thanks in advance

答:
You can do:</p>

```<code> select (Case when name = 'Carl' then 'Man' else name end)
</code>```

Body:
I have trouble with sql command in MS Sql server .....
I would like to  check names in table. in Column are e.g. Carl, Loius, Manfred, Jenny ....
Is there any way, to create case or if statement :

Case  when name = 'Carl' then 'Man'
else Return original value(name) from table?

(Louis, Manfred, Jenny) ?

If yes, how can i achieve that ? Case statement? If statement?
Thanks in advance

Body:
You can do:

 select (Case when name = 'Carl' then 'Man' else name end)


问:
cell tower location for CDMA android phone using getBaseStationLatitude()/Longitude()
I'm developing an android app for CDMA phones that will gather the latitude/longitude of the cell tower they are connected to.

First: is this even possible?

Second: I've looked at previous posts where it says to simply add "CellLocation.requestLocationUpdate();" but it didn't have any effect. Here's the portion of code where I'm trying to retrieve the locations...

```<code>CdmaCellLocation CdmaLocation = (CdmaCellLocation)telephonyManager.getCellLocation();
int Longitude = CdmaLocation.getBaseStationLongitude();
int Latitude = CdmaLocation.getBaseStationLatitude();
</code>```

Looking at the code for the CdmaCellLocation class reveals that those values are defaulted to Integer.MAX_VALUE, but how do you actually set the latitude and longitude?

答:
you have to use PhoneStateListener  with LISTEN_CELL_LOCATION and the corresponding callback function onCellLocationChanged(CellLocation) and LISTEN_CELL_INFO with callback function onCellInfoChanged(List) and possibly LISTEN_SIGNAL_STRENGHTS with callback onSignalStrengthsChanged(Signal Strength)

to quit getting change notification from the PhoneStateListener use LISTEN_NONE

http://www.truiton.com/2014/08/android-phonestatelistener-example/

https://developer.android.com/reference/android/telephony/PhoneStateListener.html

Body:
I'm developing an android app for CDMA phones that will gather the latitude/longitude of the cell tower they are connected to.

First: is this even possible?

Second: I've looked at previous posts where it says to simply add "CellLocation.requestLocationUpdate();" but it didn't have any effect. Here's the portion of code where I'm trying to retrieve the locations...

CdmaCellLocation CdmaLocation = (CdmaCellLocation)telephonyManager.getCellLocation();
int Longitude = CdmaLocation.getBaseStationLongitude();
int Latitude = CdmaLocation.getBaseStationLatitude();

Looking at the code for the CdmaCellLocation class reveals that those values are defaulted to Integer.MAX_VALUE, but how do you actually set the latitude and longitude?


问:
Data structures for bioinformatics
What are some data structures that should be known by somebody involved in bioinformatics? I guess that anyone is supposed to know about lists, hashes, balanced trees, etc., but I expect that there are domain specific data structures. Is there any book devoted to this subject?</p>

答:
Many projects in bioinformatics involve combining information from different, semi-structured sources. RDF and ontologies are essential for much of this. See, for example, the bio2RDF project. http://bio2rdf.org/. A good understanding of identifiers is valuable.

Much bioinformatics is exploratory and rapid lightweight tools are often used. See workflow tools such as Taverna where the primary resource is often a set of web services - so HTTP/REST are common.

Title: Data structures for bioinformatics


问:
'System.OutOfMemoryException' was thrown when there is still plenty of memory free
This is my code:

```<code>int size = 100000000;
double sizeInMegabytes = (size * 8.0) / 1024.0 / 1024.0; //762 mb
double[] randomNumbers = new double[size];
</code>```

Exception:
Exception of type 'System.OutOfMemoryException' was thrown.

I have 4GB memory on this machine 2.5GB is free when I start this running, there is clearly enough space on the PC to handle the 762mb of 100000000 random numbers. I need to store as many random numbers as possible given available memory. When I go to production there will be 12GB on the box and I want to make use of it.

Does the CLR constrain me to a default max memory to start with? and how do I request more?

Update

I thought breaking this into smaller chunks and incrementally adding to my memory requirements would help if the issue is due to memory fragmentation, but it doesn't I can't get past a total ArrayList size of 256mb regardless of what I do tweaking blockSize.

```<code>private static IRandomGenerator rnd = new MersenneTwister();
private static IDistribution dist = new DiscreteNormalDistribution(1048576);
private static List<double> ndRandomNumbers = new List<double>();

private static void AddNDRandomNumbers(int numberOfRandomNumbers) {
    for (int i = 0; i < numberOfRandomNumbers; i++) {
      ndRandomNumbers.Add(dist.ICDF(rnd.nextUniform()));
  }
}
</code>```

From my main method:

```<code>int blockSize = 1000000;

while (true) {
  try
  {
    AddNDRandomNumbers(blockSize);
  }
  catch (System.OutOfMemoryException ex)
  {
    break;
  }
}
double arrayTotalSizeInMegabytes = (ndRandomNumbers.Count * 8.0) / 1024.0 / 1024.0;
</code>```

答: I had a similar problem, it was due to a StringBuilder.ToString();</p>

Body:
This is my code:

int size = 100000000;
double sizeInMegabytes = (size * 8.0) / 1024.0 / 1024.0; //762 mb
double[] randomNumbers = new double[size];

Exception:
Exception of type 'System.OutOfMemoryException' was thrown.

I have 4GB memory on this machine 2.5GB is free when I start this running, there is clearly enough space on the PC to handle the 762mb of 100000000 random numbers. I need to store as many random numbers as possible given available memory. When I go to production there will be 12GB on the box and I want to make use of it.

Does the CLR constrain me to a default max memory to start with? and how do I request more?

Update

I thought breaking this into smaller chunks and incrementally adding to my memory requirements would help if the issue is due to memory fragmentation, but it doesn't I can't get past a total ArrayList size of 256mb regardless of what I do tweaking blockSize.

private static IRandomGenerator rnd = new MersenneTwister();
private static IDistribution dist = new DiscreteNormalDistribution(1048576);
private static List<double> ndRandomNumbers = new List<double>();

private static void AddNDRandomNumbers(int numberOfRandomNumbers) {
    for (int i = 0; i < numberOfRandomNumbers; i++) {
      ndRandomNumbers.Add(dist.ICDF(rnd.nextUniform()));
  }
}

From my main method:

int blockSize = 1000000;

while (true) {
  try
  {
    AddNDRandomNumbers(blockSize);
  }
  catch (System.OutOfMemoryException ex)
  {
    break;
  }
}
double arrayTotalSizeInMegabytes = (ndRandomNumbers.Count * 8.0) / 1024.0 / 1024.0;


问:
C# Garbage collection of object that has a running timer
I have created an object that needs to update it's status in a set interval so I am using a Timer for this. Many of these objects are displayed in different lists. And when such a list is reloaded(which happens often) the object is no longer referenced, the timer is still running tho.

I know I can prevent this by calling dispose, but a developer using this object can forgot to implement the call to dispose and I think will cause a mayor memory leak, am I right in this and what tools can I employ to make sure the object get garbage collected.

Below is a simplified version of how the classes are used.

The Object

```<code>public class Test : IDisposable
{
    protected readonly Timer Timer;
    protected int Count = 0;
    private bool disposed = false;

    public Test()
    {
        Timer = new Timer();
        Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;

        Timer.Elapsed += Timer_Elapsed;
        Timer.AutoReset = true;
        Timer.Start();
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Count++;
    }

    public void Dispose() // implementing IDisposable
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Free other state (managed objects).
            }
            Timer.Stop();
            Timer.Elapsed -= Timer_Elapsed;
            Timer.Dispose();

            // Free your own state (unmanaged objects).
            // Set large fields to null.
            disposed = true;
        }
    }

    // Use C# destructor syntax for finalization code.
    ~Test()
    {
        // Simply call Dispose(false).
        Dispose(false);
    }
}
</code>```

The List class

```<code>public partial class MainWindow : Window
{

    public List<Test> TestsCollection = new List<Test>();
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        TestsCollection.Clear();
        TestsCollection.Add(new Test());
        GC.Collect();
    }
}
</code>```

答:
In this case it seems there will indeed be a leak if you won't Dispose your Test, and finalizer won't help (at least all my tests show that this is how it will behave).

As stated here - timer internally registers callback in GCHandle table, which prevents situation that callback might be invalid when it's time to fire it. Because your callback (Timer_Elapsed) is not static - that means it holds reference to this and so your Test object cannot be collected, because there is rooted reference (GCHandle) to your callback. Now, your object in turn has reference to timer, because you store it in a field. So after all, there is reference from root to both your Test object and your timer, and neither of them can be garbage collected.

To fix the issue - you need to break some of the strong references. You can do that for example like this:

```<code>public class Test : IDisposable {
    protected readonly Timer Timer;
    protected int Count = 0;
    private bool disposed = false;

    public Test() {
        Timer = new Timer(Timer_Elapsed, new WeakReference<Test>(this), 0, 1000);
    }

    private static void Timer_Elapsed(object state) {
        var wr = (WeakReference<Test>) state;
        Test test;
        if (wr.TryGetTarget(out test)) {
            test.Count++;
            Console.WriteLine(test.Count);
        }
    }

    public void Dispose() // implementing IDisposable
    {
        if (!disposed) {
            Timer.Dispose();
            disposed = true;
        }
    }
}
</code>```

There we first replace System.Timers.Timer with System.Threading.Timer and also make callback method static, so that it no longer prevent parent Test object from collection. However, we need to access Test object somehow in callback - so we pass WeakReference as a state there (we cannot pass object itself because it will create the same situation we are trying to avoid). In callback we check if Test object is still alive, and if yes - do what is needed with it.

We also remove destructor because it's not necessary here. When Test object is garbage collected - Timer will also be collected and it's own destructor will be called.

Body:
I have created an object that needs to update it's status in a set interval so I am using a Timer for this. Many of these objects are displayed in different lists. And when such a list is reloaded(which happens often) the object is no longer referenced, the timer is still running tho.

I know I can prevent this by calling dispose, but a developer using this object can forgot to implement the call to dispose and I think will cause a mayor memory leak, am I right in this and what tools can I employ to make sure the object get garbage collected.

Below is a simplified version of how the classes are used.

The Object

public class Test : IDisposable
{
    protected readonly Timer Timer;
    protected int Count = 0;
    private bool disposed = false;

    public Test()
    {
        Timer = new Timer();
        Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;

        Timer.Elapsed += Timer_Elapsed;
        Timer.AutoReset = true;
        Timer.Start();
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Count++;
    }

    public void Dispose() // implementing IDisposable
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Free other state (managed objects).
            }
            Timer.Stop();
            Timer.Elapsed -= Timer_Elapsed;
            Timer.Dispose();

            // Free your own state (unmanaged objects).
            // Set large fields to null.
            disposed = true;
        }
    }

    // Use C# destructor syntax for finalization code.
    ~Test()
    {
        // Simply call Dispose(false).
        Dispose(false);
    }
}

The List class

public partial class MainWindow : Window
{

    public List<Test> TestsCollection = new List<Test>();
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        TestsCollection.Clear();
        TestsCollection.Add(new Test());
        GC.Collect();
    }
}

Body:
In this case it seems there will indeed be a leak if you won't Dispose your Test, and finalizer won't help (at least all my tests show that this is how it will behave).

As stated here - timer internally registers callback in GCHandle table, which prevents situation that callback might be invalid when it's time to fire it. Because your callback (Timer_Elapsed) is not static - that means it holds reference to this and so your Test object cannot be collected, because there is rooted reference (GCHandle) to your callback. Now, your object in turn has reference to timer, because you store it in a field. So after all, there is reference from root to both your Test object and your timer, and neither of them can be garbage collected.

To fix the issue - you need to break some of the strong references. You can do that for example like this:

public class Test : IDisposable {
    protected readonly Timer Timer;
    protected int Count = 0;
    private bool disposed = false;

    public Test() {
        Timer = new Timer(Timer_Elapsed, new WeakReference<Test>(this), 0, 1000);
    }

    private static void Timer_Elapsed(object state) {
        var wr = (WeakReference<Test>) state;
        Test test;
        if (wr.TryGetTarget(out test)) {
            test.Count++;
            Console.WriteLine(test.Count);
        }
    }

    public void Dispose() // implementing IDisposable
    {
        if (!disposed) {
            Timer.Dispose();
            disposed = true;
        }
    }
}

There we first replace System.Timers.Timer with System.Threading.Timer and also make callback method static, so that it no longer prevent parent Test object from collection. However, we need to access Test object somehow in callback - so we pass WeakReference as a state there (we cannot pass object itself because it will create the same situation we are trying to avoid). In callback we check if Test object is still alive, and if yes - do what is needed with it.

We also remove destructor because it's not necessary here. When Test object is garbage collected - Timer will also be collected and it's own destructor will be called.


问:
Relative Link Paths in Github
Hi I can't seem to find out why

```<code>[link](Subfolder/file)
</code>```

doesn't work...

Any Ideas?

答: Alright, turns out relative paths are having issues with spaces...</p>

Title: Relative Link Paths in Github

Body:
Hi I can't seem to find out why

[link](Subfolder/file)

doesn't work...

Any Ideas?


问:
Angular form save not working with dynamic push data
I am new to angular and stuck with dynamic data binding. I have four data
   fields 2 static and 2 dynamically adding after add button. When I click add
   button only two of the fields are shown on the display and remaining data
   is not populated. I might had make some mistake in data passing.
   The first two fields are static and second two are dynamic need to add as
   user clicks. The same happens when using form.
   Will any one please help me resolve this. Thanks in advance.
   Below is my code:</p>

Controller:

```<code>var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.items = [];

  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

  $scope.add = function(itemToAdd) {

    var index = $scope.itemsToAdd.indexOf(itemToAdd);

    $scope.itemsToAdd.splice(index, 1);

    $scope.items.push(angular.copy(itemToAdd))
  }

  $scope.addNew = function() {

    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});
</code>```

View (HTML):

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>

  <div ng-repeat="item in items">
     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}
  </div>
    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />
  <div ng-repeat="itemToAdd in itemsToAdd">
    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>
  </div>
  <div>
    <button ng-click="addNew()">Add new</button>
  </div>
</body>
</code>```

答:
This section:

```<code> <input type="text" ng-model="itemToAdd.regno" />
 <input type="text" ng-model="itemToAdd.section" />
</code>```

is outside ng-repeat and thus does not know what itemToAdd is; chnage it to this:

```<code><div ng-repeat="itemToAdd in itemsToAdd">
 <input type="text" ng-model="itemToAdd.regno" />
 <input type="text" ng-model="itemToAdd.section" />

 <input type="text" ng-model="itemToAdd.firstName" />
 <input type="text" ng-model="itemToAdd.lastName" />
<button ng-click="add(itemToAdd)">Add</button>
</code>```

But this only give you empty display since you are not defining regno and section's default values anywhere. Define them in your code:

```<code>$scope.itemsToAdd = [{
  firstName: '',
   lastName: '',
  section: 'defaultSection',
  regno: 'defaultRegNo'
}];
</code>```

and

```<code> $scope.addNew = function() {

$scope.itemsToAdd.push({
  firstName: '',
   lastName: '',
  section: 'defaultSection',
  regno: 'defaultRegNo'
});
};
</code>```

Body:
I am new to angular and stuck with dynamic data binding. I have four data
   fields 2 static and 2 dynamically adding after add button. When I click add
   button only two of the fields are shown on the display and remaining data
   is not populated. I might had make some mistake in data passing.
   The first two fields are static and second two are dynamic need to add as
   user clicks. The same happens when using form.
   Will any one please help me resolve this. Thanks in advance.
   Below is my code:

Controller:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.items = [];

  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

  $scope.add = function(itemToAdd) {

    var index = $scope.itemsToAdd.indexOf(itemToAdd);

    $scope.itemsToAdd.splice(index, 1);

    $scope.items.push(angular.copy(itemToAdd))
  }

  $scope.addNew = function() {

    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});

View (HTML):

Hello {{name}}!

     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}

    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />

    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>

    <button ng-click="addNew()">Add new</button>

Body:
This section:

 <input type="text" ng-model="itemToAdd.regno" />
 <input type="text" ng-model="itemToAdd.section" />

is outside ng-repeat and thus does not know what itemToAdd is; chnage it to this:

<div ng-repeat="itemToAdd in itemsToAdd">
 <input type="text" ng-model="itemToAdd.regno" />
 <input type="text" ng-model="itemToAdd.section" />

 <input type="text" ng-model="itemToAdd.firstName" />
 <input type="text" ng-model="itemToAdd.lastName" />
<button ng-click="add(itemToAdd)">Add</button>

But this only give you empty display since you are not defining regno and section's default values anywhere. Define them in your code:

$scope.itemsToAdd = [{
  firstName: '',
   lastName: '',
  section: 'defaultSection',
  regno: 'defaultRegNo'
}];

and

 $scope.addNew = function() {

$scope.itemsToAdd.push({
  firstName: '',
   lastName: '',
  section: 'defaultSection',
  regno: 'defaultRegNo'
});
};


问:
Arquillian Graphene @Location placeholder
I'm learning Arquillian right now I wonder how to create page that has a placeholder inside the path. For example:

```<code>@Location("/posts/{id}")
public class BlogPostPage {
     public String getContent() {
          // ...
     }
}
</code>```

or

```<code>@Location("/posts/{name}")
@Location("/specific-page?requiredParam={value}")
</code>```

I have looking for an answer on graphine and arquillian reference guides without success. I used library from other language that have support for page-objects, but it has build-in support for placeholders.

答:
This is not possible currently in Graphene. I've created ARQGRA-500.

It's possible to extend Graphene to add dynamic parameters now. Here's how. (Arquillian 1.1.10.Final, Graphene 2.1.0.Final.)

Create an interface.

```<code>import java.util.Map;

public interface LocationParameterProvider {

    Map<String, String> provideLocationParameters();

}
</code>```

Create a custom LocationDecider to replace the corresponding Graphene's one. I replace the HTTP one. This Decider will add location parameters to the URI, if it sees that the test object implements our interface.

```<code>import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.graphene.location.decider.HTTPLocationDecider;
import org.jboss.arquillian.graphene.spi.location.Scheme;
import org.jboss.arquillian.test.spi.context.TestContext;

public class HTTPParameterizedLocationDecider extends HTTPLocationDecider {

    @Inject
    private Instance<TestContext> testContext;

    @Override
    public Scheme canDecide() {
        return new Scheme.HTTP();
    }

    @Override
    public String decide(String location) {
        String uri = super.decide(location);

        // not sure, how reliable this method of getting the current test object is
        // if it breaks, there is always a possibility of observing
        // org.jboss.arquillian.test.spi.event.suite.TestLifecycleEvent's (or rather its
        // descendants) and storing the test object in a ThreadLocal
        Object testObject = testContext.get().getActiveId();
        if (testObject instanceof LocationParameterProvider) {
            Map<String, String> locationParameters =
                    ((LocationParameterProvider) testObject).provideLocationParameters();

            StringBuilder uriParams = new StringBuilder(64);
            boolean first = true;
            for (Entry<String, String> param : locationParameters.entrySet()) {
                uriParams.append(first ? '?' : '&');
                first = false;
                try {
                    uriParams.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    uriParams.append('=');
                    uriParams.append(URLEncoder.encode(param.getValue(), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
            uri += uriParams.toString();
        }

        return uri;
    }

}
</code>```

Our LocationDecider must be registered to override the Graphene's one.

```<code>import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.arquillian.graphene.location.decider.HTTPLocationDecider;
import org.jboss.arquillian.graphene.spi.location.LocationDecider;

public class MyArquillianExtension implements LoadableExtension {

    @Override
    public void register(ExtensionBuilder builder) {
        builder.override(LocationDecider.class, HTTPLocationDecider.class,
            HTTPParameterizedLocationDecider.class);
    }

}
</code>```

MyArquillianExtension should be registered via SPI, so create a necessary file in your test resources, e.g. for me the file path is src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension. The file must contain a fully qualified class name of MyArquillianExtension.

And that's it. Now you can provide location parameters in a test.

```<code>import java.util.HashMap;
import java.util.Map;

import org.jboss.arquillian.graphene.page.InitialPage;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Test;

public class TestyTest implements LocationParameterProvider {

    @Override
    public Map<String, String> provideLocationParameters() {
        Map<String, String> params = new HashMap<>();
        params.put("mykey", "myvalue");
        return params;
    }

    @Test
    public void test(@InitialPage TestPage page) {
    }

    @Location("MyTestView.xhtml")
    public static class TestPage {

    }

}
</code>```

I've focused on parameters specifically, but hopefully this paves the way for other dynamic path manipulations.

Of course this doesn't fix the Graphene.goTo API. This means before using goTo you have to provide parameters via this roundabout provideLocationParameters way. It's weird. You can make your own alternative API, goTo that accepts parameters, and modify your LocationDecider to support other ParameterProviders.

Body:
I'm learning Arquillian right now I wonder how to create page that has a placeholder inside the path. For example:

@Location("/posts/{id}")
public class BlogPostPage {
     public String getContent() {
          // ...
     }
}

or

@Location("/posts/{name}")
@Location("/specific-page?requiredParam={value}")

I have looking for an answer on graphine and arquillian reference guides without success. I used library from other language that have support for page-objects, but it has build-in support for placeholders.

Body:
This is not possible currently in Graphene. I've created ARQGRA-500.

It's possible to extend Graphene to add dynamic parameters now. Here's how. (Arquillian 1.1.10.Final, Graphene 2.1.0.Final.)

Create an interface.

import java.util.Map;

public interface LocationParameterProvider {

    Map<String, String> provideLocationParameters();

}

Create a custom LocationDecider to replace the corresponding Graphene's one. I replace the HTTP one. This Decider will add location parameters to the URI, if it sees that the test object implements our interface.

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.graphene.location.decider.HTTPLocationDecider;
import org.jboss.arquillian.graphene.spi.location.Scheme;
import org.jboss.arquillian.test.spi.context.TestContext;

public class HTTPParameterizedLocationDecider extends HTTPLocationDecider {

    @Inject
    private Instance<TestContext> testContext;

    @Override
    public Scheme canDecide() {
        return new Scheme.HTTP();
    }

    @Override
    public String decide(String location) {
        String uri = super.decide(location);

        // not sure, how reliable this method of getting the current test object is
        // if it breaks, there is always a possibility of observing
        // org.jboss.arquillian.test.spi.event.suite.TestLifecycleEvent's (or rather its
        // descendants) and storing the test object in a ThreadLocal
        Object testObject = testContext.get().getActiveId();
        if (testObject instanceof LocationParameterProvider) {
            Map<String, String> locationParameters =
                    ((LocationParameterProvider) testObject).provideLocationParameters();

            StringBuilder uriParams = new StringBuilder(64);
            boolean first = true;
            for (Entry<String, String> param : locationParameters.entrySet()) {
                uriParams.append(first ? '?' : '&');
                first = false;
                try {
                    uriParams.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    uriParams.append('=');
                    uriParams.append(URLEncoder.encode(param.getValue(), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
            uri += uriParams.toString();
        }

        return uri;
    }

}

Our LocationDecider must be registered to override the Graphene's one.

import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.arquillian.graphene.location.decider.HTTPLocationDecider;
import org.jboss.arquillian.graphene.spi.location.LocationDecider;

public class MyArquillianExtension implements LoadableExtension {

    @Override
    public void register(ExtensionBuilder builder) {
        builder.override(LocationDecider.class, HTTPLocationDecider.class,
            HTTPParameterizedLocationDecider.class);
    }

}

MyArquillianExtension should be registered via SPI, so create a necessary file in your test resources, e.g. for me the file path is src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension. The file must contain a fully qualified class name of MyArquillianExtension.

And that's it. Now you can provide location parameters in a test.

import java.util.HashMap;
import java.util.Map;

import org.jboss.arquillian.graphene.page.InitialPage;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Test;

public class TestyTest implements LocationParameterProvider {

    @Override
    public Map<String, String> provideLocationParameters() {
        Map<String, String> params = new HashMap<>();
        params.put("mykey", "myvalue");
        return params;
    }

    @Test
    public void test(@InitialPage TestPage page) {
    }

    @Location("MyTestView.xhtml")
    public static class TestPage {

    }

}

I've focused on parameters specifically, but hopefully this paves the way for other dynamic path manipulations.

Of course this doesn't fix the Graphene.goTo API. This means before using goTo you have to provide parameters via this roundabout provideLocationParameters way. It's weird. You can make your own alternative API, goTo that accepts parameters, and modify your LocationDecider to support other ParameterProviders.


问:
S.O.A. with .NET for scalability
Anyone know where I can find useful resource for some information for this.
I reckon SOA is the way to go for scalabilty, but are there down sides such as performance and security I should look at.
Overall what architecture should be considered best for enterprise web applications

A good , complete, up to date book would be valuable, any suggestions?

答:
Here is an article with some real performance data on systems where every class is a service

WCF Service Performance

Title: S.O.A. with .NET for scalability


答:
you mean something like this ?</p>

```<code>select name,
       case when name = 'Carl' then 'Man'
            when name = 'Jenny' then 'women'
       else name end
from   yourtable
</code>```

Title: SQL if/case statement - returning value from db

Body:
you mean something like this ?

select name,
       case when name = 'Carl' then 'Man'
            when name = 'Jenny' then 'women'
       else name end
from   yourtable


问:
Django utilizing/pulling data from other databases
My question below was answered somewhat in past back in 2013 here. But I am looking for more robust and latest solution if there is any.

I have a Django app app1 and I want to tie up data in Django from other databases who are constantly updating on daily basis. For example: In app1, I have model model where user has to input sales order from sap and corresponding opportunity number from salesforce. I have tools who dump data from sap into sapdb and salesforce into salesforcedb.

My model in app1 looks like:

```<code>class SalesOrderMapping(models.Model):
    sales_order = models.CharField("Sales Order #", max_length=10, primary_key=True)
    opportunity_number = models.CharField("Opportunity Number", max_length=30)

    class Meta:
        verbose_name_plural = "Sales Order / Opportunity Mapping"
        ordering = ('sales_order', 'opportunity_number')

    def __str__(self):
        return self.sales_order
</code>```

So as you can see that in above model, I have opportunity_number, I want user to type in sales_order and instead of typing in opportunity_number it can be autocomplete text box(ideally) or a drop down populated by a table in salesforcedb. So far I have been able to describe the databases in settings.py. Can somebody point me in right direction?

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoportal',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    },

    'sap': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sapdb',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    },

    'sfdc': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'salesforcedb',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}
</code>```

答:
First you will need a database router for your apps, I'll try to do something similar to what you need with the information given

app1/routers.py

```<code>class App1Router(object):
    def db_for_read(self, model, **hints):

        if model._meta.app_label == 'app1':
            return 'default'
        return None
    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to app1.
        """
        if model._meta.app_label == 'app1':
            return 'default'
        return None
    def allow_relation(self, obj1, obj2, **hints):
         db_list = ('default', 'sap', 'sfdc')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True
</code>```

and in your settings.py file add the following

```<code>DATABASE_ROUTERS = ['app1.routers.App1Router',]
</code>```

You can use the inspectdb command to create the models of the existing databases, e.g.:

```<code>./manage.py inspectdb --database "sap"
</code>```

I hope it helps

Source: Personal experience and the Django Documentation https://docs.djangoproject.com/en/1.10/topics/db/multi-db/

Body:
My question below was answered somewhat in past back in 2013 here. But I am looking for more robust and latest solution if there is any.

I have a Django app app1 and I want to tie up data in Django from other databases who are constantly updating on daily basis. For example: In app1, I have model model where user has to input sales order from sap and corresponding opportunity number from salesforce. I have tools who dump data from sap into sapdb and salesforce into salesforcedb.

My model in app1 looks like:

class SalesOrderMapping(models.Model):
    sales_order = models.CharField("Sales Order #", max_length=10, primary_key=True)
    opportunity_number = models.CharField("Opportunity Number", max_length=30)

    class Meta:
        verbose_name_plural = "Sales Order / Opportunity Mapping"
        ordering = ('sales_order', 'opportunity_number')

    def __str__(self):
        return self.sales_order

So as you can see that in above model, I have opportunity_number, I want user to type in sales_order and instead of typing in opportunity_number it can be autocomplete text box(ideally) or a drop down populated by a table in salesforcedb. So far I have been able to describe the databases in settings.py. Can somebody point me in right direction?

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoportal',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    },

    'sap': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sapdb',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    },

    'sfdc': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'salesforcedb',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

Body:
First you will need a database router for your apps, I'll try to do something similar to what you need with the information given

app1/routers.py

class App1Router(object):
    def db_for_read(self, model, **hints):

        if model._meta.app_label == 'app1':
            return 'default'
        return None
    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to app1.
        """
        if model._meta.app_label == 'app1':
            return 'default'
        return None
    def allow_relation(self, obj1, obj2, **hints):
         db_list = ('default', 'sap', 'sfdc')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True

and in your settings.py file add the following

DATABASE_ROUTERS = ['app1.routers.App1Router',]

You can use the inspectdb command to create the models of the existing databases, e.g.:

./manage.py inspectdb --database "sap"

I hope it helps

Source: Personal experience and the Django Documentation https://docs.djangoproject.com/en/1.10/topics/db/multi-db/


问:
Entity Framework Core jsonb column type
I am using Entity Framework Core with npgsql postgresql for Entity Framework Core.

My question is, using migrations, how do I mark a class property to generate a JSONB column type?

For example:

```<code>public class MyTableClass
{
    public int Id { get; set; }

    // My JSONB column
    public string Data { get; set; }
}
</code>```

Thanks in advance.

答:
Based on H. Herzl comment:

My final solution was something like this:

```<code>public class MyTableClass
{
    public int Id { get; set; }

    [Column(TypeName = "jsonb")]
    public string Data { get; set; }
}
</code>```

Migrations generated this:

```<code>Data = table.Column<string>(type: "jsonb", nullable: true),
</code>```

When updated the database with migrations, the Data column was created correctly with jsonb type.

Thank you H. Herzl!

Title: Entity Framework Core jsonb column type

Body:
I am using Entity Framework Core with npgsql postgresql for Entity Framework Core.

My question is, using migrations, how do I mark a class property to generate a JSONB column type?

For example:

public class MyTableClass
{
    public int Id { get; set; }

    // My JSONB column
    public string Data { get; set; }
}

Thanks in advance.

Body:
Based on H. Herzl comment:

My final solution was something like this:

public class MyTableClass
{
    public int Id { get; set; }

    [Column(TypeName = "jsonb")]
    public string Data { get; set; }
}

Migrations generated this:

Data = table.Column<string>(type: "jsonb", nullable: true),

When updated the database with migrations, the Data column was created correctly with jsonb type.

Thank you H. Herzl!


问:
How to handle Null array in Linq
I have a methods that takes multiple arrays and filter data using linq, the problem I am having is that one or more arrays could be null and I am not sure how to handle null arrays in Linq.:

```<code>public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
        {
            return MongoContext.Products.AsQueryable<SGProduct>().AsEnumerable().Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID).ToList().ToPagedList(page, 6);
        }
</code>```

The houseID array could be null also I will have more parameters to this method like Size array etc.

Any suggestions.
Thanks

答:
Just add null check for array, end create empty one if it's null.

```<code>public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
{
    if(houseID == null) houseID = new string[] {};
    return MongoContext.Products.AsQueryable<SGProduct>().AsEnumerable().Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID).ToList().ToPagedList(page, 6);
}
</code>```

Also, you can query variable and build it with conditions as you go. And then you have finished, just materialize and return records.

```<code>public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
{
    var query = MongoContext.Products.AsQueryable<SGProduct>();
    if(houseID == null)
        query = query.Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID);

    return query.ToList().ToPagedList(page, 6);
}
</code>```

Title: How to handle Null array in Linq

Body:
I have a methods that takes multiple arrays and filter data using linq, the problem I am having is that one or more arrays could be null and I am not sure how to handle null arrays in Linq.:

public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
        {
            return MongoContext.Products.AsQueryable<SGProduct>().AsEnumerable().Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID).ToList().ToPagedList(page, 6);
        }

The houseID array could be null also I will have more parameters to this method like Size array etc.

Any suggestions.
Thanks

Body:
Just add null check for array, end create empty one if it's null.

public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
{
    if(houseID == null) houseID = new string[] {};
    return MongoContext.Products.AsQueryable<SGProduct>().AsEnumerable().Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID).ToList().ToPagedList(page, 6);
}

Also, you can query variable and build it with conditions as you go. And then you have finished, just materialize and return records.

public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
{
    var query = MongoContext.Products.AsQueryable<SGProduct>();
    if(houseID == null)
        query = query.Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID);

    return query.ToList().ToPagedList(page, 6);
}


问:
stderr can only be printed on screen but cannot be piped
I just encountered something strange about stdout and stderr!

This works perfectly:

```<code>$ ( { { echo "This is stdout"; echo "This is stderr" 1>&2; } | sed "s/^/stdout captured - /"; } 3>&2 2>&1 1>&3 ) | sed "s/^/stderr captured - /"
stderr captured - This is stderr
stdout captured - This is stdout
</code>```

However, see this:

```<code>$ sudo postfix status >/dev/null
postfix/postfix-script: the Postfix mail system is not running
$ sudo postfix status 2>/dev/null
$
</code>```

I think, definitely the message on screen is STDERR, BUT:

```<code>$ ( { { sudo postfix status; } | sed "s/^/stdout captured - /"; } 3>&2 2>&1 1>&3 ) | sed "s/^/stderr captured - /"
$
</code>```

Nothing captured. I simply issue below command and get nothing again:

```<code>$ `sudo postfix status 2>/tmp/somelog` && cat /tmp/somelog
$
</code>```

It seems beyond my knowledge about bash

ps: I'm on MAC OSX 10.11.6, terminal.

答:
I think this has to do with the postfix command actually behaving differently when it is part of a pipe.

I tried this on my system :

```<code>sudo postfix status 2>log
</code>```

And log turns out empty.  Same thing with :

```<code>postfix status 2>log
</code>```

It seems postfix suppresses this output when its output is not going to a terminal.

Body:
I just encountered something strange about stdout and stderr!

This works perfectly:

$ ( { { echo "This is stdout"; echo "This is stderr" 1>&2; } | sed "s/^/stdout captured - /"; } 3>&2 2>&1 1>&3 ) | sed "s/^/stderr captured - /"
stderr captured - This is stderr
stdout captured - This is stdout

However, see this:

$ sudo postfix status >/dev/null
postfix/postfix-script: the Postfix mail system is not running
$ sudo postfix status 2>/dev/null
$

I think, definitely the message on screen is STDERR, BUT:

$ ( { { sudo postfix status; } | sed "s/^/stdout captured - /"; } 3>&2 2>&1 1>&3 ) | sed "s/^/stderr captured - /"
$

Nothing captured. I simply issue below command and get nothing again:

$ `sudo postfix status 2>/tmp/somelog` && cat /tmp/somelog
$

It seems beyond my knowledge about bash

ps: I'm on MAC OSX 10.11.6, terminal.

Body:
I think this has to do with the postfix command actually behaving differently when it is part of a pipe.

I tried this on my system :

sudo postfix status 2>log

And log turns out empty.  Same thing with :

postfix status 2>log

It seems postfix suppresses this output when its output is not going to a terminal.


问:
One page menu on scroll with underline sliding links as active
I have a one page scroll menu with an underline sliding in from left to right when hovering a link. I need help on how to make a link active (meaning the line full) when in specific section such as "About".

Heres a picture that might help to show what I'm talking about (notice the link "Run" being highlighted):

I've seen many examples of a link being active online but its very confusing cause I haven't found one with my specific problem.

The closest example I found online was this http://jsfiddle.net/mdesdev/zkrh7/ but i still can't figure out how to fix the underline active.

I have created a js fiddle to show what I have so far:
    https://jsfiddle.net/rsrsrs/36rtdboh/

HTML:

```<code><div id="nav_Wrapper_dk">
<nav id="dk_Nav" role="navigation" class="cf">

    <div><a href="#home" class="link_Button sliding-u-l-r scroll">Home</a>      </div>
    <div><a href="#about" class="link_Button sliding-u-l-r scroll">About us</a></div>
    <div><a href="#link3" class="link_Button sliding-u-l-r">Gallery</a></div>
    <div><a href="#link4" class="link_Button sliding-u-l-r">Find Us</a></div>
    <div><a href="#link5" class="link_Button sliding-u-l-r">Contact</a></div>
    <div><a href="#link6" class="link_Button sliding-u-l-r">Catering</a></div>
    <div><a href="#link7" class="link_Button sliding-u-l-r">Blog</a></div>

</nav>

</div>

<div id="home"></div>

<div id="about"></div>
</code>```

CSS:

```<code>#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    width: 742.6167px;
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
    background: white;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        margin-right: 44.8px;
    }

#dk_Nav div a {
  text-decoration: none
}

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}
</code>```

Javascript:

```<code>// Scroll Menu
jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
  event.preventDefault();
  $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});
</code>```

Any sort of help would be highly appreciated, thanks!

答:
Modify your css class like this

```<code>.sliding-u-l-r:hover:after, .sliding-u-l-r.active:after {
    width: 100%;
    background: black;
}
</code>```

and your javascript to something like this

```<code>jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
    event.preventDefault();
    $( ".scroll" ).removeClass("active");
    $( this ).addClass("active");
    $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});
</code>```

Body:
I have a one page scroll menu with an underline sliding in from left to right when hovering a link. I need help on how to make a link active (meaning the line full) when in specific section such as "About".

Heres a picture that might help to show what I'm talking about (notice the link "Run" being highlighted):

I've seen many examples of a link being active online but its very confusing cause I haven't found one with my specific problem.

The closest example I found online was this http://jsfiddle.net/mdesdev/zkrh7/ but i still can't figure out how to fix the underline active.

I have created a js fiddle to show what I have so far:
    https://jsfiddle.net/rsrsrs/36rtdboh/

HTML:

Home

About us

Gallery

Find Us

Contact

Catering

Blog

CSS:

#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    width: 742.6167px;
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
    background: white;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        margin-right: 44.8px;
    }

#dk_Nav div a {
  text-decoration: none
}

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}

Javascript:

// Scroll Menu
jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
  event.preventDefault();
  $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});

Any sort of help would be highly appreciated, thanks!

Body:
Modify your css class like this

.sliding-u-l-r:hover:after, .sliding-u-l-r.active:after {
    width: 100%;
    background: black;
}

and your javascript to something like this

jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
    event.preventDefault();
    $( ".scroll" ).removeClass("active");
    $( this ).addClass("active");
    $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});


问:
How can a struct inherits itself?
```<code>template <bool condition>
struct when;

template <typename It, typename = void>
struct at_impl : at_impl<It, when<true>> { };

struct at_t {
    template <typename Xs, typename N>
    constexpr decltype(auto) operator()(Xs&& xs, N const& n) const;
};

constexpr at_t at{};

int main()
{
}
</code>```

How could this program compiled? How can a struct inherits itself?!
I don't know what's going on here. Is this a new feture in c++?

答:
How can a struct inherits itself?

No. A struct can not inherit itself.

A struct that is an instance of a struct template can inherit another instance of the same template, as long as the parent is instantiated with different template arguments †.

at_impl is not a struct; it is a template.at_impl<It, when<true>> is an instance of the template, and it is a struct.

Note that the parent struct must be complete at the time the derived struct is instantiated. This is possible if the parent is a specialization. Your example shows neither the definition of at_impl<It, when<true>> specialization, nor any instantiation of at_impl.

This is analogous to functions. A function can call itself recursively, but the function arguments must change. If a function calls itself with the same arguments, then the recursion can never terminate. A function with no arguments can not be recursive ††.

Now, a template has arguments and is analogous to a function with parameters. A type has no template arguments and is analogous to a function with no parameters. Instantiating a template results in a type and is analogous to a function call.

† This is a necessary condition for the termination of the recursion, but not sufficient.

†† Unless the function depends on global state, but from abstract point of view, we must consider global state as an implicit argument in this context.

Title: How can a struct inherits itself?

Body:
template <bool condition>
struct when;

template <typename It, typename = void>
struct at_impl : at_impl<It, when<true>> { };

struct at_t {
    template <typename Xs, typename N>
    constexpr decltype(auto) operator()(Xs&& xs, N const& n) const;
};

constexpr at_t at{};

int main()
{
}

How could this program compiled? How can a struct inherits itself?!
I don't know what's going on here. Is this a new feture in c++?


问:
datetime issue with 01/01/1900
i have a datetime column in sql server and its optional field and if the user decided not to enter then i want to insert the value as NULL in the table and i define something like this:

```<code>@deadlineDate datetime = null
</code>```

when i am inserting into sql server i have this code in asp.net

```<code>private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return null;
    }
    return getDeadlineDate.Value;

}
</code>```

but the problem is: its inserting

```<code>1900-01-01 00:00:00.000
</code>```

in the sql table instead of NULL

what i am doing wrong here?

UPDATE:

```<code>private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return DBNull.Value; //throws error....
    }
    return getDeadlineDate.Value;
}
</code>```

答:
If you are sending query as parameter (of string type) to another method which executes the query like the one below:

```<code>        int userno = 123;
        string date_variable = null;

        string query = string.Format(
                    @"INSERT INTO system_log (userno,ref_date) values ({0},'{1}');",userno,date_variable);

        obj.executeInsert(query,conn);
</code>```

This might again save the default date when executed using ExecuteNonQuery() or something else.

Even passing (object)date_variable ?? DBNull.Value; wont work in this scenario

Then you can simply set date_variable as "null"

```<code>        if (string.IsNullOrEmpty(date_variable))
            date_variable= "null";
        else
            date_variable= "'" + date_variable+ "'";
        string query = string.Format(
                @"INSERT INTO system_log (userno,ref_date) values ({0},{1});",123,date_variable);
         obj.executeInsert(query,conn);
</code>```

Title: datetime issue with 01/01/1900

Body:
i have a datetime column in sql server and its optional field and if the user decided not to enter then i want to insert the value as NULL in the table and i define something like this:

@deadlineDate datetime = null

when i am inserting into sql server i have this code in asp.net

private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return null;
    }
    return getDeadlineDate.Value;

}

but the problem is: its inserting

1900-01-01 00:00:00.000

in the sql table instead of NULL

what i am doing wrong here?

UPDATE:

private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return DBNull.Value; //throws error....
    }
    return getDeadlineDate.Value;
}

Body:
If you are sending query as parameter (of string type) to another method which executes the query like the one below:

        int userno = 123;
        string date_variable = null;

        string query = string.Format(
                    @"INSERT INTO system_log (userno,ref_date) values ({0},'{1}');",userno,date_variable);

        obj.executeInsert(query,conn);

This might again save the default date when executed using ExecuteNonQuery() or something else.

Even passing (object)date_variable ?? DBNull.Value; wont work in this scenario

Then you can simply set date_variable as "null"

        if (string.IsNullOrEmpty(date_variable))
            date_variable= "null";
        else
            date_variable= "'" + date_variable+ "'";
        string query = string.Format(
                @"INSERT INTO system_log (userno,ref_date) values ({0},{1});",123,date_variable);
         obj.executeInsert(query,conn);


问:
Table of totals for the last 12 months, both by month and running
I'd like to have a table that contains 12 rows, one for each of the last 12 months, and two additional columns:

That month's (and only that month's) total spend

Total spend to date, since the beginning of time

The table could look like:

```<code>Month   MonthTotal      RunningTotal
Apr 16  0               6710
May 16  0               6710
Jun 16  2000            8710
Jul 16  0               8710
Aug 16  0               8710
Sep 16  0               8710
Oct 16  1000            9710
Nov 16  0               9710
Dec 16  0               9710
Jan 17  500             10210
Feb 17  0               10210
Mar 17  0               10210
</code>```

I'm almost there but I'm hitting an issue when I have months with no purchases in them - that column is being output as null. Here's my current query:

```<code>with Y(n) as
(
    select 0
    union all
    select n + 1
    from Y
    where n < 11
)

select
    convert(varchar, M.Month) + '/' + convert(varchar, M.Year % 100) as Month,
    isnull(sum(A.Value), 0) as MonthAssetValue,
    sum(A.Value) over (order by A.DateAquired rows between unbounded preceding and current row) as TotalAssetValue

from (
    select
        datepart(year, dateadd(month, -n, getdate())) as [Year],
        datepart(month, dateadd(month, -n, getdate())) as [Month]

    from
        Y
) M

left outer join Asset A
    on (datepart(year, A.DateAquired) = M.Year and datepart(month, A.DateAquired) = M.Month)

group by
    M.Year,
    M.Month,
    A.DateAquired,
    A.Value

order by
    M.Year,
    M.Month
</code>```

Any ideas where I'm going wrong?

Edit:

This is the output I currently get:

```<code>Month   MonthTotal      RunningTotal
Apr 16  0               null
May 16  0               null
Jun 16  2000            8710
Jul 16  0               null
Aug 16  0               null
Sep 16  0               null
Oct 16  1000            9710
Nov 16  0               null
Dec 16  0               null
Jan 17  500             10210
Feb 17  0               null
Mar 17  0               null
</code>```

答:
You can use rolling windowing function</p>

```<code>SELECT Month, MonthTotal, [Sum 12 Months] = SUM(MonthTotal) OVER (ORDER BY [Month] ROWS BETWEEN 11 PRECEDING AND CURRENT ROW)
    FROM YourTable
</code>```

Body:
I'd like to have a table that contains 12 rows, one for each of the last 12 months, and two additional columns:

That month's (and only that month's) total spend

Total spend to date, since the beginning of time

The table could look like:

Month   MonthTotal      RunningTotal
Apr 16  0               6710
May 16  0               6710
Jun 16  2000            8710
Jul 16  0               8710
Aug 16  0               8710
Sep 16  0               8710
Oct 16  1000            9710
Nov 16  0               9710
Dec 16  0               9710
Jan 17  500             10210
Feb 17  0               10210
Mar 17  0               10210

I'm almost there but I'm hitting an issue when I have months with no purchases in them - that column is being output as null. Here's my current query:

with Y(n) as
(
    select 0
    union all
    select n + 1
    from Y
    where n < 11
)

select
    convert(varchar, M.Month) + '/' + convert(varchar, M.Year % 100) as Month,
    isnull(sum(A.Value), 0) as MonthAssetValue,
    sum(A.Value) over (order by A.DateAquired rows between unbounded preceding and current row) as TotalAssetValue

from (
    select
        datepart(year, dateadd(month, -n, getdate())) as [Year],
        datepart(month, dateadd(month, -n, getdate())) as [Month]

    from
        Y
) M

left outer join Asset A
    on (datepart(year, A.DateAquired) = M.Year and datepart(month, A.DateAquired) = M.Month)

group by
    M.Year,
    M.Month,
    A.DateAquired,
    A.Value

order by
    M.Year,
    M.Month

Any ideas where I'm going wrong?

Edit:

This is the output I currently get:

Month   MonthTotal      RunningTotal
Apr 16  0               null
May 16  0               null
Jun 16  2000            8710
Jul 16  0               null
Aug 16  0               null
Sep 16  0               null
Oct 16  1000            9710
Nov 16  0               null
Dec 16  0               null
Jan 17  500             10210
Feb 17  0               null
Mar 17  0               null

Body:
You can use rolling windowing function

SELECT Month, MonthTotal, [Sum 12 Months] = SUM(MonthTotal) OVER (ORDER BY [Month] ROWS BETWEEN 11 PRECEDING AND CURRENT ROW)
    FROM YourTable