问:
Intersect two shapely polygons on the Earth projection
as i know, shapely use only cartesian coordinate system. I have two point on the earth with lat and lon coordinates. I need create buffer with 1km radius around this two points and find polygon, where this buffers intersect.

But construstion

buffer = Point(54.4353,65.87343).buffer(0.001) create simple circle, but in projection on the Earth it becomes ellipse, but i need two real circle with 1 km radius.

I think, i need convert my buffers into new projection and then intersect it, but dont now how correct do it.

答:
You need to do what you say. For that, you will need to use a library that handles projections (pyproj is the choice here). There is a similar question in Geodesic buffering in python

```<code>import pyproj
from shapely.geometry import MultiPolygon, Polygon, Point
from shapely.ops import transform as sh_transform
from functools import partial

wgs84_globe = pyproj.Proj(proj='latlong', ellps='WGS84')

def point_buff_on_globe(lat, lon, radius):
    #First, you build the Azimuthal Equidistant Projection centered in the
    # point given by WGS84 lat, lon coordinates
    aeqd = pyproj.Proj(proj='aeqd', ellps='WGS84', datum='WGS84',
                       lat_0=lat, lon_0=lon)
    #You then transform the coordinates of that point in that projection
    project_coords = pyproj.transform(wgs84_globe, aeqd,  lon, lat)
    # Build a shapely point with that coordinates and buffer it in the aeqd projection
    aeqd_buffer = Point(project_coords).buffer(radius)
    # Transform back to WGS84 each coordinate of the aeqd buffer.
    # Notice the clever use of sh_transform with partial functor, this is
    # something that I learned here in SO. A plain iteration in the coordinates
    # will do the job too.
    projected_pol = sh_transform(partial(pyproj.transform, aeqd, wgs84_globe),
                          aeqd_buffer)
    return projected_pol
</code>```

The function point_buff_on_globe will give you a polygon in lat lon that is the result of buffering the given point in the Azimuthal Equidistant Projection centered in that point (the best you can do with your requirements. Two observations:

I don't remember the units of the radius argument. I think is in meters, so if you need a 10 km buffer, you will need to pass it 10e3. But please, check it!

Beware of using this with radius to wide or points that are to far away from each other. Projections work well when the points are near to the point you are centering the projection.

Body:
You need to do what you say. For that, you will need to use a library that handles projections (pyproj is the choice here). There is a similar question in Geodesic buffering in python

import pyproj
from shapely.geometry import MultiPolygon, Polygon, Point
from shapely.ops import transform as sh_transform
from functools import partial

wgs84_globe = pyproj.Proj(proj='latlong', ellps='WGS84')

def point_buff_on_globe(lat, lon, radius):
    #First, you build the Azimuthal Equidistant Projection centered in the
    # point given by WGS84 lat, lon coordinates
    aeqd = pyproj.Proj(proj='aeqd', ellps='WGS84', datum='WGS84',
                       lat_0=lat, lon_0=lon)
    #You then transform the coordinates of that point in that projection
    project_coords = pyproj.transform(wgs84_globe, aeqd,  lon, lat)
    # Build a shapely point with that coordinates and buffer it in the aeqd projection
    aeqd_buffer = Point(project_coords).buffer(radius)
    # Transform back to WGS84 each coordinate of the aeqd buffer.
    # Notice the clever use of sh_transform with partial functor, this is
    # something that I learned here in SO. A plain iteration in the coordinates
    # will do the job too.
    projected_pol = sh_transform(partial(pyproj.transform, aeqd, wgs84_globe),
                          aeqd_buffer)
    return projected_pol

The function point_buff_on_globe will give you a polygon in lat lon that is the result of buffering the given point in the Azimuthal Equidistant Projection centered in that point (the best you can do with your requirements. Two observations:

I don't remember the units of the radius argument. I think is in meters, so if you need a 10 km buffer, you will need to pass it 10e3. But please, check it!

Beware of using this with radius to wide or points that are to far away from each other. Projections work well when the points are near to the point you are centering the projection.


来源: stackexchange

问:
I need to check the logs from current time to before 2 hours
I need to  check the logs from current time to before 2 hours, can you please suggest me a command </p>

答:
For listing all logs in the current directory within last 2 hours (120 mins)

```<code>find . -mmin -120 -maxdepth 1
</code>```

for logs within in last 1 day in the current directory.

```<code>find . -mtime -1  -maxdepth 1
</code>```

You can use the find command to find all files that have been modified after a certain period of time.

Source : https://unix.stackexchange.com/questions/10041/how-to-get-only-files-created-after-a-date-with-ls

ContentLicense: CC BY-SA 3.0

Body:
For listing all logs in the current directory within last 2 hours (120 mins)

find . -mmin -120 -maxdepth 1

for logs within in last 1 day in the current directory.

find . -mtime -1  -maxdepth 1

You can use the find command to find all files that have been modified after a certain period of time.

Source : https://unix.stackexchange.com/questions/10041/how-to-get-only-files-created-after-a-date-with-ls


问:
If condition wrongly working
The Following PHP if condition statement is processing wrong and is not working.

File $fname has text values: "990,1000" with a comma in between:

```<code>$myfile = fopen($fname, "r") or die("<script
type='text/javascript'>window.location.href =
'http://www.autorekrooter.com/activation.html';</script>");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?
echo "<br>myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " .
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "<script>alert('You can't proceed further');</script>";
//echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
exit();
}
else{
echo "<script type='text/javascript'>window.location.href =
'gui.php';</script>";
echo "You can proceed";
exit();
}
</code>```

When I run the above in a php file the if statement always takes value of myArray[0] >= myArray[1] as true and show the reigster.html whereas in the $fname file it is 990,1000 myArray[0]=990 and myArray[1]=1000 so myArray[0] should not be greater than myArray[1] and the else statement should run but the opposite is happening.

Any suggestions as to why this is not working?

Many Thanks in advance for your answers.

Title: If condition wrongly working

Body:
The Following PHP if condition statement is processing wrong and is not working.

File $fname has text values: "990,1000" with a comma in between:

$myfile = fopen($fname, "r") or die("");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?
echo "
myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " .
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "";
//echo "";
exit();
}
else{
echo "";
echo "You can proceed";
exit();
}

When I run the above in a php file the if statement always takes value of myArray[0] >= myArray[1] as true and show the reigster.html whereas in the $fname file it is 990,1000 myArray[0]=990 and myArray[1]=1000 so myArray[0] should not be greater than myArray[1] and the else statement should run but the opposite is happening.

Any suggestions as to why this is not working?

Many Thanks in advance for your answers.

Body:
try:
f ((int)$myArray[0]>=(int)$myArray[1]){


问:
How to prevent from downloading and running script?
I wonder if it is possible in JavaScript to prevent  object from running?

I need to make it like it never existed. Is there an event where I can prevent from executing a script (based on src argument)?

I'm targeting Internet Explorer 8 but solution for other browsers are also welcomed (though it won't help me in anything ;)).

And please no JQuery or other libraries. I'm writing in C++ an IE add-on but I can use interfaces from MSHTML to 'use' JavaScript.

答: In IE (MSHTML) it's simple. You just 404 the HTTP request to get unwantedscript.js.

ContentLicense: CC BY-SA 2.5


问:
Creating Mock reference and setup methods for complex operations using MOQ
I have two  methods , OpenCertificateStore and FindCertificateBySubjectName and implemented them as following:

```<code> public void OpenCertificateStore()
        {
            if (_certificateStore == default(X509Store))
                _certificateStore = new X509Store(StoreLocation.CurrentUser);

            _certificateStore.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived);
        }

        public X509Certificate2Collection FindCertificateBySubjectName(string certificateSubjectName)
        {
            X509Certificate2Collection certificates = new X509Certificate2Collection();
            if (_certificateStore != default(X509Store))
            {
                certificates = _certificateStore.Certificates.Find(X509FindType.FindBySubjectName, certificateSubjectName, true);
            }

            return certificates;
        }
</code>```

I have my unit test as below:

```<code>[TestClass]
    public class MyHealthTests
    {
        private Mock<Logger> _logger;
        private Mock<MYCertificateManager> _certManager;

        [TestInitialize]
        public void Initialize()
        {
             _logger = new Mock<Logger>();
             _certManager = new Mock<MYCertificateManager>();
        }

        [TestMethod]
        public void PassName_FindCertiFicatebyName_ShouldReturnValid()
        {

            MyCertificateHelper myCertHelper = new MyCertificateHelper(_logger.Object,_certManager.Object);

            myCertHelper.OpenCertificateStore();
            var certNameCollection = myCertHelper.FindCertificateBySubjectName("Valid Cert Name");
            Assert.IsNotNull(certNameCollection);
            Assert.IsTrue(certNameCollection.Count > 0);
        }
    }
</code>```

Which works fine , but it would be lot better if I can find a way to mock myCertHelper.

If I do mok them , it returns null as it's not querying actual certificate store.

答:
How do you mock MyCertificateHelper?

You don't.

Doing so would have no benefit. If you did, then all of the classes in your test would be mocked out and you would no longer actually be testing any of your code. At that point, you might as well delete the test. It wouldn't do anything but cost you money to maintain it.

Prefixing everything with My is useless. Worse than useless, it's noisy and distracting. Drop it.

I don't like the temporal coupling in your design. I don't like needing to call methods like Open or Init. It's easy to forget to call it or call it too many times. It's better if the constructor puts the class into a usable state.

It's nice that you're injecting and kicking the logger, but I find injecting loggers to be a code smell. I find it's much nicer to have my classes raise events and have the logger listen for those events. It removes the need to mock the logger all the time and provides nice hooks for other code to leverage. This kind of event driven design ends up in code that is much more open to extension, but closed for modification.

OwnerDisplayName: Simsons

Body:
I have two  methods , OpenCertificateStore and FindCertificateBySubjectName and implemented them as following:

 public void OpenCertificateStore()
        {
            if (_certificateStore == default(X509Store))
                _certificateStore = new X509Store(StoreLocation.CurrentUser);

            _certificateStore.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived);
        }

        public X509Certificate2Collection FindCertificateBySubjectName(string certificateSubjectName)
        {
            X509Certificate2Collection certificates = new X509Certificate2Collection();
            if (_certificateStore != default(X509Store))
            {
                certificates = _certificateStore.Certificates.Find(X509FindType.FindBySubjectName, certificateSubjectName, true);
            }

            return certificates;
        }

I have my unit test as below:

