问:
caret lda2 parameters values
In order to get the possible values of lda2 parameters I run

```<code>getModelInfo("lda2")[[1]]$grid
</code>```

and got

```<code>function(x, y, len = NULL, search = "grid") data.frame(dimen = 1:min(ncol(x), length(levels(y)) - 1))
</code>```

therefore there's only one parameter: dimen

In my case

```<code>ncol(x)=32
levels(y)=2
</code>```

so

min(ncol(x), length(levels(y)) - 1) = 1

Does this mean that dimen can only take the 1 value?

答:
No.

The : generates a sequence of values. dimen is therefore between 1 and min(ncol(x), length(levels(y)) - 1). The exact values that dimen can take depends on your input data.

For example:

```<code>library(tidyverse)

x <- mtcars %>%
     select(-carb)
y <- mtcars$carb %>% as.factor

dimen <- 1:min(ncol(x), length(levels(y)) - 1)
dimen
> [1] 1 2 3 4 5
</code>```

Title: caret lda2 parameters values

Body:
In order to get the possible values of lda2 parameters I run

getModelInfo("lda2")[[1]]$grid

and got

function(x, y, len = NULL, search = "grid") data.frame(dimen = 1:min(ncol(x), length(levels(y)) - 1))

therefore there's only one parameter: dimen

In my case

ncol(x)=32
levels(y)=2

so

min(ncol(x), length(levels(y)) - 1) = 1

Does this mean that dimen can only take the 1 value?

Body:
No.

The : generates a sequence of values. dimen is therefore between 1 and min(ncol(x), length(levels(y)) - 1). The exact values that dimen can take depends on your input data.

For example:

library(tidyverse)

x <- mtcars %>%
     select(-carb)
y <- mtcars$carb %>% as.factor

dimen <- 1:min(ncol(x), length(levels(y)) - 1)
dimen
> [1] 1 2 3 4 5


来源: stackexchange

问:
getting lastmodified date of image using HTML5 tag
I have tried to use the HTML5 tag to capture image with smartphone (android, iOS, windows) camera or choose image from gallery. It is an ionic project, which has to run with web browser (without installing app on phone) on apache server.

```<code><input id="camera" type="file" accept="image/*" >
</code>```

Now I need to get the lastmodified date of gallery image to check the age of the images which is selected.

But I didn't find any working solution... can anyone help me?
It would be very nice...

Thanks so much!
Greetings

---edited---
Thanks for the solution:

```<code>var fileInput = document.getElementById("myFileInput")
var file = fileInput.files[0]
var lastModified = fileInput.files[0].lastModified
</code>```

But this doesn't work with iOS...

The content of file object (file) in...

OSX chrome:

```<code>{"0":{}}
</code>```

android chrome:

```<code>{"0":{}}
</code>```

safari iPhone:

```<code>{"0":{},"length":1}
</code>```

I don't know why this object doesn't show more attributes... because on chrome for OSX and Android file.lastModified shows the date in ms.

is there anybody who can help out here?
Thanks so much!

答:
It seems like it's possible like so:

```<code>var fileInput = document.getElementById("myFileInput")
var file = fileInput.files[0]
var lastModified = fileInput.files[0].lastModified
</code>```

Here's a fiddle:
jsFiddle

ContentLicense: CC BY-SA 3.0

Body:
I have tried to use the HTML5 tag to capture image with smartphone (android, iOS, windows) camera or choose image from gallery. It is an ionic project, which has to run with web browser (without installing app on phone) on apache server.

<input id="camera" type="file" accept="image/*" >

Now I need to get the lastmodified date of gallery image to check the age of the images which is selected.

But I didn't find any working solution... can anyone help me?
It would be very nice...

Thanks so much!
Greetings

---edited---
Thanks for the solution:

var fileInput = document.getElementById("myFileInput")
var file = fileInput.files[0]
var lastModified = fileInput.files[0].lastModified

But this doesn't work with iOS...

The content of file object (file) in...

OSX chrome:

{"0":{}}

android chrome:

{"0":{}}

safari iPhone:

{"0":{},"length":1}

I don't know why this object doesn't show more attributes... because on chrome for OSX and Android file.lastModified shows the date in ms.

is there anybody who can help out here?
Thanks so much!

Body:
It seems like it's possible like so:

var fileInput = document.getElementById("myFileInput")
var file = fileInput.files[0]
var lastModified = fileInput.files[0].lastModified

Here's a fiddle:
jsFiddle


问:
How to add extra whitespace in PHP?
I was wondering how can I add extra whitespace in php is it something like \s please help thanks.

Is there a tutorial that list these kind of things thanks.

答:
use this one. it will provide 60 spaces. that is your second parameter.

``` echo str_repeat(" ", 60); ```

ContentLicense: CC BY-SA 2.5

Title: How to add extra whitespace in PHP?

Body:
use this one. it will provide 60 spaces. that is your second parameter.

 echo str_repeat("&nbsp;", 60);


问:
Content sent through jQuery ajax is getting cut off
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.

I have set up a test case:

```<code><html>

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script >
$(document).ready(function(){
      var contents = $('html').html();
      var filename = "test/000.html";
      $.ajax({
         type: "POST",
         url: "/file.php",
         data: "content="+contents+"&fn="+filename,
         dataType: "html",
         success: function(msg, ts, xh){
             console.log(msg);
             console.log(ts);
             console.log(xh);
             alert("success");
         },
         processData: false,
         error: function(X, textStatus, error){
             alert("Error saving... please try again now.")
         }
     });
});
</script>

</head>

<body>

<div id="rteContainer" class="dev">
  <div id="textEditor">
    <form>
    <textarea name="balh" id="balh" rows="25" cols="103"></textarea>
    <input type="button" id="updateContent" value="Update Changes">
    <input type="button" id="closeEditor" value="Close Without Saving">
    </form>
  </div>
</div>

</body>
</html>
</code>```

the file.php file is:

```<code><?php
header("Content-type:text/html;charset:UTF-8");
$content = "<html>".stripslashes(urldecode($_POST["content"]))."</html>";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>
</code>```

Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.

答: I suspect that the ampersand in the javascript is causing a problem.  Try replacing it with '&' and see if that fixes it.</p>

Body:
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.

I have set up a test case:

    <form>
    <textarea name="balh" id="balh" rows="25" cols="103"></textarea>
    <input type="button" id="updateContent" value="Update Changes">
    <input type="button" id="closeEditor" value="Close Without Saving">
    </form>

the file.php file is:

<?php
header("Content-type:text/html;charset:UTF-8");
$content = "".stripslashes(urldecode($_POST["content"]))."";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>

Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.


问:
Get crosshair values across multiple Flot Charts
I'm using the jQuery Flot Charts plugin in one of my projects. I have several charts standing in the same column and what I'm trying to do is: Show the crosshair on all of the charts if you hover on any of them. I'm doing this successfully using the following code.

```<code>//graphs - this is an object which contains the references to all of my graphs.

$.each(graphs, function(key, value) {
    $(key).bind("plothover",  function (event, pos, item) {
        $.each(graphs, function(innerKey, innerValue) {
            if(key != innerKey) {
                innerValue.setCrosshair({x: pos.x});
            }
        });
        if(item) {
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);
            console.log("x:" + x + ", " + "y:" + y);
        }
    });
});
</code>```

I'm iterating over the graphs, adding the crosshair and bind it to each other. So, now, when you hover over one of the graphs you'll see the crosshair in the same position on all of the others.

No problems with this. However I'm having problems with the second part of my code:

```<code>if(item) {
    var x = item.datapoint[0].toFixed(2),
        y = item.datapoint[1].toFixed(2);
    console.log("x:" + x + ", " + "y:" + y);
}
</code>```

And the problem is that I'm getting the console.log to print values only when I hover the actual point with my mouse while I want to get that value whenever the crosshair crosses that point, not necessarily the mouse pointer. Any clues what I'm doing wrong or maybe there's a setting in the graph options for that to work?

And another thing is that I can get the value for one graph only - the one my mouse is on, I don't seem to be able to get the values for the rest of the graphs where the crosshair is also moving.

答:
The highlighting with

```<code>if(item) {
    var x = item.datapoint[0].toFixed(2),
        y = item.datapoint[1].toFixed(2);
    console.log("x:" + x + ", " + "y:" + y);
}
</code>```

only works when the cursor is near a point (otherwise item is null).

To get the nearest point to the crosshair, you have to do the highlighting manually by searching the nearest point and interpolate (for every graph). The code for that could look like this:

```<code>var axes = value.getAxes();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
    pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
    return;
}
$('#output').html("x: " + pos.x.toPrecision(2));

$.each(graphs, function(innerKey, innerValue) {
    var i, series = innerValue.getData()[0];

    // Find the nearest points, x-wise
    for (i = 0; i < series.data.length; ++i) {
        if (series.data[i][0] > pos.x) {
            break;
        }
    }

    // Now Interpolate
    var y,
        p1 = series.data[i - 1],
        p2 = series.data[i];

    if (p1 == null) {
        y = p2[1];
    } else if (p2 == null) {
        y = p1[1];
    } else {
        y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
    }

    $('#output').html($('#output').html() + "<br />" + "y (" + innerValue.getData()[0].label + "): " + y.toPrecision(2));
</code>```

See this fiddle for a full working example. Some Remarks to the new code and fiddle:

has sine and cosine values as example data, so uses floating point numbers, change accordingly for int numbers and/or date values

uses a
 element for output instead of the console

point-finding and interpolation code can be optimized further if needed (basic version here taken from the example on the Flot page)

works only if there is only one data series per graph

Body:
I'm using the jQuery Flot Charts plugin in one of my projects. I have several charts standing in the same column and what I'm trying to do is: Show the crosshair on all of the charts if you hover on any of them. I'm doing this successfully using the following code.

//graphs - this is an object which contains the references to all of my graphs.

$.each(graphs, function(key, value) {
    $(key).bind("plothover",  function (event, pos, item) {
        $.each(graphs, function(innerKey, innerValue) {
            if(key != innerKey) {
                innerValue.setCrosshair({x: pos.x});
            }
        });
        if(item) {
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);
            console.log("x:" + x + ", " + "y:" + y);
        }
    });
});

I'm iterating over the graphs, adding the crosshair and bind it to each other. So, now, when you hover over one of the graphs you'll see the crosshair in the same position on all of the others.