[TestClass]
    public class MyHealthTests
    {
        private Mock<Logger> _logger;
        private Mock<MYCertificateManager> _certManager;

        [TestInitialize]
        public void Initialize()
        {
             _logger = new Mock<Logger>();
             _certManager = new Mock<MYCertificateManager>();
        }

        [TestMethod]
        public void PassName_FindCertiFicatebyName_ShouldReturnValid()
        {

            MyCertificateHelper myCertHelper = new MyCertificateHelper(_logger.Object,_certManager.Object);

            myCertHelper.OpenCertificateStore();
            var certNameCollection = myCertHelper.FindCertificateBySubjectName("Valid Cert Name");
            Assert.IsNotNull(certNameCollection);
            Assert.IsTrue(certNameCollection.Count > 0);
        }
    }

Which works fine , but it would be lot better if I can find a way to mock myCertHelper.

If I do mok them , it returns null as it's not querying actual certificate store.

OwnerDisplayName: RubberDuck


问:
Is there an official facebook messenger chatbot NodeJS API?
I see a lot of node.js package to integrate messenger chatbot.
I would like to know what is the best solution / package ?
Is there a recommandation provided by Facebook ?</p>

答: See the FB Node.js Messenger Quick Start Guide: https://developers.facebook.com/docs/messenger-platform/guides/quick-start</p>


问:
How to scroll to bottom of div element Selenium Webdriver
I have a use case wherein there's a div element on the webpage, it appears like a popup dialog as soon as you click a link (its not an actual popup, its something like dialog boxes which opens in Facebook when you click a link to check reactions on your posts etc.)

I'm using Selenium WebDriver with Java to automate tests for this application, my use case involves me to scroll to the bottom of the dialog box where there is a link to show more items, when user clicks show more, it populates another 10 items in the list and so on until there are no other items left for the user to visit.

So basically I have to scroll down on that particular div element till I keep seeing Show More link and when driver is not able to find show more link it should stop.

Note - I can't just scroll to bottom of the page using javascript window.scrollTo() as it will scroll down through whole webpage, however I just want to scroll to bottom of that division element only.

If anybody have any idea on how to achieve this please let me know.

Thanks for the help in advance !

答:
```<code>WebElement ele= driver.findElement(By.id("id_of_element"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", ele);
</code>```

or

```<code>WebElement ele= driver.findElement(By.id("id_of_element"));
Actions builder = new Actions(driver);
builder.moveToElement(ele).click();
Action build=builder.build();
build.perform();
</code>```

Body:
WebElement ele= driver.findElement(By.id("id_of_element"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", ele);

or

WebElement ele= driver.findElement(By.id("id_of_element"));
Actions builder = new Actions(driver);
builder.moveToElement(ele).click();
Action build=builder.build();
build.perform();


问:
Creating Java Calendar, basic parameters
I would like to send a Java Calendar object over a web service (soap). I notice that this kind of object is too complex and there should be a better method to send the same information.

What are the basic attributes that should be sended over the web service, so the client can create a Java Calendar out of this attributes?

I'm guessing: TimeZone, Date, and Time?

Also, how can the client recreate the Calendar based on those attributes?

Thanks!

答:
I suppose the Calendar instance that you would like to send is of type java.util.GregorianCalendar. In that case, you could just use xsd:dateTime. For SOAP, Java will usually bind that to a javax.xml.datatype.XMLGregorianCalendar instance.

Translating between GregorianCalendarand XMLGregorianCalendar:

GregorianCalendar -> XMLGregorianCalendar: javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar(GregorianCalendar)

XMLGregorianCalendar -> GregorianCalendar: XMLGregorianCalendar.toGregorianCalendar()


问:
Download a file in django with a button using xmlhttprequest
I looked at many same questions but none resolved my problem,
I'm trying to download a file generated in my view using a button.
Problem : I get an empty file while clicking on download button

My view:

```<code>class dumpView(View):

template_name = 'download.html'
def get(self, request):
    file = open("/home/test.pdf", "rwbt")
    response = HttpResponse(file.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachement; filename=%s' % file
    return render(request, 'download.html')
</code>```

My url:

```<code>url(r'^dump/', dumpView.as_view()),
</code>```

My template:

```<code> {% extends 'base.html' %}
 {% load staticfiles %}
 {% block content %}
 <div class="container">
 <div class="row">
    <div class="jumbotron">
        <div class="row">
            <center>
                <a href="javascript:void(0)" class="btn btn-primary btn-lg dump">Download</a>
            </center>
        </div>
    </div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script src="{% static 'js/home.js' %}"></script>
{% endblock %}
</code>```

My Django view is rendering the response. I did add an on click handler to the button with class dump in the UI to make a XHR request to the “/dump” URL  and recieve response as a blob and download the file with custom name and date.

My js :

```<code>$(".dump").on("click", function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    var a, today;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhttp.response);
        today = new Date();
        a.download = "file_" + today.toDateString().split(" ").join("_") + ".pdf";
        a.style.display = 'none';
        document.body.appendChild(a);
        return a.click();
    }
};
xhttp.open("GET", "/dump", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.responseType = 'blob';
xhttp.send();
});
</code>```

答:
In your view, I suggest adding a size to your response

```<code>content = file(filename).read()
response = HttpResponse(content, content_type='text/plain')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = 'attachment; filename=%s' % 'my_pdf.pdf'
</code>```

As @bob-vork just said, the filename from Content-Disposition should not be the python file object, but the name your download will have.

How about registering the view in urls.py then replace the javascript by:

```<code><input type="button" value="Download" onclick="window.open('download_my_pdf')">
</code>```

EDIT :

Since you're going with the suggested HTML, then I'll put more details to my solution.

First, you can drop the home.js. As you understood

```<code><a href="javascript:void(0)" class="btn btn-primary btn-lg dump">Download</a>
</code>```

becomes

```<code><input type="button" value="Download" onclick="window.open('download_my_pdf')">
</code>```

your views.py should return directly the response

```<code>from django.http import HttpResponse
from wsgiref.util import FileWrapper

@login_required
def download_pdf(request):
    filename = 'whatever_in_absolute_path__or_not.pdf'
    content = FileWrapper(filename)
    response = HttpResponse(content, content_type='application/pdf')
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=%s' % 'whatever_name_will_appear_in_download.pdf'
    return response
</code>```

Pay attention to put the right content_type as well. Note that I haven't tested the view (especially the FileWrapper), I adapted some code I had for plain text. This is also why you have a TypeError if you treat the pdf as a text file.

In urls.py

```<code>urlpatterns = (
    [...]
    url('download_my_pdf', download_pdf),
)
</code>```

Body:
I looked at many same questions but none resolved my problem,
I'm trying to download a file generated in my view using a button.
Problem : I get an empty file while clicking on download button

My view:

class dumpView(View):

template_name = 'download.html'
def get(self, request):
    file = open("/home/test.pdf", "rwbt")
    response = HttpResponse(file.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachement; filename=%s' % file
    return render(request, 'download.html')

My url:

url(r'^dump/', dumpView.as_view()),

My template:

 {% extends 'base.html' %}
 {% load staticfiles %}
 {% block content %}

                Download

{% endblock %}
{% block javascript %}

{% endblock %}

My Django view is rendering the response. I did add an on click handler to the button with class dump in the UI to make a XHR request to the “/dump” URL  and recieve response as a blob and download the file with custom name and date.

My js :

$(".dump").on("click", function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    var a, today;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhttp.response);
        today = new Date();
        a.download = "file_" + today.toDateString().split(" ").join("_") + ".pdf";
        a.style.display = 'none';
        document.body.appendChild(a);
        return a.click();
    }
};
xhttp.open("GET", "/dump", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.responseType = 'blob';
xhttp.send();
});

Body:
In your view, I suggest adding a size to your response

content = file(filename).read()
response = HttpResponse(content, content_type='text/plain')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = 'attachment; filename=%s' % 'my_pdf.pdf'

As @bob-vork just said, the filename from Content-Disposition should not be the python file object, but the name your download will have.

How about registering the view in urls.py then replace the javascript by:

<input type="button" value="Download" onclick="window.open('download_my_pdf')">

EDIT :

Since you're going with the suggested HTML, then I'll put more details to my solution.

First, you can drop the home.js. As you understood

<a href="javascript:void(0)" class="btn btn-primary btn-lg dump">Download</a>

becomes

<input type="button" value="Download" onclick="window.open('download_my_pdf')">

your views.py should return directly the response

from django.http import HttpResponse
from wsgiref.util import FileWrapper

@login_required
def download_pdf(request):
    filename = 'whatever_in_absolute_path__or_not.pdf'
    content = FileWrapper(filename)
    response = HttpResponse(content, content_type='application/pdf')
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=%s' % 'whatever_name_will_appear_in_download.pdf'
    return response

Pay attention to put the right content_type as well. Note that I haven't tested the view (especially the FileWrapper), I adapted some code I had for plain text. This is also why you have a TypeError if you treat the pdf as a text file.

In urls.py

urlpatterns = (
    [...]
    url('download_my_pdf', download_pdf),
)


问:
How to insert value into foreign key in SQL server? (Avoid the duplicate key.)
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

```<code>create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)
</code>```

Here are my insert statements

```<code>insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
</code>```

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

答:
As the column 'sinum' is primary key, you can't define it explicitly.

So please have a try with below.

```<code>Insert into person (gender,age,emailAddr, phoneNum) values ( 'female', 24, 'dds', 2121)

Declare @sinnum=IDENT_CURRENT('Person')

If @@error=0

Insert into employee(lastName,firstName, sinnum, departmentId, position,baseSalary) values ('Snow','John',@sinnum,20,'clerk',4000)
</code>```

Ident_current will save the last inserted primary key value in the mentioned table. Saving that value in a temporary variable, inorder to use the same value as FK in the employee table.

@@error used here to ensure insert on employee table only on successful insert made in person table.

Body:
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)

Here are my insert statements

insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

Body:
As the column 'sinum' is primary key, you can't define it explicitly.

So please have a try with below.

Insert into person (gender,age,emailAddr, phoneNum) values ( 'female', 24, 'dds', 2121)

Declare @sinnum=IDENT_CURRENT('Person')

If @@error=0

Insert into employee(lastName,firstName, sinnum, departmentId, position,baseSalary) values ('Snow','John',@sinnum,20,'clerk',4000)

Ident_current will save the last inserted primary key value in the mentioned table. Saving that value in a temporary variable, inorder to use the same value as FK in the employee table.

@@error used here to ensure insert on employee table only on successful insert made in person table.


问:
Spark doesn't download dependencies from mysql:mysql-connector-java:5.1.35
I'm specifying the following and I still get a class not found exception.

```<code>spark.jars.packages=mysql:mysql-connector-java:5.1.35
</code>```

Any idea what could be happening?

答:
Correct syntax for conf/spark-defaults.conf doesn't include =:

```<code>spark.jars.packages mysql:mysql-connector-java:5.1.35
</code>```

Body:
I'm specifying the following and I still get a class not found exception.

spark.jars.packages=mysql:mysql-connector-java:5.1.35

Any idea what could be happening?

Body:
Correct syntax for conf/spark-defaults.conf doesn't include =:

spark.jars.packages mysql:mysql-connector-java:5.1.35


问:
Data Not displaying while passing from controller
In asp.net MVC getting the model value but while passing to view nothing displayed.

Controller

```<code>  public ActionResult Index(plan plan1)
        {
            var myCharge = new StripeChargeCreateOptions();

            string apiKey = "";
            var stripeClient = new StripeClient(apiKey);
            var planService = new StripePlanService(apiKey);
            StripePlan response = planService.Get("1234");
            plan1.Amount = (response.Amount).ToString();

            return View();
        }
</code>```

view

```<code><div>
    @Html.TextBoxFor(m => m.Amount)

</div>
</code>```

How to display the Amount value inside textbox

答:
It is because you are not passing hte model object back to view, you need to pass the instance plan1 back to view from action, just change your last line of action code to :

```<code>return View(plan1);
</code>```

The View gets information about the model object which is passed from the controller action, you are not passing it back, so there is no way for View to know that it needs to use plan1 object state to render the View.

I hope it makes sense to you now that why it is not displaying your data.

Body:
In asp.net MVC getting the model value but while passing to view nothing displayed.

Controller

  public ActionResult Index(plan plan1)
        {
            var myCharge = new StripeChargeCreateOptions();

            string apiKey = "";
            var stripeClient = new StripeClient(apiKey);
            var planService = new StripePlanService(apiKey);
            StripePlan response = planService.Get("1234");
            plan1.Amount = (response.Amount).ToString();

            return View();
        }

view

    @Html.TextBoxFor(m => m.Amount)

How to display the Amount value inside textbox

Body:
It is because you are not passing hte model object back to view, you need to pass the instance plan1 back to view from action, just change your last line of action code to :

return View(plan1);

The View gets information about the model object which is passed from the controller action, you are not passing it back, so there is no way for View to know that it needs to use plan1 object state to render the View.

I hope it makes sense to you now that why it is not displaying your data.


问:
angularjs templateUrl in WebContent
I am deplying my angular app in java dynamic web project, directory map:

```<code>->WebContent
---->javaScript
------>directives
index.html
</code>```

and in my directives folder I have form directive:

```<code>var app = angular.module('myApp');
    app.directive('formDirective', formDirective);

function formDirective() {

    var directive = {
        restrict: 'EA',
        templateUrl: 'formDirective.html', //the request
        scope: {
        },
        controller: FormControllerDir,
        controllerAs: 'vm',
        bindToController: true
    };
    return directive;
}
function FormControllerDir() {
    console.log('FormController');
}
</code>```

and formDirective.html is placed under the same dir, but angular search for the file under root:

```<code>GET http://localhost:8080/P2P/formDirective.html 404 (Not Found)
</code>```

P2P is my project name, how do I change it to:

```<code>http://localhost:8080/P2P/JavaScript/directives/formDirective.html
</code>```

答:
So it was simple just add the full path form context -

templateUrl: 'JavaScript/directives/formDirective/formDirective.html'

Title: angularjs templateUrl in WebContent

Body:
I am deplying my angular app in java dynamic web project, directory map:

->WebContent
---->javaScript
------>directives
index.html

and in my directives folder I have form directive:

var app = angular.module('myApp');
    app.directive('formDirective', formDirective);

function formDirective() {

    var directive = {
        restrict: 'EA',
        templateUrl: 'formDirective.html', //the request
        scope: {
        },
        controller: FormControllerDir,
        controllerAs: 'vm',
        bindToController: true
    };
    return directive;
}
function FormControllerDir() {
    console.log('FormController');
}

and formDirective.html is placed under the same dir, but angular search for the file under root:

GET http://localhost:8080/P2P/formDirective.html 404 (Not Found)

P2P is my project name, how do I change it to:

http://localhost:8080/P2P/JavaScript/directives/formDirective.html


问:
Copying All Class Fields and Properties To Another Class
I have a class which normally contains Fields, Properties. What i want to achieve is instead of this:

```<code>class Example
{
    public string Field = "EN";
    public string Name { get; set; }
    public int? Age { get; set; }
    public List<string> A_State_of_String { get; set; }
}

public static void Test()
{
    var c1 = new Example
    {
        Name = "Philip",
        Age = null,
        A_State_of_String = new List<string>
        {
            "Some Strings"
        }
    };
    var c2 = new Example();

    //Instead of doing that
    c2.Name = string.IsNullOrEmpty(c1.Name) ? "" : c1.Name;
    c2.Age = c1.Age ?? 0;
    c2.A_State_of_String = c1.A_State_of_String ?? new List<string>();

    //Just do that
    c1.CopyEmAll(c2);
}
</code>```

What i came up with but doesn't work as expected.

```<code>public static void CopyEmAll(this object src, object dest)
{
    if (src == null) {
        throw new ArgumentNullException("src");
    }

    foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src)) {
        var val = item.GetValue(src);
        if (val == null) {
            continue;
        }
        item.SetValue(dest, val);
    }
}
</code>```

Problems:

Although i checked for null, it seems to bypass it.

Doesn't seem to copy Fields.

Notes:

I don't want to use AutoMapper for some technical issues.

I want the method to copy values and not creating new object. [just mimic the behavior i stated in the example]

I want the function to be recursive [if the class contains another classes it copies its values too going to the most inner one]

Don't want to copy null or empty values unless i allow it to.

Copies all Fields, Properties, or even Events.

答:
You can use serialization to serialize object A and deserialize as object B - if they have very same structure, you can look here for object deep copy.
Deep cloning objects

I know you don't want to use Automapper, but if the types have only SIMILAR structure, you should maybe use Automapper which is based on reflection. You can download a nuget and find some information here:
https://www.nuget.org/packages/AutoMapper/

your code then will look like

```<code>public TOutput CopyAll<TInput, TOutput>(TInput input)
{
    var config = new MapperConfiguration(cfg => cfg.CreateMap<TInput, TOutput>());
    IMapper mapper = config.CreateMapper();
    return mapper.Map<TOutput>(vstup);
}
</code>```

Body:
I have a class which normally contains Fields, Properties. What i want to achieve is instead of this:

class Example
{
    public string Field = "EN";
    public string Name { get; set; }
    public int? Age { get; set; }
    public List<string> A_State_of_String { get; set; }
}

public static void Test()
{
    var c1 = new Example
    {
        Name = "Philip",
        Age = null,
        A_State_of_String = new List<string>
        {
            "Some Strings"
        }
    };
    var c2 = new Example();

    //Instead of doing that
    c2.Name = string.IsNullOrEmpty(c1.Name) ? "" : c1.Name;
    c2.Age = c1.Age ?? 0;
    c2.A_State_of_String = c1.A_State_of_String ?? new List<string>();

    //Just do that
    c1.CopyEmAll(c2);
}

What i came up with but doesn't work as expected.

public static void CopyEmAll(this object src, object dest)
{
    if (src == null) {
        throw new ArgumentNullException("src");
    }

    foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src)) {
        var val = item.GetValue(src);
        if (val == null) {
            continue;
        }
        item.SetValue(dest, val);
    }
}

Problems:

Although i checked for null, it seems to bypass it.

Doesn't seem to copy Fields.

Notes:

I don't want to use AutoMapper for some technical issues.

I want the method to copy values and not creating new object. [just mimic the behavior i stated in the example]

I want the function to be recursive [if the class contains another classes it copies its values too going to the most inner one]

Don't want to copy null or empty values unless i allow it to.

Copies all Fields, Properties, or even Events.

Body:
You can use serialization to serialize object A and deserialize as object B - if they have very same structure, you can look here for object deep copy.
Deep cloning objects

I know you don't want to use Automapper, but if the types have only SIMILAR structure, you should maybe use Automapper which is based on reflection. You can download a nuget and find some information here:
https://www.nuget.org/packages/AutoMapper/

your code then will look like

public TOutput CopyAll<TInput, TOutput>(TInput input)
{
    var config = new MapperConfiguration(cfg => cfg.CreateMap<TInput, TOutput>());
    IMapper mapper = config.CreateMapper();
    return mapper.Map<TOutput>(vstup);
}


问:
Recovering from failure in orchestrated deployments
In monolithic systems without orchestration, whenever there’s a temporary problem accessing a resource (ex. Connecting to a database), the typical approach is to keep retrying until recovery is achieved.

In systems with a microservices architecture, where typically the boot process is light, removing the retry logic from the application and abort the process, letting the orchestrator restart the process, can reduce the application's complexity. If the orchestrator can deal with service dependencies, it might even know exactly what needs to be recovered and when is appropriate to start the service again. There’s no “blind” retry.

If the service has persistent connections from clients, then terminating the service might be a problem, other than that I think terminating the process is an approach to consider.

Does anyone has any experiente that can share? Feedback would be very helpful.

答: Using init containers and readyness checks can solve your issue: https://blog.giantswarm.io/wait-for-it-using-readiness-probes-for-service-dependencies-in-kubernetes/</p>


问:
Search a list of terms from google using python 2.7
I have followed this SO question Searching in Google with Python and executed as explained in answer no. 2.
I used pip install Google-Search-API, then executed following code:

from google import google

    num_page = 3

    search_results = google.search("Agriculture", num_page)

But even after successfully installing the API, I am getting the import error

答: I think you have to use this google module. More about it, here


问:
Async post request and assigning returned data
So I am learning AngularJS and I am trying to replace my not-so-pretty method of getting data from a webservice and realtime assinging it to a variable that is binded using ng-repeat. The thing I want to achieve mostly is to have asynchronous call. I can't use it now because AJAX is returning data after data is returned to a scope variable.

My current code looks like this:

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

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            $scope.results = getListt();
            loadingAnimationStop();
        };

        function getListt() {
            var returnData;
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    returnData = JSON.parse(data);
                }
            });
            return returnData;
        }
    }
);
</code>```

And in HTML I indicate search function by using ng-click

```<code><button ng-click="searchListt()">Search</button>
</code>```

答:
I updated your code here. getListt(); function call from searchListt function. Once ajax call will success then response data assign to $scope.results

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

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            getListt();

        };

        function getListt() {
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    $scope.results = JSON.parse(data);
                    loadingAnimationStop();
                }
            });
        }
    }
);
</code>```

Body:
So I am learning AngularJS and I am trying to replace my not-so-pretty method of getting data from a webservice and realtime assinging it to a variable that is binded using ng-repeat. The thing I want to achieve mostly is to have asynchronous call. I can't use it now because AJAX is returning data after data is returned to a scope variable.