No problems with this. However I'm having problems with the second part of my code:

if(item) {
    var x = item.datapoint[0].toFixed(2),
        y = item.datapoint[1].toFixed(2);
    console.log("x:" + x + ", " + "y:" + y);
}

And the problem is that I'm getting the console.log to print values only when I hover the actual point with my mouse while I want to get that value whenever the crosshair crosses that point, not necessarily the mouse pointer. Any clues what I'm doing wrong or maybe there's a setting in the graph options for that to work?

And another thing is that I can get the value for one graph only - the one my mouse is on, I don't seem to be able to get the values for the rest of the graphs where the crosshair is also moving.

Body:
The highlighting with

if(item) {
    var x = item.datapoint[0].toFixed(2),
        y = item.datapoint[1].toFixed(2);
    console.log("x:" + x + ", " + "y:" + y);
}

only works when the cursor is near a point (otherwise item is null).

To get the nearest point to the crosshair, you have to do the highlighting manually by searching the nearest point and interpolate (for every graph). The code for that could look like this:

var axes = value.getAxes();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
    pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
    return;
}
$('#output').html("x: " + pos.x.toPrecision(2));

$.each(graphs, function(innerKey, innerValue) {
    var i, series = innerValue.getData()[0];

    // Find the nearest points, x-wise
    for (i = 0; i < series.data.length; ++i) {
        if (series.data[i][0] > pos.x) {
            break;
        }
    }

    // Now Interpolate
    var y,
        p1 = series.data[i - 1],
        p2 = series.data[i];

    if (p1 == null) {
        y = p2[1];
    } else if (p2 == null) {
        y = p1[1];
    } else {
        y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
    }

    $('#output').html($('#output').html() + "<br />" + "y (" + innerValue.getData()[0].label + "): " + y.toPrecision(2));

See this fiddle for a full working example. Some Remarks to the new code and fiddle:

has sine and cosine values as example data, so uses floating point numbers, change accordingly for int numbers and/or date values

uses a <p> element for output instead of the console

point-finding and interpolation code can be optimized further if needed (basic version here taken from the example on the Flot page)

works only if there is only one data series per graph


问:
React-Native import files outside of main directory
I am trying to make a demo app for some components using Expo and react-native. (Or I also could use regular React-Native)

My problem is I cannot import files outside of the demo app

Here is the structure I have

|-- Components/
|  |-- libs
|  |-- node_modules
|  |-- index.js
|  |-- package.json
|  |-- demo/
|  |  |-- node_modules
|  |  |-- App.js
|  |  |-- package.json

Inside of demo/App.js, I am trying to import one of my components from the upper directory but with no luck. All the components are exported in ./index.js

Inside of App.js, I tried :
import {MyComponent} from 'Components', import {MyComponent} from '../index', or import {MyComponent} from '../../Components/' but none seem to work.

I got the following type of error Directory /Users/kevin/web/myprojects/Components/index doesn't exist

What Am I doing wrong ?

答:
The way the react-native packager works right now, it's just going to scan the roots of your project and below when creating the JavaScript bundle, so it will be really hard to do this.

You basically just need to put the files under the root of your directory. There are some tools out there for syncing files from another directory into a directory under the root so you could use one of those if you really need to.

Some people are working on ways to make symlinks work with this. Notably, you might look at Haul from Callstack. https://github.com/callstack-io/haul
But that isn't integrated into Expo yet.


问:
C# WPF - How to always get the current text from a textbox?
I have a TextBox in FileWindow.xaml :

```<code><TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="233,230,0,0" TextWrapping="Wrap" Text="{Binding FileName}" VerticalAlignment="Top" Width="120"/>
</code>```

In ViewModel.cs:

```<code>public String FileName
{
    get { return _model.filename; }
    set
    {
        if (value != _model.filename)
        {
            _model.filename = value;
            OnPropertyChanged();
        }
    }
}
</code>```

In Model.cs:

```<code>private String _filename = "example.txt";
public String filename { get { return _filename; } set { _filename = value; } }
</code>```

I want that every time I type in the TextBox, the _filename in Model.cs gets updated.

The default text in the TextBox is example.txt, but if I change it, the _filename in Model.cs doesn't change. What am I doing wrong?

答:
Try to set the UpdateSourceTrigger property of the binding to PropertyChanged:

```<code>Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}"
</code>```

Body:
I have a TextBox in FileWindow.xaml :

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="233,230,0,0" TextWrapping="Wrap" Text="{Binding FileName}" VerticalAlignment="Top" Width="120"/>

In ViewModel.cs:

public String FileName
{
    get { return _model.filename; }
    set
    {
        if (value != _model.filename)
        {
            _model.filename = value;
            OnPropertyChanged();
        }
    }
}

In Model.cs:

private String _filename = "example.txt";
public String filename { get { return _filename; } set { _filename = value; } }

I want that every time I type in the TextBox, the _filename in Model.cs gets updated.

The default text in the TextBox is example.txt, but if I change it, the _filename in Model.cs doesn't change. What am I doing wrong?

Body:
Try to set the UpdateSourceTrigger property of the binding to PropertyChanged:

Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}"


问:
Substring comparision with std::memcmp or string::compare?
I want to find a given string within another string. Possible start poisition in known by previous calculations. Example:

```<code>int main()
{
    std::string input("Foo Bar Hash Bang");
    std::string keyword("Bar");

    const char* inputStart = input.c_str() + 4; // at 'B'
    std::cout << "memcmp=" << std::memcmp(inputStart, keyword.c_str(), keyword.length()) << "\n";

    std::cout << "compare=" << input.compare(4, keyword.length(), keyword) << "\n";

    return 0;
}
</code>```

Ideone

Are both equivalent? If the keyword length would exceed the input length from the start position the comparision with memcmp would be still correct. Is strncmp the safer approach?

答:
It is safe, and redundant, as std::char_traits<char>::compare anyway uses memcmp on most of the standard library vendors (I checked VC++ and GCC, which uses memcmp and __builtin_memcmp respectively) .

so as for performance - it won't change much.

better stick to std::string::compare.

Body:
I want to find a given string within another string. Possible start poisition in known by previous calculations. Example:

int main()
{
    std::string input("Foo Bar Hash Bang");
    std::string keyword("Bar");

    const char* inputStart = input.c_str() + 4; // at 'B'
    std::cout << "memcmp=" << std::memcmp(inputStart, keyword.c_str(), keyword.length()) << "\n";

    std::cout << "compare=" << input.compare(4, keyword.length(), keyword) << "\n";

    return 0;
}

Ideone

Are both equivalent? If the keyword length would exceed the input length from the start position the comparision with memcmp would be still correct. Is strncmp the safer approach?


问:
sp_executesql with always true condition
i have been using dynamic queries in sql-server like:

```<code>declare @sql nvarchar (1000),@condition nvarchar(100)='';
set @sql=N'select * from tablename where (0=0)'+@condition+'';
exec(@sql)
</code>```

by this i was able to get my result whether the @condition has any value or not.
But i got to know that sp_executesql is better then exec as it promote query plan reuse.

So, i tried my query with `sp_executesql,

```<code>set @sql =N'select * from dbo.testclient where (0=0) @condition'
exec sp_executesql @sql,N'@condition nvarchar(100)',@condition
</code>```

but it failed with an error as

```<code>Incorrect syntax near '@condition'.
</code>```

My problem is how can i make the above query to work with sp_executesql where the parameter @condition can be a condition or blank (' ') and what am i doing wrong.

答:
When you use variables such as @condition in sp_executesql, it does not simply replace your variable in the sql string with the content of the variable.

What happens is that the variable is bound to the supplied value and the sql statement is untouched.

This all means that you need to create a full sql statement which uses variables if you want to leverage query plan reuse.

For example:

```<code>SET @byIDsql = 'select * from tableName where (0=0) and Id = @Id'
SET @byNameSQL = 'select * from tableName where (0=0) and FirstName = @FirstName'
</code>```

Then you can use sp_executesql to supply the value of @id and @firstName and get query plan reuse.

```<code>exec sp_executesql @byIDsql, N'@ID INT', 15
</code>```

Body:
i have been using dynamic queries in sql-server like:

declare @sql nvarchar (1000),@condition nvarchar(100)='';
set @sql=N'select * from tablename where (0=0)'+@condition+'';
exec(@sql)

by this i was able to get my result whether the @condition has any value or not.
But i got to know that sp_executesql is better then exec as it promote query plan reuse.

So, i tried my query with `sp_executesql,

set @sql =N'select * from dbo.testclient where (0=0) @condition'
exec sp_executesql @sql,N'@condition nvarchar(100)',@condition

but it failed with an error as

Incorrect syntax near '@condition'.

My problem is how can i make the above query to work with sp_executesql where the parameter @condition can be a condition or blank (' ') and what am i doing wrong.

Body:
When you use variables such as @condition in sp_executesql, it does not simply replace your variable in the sql string with the content of the variable.

What happens is that the variable is bound to the supplied value and the sql statement is untouched.

This all means that you need to create a full sql statement which uses variables if you want to leverage query plan reuse.

For example:

SET @byIDsql = 'select * from tableName where (0=0) and Id = @Id'
SET @byNameSQL = 'select * from tableName where (0=0) and FirstName = @FirstName'

Then you can use sp_executesql to supply the value of @id and @firstName and get query plan reuse.

exec sp_executesql @byIDsql, N'@ID INT', 15


问:
How to convert this apache rewrite rule to nginx
I've been struggling to convert my past apache rewrite rule to nginx (also not sure if I'm placing it in the right place so would appreciate if you can tell me where to place it).

Basically this was apache rewrite rule on my .htaccess file on Wordpress:

```<code><IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^/?hosts/(.*)$ /user/$1 [R,L]
</IfModule>
</code>```

As you can see, I'm using this rule in order redirect from example.com/hosts/username to example.com/user/username

I've used this converting tool https://labs.gidix.de/nginx/ and it outputs this conversion: rewrite ^/?hosts/(.*)$ /user/$1 last; - however I tried placing this in Ajenti's(control panel) advanced custom configuration but it's not working.

答:
as an option</p>

```<code>location ~ ^/hosts/(.*)$ {
    return 301 $scheme://$host/user/$1;
}
</code>```

Body:
I've been struggling to convert my past apache rewrite rule to nginx (also not sure if I'm placing it in the right place so would appreciate if you can tell me where to place it).

Basically this was apache rewrite rule on my .htaccess file on Wordpress:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^/?hosts/(.*)$ /user/$1 [R,L]
</IfModule>

As you can see, I'm using this rule in order redirect from example.com/hosts/username to example.com/user/username

I've used this converting tool https://labs.gidix.de/nginx/ and it outputs this conversion: rewrite ^/?hosts/(.*)$ /user/$1 last; - however I tried placing this in Ajenti's(control panel) advanced custom configuration but it's not working.

Body:
as an option

location ~ ^/hosts/(.*)$ {
    return 301 $scheme://$host/user/$1;
}


问:
How to hook jenkins in bitbucket
I am not able to find how to add hooks of jenkin in bitbucket,
Previously there was a link in bitbucket for hooks but now it is missing

Please help

UPDATE:-
 All the solution that are given on stackoverflow are outdated as bitbucket has change few feature

答: Under Build triggers there is a checkbox with label "Build when a change is pushed to BitBucket" check this box, when changes are pushed to bitbucket it will start a build.

Title: How to hook jenkins in bitbucket


问:
Save / load scipy sparse csr_matrix in portable data format
How do you save/load a scipy sparse csr_matrix in a portable format?  The scipy sparse matrix is created on Python 3 (Windows 64-bit) to run on Python 2 (Linux 64-bit).  Initially, I used pickle (with protocol=2 and fix_imports=True) but this didn't work going from Python 3.2.2 (Windows 64-bit) to Python 2.7.2 (Windows 32-bit) and got the error:

```<code>TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).
</code>```

Next, tried numpy.save and numpy.load as well as scipy.io.mmwrite() and scipy.io.mmread() and none of these methods worked either.

答:
Now you can use scipy.sparse.save_npz :
https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.save_npz.html

Body:
How do you save/load a scipy sparse csr_matrix in a portable format?  The scipy sparse matrix is created on Python 3 (Windows 64-bit) to run on Python 2 (Linux 64-bit).  Initially, I used pickle (with protocol=2 and fix_imports=True) but this didn't work going from Python 3.2.2 (Windows 64-bit) to Python 2.7.2 (Windows 32-bit) and got the error:

TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).

Next, tried numpy.save and numpy.load as well as scipy.io.mmwrite() and scipy.io.mmread() and none of these methods worked either.


问:
UniqueConstraint is not reflecting into table
I require email_id to be unique so I have kept it as unique Constraint. But the changes is not reflecting into DDL. I have done the same in another table compliance_user and it works fine there. But why not its happening in registration table ?

registration.java

```<code> package com.uforic.compliance.spring.model;

 import java.util.Date;

 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
 import javax.persistence.ManyToOne;
 import javax.persistence.Table;
 import javax.persistence.Transient;
 import javax.persistence.UniqueConstraint;

@Entity
@Table(name="registration",uniqueConstraints = {@UniqueConstraint(columnNames ="email_id")})
public class Registration {

@Id
@Column(name="reg_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int regId;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@Column(name="email_id")
private String emailId;

@Column(name="password")
private String password;

@Column(name="confirm_password")
private String confirmPassword;

@Column(name="ref_email_id")
private String RefEmailId;

@Column(name="company_name")
private String companyName;

@Column(name="role_id_fk")
private int roleMaster;

@Transient
private String compliance;

@Transient
private String year;

@Transient
private Integer accessRights;

@Transient
private Integer userGroupId;

public int getRegId() {
    return regId;
}

public void setRegId(int regId) {
    this.regId = regId;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getConfirmPassword() {
    return confirmPassword;
}

public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
}

public String getRefEmailId() {
    return RefEmailId;
}

public void setRefEmailId(String refEmailId) {
    RefEmailId = refEmailId;
}

public String getCompanyName() {
    return companyName;
}

public void setCompanyName(String companyName) {
    this.companyName = companyName;
}

public int getRoleMaster() {
    return roleMaster;
}

public void setRoleMaster(int roleMaster) {
    this.roleMaster = roleMaster;
}

public String getCompliance() {
    return compliance;
}

public void setCompliance(String compliance) {
    this.compliance = compliance;
}

public String getYear() {
    return year;
}

public void setYear(String year) {
    this.year = year;
}

public Integer getAccessRights() {
    return accessRights;
}

public void setAccessRights(Integer accessRights) {
    this.accessRights = accessRights;
}

public Integer getUserGroupId() {
    return userGroupId;
}

public void setUserGroupId(Integer userGroupId) {
    this.userGroupId = userGroupId;
}

@Override
public String toString() {
    return "Registration [regId=" + regId + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId="
            + emailId + ", password=" + password + ", confirmPassword=" + confirmPassword + ", RefEmailId="
            + RefEmailId + ", companyName=" + companyName + ", roleMaster=" + roleMaster + "]";
}

}
</code>```

registration DDL

```<code>  CREATE TABLE registration
(
reg_id serial NOT NULL,
ref_email_id character varying(255),
company_name character varying(255),
confirm_password character varying(255),
email_id character varying(255),
first_name character varying(255),
last_name character varying(255),
password character varying(255),
role_id_fk integer,
CONSTRAINT registration_pkey PRIMARY KEY (reg_id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE registration
OWNER TO compliance;
</code>```

答: It worked after regenerating DDL</p>

Body:
I require email_id to be unique so I have kept it as unique Constraint. But the changes is not reflecting into DDL. I have done the same in another table compliance_user and it works fine there. But why not its happening in registration table ?

registration.java

 package com.uforic.compliance.spring.model;

 import java.util.Date;

 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
 import javax.persistence.ManyToOne;
 import javax.persistence.Table;
 import javax.persistence.Transient;
 import javax.persistence.UniqueConstraint;

@Entity
@Table(name="registration",uniqueConstraints = {@UniqueConstraint(columnNames ="email_id")})
public class Registration {

@Id
@Column(name="reg_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int regId;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@Column(name="email_id")
private String emailId;

@Column(name="password")
private String password;

@Column(name="confirm_password")
private String confirmPassword;

@Column(name="ref_email_id")
private String RefEmailId;

@Column(name="company_name")
private String companyName;

@Column(name="role_id_fk")
private int roleMaster;

@Transient
private String compliance;

@Transient
private String year;

@Transient
private Integer accessRights;

@Transient
private Integer userGroupId;

public int getRegId() {
    return regId;
}

public void setRegId(int regId) {
    this.regId = regId;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getConfirmPassword() {
    return confirmPassword;
}

public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
}

public String getRefEmailId() {
    return RefEmailId;
}

public void setRefEmailId(String refEmailId) {
    RefEmailId = refEmailId;
}

public String getCompanyName() {
    return companyName;
}

public void setCompanyName(String companyName) {
    this.companyName = companyName;
}

public int getRoleMaster() {
    return roleMaster;
}

public void setRoleMaster(int roleMaster) {
    this.roleMaster = roleMaster;
}

public String getCompliance() {
    return compliance;
}

public void setCompliance(String compliance) {
    this.compliance = compliance;
}

public String getYear() {
    return year;
}

public void setYear(String year) {
    this.year = year;
}

public Integer getAccessRights() {
    return accessRights;
}

public void setAccessRights(Integer accessRights) {
    this.accessRights = accessRights;
}

public Integer getUserGroupId() {
    return userGroupId;
}

public void setUserGroupId(Integer userGroupId) {
    this.userGroupId = userGroupId;
}

@Override
public String toString() {
    return "Registration [regId=" + regId + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId="
            + emailId + ", password=" + password + ", confirmPassword=" + confirmPassword + ", RefEmailId="
            + RefEmailId + ", companyName=" + companyName + ", roleMaster=" + roleMaster + "]";
}

}

registration DDL