My current code looks like this:

var app = angular.module("Listt", []);

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            $scope.results = getListt();
            loadingAnimationStop();
        };

        function getListt() {
            var returnData;
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    returnData = JSON.parse(data);
                }
            });
            return returnData;
        }
    }
);

And in HTML I indicate search function by using ng-click

<button ng-click="searchListt()">Search</button>

Body:
I updated your code here. getListt(); function call from searchListt function. Once ajax call will success then response data assign to $scope.results

var app = angular.module("Listt", []);

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            getListt();

        };

        function getListt() {
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    $scope.results = JSON.parse(data);
                    loadingAnimationStop();
                }
            });
        }
    }
);


问:
Download and play partial audio files in Python
I have an audio streaming application that uses requests to download the audio file and then played using Gstreamer.

I want to trim the first few seconds of all the audio files that i have. I could use ffmpeg to trim but that would waste cpu resources on my embedded platform and also waste network bandwidth

(The number of songs are around 1000, and they get downloaded continously, so it does make a difference)

I have tried downloading partial file using the range header in requests but that doesn't work. I can't play the file.

Can someone please tell me how i can make this work?

The audio files are generally .m4a / .webm but they are extracted from youtube so can't say for sure.

答:
This is an uneasy task.. there is no clean way how to do it..

you can probably use the valve element set it to drop by default..
and then put some timer which sets the drop to false..

not sure how this will work, you need to try.

Here are some hints:


问:
implement toString for enum typeScript
I would like to know if it is possible to redefine toString() for an enum.

Here is my enum:

enum Person{
  FOO = 10,
  FAA = 1,
  FII = 2
}
```

I want to redefine toString so that when Person.FOO.toString() is called, that return "FOO". Is that possible?

答:
If you look at the compiled javascript for your code:

```<code>var Person;
(function (Person) {
    Person[Person["FOO"] = 10] = "FOO";
    Person[Person["FAA"] = 1] = "FAA";
    Person[Person["FII"] = 2] = "FII";
})(Person || (Person = {}));
</code>```

You'll notice that Person.FOO is just a number (10 to be specific), so the only way to override the toString for it requires you to override it for all numbers, and you probably don't want that.

If you're looking for the name of the enum (instead of the ordinal) then you can simply do this:

```<code>console.log(Person[Person.FOO]); // "FOO"
</code>```

Title: implement toString for enum typeScript

Body:
I would like to know if it is possible to redefine toString() for an enum.

Here is my enum:

enum Person{
  FOO = 10,
  FAA = 1,
  FII = 2
}

I want to redefine toString so that when Person.FOO.toString() is called, that return "FOO". Is that possible?

Body:
If you look at the compiled javascript for your code:

var Person;
(function (Person) {
    Person[Person["FOO"] = 10] = "FOO";
    Person[Person["FAA"] = 1] = "FAA";
    Person[Person["FII"] = 2] = "FII";
})(Person || (Person = {}));

You'll notice that Person.FOO is just a number (10 to be specific), so the only way to override the toString for it requires you to override it for all numbers, and you probably don't want that.

If you're looking for the name of the enum (instead of the ordinal) then you can simply do this:

console.log(Person[Person.FOO]); // "FOO"


问:
How to get value of checkbox from checkboxlistFor using jquery ajax in MVC
I have a checkboxlistfor control in mvc 5 and want the value of the selected checkbox, once I get the value then send ajax request and fetch the data as per id,
below is the reference link where similar kind of functionality is achieved, in this he has used "for loop" for multiple checkboxes, and I am using checkboxlistfor, using this I am not able to get the value of the selected checkbox.

"https://forums.asp.net/t/2078931.aspx?How+to+get+data+from+checkbox+list+using+jquery+ajax+in+MVC+"

Below is the code I am using to bind checkboxlistfor code

view

```<code>@Html.CheckBoxListFor(model => model.sbuIDs,
                      model => model.Availablesbu,
                      sb => sb.sbuID,
                      sb => sb.sbuName,
                      model => model.Selectedsbu,
                      htmlListInfo)
</code>```

controller code

```<code>[HttpGet]
public ActionResult AddUsers()
{
    var Uvm = new UsersViewModel();

    var Selectedsbu = new List<sbu>();
    Uvm.Availablesbu = _User.Getallsbu();
    Uvm.Selectedsbu = Selectedsbu;
    return View(Uvm);
}

public class sbu
{
    public int UserID { get; set; }
    public int sbuID { get; set; }
    public string sbuName { get; set; }
}

public class UsersViewModel()
{
    public IEnumerable<sbu> sbu = null;
    sbu = new List<sbu>();
    public IEnumerable<sbu> Availablesbu { get; set; }
    public IEnumerable<sbu> Selectedsbu { get; set; }
    public string[] sbuIDs { get; set; }
}
</code>```

Update

Below is the ajax request i will use:

```<code><script>
    $("#CheckBoxListFor").change(function () {
        debugger;
        var favorite = [];
        $.each($("input[name='sbuIDs']:checked"), function () {
            favorite.push($(this).val());
        });

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            url: '@Url.Action("Getvalues", "Home")',

            data: JSON.stringify({ values: favorite })
        });

    });
</script>
</code>```

Controller code

```<code>public JsonResult Getvalues(string[] values)
{
    //
}
</code>```

答:
Below is the ajax request i have use

```<code><script>
                            $("#CheckBoxListFor").change(function () {
                                debugger;
                                var favorite = [];
                                $.each($("input[name='sbuIDs']:checked"), function () {
                                    favorite.push($(this).val());
                                });

                                $.ajax({
                                    type: "POST",
                                    dataType: "json",
                                    contentType: "application/json",
                                    url: '@Url.Action("Getvalues", "Home")',

                                    data: JSON.stringify({ values: favorite })
                                });

                            });

                        </script>
</code>```

Controller code

```<code> public JsonResult Getvalues(string[] values)
    {
</code>```

....
}

Body:
I have a checkboxlistfor control in mvc 5 and want the value of the selected checkbox, once I get the value then send ajax request and fetch the data as per id,
below is the reference link where similar kind of functionality is achieved, in this he has used "for loop" for multiple checkboxes, and I am using checkboxlistfor, using this I am not able to get the value of the selected checkbox.

"https://forums.asp.net/t/2078931.aspx?How+to+get+data+from+checkbox+list+using+jquery+ajax+in+MVC+"

Below is the code I am using to bind checkboxlistfor code

view

@Html.CheckBoxListFor(model => model.sbuIDs,
                      model => model.Availablesbu,
                      sb => sb.sbuID,
                      sb => sb.sbuName,
                      model => model.Selectedsbu,
                      htmlListInfo)

controller code

[HttpGet]
public ActionResult AddUsers()
{
    var Uvm = new UsersViewModel();

    var Selectedsbu = new List<sbu>();
    Uvm.Availablesbu = _User.Getallsbu();
    Uvm.Selectedsbu = Selectedsbu;
    return View(Uvm);
}

public class sbu
{
    public int UserID { get; set; }
    public int sbuID { get; set; }
    public string sbuName { get; set; }
}

public class UsersViewModel()
{
    public IEnumerable<sbu> sbu = null;
    sbu = new List<sbu>();
    public IEnumerable<sbu> Availablesbu { get; set; }
    public IEnumerable<sbu> Selectedsbu { get; set; }
    public string[] sbuIDs { get; set; }
}

Update

Below is the ajax request i will use:

Controller code

public JsonResult Getvalues(string[] values)
{
    //
}

Body:
Below is the ajax request i have use

<script>
                            $("#CheckBoxListFor").change(function () {
                                debugger;
                                var favorite = [];
                                $.each($("input[name='sbuIDs']:checked"), function () {
                                    favorite.push($(this).val());
                                });

                                $.ajax({
                                    type: "POST",
                                    dataType: "json",
                                    contentType: "application/json",
                                    url: '@Url.Action("Getvalues", "Home")',

                                    data: JSON.stringify({ values: favorite })
                                });

                            });

                        </script>

Controller code

 public JsonResult Getvalues(string[] values)
    {

....
}


问:
Angularjs second dropdown depend on first
Please i have a question. how could i create a second dropdown depend on select item from first dropdown.

```<code><div ng-app="myapp">
<fieldset ng-controller="FirstCtrl">
    <select
        ng-options="p.id for p in jobs"
        ng-model="selectedPerson"></select>
    {{ selectedPerson }}
</fieldset>
</code>```

答:
I have a interesting example to show you how the select list can depend on another. In fact, the select options of a list can be made dependent on the value of the first select list.

HTML

Controller

```<code>var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.jobs1 = [
    {
        "id": 600,
        "sector": "Controlling",
        "cost": 4700
    },
    {
        "id": 600,
        "sector": "finance",
        "cost": 4700

    },
    {
        "id": 40,
        "sector": "IT",
        "cost": 7600

    },
    {
        "id": 50,
        "sector": "Controlling",
        "cost": 4600

    },
    {
        "id": 50,
        "sector": "IT",
        "cost": 4600

    },{
        "id": 41,
        "sector": "Controlling",
        "cost": 1100

    },
    {
        "id": 41,
        "sector": "IT",
        "cost": 1100

    }
];
$scope.jobs2 = [];

$scope.firstSelectChange = function(){
  $scope.jobs2 = [];
  $scope.selectedPerson2 = '';
 for(var i=0; i<$scope.jobs1.length; i++){
       if($scope.jobs1[i].id === $scope.selectedPerson1.id){
           $scope.jobs2.push($scope.jobs1[i]);
       }
    }
}

});
</code>```

You can observe that when you select a option in first select list then the options on second select list are changed dynamically.

For more experiment and observation here is the link to working JSFIDDLE

Body:
Please i have a question. how could i create a second dropdown depend on select item from first dropdown.

<fieldset ng-controller="FirstCtrl">
    <select
        ng-options="p.id for p in jobs"
        ng-model="selectedPerson"></select>
    {{ selectedPerson }}
</fieldset>

Body:
I have a interesting example to show you how the select list can depend on another. In fact, the select options of a list can be made dependent on the value of the first select list.

HTML

Controller

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.jobs1 = [
    {
        "id": 600,
        "sector": "Controlling",
        "cost": 4700
    },
    {
        "id": 600,
        "sector": "finance",
        "cost": 4700

    },
    {
        "id": 40,
        "sector": "IT",
        "cost": 7600

    },
    {
        "id": 50,
        "sector": "Controlling",
        "cost": 4600

    },
    {
        "id": 50,
        "sector": "IT",
        "cost": 4600

    },{
        "id": 41,
        "sector": "Controlling",
        "cost": 1100

    },
    {
        "id": 41,
        "sector": "IT",
        "cost": 1100

    }
];
$scope.jobs2 = [];

$scope.firstSelectChange = function(){
  $scope.jobs2 = [];
  $scope.selectedPerson2 = '';
 for(var i=0; i<$scope.jobs1.length; i++){
       if($scope.jobs1[i].id === $scope.selectedPerson1.id){
           $scope.jobs2.push($scope.jobs1[i]);
       }
    }
}

});

You can observe that when you select a option in first select list then the options on second select list are changed dynamically.

For more experiment and observation here is the link to working JSFIDDLE


问:
How to inject a Spring bean into JpaRepositoryFactoryBean
I have my own custom Spring Data common repository in order to provide common behavior to all Spring Data repositories. And all I need is to modify EntityManager when repository is being created. But I can't inject a Spring bean into JpaRepositoryFactoryBean due to the bean is created via new operator. </p>

```<code>public class BasicJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {

 @Autowired
 private SomeService service; // - it does not work

  @Override
  protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
    // do some logic here
    service.doSmth();
    return new CommonRepositoryFactory<>(em);
  }

  private static class CommonRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

    private final EntityManager em;

    public CommonRepositoryFactory(EntityManager em) {
      super(em);
      this.em = em;
    }

    @SuppressWarnings("unchecked")
    protected Object getTargetRepository(RepositoryMetadata metadata) {
      JpaEntityInformation entityInformation = getEntityInformation(metadata.getDomainType());
      return new CommonRepositoryImpl(entityInformation, em);
    }

    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
      return CommonRepositoryImpl.class;
    }
  }

}
</code>```

答: Implement a setter in that class or one that extends from it.</p>

Body:
I have my own custom Spring Data common repository in order to provide common behavior to all Spring Data repositories. And all I need is to modify EntityManager when repository is being created. But I can't inject a Spring bean into JpaRepositoryFactoryBean due to the bean is created via new operator.

public class BasicJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {

 @Autowired
 private SomeService service; // - it does not work

  @Override
  protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
    // do some logic here
    service.doSmth();
    return new CommonRepositoryFactory<>(em);
  }

  private static class CommonRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

    private final EntityManager em;

    public CommonRepositoryFactory(EntityManager em) {
      super(em);
      this.em = em;
    }

    @SuppressWarnings("unchecked")
    protected Object getTargetRepository(RepositoryMetadata metadata) {
      JpaEntityInformation entityInformation = getEntityInformation(metadata.getDomainType());
      return new CommonRepositoryImpl(entityInformation, em);
    }

    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
      return CommonRepositoryImpl.class;
    }
  }

}


问:
Integrating angular cli project with groovy gradle app
I'm trying to integrate the seed project of angular-cli with my java app that is packaged by Gradle and deployed in tomcat server.

How to integrate the angular build with Gradle build? And where is best to put the compiled scss files for my project.  I'm thinking of having them under assets and the compiled css files will be generated under assests as well.

Here is my folders structure:

```<code>myApp
├── gradle
├── src
│   └── main
│       ├── groovy
│       ├── resources
│       ├── webapp
│       └── ngapp
             ├── angular-cli.json
             ├── e2e
             ├── karma.conf.js
             ├── node_modules
             ├── package.json
             ├── protractor.conf.js
             ├── tslint.json
             ├── tsconfig.json
             ├── WEB-INF
             ├── src
                 ├── app //app component and other features components here
                 ├── assets
                 ├── environments
                 ├── typings.d.ts
                 ├── index.html
                 ├── main.ts
                 ├── polyfills.ts
                 ├── styles.css
                 └── tsconfig.app.json