  CREATE TABLE registration
(
reg_id serial NOT NULL,
ref_email_id character varying(255),
company_name character varying(255),
confirm_password character varying(255),
email_id character varying(255),
first_name character varying(255),
last_name character varying(255),
password character varying(255),
role_id_fk integer,
CONSTRAINT registration_pkey PRIMARY KEY (reg_id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE registration
OWNER TO compliance;

Body: It worked after regenerating DDL


问:
Which NSCoder does .pbxproj format use?
Inside the .xcodeproj bundle, main project data is actually stored in the .pbxproj file. It is quite obviously an archived dictionary, but I have not been able to find which coder did Apple use? Is it a custom subclass of NSCoder, or is it documented and I didn't look hard enough?

答: It's actually an old-style property list, so I'd say the NSDictionary facilities for writing a dictionary to a file. But there are also embedded comments, so it might be some sort of custom code.</p>

Title: Which NSCoder does .pbxproj format use?


问:
spark consume from stream -- considering data for longer period
We have a spark job running which consumes data from kafka stream , do some analytics and store the result.

Since data is consumed as they are produced to kafka, if we want to get

count for the whole day,    count for an hour,      average for the whole
  day

that is not possible with this approach. Is there any way which we should follow to accomplish such requirement

Appreciate any help

Thanks and Regards

Raaghu.K

答:
Your streaming job is not supposed to calculate the Daily count/Avg.

Approach 1 :
You can store the data consumer from Kafka into a persistent storage like DB/HBase/HDFS , and then you can run Daily batch which will calculate all the statistics for you like Daily count or avg.

Approach 2 :
In order to get that information form streaming itself you need to use Accumulators which will hold the record count,sum. and calculate avg according.

Approach 3 :
Use streaming window, but holding data for a day doesn't make any sense. If you need 5/10 min avg, you can use this.

I think the first method is preferable as it will give you more flexibility to calculate all the analytics you want.

ContentLicense: CC BY-SA 4.0


问:
How can I write the query as raw in Laravel?
Here is my query:

```<code>SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");
</code>```

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

```<code>DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();
</code>```

答:
Try this</p>

```<code>DB::select(DB::raw('SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2")'));
</code>```

Body:
Here is my query:

SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();

Body:
Try this

DB::select(DB::raw('SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2")'));


问:
White space at start of encoded json array
Admittedly it has been a while since I have been in the php world, but i'm not sure why I am getting 3 spaces at the start of my json_encode string.

```<code>"   [{"id":"1","display_name":"Bob"}]"
</code>```

This is the php i have:

```<code>$stmt = $conn->prepare("SELECT * FROM users");

$queryResult = array();
if ($stmt->execute()) {
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $queryResult[] = $row;
  }
  echo json_encode($queryResult);
}
</code>```

When I echo print_r($stmt->fetch(PDO::FETCH_ASSOC)) I get the following:

```<code>   Array
(
    [id] => 1
    [display_name] => Twitch Dock John
)
</code>```

The 3 spaces are there as well.. what have I done wrong (expecting an incoming face-palm moment)?

答:
You can possibly figure the spot in your codebase where output starts by determining where HTTP headers have been sent:</p>

```<code>if (headers_sent($file, $line)) {
    echo "Ouput starts on: $file: $line\n";
}
</code>```

Body:
Admittedly it has been a while since I have been in the php world, but i'm not sure why I am getting 3 spaces at the start of my json_encode string.

"   [{"id":"1","display_name":"Bob"}]"

This is the php i have:

$stmt = $conn->prepare("SELECT * FROM users");

$queryResult = array();
if ($stmt->execute()) {
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $queryResult[] = $row;
  }
  echo json_encode($queryResult);
}

When I echo print_r($stmt->fetch(PDO::FETCH_ASSOC)) I get the following:

   Array
(
    [id] => 1
    [display_name] => Twitch Dock John
)

The 3 spaces are there as well.. what have I done wrong (expecting an incoming face-palm moment)?

Body:
You can possibly figure the spot in your codebase where output starts by determining where HTTP headers have been sent:

if (headers_sent($file, $line)) {
    echo "Ouput starts on: $file: $line\n";
}


问:
RestApiSDK references outdated PayPalCoreSDK dll
Solution below

I'm trying to implement PayPal payment in an ASP.NET website, but when I run it on Azure, it tells me the assembly being referred to by RestApiSDK 0.1.1.0 is wrong. Local it all works.

```<code>Could not load file or assembly 'PayPalCoreSDK, Version=1.5.2.0, Culture=neutral, PublicKeyToken=5b4afc1ccaef40fb' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code>```

I checked with .NET Reflector and the assembly being referred to is indeed 1.5.2.0, though the latest version in NuGet Packages is 1.6.0.0. I also uninstalled both packages and re-installed them, but no luck.

So, I have two questions:

Why does this work on my localhost?

How do I fix this to work on Azure Websites as well?

Edit: As @JasonZ suggested, I installed a new version of the PayPal SDK for .NET and that worked. Thanks!

答:
Upgrade the nuget package

PM> install-package PayPalCoreSDK -version 1.7.0

(To upgrade the package using visual studio [Top Menu] -> Tools -> NuGet Package Manager -> Package Manager Console)

Please follow the following link for more information.  https://www.nuget.org/packages/PayPalCoreSDK/

Body:
Solution below

I'm trying to implement PayPal payment in an ASP.NET website, but when I run it on Azure, it tells me the assembly being referred to by RestApiSDK 0.1.1.0 is wrong. Local it all works.

Could not load file or assembly 'PayPalCoreSDK, Version=1.5.2.0, Culture=neutral, PublicKeyToken=5b4afc1ccaef40fb' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I checked with .NET Reflector and the assembly being referred to is indeed 1.5.2.0, though the latest version in NuGet Packages is 1.6.0.0. I also uninstalled both packages and re-installed them, but no luck.

So, I have two questions:

Why does this work on my localhost?

How do I fix this to work on Azure Websites as well?

Edit: As @JasonZ suggested, I installed a new version of the PayPal SDK for .NET and that worked. Thanks!


问:
Youtube video uploads rejected before API quota limit reached
The API quota for my project was successfully increased to 4M through the application process. This is confirmed in the details for the quota via the Google Developer console quota page for the enabled API.

Videos are, however, being rejected with this message after just the standard 50 uploads with this message:

Task 310: Upload failed. Exception: HttpError 400 "The user has exceeded the number of videos they may upload."

Here is an example of a successfully published video.

Thousands of videos are waiting in the queue from an event that finished days ago. Several people from Google have been trying to help but this morning I was asked to post on Stack Overflow.

答:
So Google support got back with a note saying that we'll just have to wait for the quota refresh... I can't even see any difference from the 'increased upload' capacity and the limit does seem to be 50 (roughly at least). I've asked them how long the anti-spam upload freeze actually is but I'll carry on breathing whilst I wait for that puppy.

Special thanks for help from DalmTo and halfer though.

Message from Google Support:

I have enabled "Increased upload" capacity for your channel. Please
  re-login to your account and check if all works fine.

We don't have any 50 videos per day limit anymore tell the truth, but
  we have antispam algorithms which may temporary suspend your Upload
  function.

This algorithm is confidential, so I can not discuss this feature in
  details.  If you can not upload videos you should just wait I am
  afraid. But I hope "Increased upload" will help.


问:
Mapping through an array of objects in javascript
i have an array of objects like this:

```<code>[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
</code>```

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

答:
Please check this:</p>

```<code>    var arrayBuySell=[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
var averageBuy = 0;
var averageSell = 0;
var totalbuy=0;
var totalbuycount=0;
var totalsellcount=0;
var totalsell=0;
for (var i = 0; i < arrayBuySell.length; i++) {
    if(arrayBuySell[i]="Buy")
      {
       totalbuy+=arrayBuySell[i].price;
       totalbuycount=arrayBuySell[i].price.Count();
      }
     else
      {
       totalsell+=arrayBuySell[i].price;
       totalsellcount=arrayBuySell[i].price.Count();
      }
  }
averageBuy =totalbuy/totalbuycount;
averageSell=totalsell/totalsellcount;
</code>```

Body:
i have an array of objects like this:

[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

Body:
Please check this:

    var arrayBuySell=[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
var averageBuy = 0;
var averageSell = 0;
var totalbuy=0;
var totalbuycount=0;
var totalsellcount=0;
var totalsell=0;
for (var i = 0; i < arrayBuySell.length; i++) {
    if(arrayBuySell[i]="Buy")
      {
       totalbuy+=arrayBuySell[i].price;
       totalbuycount=arrayBuySell[i].price.Count();
      }
     else
      {
       totalsell+=arrayBuySell[i].price;
       totalsellcount=arrayBuySell[i].price.Count();
      }
  }
averageBuy =totalbuy/totalbuycount;
averageSell=totalsell/totalsellcount;


问:
Determine TLS version from established SqlConnection
In a live system, we are making multiple connections to various MSSQL servers using the SqlConnection object in C#.

As a client is in the process of updating their SQL servers to TLS 1.2, I would like to know if there is a way to determine which implementation of TLS is in use on an active connection.

I would like to achieve this entirely in C# if possible, but can use alternative languages so long as the end result is a self contained application.

The purpose of this is to provide the client with a quick test tool which will help in ensuring that the software is working correctly with TLS 1.2 on an integration environment before the changes are made to the live system.

I have spent several hours looking into this, but am so far unable to find anything helpful. All the resources I have found are aimed at ASP developers, and do not go into detail on connecting directly to the SQL server in a desktop application.

The application is using .NET 4.5, so TLS 1.2 should be available.

Many thanks

答:
For the benefit of anybody who stumbles accross this question looking for a solution to the same problem, the comment posted by Ed Harper is correct - I don't think there's a way to determine the TLS version in use by a connection from within SQL Server. You might have to resort to packet capture to determine the TLS version.

When using .NET 4.5 and above, TLS 1.2 is supported, and if a connection is established to a service which explicitly specifies TLS 1.2, the connection should work correctly.

As TLS applies to the transport OSI layer, packet capture is the correct way to confirm the TLS version, as described in the link also posted by Ed Harper - https://networkengineering.stackexchange.com/questions/20227/find-ssl-version-in-tcp-packets-in-established-tcp-connection

As our code is written for .NET 4.5, the switch to enforcing TLS 1.2 did not require any code changes.


问:
Custom Fields not showing in custom post type post
I have a custom post type named "Designer" Each posts will be using different unique Advanced Custom Fields as each posts has unique templates.With the below code I am able to give rules for each posts in Designer post type and save but the custom fields are not displaying on post edit pages on backend.
Normally this code should ork but no idea what happend to the code

Please Help.

```<code>add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices )
{
    $choices['Custom Post types']['cpt_parent'] = 'Custom post type parent';

    return $choices;
}
add_filter('acf/location/rule_values/cpt_parent',    'acf_location_rules_values_cpt_parent');
function acf_location_rules_values_cpt_parent( $choices )
{
    $args = array(
        'hierarchical' => true,
        '_builtin' => false
    );
    $posttypes = get_post_types( $args );

    if( $posttypes )
    {
        foreach( $posttypes as $posttype ):

            if( $posttype != 'acf' ):
                $args = array(
                'post_type' => 'designer',
                'posts_per_page' => -1,
                'post_status' => 'publish'
                );
                $customposts = get_posts( $args );
                if ( $customposts  ) {
                    foreach( $customposts as $custompost ){
                        $choices[ $custompost->ID] = $custompost->post_title;
                    }
                }
            endif;
        endforeach;
    }

    return $choices;
}

//MATCH THE RULE
add_filter('acf/location/rule_match/cpt_parent',              'acf_location_rules_match_cpt_parent', 10, 3);
function acf_location_rules_match_cpt_parent( $match, $rule, $options )
{
    global $post;
    $selected_post = (int) $rule['value'];

    // post parent
    $post_parent = $post->post_parent;
    if( $options['page_parent'] ) {

        $post_parent = $options['page_parent'];

    }

    if ($rule['operator'] == "=="){
        $match = ( $post_parent == $selected_post );
    }
    elseif ($rule['operator'] != "!="){
        $match = ( $post_parent != $selected_post );
    }

    return $match;
}
</code>```

答: If I understand your problem correctly, in wp-admin post edit page click on screen options on the upper right corner. In the menu that appears make sure the Custom fields is selected. This will make the custom fields appear for edit.</p>

Body:
I have a custom post type named "Designer" Each posts will be using different unique Advanced Custom Fields as each posts has unique templates.With the below code I am able to give rules for each posts in Designer post type and save but the custom fields are not displaying on post edit pages on backend.
Normally this code should ork but no idea what happend to the code

Please Help.

add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices )
{
    $choices['Custom Post types']['cpt_parent'] = 'Custom post type parent';

    return $choices;
}
add_filter('acf/location/rule_values/cpt_parent',    'acf_location_rules_values_cpt_parent');
function acf_location_rules_values_cpt_parent( $choices )
{
    $args = array(
        'hierarchical' => true,
        '_builtin' => false
    );
    $posttypes = get_post_types( $args );

    if( $posttypes )
    {
        foreach( $posttypes as $posttype ):

            if( $posttype != 'acf' ):
                $args = array(
                'post_type' => 'designer',
                'posts_per_page' => -1,
                'post_status' => 'publish'
                );
                $customposts = get_posts( $args );
                if ( $customposts  ) {
                    foreach( $customposts as $custompost ){
                        $choices[ $custompost->ID] = $custompost->post_title;
                    }
                }
            endif;
        endforeach;
    }

    return $choices;
}

//MATCH THE RULE
add_filter('acf/location/rule_match/cpt_parent',              'acf_location_rules_match_cpt_parent', 10, 3);
function acf_location_rules_match_cpt_parent( $match, $rule, $options )
{
    global $post;
    $selected_post = (int) $rule['value'];

    // post parent
    $post_parent = $post->post_parent;
    if( $options['page_parent'] ) {

        $post_parent = $options['page_parent'];

    }

    if ($rule['operator'] == "=="){
        $match = ( $post_parent == $selected_post );
    }
    elseif ($rule['operator'] != "!="){
        $match = ( $post_parent != $selected_post );
    }

    return $match;
}


问:
Hide button until we upload image or text
we have a button "save design" in page also we have option to upload image or text in the page.
until user upload image or Add text, we dont want to display button "save design"

we are using below code for "save design"

```<code>_getControlPanelHtml: function()
    {
        if (this.config.editorEnabled) {
            return '<div id="aitcg-control-panel">' +
                '<button id="submit-editorApply-{{rand}}" >SAVE DESIGN</button>' +
                '<button >Reset</button>' +
                '</div>';
        }
        return '';
    },

    initObservers: function()
    {
        if (this.config.editorEnabled) {
            $('submit-editorApply-' + this.config.rand).observe('click', this.submitApply.bindAsEventListener(this));
            $('submit-editorReset-' + this.config.rand).observe('click', this.submitReset.bindAsEventListener(this));
        }
    },

    submitApply: function(event)
    {
        Event.stop(event);
        this.option.apply();
    },
</code>```

I tried below code to hide the "save design" until we upload image or text.
i followed this link  i added style="display: none; and than used  show() jQuery method.

```<code><script>
    $('submit-editorApply-').show();
    _getControlPanelHtml: function()
    {
        if (this.config.editorEnabled) {
            return '<div id="aitcg-control-panel">' +
                '<button id="submit-editorApply-{{rand}}" style="display:none;" >SAVE DESIGN</button>' +
                '<button >Reset</button>' +
                '</div>';
        }
        return '';
    },

</script>
</code>```

答:
add this code in css

```<code>#aitcg-control-panel{
    display:none;
}
</code>```

Use the .ajaxComplete function of jQuery to detect the ajax and if it is to the following url's show it.

Check the following code

```<code>$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "aitcg/ajax/addText/" || settings.url === "aitcg/ajax/addImage/" ) {
    jQuery("#aitcg-control-panel").show();
  }
});
</code>```

use jQuery instead of $ to select elements.

The above codes works fine when tested on browser.

If you are having any problem with the css,

Add the following instead of css.

```<code>jQuery(document).ready(function(){
    jQuery("#aitcg-control-panel").hide();
});
</code>```

Body:
we have a button "save design" in page also we have option to upload image or text in the page.
until user upload image or Add text, we dont want to display button "save design"

we are using below code for "save design"

_getControlPanelHtml: function()
    {
        if (this.config.editorEnabled) {
            return '
' +
                '<button id="submit-editorApply-{{rand}}" >SAVE DESIGN</button>' +
                '<button >Reset</button>' +
                '
';
        }
        return '';
    },

    initObservers: function()
    {
        if (this.config.editorEnabled) {
            $('submit-editorApply-' + this.config.rand).observe('click', this.submitApply.bindAsEventListener(this));
            $('submit-editorReset-' + this.config.rand).observe('click', this.submitReset.bindAsEventListener(this));
        }
    },

    submitApply: function(event)
    {
        Event.stop(event);
        this.option.apply();
    },

I tried below code to hide the "save design" until we upload image or text.
i followed this link  i added style="display: none; and than used  show() jQuery method.

Body:
add this code in css

#aitcg-control-panel{
    display:none;
}

Use the .ajaxComplete function of jQuery to detect the ajax and if it is to the following url's show it.

Check the following code

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "aitcg/ajax/addText/" || settings.url === "aitcg/ajax/addImage/" ) {
    jQuery("#aitcg-control-panel").show();
  }
});

use jQuery instead of $ to select elements.

The above codes works fine when tested on browser.

If you are having any problem with the css,

Add the following instead of css.

jQuery(document).ready(function(){
    jQuery("#aitcg-control-panel").hide();
});


问:
In ASP.NET Core MVC Route "MyWebsite/{id}" not hit
I am using ASP.NET Core MVC 1.1 with Visual Studio 2017 RTM. My route configuration is below

```<code>app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
</code>```

And my HomeController/Index action looks something like below

```<code>public async Task<IActionResult> Index(int? id)
</code>```

The localhost url hits the Index action just fine with id being null. But when I type localhost/5, it doesn't hit this action, instead it gives 404 error. This is really really frustrating as intuitively I thought that if localhost hits Index, then localhost/5 should hit it as well

答:
template: "{controller=Home}/{action=Index}/{id?}" means that when no controller and action is specified (just the base url like Localhost:XXXX), go to a controller called Home and action named Index and the id can be optional. If you want to pass a value as Id to Index method in Home controller, you have to ::

Change your url to Localhost:XXXX/Home/Index/1

Add a route attribute on index method that [Route("id?")] and you will be able to achieve your desired result. This might disrupt the default routing

Body:
I am using ASP.NET Core MVC 1.1 with Visual Studio 2017 RTM. My route configuration is below

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

And my HomeController/Index action looks something like below

public async Task<IActionResult> Index(int? id)

The localhost url hits the Index action just fine with id being null. But when I type localhost/5, it doesn't hit this action, instead it gives 404 error. This is really really frustrating as intuitively I thought that if localhost hits Index, then localhost/5 should hit it as well


问:
Delphi : How to plot a simple 2d graph?
I'm using Delphi for my computer science coursework and need my program to plot a simple graph for projectile motion. I've struggled in finding a way to implement this and was wondering if anyone has had experience in drawing graphs or would be able to point me in the right direction. </p>

<p>The main idea that I have tried is plotting all the x values and drawing a line to the corresponding y value at that given time, but each time it comes out really weird and doesn't work. </p>

答:
Steps for simple graph:

1. Provide data values in array/list

2. Find minimal and maximal values for X and Y components

3. Calculate linear formulas for mapping data values to screen coordinates (min x = > left of rectangle for drawing and so on)

4. Draw line segments applying formulas to get coordinates

5. If needed, draw axes

P.S. Is TChart using prohibited?

Title: Delphi : How to plot a simple 2d graph?

Body:
I'm using Delphi for my computer science coursework and need my program to plot a simple graph for projectile motion. I've struggled in finding a way to implement this and was wondering if anyone has had experience in drawing graphs or would be able to point me in the right direction.

The main idea that I have tried is plotting all the x values and drawing a line to the corresponding y value at that given time, but each time it comes out really weird and doesn't work.


问:
Is it possible to create TODOs or Comments while in Debug mode
I would like to flag a line of code for changing while I'm in debug mode, and associate some thoughts with it.  I've tried adding comments, but the debugger thinks that I'm trying to change code, and won't continue until I rebuild.  Something like Word's comment system would work too.

I know I could work around this if I turned on edit and continue, but there are good reasons why edit and continue is not turned on, and it's not really needed for what I'm asking.

I'm guessing there must be an extension out there that meets this need.

Update: If I try to add comments while edit and continue is turned off, I get a message that says, "This source file has changed. It no longer matches the version of the file used to build the application being debugged".  I had given up when I saw that message, but it turns out I can just say ok and move on.

答:
If you want to add comments to your codes or even modify your codes while debugging your application.

But, remember: you should Enable and Disable Edit and Continue(see here) and check you are in break mode(rather than debug mode).


问:
Ionic 2 - Sticky header
I need to create a sticky header in my app, which holds the value of the current block.

I retrieve the scroll position using this code:

```<code>import { Component, ViewChild } from '@angular/core';
import { Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content)
  content:Content;

  ngAfterViewInit() {
    // I want to trigger the listener during the scroll event
    this.content.ionScroll.subscribe((data)=>{
      this.onPageScroll(data);
    });
  }

  onPageScroll(data) {
   console.log("top:", data['scrollTop'])
  }

  :
  :
</code>```

In order to determine which element to show in the sticky header, I have at the end of each block a hidden element:

```<code><div class="titleTag" style="display:none">{{event.title}}</div>
</code>```

When I try to retrieve the position of these elements:

```<code>let titleTags = document.getElementsByClassName('titleTag');
for (let el of <any>titleTags) {
  console.log(" > offsetTop", el.offsetTop);
}
</code>```

I get 0.

I tried also offsetHeight and scrollTop, both return 0 as well.

Any idea??

答:
In order to directly get elements in Ionic 2/Angular 2 use ElementRef.

```<code>import {ElementRef} from '@angular/core';

//class..
constructor(public el:ElementRef){}

//in your function...
let titleTags =this.el.nativeElement.getElementsByClassName('titleTag');
for (let el of <any>titleTags) {
  console.log(" > offsetTop", el.offsetTop);
}
</code>```

Title: Ionic 2 - Sticky header

Body:
I need to create a sticky header in my app, which holds the value of the current block.

I retrieve the scroll position using this code:

import { Component, ViewChild } from '@angular/core';
import { Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content)
  content:Content;

  ngAfterViewInit() {
    // I want to trigger the listener during the scroll event
    this.content.ionScroll.subscribe((data)=>{
      this.onPageScroll(data);
    });
  }

  onPageScroll(data) {
   console.log("top:", data['scrollTop'])
  }

  :
  :

In order to determine which element to show in the sticky header, I have at the end of each block a hidden element:

{{event.title}}

When I try to retrieve the position of these elements:

let titleTags = document.getElementsByClassName('titleTag');
for (let el of <any>titleTags) {
  console.log(" > offsetTop", el.offsetTop);
}

I get 0.

I tried also offsetHeight and scrollTop, both return 0 as well.