</code>```

.angular-cli.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "ngapp"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "../webapp/ng",
      "assets": [
        "assets"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "tsconfig": "tsconfig.json",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/main/ngapp/tsconfig.json"
    }
  ],
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</code>```

tsconfig.json:

```<code>  {
      "compileOnSave": false,
      "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "baseUrl": "src/main/ngapp",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
          "node_modules/@types"
        ],
        "lib": [
          "es2016",
          "dom"
        ]
      }
}
</code>```

答:
Perhaps issue with

```<code> "lint": [{
  "project": "src/main/ngapp/tsconfig.json"
}]
</code>```

Usually it looks like that

```<code>"lint": [{
  "project": "src/tsconfig.json"
}]
</code>```

Body:
I'm trying to integrate the seed project of angular-cli with my java app that is packaged by Gradle and deployed in tomcat server.

How to integrate the angular build with Gradle build? And where is best to put the compiled scss files for my project.  I'm thinking of having them under assets and the compiled css files will be generated under assests as well.

Here is my folders structure:

myApp
├── gradle
├── src
│   └── main
│       ├── groovy
│       ├── resources
│       ├── webapp
│       └── ngapp
             ├── angular-cli.json
             ├── e2e
             ├── karma.conf.js
             ├── node_modules
             ├── package.json
             ├── protractor.conf.js
             ├── tslint.json
             ├── tsconfig.json
             ├── WEB-INF
             ├── src
                 ├── app //app component and other features components here
                 ├── assets
                 ├── environments
                 ├── typings.d.ts
                 ├── index.html
                 ├── main.ts
                 ├── polyfills.ts
                 ├── styles.css
                 └── tsconfig.app.json

.angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "ngapp"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "../webapp/ng",
      "assets": [
        "assets"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "tsconfig": "tsconfig.json",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/main/ngapp/tsconfig.json"
    }
  ],
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

tsconfig.json:

  {
      "compileOnSave": false,
      "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "baseUrl": "src/main/ngapp",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
          "node_modules/@types"
        ],
        "lib": [
          "es2016",
          "dom"
        ]
      }
}

Body:
Perhaps issue with

 "lint": [{
  "project": "src/main/ngapp/tsconfig.json"
}]

Usually it looks like that

"lint": [{
  "project": "src/tsconfig.json"
}]


问:
MySQL - Get values by Column
I have a sample table like

I want to get records like

```<code>Array(
  'col-1' => ['v1','v4','v7'],
  'col-2' => ['v2','v5','v8'],
  'col-3' => ['v3','v6','v9'],
)
</code>```

Is there a way to get it in MySQL

答:
Hi I think you need to change your DB structure

you can create two tables e.g

```<code>// Product Table i wish
id | name
---------
1  | test
2  | Examplace product
</code>```

then you can create the other table

product_colum_table

```<code>id | product_id | product_colum_or_data
1  | 1          |  Something
2  | 1          | some other data
3  | 2          | product name
4  | 2          | test
</code>```

then you can have access the using join.

I hope this helps

Title: MySQL - Get values by Column

Body:
I have a sample table like

I want to get records like

Array(
  'col-1' => ['v1','v4','v7'],
  'col-2' => ['v2','v5','v8'],
  'col-3' => ['v3','v6','v9'],
)

Is there a way to get it in MySQL

Body:
Hi I think you need to change your DB structure

you can create two tables e.g

// Product Table i wish
id | name
---------
1  | test
2  | Examplace product

then you can create the other table

product_colum_table

id | product_id | product_colum_or_data
1  | 1          |  Something
2  | 1          | some other data
3  | 2          | product name
4  | 2          | test

then you can have access the using join.

I hope this helps


问:
What does Error: missing 'probdata' mean in OpenMDAO
I'm just get stared at OpenMDAO and multidisciplinary optimization, I'm going to use OpenMDAO to build a CO(Collaborative Optimization) framwork on the classical Sellar problem.

However, when I ran this code I always get the following error:

TypeError: _init_sys_data() missing 1 required positional argument: 'probdata'

which occurs when running the problem.setup()

I've no idear what does this error mean since there's no difference of this line of code to the OpenMDAO standard tut.

Could somebody give me some advices?

Here's the code, some hints from this question

Sellar problem formed as CO:

```<code>    SystemOpt
    min     x1**2  + z2 + y1 + eye(-y2)
    w.r.t   z1, z2, x1, y1, y2
    s.t     (z1 - z1_d1)**2 + (x1 - x1_d1)**2 + (z2 - z2_d1)**2 + 0.2 * (y2 - y2_d1) <= epsilon
            (y2 - y2_d2)**2 + (y1 - y1_d2)**2 + (z1 - z1_d2)**2 + (z2 - z2_d2)**2 <= epsilon
            -10 <= z1 <= 10
            0 <= z2 <= 10
            0 <= x1 <= 10

    SobOpt1
        min     (z1 - z1_d1)**2 + (x1 - x1_d1)**2 + (z2 - z2_d1)**2 + 0.2 * (y2 - y2_d1)
        w.r.t   z1_d1, x1_d1, z2_d1, y2_d1
        s.t     z1_d1**2 + x1_d1 + z2_d1 - 0.2 * y2_d1 >= 3.16
                0 <= x1_d1 <=10
                -10 <= z1_d1 <= 10
                0 <= z2_d1 <= 10

    SubOpt2
        min     (y2 - y2_d2)**2 + (y1 - y1_d2)**2 + (z1 - z1_d2)**2 + (z2 - z2_d2)**2
        w.r.t   y2_d2, y1_d2, z1_d2, z2_d2
        s.t     y1_d2 ** 0.5 + z1_d2 + z2_d2 <= 24
                -10 <= z1_d2 <= 10
                0 <= z2_d2 <= 10
</code>```

==================================================