Any idea??

Body:
In order to directly get elements in Ionic 2/Angular 2 use ElementRef.

import {ElementRef} from '@angular/core';

//class..
constructor(public el:ElementRef){}

//in your function...
let titleTags =this.el.nativeElement.getElementsByClassName('titleTag');
for (let el of <any>titleTags) {
  console.log(" > offsetTop", el.offsetTop);
}


问:
Systeminfo: Product ID
If you type systeminfo at the command prompt, there is a listing for Product ID.  Can someone explain what this is exactly, and would it make a good seed for a registration code algorithm?

答:
i believe it's representative (or is) your windows product key.  Either way, all you really want is a GUID.

From http://technet.microsoft.com/en-us/library/bb878062.aspx

You can find the product ID of your
  installation by right clicking on My
  Computer and choose Properties, then
  viewing the General tab. You can also
  find the product key in the registry
  at:
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
  NT\ CurrentVersion\ProductId.

OwnerDisplayName: stout

Title: Systeminfo: Product ID

OwnerDisplayName: Bramha Ghosh


问:
Graphic Scrollbar modification on Auto DIV Scroller script
We're using this autoscroller script: http://scripterlative.com/files/autodivscroll.htm (the bottom version).

However, we got really stuck since we don't know how to replace the moving "scrollbar" on the scroller side with a pure and simple line with up arrow on top and bottom arrow on bottom.

Functions wise we want this sidebar to behave exactly like the original sidebar and of course be cross browser compatible. We just want to get rid of the original scrollbar and replace it with a much cleaner and more stylish style.

Is this doable?! How?

Best regards Stefan

答:
Just found jScrollPane on AjaxRain.

Implementing an autoscroll would take some coding, but should definitely be possible by just sending the click messages to the div manually so that it would do the scrolling. If it looks like this will suit your needs, I'd chip in with some additional implementation code. That topic may actually be better suited for another question, if you decide on jScrollPane.

Edit: updated link above. also, there are demos there for scrolling on hover and clicking on a link to jump to an anchor. Custom code for an autoscroll should be relatively simple to write from there.


问:
casting 8-bit pointer to long
I am trying to use a 3rd party c library in my c++ project, which I develop using Visual Studio on Windows 64-bit.
Both 32bit and 64bit compiled successfully; however, I found an issue in the external library when running in 64bit, as it does the following:

```<code>double* foo(){
     double* b; long a; long i;
     /*
       ... do some stuff to assign values to b, a, i ...
     */
     return ( (long)b + a + i );
}
</code>```

The problem is (on windows at least) that double* is represented by 4 bytes in x86 architectures and 8 bytes in x64 , so casting of b in the return statement is screwed.

My question is, is there a way I can "extract" the 4-bytes address of pointer b from its 8-bit representation, so as to keep the expression (b+a) meaningful?

Thanks

答:
Presumably the cast is to avoid doing pointer arithmetric on multiples of sizeof(double).

You can do the same with char * pointers, avoiding the size issue completely. I also added cast back to original pointer type which code was missing.

```<code>return (double *)( (char *)b + a + i );
</code>```

Note: You should be aware that you can easily create unaligned pointer, which can lead to undefined behaviour if dereferenced. This was also problem with your original code.

Be careful; your code looks very questionable, and it may have other potential mines.

Title: casting 8-bit pointer to long

Body:
I am trying to use a 3rd party c library in my c++ project, which I develop using Visual Studio on Windows 64-bit.
Both 32bit and 64bit compiled successfully; however, I found an issue in the external library when running in 64bit, as it does the following:

double* foo(){
     double* b; long a; long i;
     /*
       ... do some stuff to assign values to b, a, i ...
     */
     return ( (long)b + a + i );
}

The problem is (on windows at least) that double* is represented by 4 bytes in x86 architectures and 8 bytes in x64 , so casting of b in the return statement is screwed.

My question is, is there a way I can "extract" the 4-bytes address of pointer b from its 8-bit representation, so as to keep the expression (b+a) meaningful?

Thanks

Body:
Presumably the cast is to avoid doing pointer arithmetric on multiples of sizeof(double).

You can do the same with char * pointers, avoiding the size issue completely. I also added cast back to original pointer type which code was missing.

return (double *)( (char *)b + a + i );

Note: You should be aware that you can easily create unaligned pointer, which can lead to undefined behaviour if dereferenced. This was also problem with your original code.

Be careful; your code looks very questionable, and it may have other potential mines.


问:
TextBox_TextChanged Event not firing in c#
The DOB_TextChanged event not firing.My code is,

Aspx code

```<code><asp:TemplateField HeaderText="DOB">
<EditItemTemplate>
  <asp:TextBox ID="DOB" CssClass="datepick" runat="server" AutoPostBack="true"
               OnTextChanged="DOB_TextChanged"></asp:TextBox>
</EditItemTemplate>
 </asp:TemplateField>
</code>```

code behind,

```<code>protected void DOB_TextChanged(object sender, EventArgs e)
{
    //mycode
}
</code>```

am i did anything wrong??

答:
Just a simple code

```<code> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
    <br />
</code>```

and

```<code>    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("button_click event raised");
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
         Response.Write("text_changed event raised : "+ TextBox1.Text);
    }
</code>```

Set the text box property AutoPostBack=True , and it will work when control goes out of TextBox only after change in text .If text is same than it will not raise the event.

Body:
The DOB_TextChanged event not firing.My code is,

Aspx code

<asp:TemplateField HeaderText="DOB">
<EditItemTemplate>
  <asp:TextBox ID="DOB" CssClass="datepick" runat="server" AutoPostBack="true"
               OnTextChanged="DOB_TextChanged"></asp:TextBox>
</EditItemTemplate>
 </asp:TemplateField>

code behind,

protected void DOB_TextChanged(object sender, EventArgs e)
{
    //mycode
}

am i did anything wrong??

Body:
Just a simple code

 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
    <br />

and

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("button_click event raised");
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
         Response.Write("text_changed event raised : "+ TextBox1.Text);
    }

Set the text box property AutoPostBack=True , and it will work when control goes out of TextBox only after change in text .If text is same than it will not raise the event.


问:
Javascript: Convert a plain array of nodes (with pointers to parent nodes) to a nested data structure
I have read many of the solutions to this problem and for example am trying with array-to-tree

Given this data:

```<code>[
  {
    "_id": 33,
    "parent": null,
    "name": "Wealth and Investment Management and Insurance",
    "code": "wm-0001",
    "__v": 0
  },
  {
    "_id": 34,
    "parent": null,
    "name": "Corporate and Investment Banking",
    "code": "cib-0001",
    "__v": 0
  },
  {
    "_id": 35,
    "parent": 33,
    "name": "WIMI Business Unit 1",
    "code": "WIMBU-0001",
    "__v": 0
  }
]
</code>```

And using this code

```<code>var arrayToTree = require('array-to-tree');
var tree = arrayToTree(data, {
            parentProperty: 'parent',
            customID: '_id'
        });
</code>```

I cannot understand why its orphaning my children? i.e. I am getting this back

```<code>[ { _id: 33,
    parent: null,
    name: 'Wealth and Investment Management and Insurance',
    code: 'wm-0001',
    __v: 0 },
  { _id: 34,
    parent: null,
    name: 'Corporate and Investment Banking',
    code: 'cib-0001',
    __v: 0 } ]
</code>```

答:
It seems that array-to-tree doesn't know what to do if _id is of type Number;

Changing this converts the flat array to a tree structure.

You can loop through the array to convert the keys _id/parent to string if they are number;

I'll only edit this if you ask for it (but the above solves)

Body:
I have read many of the solutions to this problem and for example am trying with array-to-tree

Given this data:

[
  {
    "_id": 33,
    "parent": null,
    "name": "Wealth and Investment Management and Insurance",
    "code": "wm-0001",
    "__v": 0
  },
  {
    "_id": 34,
    "parent": null,
    "name": "Corporate and Investment Banking",
    "code": "cib-0001",
    "__v": 0
  },
  {
    "_id": 35,
    "parent": 33,
    "name": "WIMI Business Unit 1",
    "code": "WIMBU-0001",
    "__v": 0
  }
]

And using this code

var arrayToTree = require('array-to-tree');
var tree = arrayToTree(data, {
            parentProperty: 'parent',
            customID: '_id'
        });

I cannot understand why its orphaning my children? i.e. I am getting this back

[ { _id: 33,
    parent: null,
    name: 'Wealth and Investment Management and Insurance',
    code: 'wm-0001',
    __v: 0 },
  { _id: 34,
    parent: null,
    name: 'Corporate and Investment Banking',
    code: 'cib-0001',
    __v: 0 } ]


问:
C# WPF - How to always get the current text from a textbox?
I have a TextBox in FileWindow.xaml :

```<code><TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="233,230,0,0" TextWrapping="Wrap" Text="{Binding FileName}" VerticalAlignment="Top" Width="120"/>
</code>```

In ViewModel.cs:

```<code>public String FileName
{
    get { return _model.filename; }
    set
    {
        if (value != _model.filename)
        {
            _model.filename = value;
            OnPropertyChanged();
        }
    }
}
</code>```

In Model.cs:

```<code>private String _filename = "example.txt";
public String filename { get { return _filename; } set { _filename = value; } }
</code>```

I want that every time I type in the TextBox, the _filename in Model.cs gets updated.

The default text in the TextBox is example.txt, but if I change it, the _filename in Model.cs doesn't change. What am I doing wrong?

答:
TextBox was not immediately sent back to the source. Instead, the source was updated only after focus was lost on the TextBox. This behavior is controlled by a property on the binding called UpdateSourceTrigger.

It defaults to the value "Default", which basically means that the source is updated based on the property that you bind to.

Default is, obviously, the default value of the UpdateSourceTrigger. The other options are PropertyChanged, LostFocus and Explicit.

```<code> <TextBox Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" />
</code>```

Body:
I have a TextBox in FileWindow.xaml :

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="233,230,0,0" TextWrapping="Wrap" Text="{Binding FileName}" VerticalAlignment="Top" Width="120"/>

In ViewModel.cs:

public String FileName
{
    get { return _model.filename; }
    set
    {
        if (value != _model.filename)
        {
            _model.filename = value;
            OnPropertyChanged();
        }
    }
}

In Model.cs:

private String _filename = "example.txt";
public String filename { get { return _filename; } set { _filename = value; } }