```<code>from __future__ import print_function
import numpy as np
from openmdao.api import ExecComp, IndepVarComp, Group
from openmdao.api import Component, ScipyOptimizer

class Discipline1(Component):
    """Component containing Discipline 1."""

    def __init__(self):
        super(Discipline1, self).__init__()

        self.add_param('z1_d1', val=0.0)
        self.add_param('x1_d1', val=0.)
        self.add_param('z2_d1', val=1.0)
        self.add_param('y2_d1', val=1.0)
        self.add_param('z1', val=1.0)
        self.add_param('x1', val=1.0)
        self.add_param('z2', val=1.0)
        self.add_param('y2', val=1.0)
        self.add_param('obj1', val=1.0)

    def solve_nonlinear(self, params, unknowns, resids):
        """
        Evaluates the equation
        y1 = z1**2 + z2 + x1 - 0.2*y2
        """

        z1_d1 = params['z']
        z2_d1 = params['z2_d1']
        x1_d1 = params['x1_d1']
        y2_d1 = params['y2_d1']
        z1 = params['z1']
        x1 = params['x2']
        z2 = params['z2']
        y2 = params['y2']

        unknowns['obj1'] = (z1 - z1_d1) ** 2 + (x1 - x1_d1) ** 2 + (z2 - z2_d1) ** 2 + 0.2 * (y2 - y2_d1)

class SubOpt1(Component):
    def __init__(self):
        """
        Sobopt of discipline1
        """
        super(SubOpt1, self).__init__()
        self.add_param('S1px', IndepVarComp('x1_d1', 1.0), promotes=['x1_d1'])
        self.add_param('S1pz', IndepVarComp('z1_d1', 5.0), promotes=['z1_d1'])
        self.add_param('S1pz', IndepVarComp('z2_d1', 5.0), promotes=['z2_d1'])
        self.add_param('S1py2', IndepVarComp('y2_d1', 2.0), promotes=['y2_d1'])
        # Add Problem
        from openmdao.api import Problem
        self.problem = prob = Problem()
        group = prob.root = Group()
        # add Component:
        group.add('Discipline', Discipline1,
                  promotes=['x1', 'z1', 'x2', 'y2', 'x1_d1', 'z1_d1', 'x2_d2', 'y2_d2', 'obj1'])
        # Add Cons
        group.add('con', ExecComp('con = z1_d1**2 + x1_d1 + z2_d1 - 0.2 * y2_d1'),
                  promotes=['con', 'z1_d1', 'x1_d1', 'z2_d1', 'y2_d1'])
        # Add Solver
        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1.0e-8

        # Add desvar
        prob.driver.add_desvar('x1_d1', lower=0.0, upper=10.0)
        prob.driver.add_desvar('z1_d1', lower=-10.0, upper=10.0)
        prob.driver.add_desvar('z2_d1', lower=0.0, upper=10.0)
        prob.driver.add_desvar('y2_d1')

        # Add obj and cons
        prob.driver.add_objective('obj1')
        prob.driver.add_constraint('con', lower=3.16)

        prob.setup()

    def solve_nonlinear(self, params=None, unknowns=None, resids=None, metadata=None):
        self.problem.run()
        unknowns['obj1'] = self.problem['obj1']

class Discipline2(Component):
    """Component containing Discipline 1."""

    def __init__(self):
        super(Discipline2, self).__init__()

        self.add_param('z1_d2', val=0.0)
        self.add_param('z2_d2', val=0.)
        self.add_param('y1_d2', val=1.0)
        self.add_param('y2_d2', val=1.0)
        self.add_param('z1', val=1.0)
        self.add_param('y1', val=1.0)
        self.add_param('z2', val=1.0)
        self.add_param('y2', val=1.0)
        # add objs
        self.add_param('obj2', val=1.0)

    def solve_nonlinear(self, params, unknowns, resids):
        """
        Evaluates the equation
        y1 = z1**2 + z2 + x1 - 0.2*y2
        """

        z1_d2 = params['z1_d2']
        z2_d2 = params['z2_d2']
        y1_d2 = params['y1_d2']
        y2_d2 = params['y2_d2']
        z1 = params['z1']
        y1 = params['y2']
        z2 = params['z2']
        y2 = params['y2']

        unknowns['obj2'] = (y2 - y2_d2) ** 2 + (y1 - y1_d2) ** 2 + (z1 - z1_d2) ** 2 + (z2 - z2_d2) ** 2

class SubOpt2(Component):
    def __init__(self):
        """
        Subopt of discipline2
        """
        super(SubOpt2, self).__init__()
        # Add Desvar
        self.add_param('S2pz', IndepVarComp('z1_d2', 5.0), promotes=['z1_d2'])
        self.add_param('S2pz', IndepVarComp('z2_d2', 5.0), promotes=['z2_d2'])
        self.add_param('S2py1', IndepVarComp('y1_d2', 2.0), promotes=['y1_d2'])
        self.add_param('S2py2', IndepVarComp('y2_d2', 5.0), promotes=['y2_d2'])

        # Add problem
        from openmdao.api import Problem
        self.problem = prob = Problem()
        group = prob.root = Group()
        # Add Component:
        group.add('Discipline2', Discipline2,
                  promotes=['obj2', 'y2', 'y2_d2', 'y1', 'y1_d2', 'z1', 'z1_d2', 'z2', 'z2_d2'])
        # Add cons:
        group.add('con2', ExecComp('con = y1_d2 ** 0.5 + z1_d2 + z2_d2'),
                  promotes=['con', 'y1_d2', 'z1_d2', 'z2_d2'])
        # Add solver:
        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1.0e-8

        # Add desvar
        prob.driver.add_desvar('y1_d2')
        prob.driver.add_desvar('y2_d2')
        prob.driver.add_desvar('z1_d2', lower=-10, upper=10)
        prob.driver.add_desvar('z2_d2', lower=0.0, upper=10.0)

        # Add ovj and cons
        prob.driver.add_objective('obj2')
        prob.driver.add_constraint('con2', upper=24)

        prob.setup()

    def solve_nonlinear(self, params=None, unknowns=None, resids=None, metadata=None):
        self.problem.run()

class System_Opt(Group):
    """
    Group containing the Sellar MDA. This version uses the disciplines
    with derivatives."""

    def __init__(self):
        super(System_Opt, self).__init__()

        self.add('px', IndepVarComp('x1', 1.0), promotes=['x1'])
        self.add('pz1', IndepVarComp('z1', 5.0), promotes=['z1'])
        self.add('pz2', IndepVarComp('z2', 5.0), promotes=['z2'])
        self.add('py1', IndepVarComp('y1', 2.0), promotes=['y1'])
        self.add('py2', IndepVarComp('y2', 2.0), promotes=['y2'])

        self.add('obj_cmp', ExecComp('obj = x1**2  + z2 + y1 + eye(-y2)',
                                     z2=0.0, x1=0.0, y1=0.0, y2=0.0),
                 promotes=['obj', 'z2', 'x1', 'y1', 'y2'])

        self.add('SubOpt1', SubOpt1, promotes=['z1_d1', 'x1_d1', 'z2_d1', 'y2_d1', 'x1', 'z1', 'x2', 'y2'])
        self.add('SubOpt2', SubOpt2, promotes=['y2_d2', 'y1_d2', 'z1_d2', 'z2_d2', 'y2', 'y1', 'z1', 'z2'])

        self.add('con_cmp1',
                 ExecComp('con1 = (z1 - z1_d1)**2 + (x1 - x1_d1)**2 + (z2 - z2_d1)**2 + 0.2 * (y2 - y2_d1)'),
                 promotes=['con1', 'z1', 'z1_d1', 'x1', 'x1_d1', 'z2', 'z2_d1', 'y2', 'y2_d1'])
        self.add('con_cmp2',
                 ExecComp('con2 = (y2 - y2_d2)**2 + (y1 - y1_d2)**2 + (z1 - z1_d2)**2 + (z2 - z2_d2)**2'),
                 promotes=['con2', 'y2', 'y2_d2', 'y1', 'y1_d2', 'z1', 'z1_d2', 'z2', 'z2_d2'])

if __name__ == '__main__':
    epsilon = 1e-5
    from openmdao.api import Problem, ScipyOptimizer

    # Add problem
    top = Problem()
    top.root = System_Opt()
    # Add solver
    top.driver = ScipyOptimizer()
    top.driver.options['optimizer'] = 'SLSQP'
    top.driver.options['tol'] = 1.0e-8

    # Add desvar
    top.driver.add_desvar('x1', lower=0.0, upper=10.0)
    top.driver.add_desvar('z1', lower=-10.0, upper=10.0)
    top.driver.add_desvar('z2', lower=0.0, upper=10.0)
    top.driver.add_desvar('y2')
    top.driver.add_desvar('y1')

    # Add obj and cons
    top.driver.add_objective('obj')
    top.driver.add_constraint('con1', upper=epsilon)
    top.driver.add_constraint('con2', upper=epsilon)

    top.setup()

    # add init params of desvar
    top['x1'] = 1.0
    top['z1'] = 1.0
    top['z2'] = 1.0
    top['y2'] = 1.0
    top['y1'] = 1.0
    top.run()
</code>```

答:
The problem you are having is related to the following lines:

self.add('SubOpt1', SubOpt1, promotes=['z1_d1', 'x1_d1', 'z2_d1', 'y2_d1', 'x1', 'z1', 'x2', 'y2'])
        self.add('SubOpt2', SubOpt2, promotes=['y2_d2', 'y1_d2', 'z1_d2', 'z2_d2', 'y2', 'y1', 'z1', 'z2'])

Note that here you passed the class into the add method, instead of an instance. You also did the same thing in SubOpt1 and SubOpt2

group.add('Discipline', Discipline1,
                  promotes=['x1', 'z1', 'x2', 'y2', 'x1_d1', 'z1_d1', 'x2_d2', 'y2_d2', 'obj1'])
        # Add Cons

Instead, you need to pass instances into them as follows:

self.add('SubOpt1', SubOpt1(), promotes=['z1_d1', 'x1_d1', 'z2_d1', 'y2_d1', 'x1', 'z1', 'x2', 'y2'])
        self.add('SubOpt2', SubOpt2(), promotes=['y2_d2', 'y1_d2', 'z1_d2', 'z2_d2', 'y2', 'y1', 'z1', 'z2'])

There are a few other minor typos in your script related to variable names, but the class vs instance issue is your main problem

Body:
I'm just get stared at OpenMDAO and multidisciplinary optimization, I'm going to use OpenMDAO to build a CO(Collaborative Optimization) framwork on the classical Sellar problem.

However, when I ran this code I always get the following error:

TypeError: _init_sys_data() missing 1 required positional argument: 'probdata'

which occurs when running the problem.setup()

I've no idear what does this error mean since there's no difference of this line of code to the OpenMDAO standard tut.

Could somebody give me some advices?

Here's the code, some hints from this question

Sellar problem formed as CO:

    SystemOpt
    min     x1**2  + z2 + y1 + eye(-y2)
    w.r.t   z1, z2, x1, y1, y2
    s.t     (z1 - z1_d1)**2 + (x1 - x1_d1)**2 + (z2 - z2_d1)**2 + 0.2 * (y2 - y2_d1) <= epsilon
            (y2 - y2_d2)**2 + (y1 - y1_d2)**2 + (z1 - z1_d2)**2 + (z2 - z2_d2)**2 <= epsilon
            -10 <= z1 <= 10
            0 <= z2 <= 10
            0 <= x1 <= 10

    SobOpt1
        min     (z1 - z1_d1)**2 + (x1 - x1_d1)**2 + (z2 - z2_d1)**2 + 0.2 * (y2 - y2_d1)
        w.r.t   z1_d1, x1_d1, z2_d1, y2_d1
        s.t     z1_d1**2 + x1_d1 + z2_d1 - 0.2 * y2_d1 >= 3.16
                0 <= x1_d1 <=10
                -10 <= z1_d1 <= 10
                0 <= z2_d1 <= 10

    SubOpt2
        min     (y2 - y2_d2)**2 + (y1 - y1_d2)**2 + (z1 - z1_d2)**2 + (z2 - z2_d2)**2
        w.r.t   y2_d2, y1_d2, z1_d2, z2_d2
        s.t     y1_d2 ** 0.5 + z1_d2 + z2_d2 <= 24
                -10 <= z1_d2 <= 10
                0 <= z2_d2 <= 10