I want that every time I type in the TextBox, the _filename in Model.cs gets updated.

The default text in the TextBox is example.txt, but if I change it, the _filename in Model.cs doesn't change. What am I doing wrong?

Body:
TextBox was not immediately sent back to the source. Instead, the source was updated only after focus was lost on the TextBox. This behavior is controlled by a property on the binding called UpdateSourceTrigger.

It defaults to the value "Default", which basically means that the source is updated based on the property that you bind to.

Default is, obviously, the default value of the UpdateSourceTrigger. The other options are PropertyChanged, LostFocus and Explicit.

 <TextBox Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" />


问:
haskell splitting a string
I have a string like this:

```<code>"Some sentence1. Some sentence2, Some sentence3, Some sentence4....."
</code>```

and I would like to turn it into a list of string

```<code>["Some sentence1", "Some sentence2", "Some sentence3.".......]
</code>```

so far this is what I have:

```<code>foo :: String -> [String]
foor [] = []
| x /= ',' = [[x]] ++ foo xs
| otherwise = [[x] ++ foo xs]
</code>```

which doesn't compile, much less work.

Help!

答: There is no x in your pattern match. That is in large part why it neither compiles nor works. But your code also does not handle periods, so it won't work correctly even once it compiles until your fix that.

Title: haskell splitting a string

Body:
I have a string like this:

"Some sentence1. Some sentence2, Some sentence3, Some sentence4....."

and I would like to turn it into a list of string

["Some sentence1", "Some sentence2", "Some sentence3.".......]

so far this is what I have:

foo :: String -> [String]
foor [] = []
| x /= ',' = [[x]] ++ foo xs
| otherwise = [[x] ++ foo xs]

which doesn't compile, much less work.

Help!


问:
C# class parameter
```<code> namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B(a);
            C c = new C(a);

            Console.WriteLine(a.intval + " " +a.strval);
            Console.ReadLine();
        }
    }

    class A
    {
        public int intval { get; set; }
        public string strval { get; set; }
    }
    class B
    {
        public A _a;
        public B(A a)
        {
            _a = a;
            _a.intval += 100;
            _a.strval += "From B;";
        }
    }
    class C
    {
        A _a;
        public C(A a)
        {
            _a = a;
            _a.intval += 1000;
            _a.strval += "From C;";
        }
    }
}
</code>```

In above code, why the instance "b" and “c” could set value to instance "a"?

In my guess, the Class B and C have their own variables "a", when we call "B b = new B(a);" or "C c = new C(a);", the value should be changed on their own fields and the variable "a" in Main would be impacted?

But, i'm wrong. Could you please help me understand the result? Thank you very much.

答: A is a reference type (class here), so if you give the same ref of your a, change its values from b or c will alter a instance.</p>

Title: C# class parameter

Body:
 namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B(a);
            C c = new C(a);

            Console.WriteLine(a.intval + " " +a.strval);
            Console.ReadLine();
        }
    }

    class A
    {
        public int intval { get; set; }
        public string strval { get; set; }
    }
    class B
    {
        public A _a;
        public B(A a)
        {
            _a = a;
            _a.intval += 100;
            _a.strval += "From B;";
        }
    }
    class C
    {
        A _a;
        public C(A a)
        {
            _a = a;
            _a.intval += 1000;
            _a.strval += "From C;";
        }
    }
}

In above code, why the instance "b" and “c” could set value to instance "a"?

In my guess, the Class B and C have their own variables "a", when we call "B b = new B(a);" or "C c = new C(a);", the value should be changed on their own fields and the variable "a" in Main would be impacted?

But, i'm wrong. Could you please help me understand the result? Thank you very much.


问:
Making a Fill In Questionaire Java Excercise
Before I begin I want to point out that I'm in severe stress and frustration due to not being able to make this excercise. I have searched and asked all over the internet and I feel hopeless. As my last hope I came to Stack Overflow to ask this question. I do not understand the excercise. It is a very strange one. I would be forever grateful to you if you could assist me in making this excercise that I am stuck with for a month. My life really depends on this. Please help me.

```<code>public class Question {
    private String text;
    private String answer;

    public Question() {
        text = "";
        answer = "";
    }

    public void setText(String questionText) {
        text = questionText;
    }

    public void setAnswer(String correctResponse){
        answer = correctResponse;
    }

    public boolean checkAnswer(String response){
        return response.equals(answer);
    }

    public void display() {
        System.out.println(text);
    }
    }
</code>```

Im going to add a class FillInQuestion to this class. Such a question is constructed with a string that contains the answer, surrounded by _ _, for exam ple, The inventor of Java was James Gosling. The question should be displayed as The inventor of Java was _____. But I'm not sure how I could make this? Could I receive the way to make a string that contains the answer in such a way.

The question is cited as "Add a class FillInQuestion to the question hierarchy of Section 9.1. Such a question is
constructed with a string that contains the answer, surrounded by _ _, for example,
"The inventor of Java was _James Gosling_". The question should be displayed as
The inventor of Java was _____"

How can I construct a string that contains the answer like that?
How can I display _James Gosling_ like ____?
What do they mean. I dont understand.

Thank you.

答:
```<code>    public class Demo
{
    public static void main(String[] args)
    {

        String question = "The inventor of Java was _James Gosling_";
        Pattern p = Pattern.compile("_(.*?)_");
        Matcher m = p.matcher(question);
        if (m.find())
        {
            System.out.println("question before edit : " + question);
            String answer = m.group(1);
            System.out.println("Answer after edit : " + m.group(1));
            question = question.replace(answer, "_______");

            System.out.println("question after edit : " + question);
        }
     }
</code>```

Body:
Before I begin I want to point out that I'm in severe stress and frustration due to not being able to make this excercise. I have searched and asked all over the internet and I feel hopeless. As my last hope I came to Stack Overflow to ask this question. I do not understand the excercise. It is a very strange one. I would be forever grateful to you if you could assist me in making this excercise that I am stuck with for a month. My life really depends on this. Please help me.

public class Question {
    private String text;
    private String answer;

    public Question() {
        text = "";
        answer = "";
    }

    public void setText(String questionText) {
        text = questionText;
    }

    public void setAnswer(String correctResponse){
        answer = correctResponse;
    }

    public boolean checkAnswer(String response){
        return response.equals(answer);
    }

    public void display() {
        System.out.println(text);
    }
    }

Im going to add a class FillInQuestion to this class. Such a question is constructed with a string that contains the answer, surrounded by _ _, for exam ple, The inventor of Java was James Gosling. The question should be displayed as The inventor of Java was _____. But I'm not sure how I could make this? Could I receive the way to make a string that contains the answer in such a way.

The question is cited as "Add a class FillInQuestion to the question hierarchy of Section 9.1. Such a question is
constructed with a string that contains the answer, surrounded by _ _, for example,
"The inventor of Java was _James Gosling_". The question should be displayed as
The inventor of Java was _____"

How can I construct a string that contains the answer like that?
How can I display _James Gosling_ like ____?
What do they mean. I dont understand.

Thank you.


问:
Keep cell position in UITableView after reload
I am refreshing my UITable every couple of minutes, in case there is new data they should be added at the beginning of the table than it reloads.

```<code>var j = 0
let n = store?.news?.count
while(j < n!){
self.news?.insert((store?.news?[j])!, at: j)
    j = j + 1
}
</code>```

No problem in saving the data at first positions.
The problem is i cannot keep the cell position after each reload it moving up ( the number of records added) , i have tried multiple functions but apparently it's only working in case data where added at the end of the table.

```<code>let contentOffset = self.tableV.contentOffset
self.tableV.reloadData()
self.tableV.contentOffset = contentOffset
</code>```

Also i tired to save the cell position and add the count of entered data to it but this kind of addition does not work.
Is there a way to add the number of entered data which is counted , lets say N to the indexPath.row?

答:
For better Approach i think you can easily add new row in tableview, there is no need to reload tableview. so remove self.tableV.reloadData()

```<code>    var j = 0
    var arrayIndexPaths : [NSIndexPath] = []
    let n = store?.news?.count
    while(j < n!){
        self.news?.insert((store?.news?[j])!, at: j)

        let indexPath = NSIndexPath(forRow: j, inSection: 0)
        j = j + 1
        arrayIndexPaths.append(indexPath)
    }

    // Now you have array of IndexPaths so you just insert New row like this way.

    self.tableview.beginUpdates()
    self.tableview.insertRowsAtIndexPaths(arrayIndexPaths, withRowAnimation: .None)
    self.tableview.endUpdates()
</code>```

UPDate Answer

And your UITableViewDelegate method like this

```<code>  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.news?.count
    }
</code>```

Body:
I am refreshing my UITable every couple of minutes, in case there is new data they should be added at the beginning of the table than it reloads.

var j = 0
let n = store?.news?.count
while(j < n!){
self.news?.insert((store?.news?[j])!, at: j)
    j = j + 1
}

No problem in saving the data at first positions.
The problem is i cannot keep the cell position after each reload it moving up ( the number of records added) , i have tried multiple functions but apparently it's only working in case data where added at the end of the table.

let contentOffset = self.tableV.contentOffset
self.tableV.reloadData()
self.tableV.contentOffset = contentOffset

Also i tired to save the cell position and add the count of entered data to it but this kind of addition does not work.
Is there a way to add the number of entered data which is counted , lets say N to the indexPath.row?

Body:
For better Approach i think you can easily add new row in tableview, there is no need to reload tableview. so remove self.tableV.reloadData()

    var j = 0
    var arrayIndexPaths : [NSIndexPath] = []
    let n = store?.news?.count
    while(j < n!){
        self.news?.insert((store?.news?[j])!, at: j)

        let indexPath = NSIndexPath(forRow: j, inSection: 0)
        j = j + 1
        arrayIndexPaths.append(indexPath)
    }

    // Now you have array of IndexPaths so you just insert New row like this way.

    self.tableview.beginUpdates()
    self.tableview.insertRowsAtIndexPaths(arrayIndexPaths, withRowAnimation: .None)
    self.tableview.endUpdates()

UPDate Answer

And your UITableViewDelegate method like this

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.news?.count
    }


问:
mysql how to insert multiple values in single column
I have two tables Patient and Details. Patient is related to Details with a foreign key. In Patient one user can have multiple values of Details.

I tried:

```<code>INSERT INTO `Patients`
        (`patientId`, `name`, `address`, `etage`,
         `Door`, `Elevator`, `key_number`, `medicineId`, `lid`,
         `doctorId`)
VALUES (109, 'Muller', 'bla bla bla ', 3,
            'links' , 1 , 'S12' ,'m9' , '{02.0 , 2.10 ,2.30}' ,
            'D11');
</code>```

When I try to insert I get the following error:

Cannot add or update a child row: a foreign key constraint fails
      (Sanitas.Patients, CONSTRAINT Patients_ibfk_2 FOREIGN KEY (lid)
      REFERENCES Details (lid))

答:
The foreign key means that every row of Patiens should have in its column lid a value that matches to a value available in the lid column of Details; most likely, there is no row in Details whose lid value is {02.0 , 2.10 ,2.30}.

With that structure, you should insert that rows once for each lid value, but that would lead to other problems (duplicate patientId key probably).

This shows some problems in your tables design: what you're describing looks like a many-to-many relationship, which requires three tables to be modeled.

The structure you'd need is

```<code>Patients
    patientId
    name
    address
    etage
    Door
    Elevator
    key_number
    medicineId
    doctorId
    --notice, no more lid here

Detail
    lid
    --whatever else you have here

PatientsDetail
    patientId
    lid
</code>```

This way you can have a single row for each patient, a single row for each detail, and a table that combines all the combinations of patients and details by associating the ids of those two entities.

The query you wrote would then be split into

```<code>INSERT INTO `Patients`
    (`patientId`, `name`, `address`, `etage`, `Door`, `Elevator`, `key_number`,
     `medicineId`, `doctorId`)
VALUES (109, 'Muller', 'bla bla bla ', 3, 'links', 1 , 'S12' ,'m9' , 'D11');

INSERT INTO `PatientsDetail` (`patientId`, `lid`)
VALUES
    (109, 02.0),
    (109, 2.10),
    (109, 2.30);
</code>```

Body:
I have two tables Patient and Details. Patient is related to Details with a foreign key. In Patient one user can have multiple values of Details.

I tried:

INSERT INTO `Patients`
        (`patientId`, `name`, `address`, `etage`,
         `Door`, `Elevator`, `key_number`, `medicineId`, `lid`,
         `doctorId`)
VALUES (109, 'Muller', 'bla bla bla ', 3,
            'links' , 1 , 'S12' ,'m9' , '{02.0 , 2.10 ,2.30}' ,
            'D11');

When I try to insert I get the following error:

Cannot add or update a child row: a foreign key constraint fails
      (Sanitas.Patients, CONSTRAINT Patients_ibfk_2 FOREIGN KEY (lid)
      REFERENCES Details (lid))

Body:
The foreign key means that every row of Patiens should have in its column lid a value that matches to a value available in the lid column of Details; most likely, there is no row in Details whose lid value is {02.0 , 2.10 ,2.30}.

With that structure, you should insert that rows once for each lid value, but that would lead to other problems (duplicate patientId key probably).

This shows some problems in your tables design: what you're describing looks like a many-to-many relationship, which requires three tables to be modeled.

The structure you'd need is

Patients
    patientId
    name
    address
    etage
    Door
    Elevator
    key_number
    medicineId
    doctorId
    --notice, no more lid here

Detail
    lid
    --whatever else you have here

PatientsDetail
    patientId
    lid

This way you can have a single row for each patient, a single row for each detail, and a table that combines all the combinations of patients and details by associating the ids of those two entities.

The query you wrote would then be split into

INSERT INTO `Patients`
    (`patientId`, `name`, `address`, `etage`, `Door`, `Elevator`, `key_number`,
     `medicineId`, `doctorId`)
VALUES (109, 'Muller', 'bla bla bla ', 3, 'links', 1 , 'S12' ,'m9' , 'D11');

INSERT INTO `PatientsDetail` (`patientId`, `lid`)
VALUES
    (109, 02.0),
    (109, 2.10),
    (109, 2.30);


问:
What does ||= (or-equals) mean in Ruby?
What does the following code mean in Ruby?

```<code>||=
</code>```

Does it have any meaning or reason for the syntax?

答:
||= is called a conditional assignment operator.

It basically works as = but with the exception that if a variable has already been assigned it will do nothing.

First example:

```<code>x ||= 10
</code>```

Second example:

```<code>x = 20
x ||= 10
</code>```

In the first example x is now equal to 10. However, in the second example x is already defined as 20. So the conditional operator has no effect. x is still 20 after running x ||= 10.

Title: What does ||= (or-equals) mean in Ruby?

Body:
What does the following code mean in Ruby?

||=

Does it have any meaning or reason for the syntax?

Body:
||= is called a conditional assignment operator.

It basically works as = but with the exception that if a variable has already been assigned it will do nothing.

First example:

x ||= 10

Second example:

x = 20
x ||= 10

In the first example x is now equal to 10. However, in the second example x is already defined as 20. So the conditional operator has no effect. x is still 20 after running x ||= 10.


问:
DB2 database restore
When I am restoring the database, by default data is going in C drive, but when I installed the db2 that time I specify the path in D drive only.
Also, sample database files created by db2 is stored in D drive.
Can anyone please tell me what is the issue?

I have run this command:

```<code>SELECT * FROM SYSIBMADM.DBPATHS
</code>```

below is the result i fetched:

```<code>LOGPATH- D:\DB2\NODE000\SQL00001\SQLOGDIR\
DB_STORAGE_PATH- C:\
LOCAL_DB_DIRECTORY -  D:\DB2\NODE000\SQLOGDIR\
DBPATH - D:\DB2\NODE000\SQL00001\
</code>```

I Want to change this DB_STORAGE_PATH C:\ to D:\ for all the database which i will be restoring.

答:
You can run db2set from db2 command line that will confirm you wheather db2 installed on path with other information;

```<code>db2-command-line> db2set

DB2_ATS_ENABLE=YES
DB2_CREATE_DB_ON_PATH=YES
DB2INSTPROF=C:\where\db2\installed\IBM\DB2\DB2COPY1
DB2COMM=TCPIP
</code>```

You can get more information of Directory structure for your installed DB2 database product (Windows) here

You can run the following command SELECT * FROM SYSIBMADM.DBPATHS. This will give details of following variables of your installed db2 database;

LOGPATH

DB_STORAGE_PATH

LOCAL_DB_DIRECTORY

DBPATH

These commands will provide you enough information to locate your installed database. Then you can restore your database providing the exact path.

To add a storage path to an existing database, issue the following ALTER DATABASE statement:

```<code>ALTER DATABASE database-name ADD STORAGE ON storage-path
</code>```

After adding one or more storage paths to the database, you may use the ALTER TABLESPACE statement to rebalance table spaces in the database so that they start to use the new storage paths immediately.

Title: DB2 database restore

Body:
When I am restoring the database, by default data is going in C drive, but when I installed the db2 that time I specify the path in D drive only.
Also, sample database files created by db2 is stored in D drive.
Can anyone please tell me what is the issue?

I have run this command:

SELECT * FROM SYSIBMADM.DBPATHS

below is the result i fetched:

LOGPATH- D:\DB2\NODE000\SQL00001\SQLOGDIR\
DB_STORAGE_PATH- C:\
LOCAL_DB_DIRECTORY -  D:\DB2\NODE000\SQLOGDIR\
DBPATH - D:\DB2\NODE000\SQL00001\

I Want to change this DB_STORAGE_PATH C:\ to D:\ for all the database which i will be restoring.

Body:
You can run db2set from db2 command line that will confirm you wheather db2 installed on path with other information;

db2-command-line> db2set

DB2_ATS_ENABLE=YES
DB2_CREATE_DB_ON_PATH=YES
DB2INSTPROF=C:\where\db2\installed\IBM\DB2\DB2COPY1
DB2COMM=TCPIP

You can get more information of Directory structure for your installed DB2 database product (Windows) here

You can run the following command SELECT * FROM SYSIBMADM.DBPATHS. This will give details of following variables of your installed db2 database;

LOGPATH

DB_STORAGE_PATH

LOCAL_DB_DIRECTORY

DBPATH

These commands will provide you enough information to locate your installed database. Then you can restore your database providing the exact path.

To add a storage path to an existing database, issue the following ALTER DATABASE statement:

ALTER DATABASE database-name ADD STORAGE ON storage-path

After adding one or more storage paths to the database, you may use the ALTER TABLESPACE statement to rebalance table spaces in the database so that they start to use the new storage paths immediately.


问:
Find number in given range without if statement in javascript
I have 3 inputs Number min and max

if number is in range between min and max the function should return number

if number is less than min the function should return min

if number is greater than max the function should return max

```<code>3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7
</code>```

I have tried doing it but cannot do it without if statement
Hint : Need to use Math function

```<code>function minCalulator(number,min,max){
    if(Math.min(number,min) == number){
        return min;
    }
    if(Math.min(number,max) === max){
            return max;
    }
    return number;
}
</code>```

How to implement this without if or any conditional statements?

答:
If only 3 numbers will be used, you can try to send values to function as an array, find min max and get them out, after this return array like that.

```<code>function myFunction(_numbers)
{
   var indexMax = _numbers.indexOf(Math.max(_numbers));
   _numbers.splice(indexMax, 1);
   var indexMin = _numbers.indexOf(Math.min(_numbers));
   _numbers.splice(indexMin, 1);
   return _numbers;
}
</code>```

Important!! This logic only works if you have 3 numbers in array like your examples.

Body:
I have 3 inputs Number min and max

if number is in range between min and max the function should return number

if number is less than min the function should return min

if number is greater than max the function should return max

3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7

I have tried doing it but cannot do it without if statement
Hint : Need to use Math function

function minCalulator(number,min,max){
    if(Math.min(number,min) == number){
        return min;
    }
    if(Math.min(number,max) === max){
            return max;
    }
    return number;
}

How to implement this without if or any conditional statements?

Body:
If only 3 numbers will be used, you can try to send values to function as an array, find min max and get them out, after this return array like that.

function myFunction(_numbers)
{
   var indexMax = _numbers.indexOf(Math.max(_numbers));
   _numbers.splice(indexMax, 1);
   var indexMin = _numbers.indexOf(Math.min(_numbers));
   _numbers.splice(indexMin, 1);
   return _numbers;
}

Important!! This logic only works if you have 3 numbers in array like your examples.