==================================================

from __future__ import print_function
import numpy as np
from openmdao.api import ExecComp, IndepVarComp, Group
from openmdao.api import Component, ScipyOptimizer

class Discipline1(Component):
    """Component containing Discipline 1."""

    def __init__(self):
        super(Discipline1, self).__init__()

        self.add_param('z1_d1', val=0.0)
        self.add_param('x1_d1', val=0.)
        self.add_param('z2_d1', val=1.0)
        self.add_param('y2_d1', val=1.0)
        self.add_param('z1', val=1.0)
        self.add_param('x1', val=1.0)
        self.add_param('z2', val=1.0)
        self.add_param('y2', val=1.0)
        self.add_param('obj1', val=1.0)

    def solve_nonlinear(self, params, unknowns, resids):
        """
        Evaluates the equation
        y1 = z1**2 + z2 + x1 - 0.2*y2
        """

        z1_d1 = params['z']
        z2_d1 = params['z2_d1']
        x1_d1 = params['x1_d1']
        y2_d1 = params['y2_d1']
        z1 = params['z1']
        x1 = params['x2']
        z2 = params['z2']
        y2 = params['y2']

        unknowns['obj1'] = (z1 - z1_d1) ** 2 + (x1 - x1_d1) ** 2 + (z2 - z2_d1) ** 2 + 0.2 * (y2 - y2_d1)

class SubOpt1(Component):
    def __init__(self):
        """
        Sobopt of discipline1
        """
        super(SubOpt1, self).__init__()
        self.add_param('S1px', IndepVarComp('x1_d1', 1.0), promotes=['x1_d1'])
        self.add_param('S1pz', IndepVarComp('z1_d1', 5.0), promotes=['z1_d1'])
        self.add_param('S1pz', IndepVarComp('z2_d1', 5.0), promotes=['z2_d1'])
        self.add_param('S1py2', IndepVarComp('y2_d1', 2.0), promotes=['y2_d1'])
        # Add Problem
        from openmdao.api import Problem
        self.problem = prob = Problem()
        group = prob.root = Group()
        # add Component:
        group.add('Discipline', Discipline1,
                  promotes=['x1', 'z1', 'x2', 'y2', 'x1_d1', 'z1_d1', 'x2_d2', 'y2_d2', 'obj1'])
        # Add Cons
        group.add('con', ExecComp('con = z1_d1**2 + x1_d1 + z2_d1 - 0.2 * y2_d1'),
                  promotes=['con', 'z1_d1', 'x1_d1', 'z2_d1', 'y2_d1'])
        # Add Solver
        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1.0e-8

        # Add desvar
        prob.driver.add_desvar('x1_d1', lower=0.0, upper=10.0)
        prob.driver.add_desvar('z1_d1', lower=-10.0, upper=10.0)
        prob.driver.add_desvar('z2_d1', lower=0.0, upper=10.0)
        prob.driver.add_desvar('y2_d1')

        # Add obj and cons
        prob.driver.add_objective('obj1')
        prob.driver.add_constraint('con', lower=3.16)

        prob.setup()

    def solve_nonlinear(self, params=None, unknowns=None, resids=None, metadata=None):
        self.problem.run()
        unknowns['obj1'] = self.problem['obj1']

class Discipline2(Component):
    """Component containing Discipline 1."""

    def __init__(self):
        super(Discipline2, self).__init__()

        self.add_param('z1_d2', val=0.0)
        self.add_param('z2_d2', val=0.)
        self.add_param('y1_d2', val=1.0)
        self.add_param('y2_d2', val=1.0)
        self.add_param('z1', val=1.0)
        self.add_param('y1', val=1.0)
        self.add_param('z2', val=1.0)
        self.add_param('y2', val=1.0)
        # add objs
        self.add_param('obj2', val=1.0)

    def solve_nonlinear(self, params, unknowns, resids):
        """
        Evaluates the equation
        y1 = z1**2 + z2 + x1 - 0.2*y2
        """

        z1_d2 = params['z1_d2']
        z2_d2 = params['z2_d2']
        y1_d2 = params['y1_d2']
        y2_d2 = params['y2_d2']
        z1 = params['z1']
        y1 = params['y2']
        z2 = params['z2']
        y2 = params['y2']

        unknowns['obj2'] = (y2 - y2_d2) ** 2 + (y1 - y1_d2) ** 2 + (z1 - z1_d2) ** 2 + (z2 - z2_d2) ** 2

class SubOpt2(Component):
    def __init__(self):
        """
        Subopt of discipline2
        """
        super(SubOpt2, self).__init__()
        # Add Desvar
        self.add_param('S2pz', IndepVarComp('z1_d2', 5.0), promotes=['z1_d2'])
        self.add_param('S2pz', IndepVarComp('z2_d2', 5.0), promotes=['z2_d2'])
        self.add_param('S2py1', IndepVarComp('y1_d2', 2.0), promotes=['y1_d2'])
        self.add_param('S2py2', IndepVarComp('y2_d2', 5.0), promotes=['y2_d2'])

        # Add problem
        from openmdao.api import Problem
        self.problem = prob = Problem()
        group = prob.root = Group()
        # Add Component:
        group.add('Discipline2', Discipline2,
                  promotes=['obj2', 'y2', 'y2_d2', 'y1', 'y1_d2', 'z1', 'z1_d2', 'z2', 'z2_d2'])
        # Add cons:
        group.add('con2', ExecComp('con = y1_d2 ** 0.5 + z1_d2 + z2_d2'),
                  promotes=['con', 'y1_d2', 'z1_d2', 'z2_d2'])
        # Add solver:
        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1.0e-8

        # Add desvar
        prob.driver.add_desvar('y1_d2')
        prob.driver.add_desvar('y2_d2')
        prob.driver.add_desvar('z1_d2', lower=-10, upper=10)
        prob.driver.add_desvar('z2_d2', lower=0.0, upper=10.0)

        # Add ovj and cons
        prob.driver.add_objective('obj2')
        prob.driver.add_constraint('con2', upper=24)

        prob.setup()

    def solve_nonlinear(self, params=None, unknowns=None, resids=None, metadata=None):
        self.problem.run()

class System_Opt(Group):
    """
    Group containing the Sellar MDA. This version uses the disciplines
    with derivatives."""

    def __init__(self):
        super(System_Opt, self).__init__()

        self.add('px', IndepVarComp('x1', 1.0), promotes=['x1'])
        self.add('pz1', IndepVarComp('z1', 5.0), promotes=['z1'])
        self.add('pz2', IndepVarComp('z2', 5.0), promotes=['z2'])
        self.add('py1', IndepVarComp('y1', 2.0), promotes=['y1'])
        self.add('py2', IndepVarComp('y2', 2.0), promotes=['y2'])

        self.add('obj_cmp', ExecComp('obj = x1**2  + z2 + y1 + eye(-y2)',
                                     z2=0.0, x1=0.0, y1=0.0, y2=0.0),
                 promotes=['obj', 'z2', 'x1', 'y1', 'y2'])

        self.add('SubOpt1', SubOpt1, promotes=['z1_d1', 'x1_d1', 'z2_d1', 'y2_d1', 'x1', 'z1', 'x2', 'y2'])
        self.add('SubOpt2', SubOpt2, promotes=['y2_d2', 'y1_d2', 'z1_d2', 'z2_d2', 'y2', 'y1', 'z1', 'z2'])

        self.add('con_cmp1',
                 ExecComp('con1 = (z1 - z1_d1)**2 + (x1 - x1_d1)**2 + (z2 - z2_d1)**2 + 0.2 * (y2 - y2_d1)'),
                 promotes=['con1', 'z1', 'z1_d1', 'x1', 'x1_d1', 'z2', 'z2_d1', 'y2', 'y2_d1'])
        self.add('con_cmp2',
                 ExecComp('con2 = (y2 - y2_d2)**2 + (y1 - y1_d2)**2 + (z1 - z1_d2)**2 + (z2 - z2_d2)**2'),
                 promotes=['con2', 'y2', 'y2_d2', 'y1', 'y1_d2', 'z1', 'z1_d2', 'z2', 'z2_d2'])

if __name__ == '__main__':
    epsilon = 1e-5
    from openmdao.api import Problem, ScipyOptimizer

    # Add problem
    top = Problem()
    top.root = System_Opt()
    # Add solver
    top.driver = ScipyOptimizer()
    top.driver.options['optimizer'] = 'SLSQP'
    top.driver.options['tol'] = 1.0e-8

    # Add desvar
    top.driver.add_desvar('x1', lower=0.0, upper=10.0)
    top.driver.add_desvar('z1', lower=-10.0, upper=10.0)
    top.driver.add_desvar('z2', lower=0.0, upper=10.0)
    top.driver.add_desvar('y2')
    top.driver.add_desvar('y1')

    # Add obj and cons
    top.driver.add_objective('obj')
    top.driver.add_constraint('con1', upper=epsilon)
    top.driver.add_constraint('con2', upper=epsilon)

    top.setup()

    # add init params of desvar
    top['x1'] = 1.0
    top['z1'] = 1.0
    top['z2'] = 1.0
    top['y2'] = 1.0
    top['y1'] = 1.0
    top.run()


问:
Remotely access info path field in SharePoint 2007
I have sharepoint document library which contains infopath files, however I want to write a c# console program to read a field of infopath file, from a client machine, via sharepoint web service.

how do i do that? I am not allowed to deploy any code to sharepoint server.

答:
Couple steps involved.

1. Get the infopath file from the Sharepoint server using webservices. You most likely will use GetListItems to find the name/URL of the file and then you can use a webclient class to stream the file.

2. Once you have the file locally (in memory) you can read any infopath using the standard XMLReader class methods.

Shouldn't be terribly complicated but does involve a few different technologies (web services, web client, XML).


问:
How to use custom domain on Heroku with Parse Server?
A Parse Server is hosted on Heroku at myapp.herokuapps.com.

The Heroku app has a custom domain example.com. The domain has the CNAME record myapp.herokuapps.com.

Connecting the Parse iOS SDK works for the endpoints:

```<code>https://myapp.herokuapps.com/parse
http://myapp.herokuapps.com/parse
http://example.com/parse
</code>```

But it does not work for

```<code>https://example.com/parse
</code>```

The Xcode console shows the error:

```<code>An SSL error has occurred and a secure connection to the server cannot be made. (Code: 100, Version: ...)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9838)
</code>```

Why isn't it working?

答:
The solution was to add a TSL certificate to the Heroku app. If you have a paid dyno the certificate is available at no extra cost.

All applications with paid dynos include ACM for free.

Open Heroku app in Heroku dashboard

Open Settings tab

In section Domains and certificates click Configure SSL and choose Automatically configure using Automated Certificate Management.

Click Add domain to add the domain from which the request should be forwarded, e.g. api.example.com.

On your domain registrar's website set the CNAME for api.example.com to the domain in the Heroku app settings, e.g. api.example.com.herokudns.com

Wait until the status of the domain in the Heroku dashboard is Done

Works.

Body:
A Parse Server is hosted on Heroku at myapp.herokuapps.com.

The Heroku app has a custom domain example.com. The domain has the CNAME record myapp.herokuapps.com.

Connecting the Parse iOS SDK works for the endpoints:

https://myapp.herokuapps.com/parse
http://myapp.herokuapps.com/parse
http://example.com/parse

But it does not work for

https://example.com/parse

The Xcode console shows the error:

An SSL error has occurred and a secure connection to the server cannot be made. (Code: 100, Version: ...)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9838)

Why isn't it working?


问:
Count non-letters in string in Javascript
How to count non letter characters in given string in Javascript, chars like numbers and white spaces, and dashes, all except letters? Thanks.</p>

答:
You can replace all your normal chars with empty and then you can count on the special characters,Numbers.

let string = "J@s12!r"
string = string.replace(/[a-zA-Z]/g,'').length;
console.log(string)```


问:
sql 2014 problems storing decimal
i have a stored procedure and i initially create a temp table.  i populate the first 3 columns and then i want to get the percentage when jobs are voided.  but i can't seem to get a good value.  if Void=10 and Total_Jobs=59 then 10/59 = 0.16 but it populates table with zero.  what am i doing wrong?</p>

```<code>Create table #tbl_WeeklyJobsRpt
(
Region_Code varchar(25),
Void int DEFAULT 0,
Total_Jobs int DEFAULT 0,
Void_Pctg decimal(10,2) DEFAULT 0
)

-- Void_Pctg
Update #tbl_WeeklyJobsRpt
  set Void_Pctg = ((Void)/Total_Jobs)
Where Void <> 0
</code>```

答:
Both values are int so the result is int too and the value is being rounded down.
Try 1.0*Void/Total_Jobs - 1.0 causes implicit cast.

Title: sql 2014 problems storing decimal

Body:
i have a stored procedure and i initially create a temp table.  i populate the first 3 columns and then i want to get the percentage when jobs are voided.  but i can't seem to get a good value.  if Void=10 and Total_Jobs=59 then 10/59 = 0.16 but it populates table with zero.  what am i doing wrong?

Create table #tbl_WeeklyJobsRpt
(
Region_Code varchar(25),
Void int DEFAULT 0,
Total_Jobs int DEFAULT 0,
Void_Pctg decimal(10,2) DEFAULT 0
)

-- Void_Pctg
Update #tbl_WeeklyJobsRpt
  set Void_Pctg = ((Void)/Total_Jobs)
Where Void <> 0


问:
Struggling with a Sql Join Statement. Fetching values from DIfferent Tables
I have three mysql database tables namely; scheduled_messages, subscribed_services, and subscription_services_msisdn.

subscribed_services has columns username and password. The id of this table = Primary Key and a foreign key to the other two tables.

scheduled_messages table has columns message, scheduled_at and subscribed_services_id which is a foreign key of table subscribed_services.

subscription_services_msisdn table has phone_number and subscribed_services_id which is a foreign key of table subscribed_services.

I need a sql statement that can get message FROM scheduled_messages WHERE scheduled_at = CURDATE() and

phone_number FROM subscription_services_msisdn WHERE subscribed_services_id = "SELECT subscribed_services_id FROM  scheduled_messages WHERE scheduled_at = CURDATE()"

and finally

username, password FROM subscribed_services WHERE id = "SELECT subscribed_services_id FROM  scheduled_messages WHERE scheduled_at = CURDATE()"

I came up with this join statement but does not work. I get 0 results even when there are on the tables.

```<code>SELECT message, phone_number, username, password from scheduled_messages
inner join
subscribed_services on scheduled_messages.id = subscribed_services.id
inner join
subscription_services_msisdn on scheduled_messages.subscribed_services_id =
subscription_services_msisdn.subscribed_services_id where scheduled_messages.scheduled_at = CURDATE();
</code>```

Sample data

```<code>from subscribed_services;
+----+---------+-----------+--------+--------------+-----------+---------------------+
| id | keyword | shortcode | org_id | username     | password  | created_at          |
+----+---------+-----------+--------+--------------+-----------+---------------------+
|  1 | Lawyer  | 21348     | 4      | Lawyer101API | qweasd123 | 2017-07-04 11:34:06 |

from scheduled_messages;
+----+---------------------------+------------------------+---------------------+---------------------+
| id | message                   | subscribed_services_id | scheduled_at        | created_at          |
+----+---------------------------+------------------------+---------------------+---------------------+
|  1 |  He also saw a poor widow |                      1 | 2017-07-04 11:32:52 | 2017-07-03 18:09:25 |
+----+---------------------------+------------------------+---------------------+---------------------+

from subscription_services_msisdn;
+----+--------------+------------------------+---------------------+---------------------+
| id | phone_number | subscribed_services_id | created_at          | updated_at          |
+----+--------------+------------------------+---------------------+---------------------+
|  1 | 224718488444 |                      1 | 2017-07-03 17:57:33 | 2017-07-03 17:57:33 |
|  2 | 224717746565 |                      1 | 2017-07-03 17:58:41 | 2017-07-03 17:58:41 |
|  3 | 224718036864 |                      1 | 2017-07-04 11:32:52 | 2017-07-04 11:32:52 |
</code>```

How can I get username, password, phone_number and message for the message scheduled at  for the current date?

Anyone help? Thank you.

答:
The way I see, you have got your join condition wrong based on the schema description provided. Can you try this and let me know if you get proper results ?</p>

```<code>SELECT
b.message, c.phone_number, a.username, a.password
from
subscribed_services a
inner join
scheduled_messages b on a.id = b.subscribed_services_id
inner join
subscription_services_msisdn c on a.id = c.subscribed_services_id
where DATE(b.scheduled_at) = CURDATE();
</code>```

Body:
I have three mysql database tables namely; scheduled_messages, subscribed_services, and subscription_services_msisdn.

subscribed_services has columns username and password. The id of this table = Primary Key and a foreign key to the other two tables.

scheduled_messages table has columns message, scheduled_at and subscribed_services_id which is a foreign key of table subscribed_services.

subscription_services_msisdn table has phone_number and subscribed_services_id which is a foreign key of table subscribed_services.

I need a sql statement that can get message FROM scheduled_messages WHERE scheduled_at = CURDATE() and

phone_number FROM subscription_services_msisdn WHERE subscribed_services_id = "SELECT subscribed_services_id FROM  scheduled_messages WHERE scheduled_at = CURDATE()"

and finally

username, password FROM subscribed_services WHERE id = "SELECT subscribed_services_id FROM  scheduled_messages WHERE scheduled_at = CURDATE()"

I came up with this join statement but does not work. I get 0 results even when there are on the tables.

SELECT message, phone_number, username, password from scheduled_messages
inner join
subscribed_services on scheduled_messages.id = subscribed_services.id
inner join
subscription_services_msisdn on scheduled_messages.subscribed_services_id =
subscription_services_msisdn.subscribed_services_id where scheduled_messages.scheduled_at = CURDATE();

Sample data

from subscribed_services;
+----+---------+-----------+--------+--------------+-----------+---------------------+
| id | keyword | shortcode | org_id | username     | password  | created_at          |
+----+---------+-----------+--------+--------------+-----------+---------------------+
|  1 | Lawyer  | 21348     | 4      | Lawyer101API | qweasd123 | 2017-07-04 11:34:06 |

from scheduled_messages;
+----+---------------------------+------------------------+---------------------+---------------------+
| id | message                   | subscribed_services_id | scheduled_at        | created_at          |
+----+---------------------------+------------------------+---------------------+---------------------+
|  1 |  He also saw a poor widow |                      1 | 2017-07-04 11:32:52 | 2017-07-03 18:09:25 |
+----+---------------------------+------------------------+---------------------+---------------------+

from subscription_services_msisdn;
+----+--------------+------------------------+---------------------+---------------------+
| id | phone_number | subscribed_services_id | created_at          | updated_at          |
+----+--------------+------------------------+---------------------+---------------------+
|  1 | 224718488444 |                      1 | 2017-07-03 17:57:33 | 2017-07-03 17:57:33 |
|  2 | 224717746565 |                      1 | 2017-07-03 17:58:41 | 2017-07-03 17:58:41 |
|  3 | 224718036864 |                      1 | 2017-07-04 11:32:52 | 2017-07-04 11:32:52 |

How can I get username, password, phone_number and message for the message scheduled at  for the current date?

Anyone help? Thank you.

Body:
The way I see, you have got your join condition wrong based on the schema description provided. Can you try this and let me know if you get proper results ?

SELECT
b.message, c.phone_number, a.username, a.password
from
subscribed_services a
inner join
scheduled_messages b on a.id = b.subscribed_services_id
inner join
subscription_services_msisdn c on a.id = c.subscribed_services_id
where DATE(b.scheduled_at) = CURDATE();


问:
Show Datum - Error message in console
I have the following div in HTML:

contents here

In JavaScript I have the following code to display the date:

```<code>var myDate= new Date();
document.getElementById('datum').innerHTML = myDate;
</code>```

I get the following error in my console:

TypeError: document.getElementById(...) is null script.js:5:5

I have already tried to put the code above the div tag, since JavaScript reads from top to bottom, but it is still the same issue.

Thank you in advance.

答:
Your code may not be getting executed after the DOM loads. Try the following:</p>

```<code>document.addEventListener('DOMContentLoaded', function() {
    var myDate= new Date();
    document.getElementById('datum').innerHTML = myDate;
});
</code>```

Title: Show Datum - Error message in console

Body:
I have the following div in HTML:

contents here

In JavaScript I have the following code to display the date:

var myDate= new Date();
document.getElementById('datum').innerHTML = myDate;

I get the following error in my console:

TypeError: document.getElementById(...) is null script.js:5:5

I have already tried to put the code above the div tag, since JavaScript reads from top to bottom, but it is still the same issue.

Thank you in advance.

Body:
Your code may not be getting executed after the DOM loads. Try the following:

document.addEventListener('DOMContentLoaded', function() {
    var myDate= new Date();
    document.getElementById('datum').innerHTML = myDate;
});