问:
Generic Class: UpdateView and DeleteView not saving data back to model
The UpdateView and DeleteView not saving data back to model

views.py

```<code>class ProjectList(ListView):
    model = Project
    template_name = 'mainapp/browse_app.html'
    context_object_name = 'projs'

class ProjectUpdate(UpdateView):
    model = Project
    fields = ['pname','desc','emailID']
    template_name = 'mainapp/project_form_edit.html'

class ProjectDelete(DeleteView):
    model = Project
    fields = ['id','pname','desc','emailID','updated_on']
    template_name = 'mainapp/index.html'
    success_url = reverse_lazy('mainapp/projs')

def form_display(request):
    data = Project.objects.all()
    return render(request,'mainapp/browse_page.html',{'data':data})
...
</code>```

browse_page.html: has an edit link and a delete button and it displays the project details of the project which is clicked

```<code>{% for i in data %}
    <center>
      <a href="#costumModal13{{ forloop.counter }}" role="button" class="btn btn-default" data-toggle="modal">{{ i }}</a>
    </center>
      <!-- Modal -->
      <div id="costumModal13{{ forloop.counter }}" class="modal" data-easein="bounceLeftIn"  tabindex="-1" role="dialog" aria-labelledby="costumModalLabel" aria-hidden="true">
        <a class="btn btn-info btn-lg fa fa-pencil-square-o" href="{% url 'project_edit' pk=i.id %}" aria-hidden="true">Edit</a>
            <form method="POST" action="{% url 'project_del' pk=i.id %}">
                {% csrf_token %}<input type="submit" value="Delete">
            </form>
            {{ i.pname }}
            {{ i.id }}
            {{ i.updated_on }}
      </div>
{% endfor %}
</code>```

urls.py

```<code>from django.contrib import admin
from django.urls import path, include, re_path
from mainapp import views
from mainapp.views import ProjectUpdate, ProjectDelete

app_name = 'mainapp'
urlpatterns = [
    path('browse/',views.form_display,name="browse_page"),
    re_path(r'^browse/(?P<pk>\d+)/$', ProjectUpdate.as_view(), name='project_edit'),
    re_path(r'^browse/delete/(?P<pk>\d+)/$', ProjectDelete.as_view(), name='project_del'),
]

</code>```

On submitting the edited form:
On clicking on delete button:

Can you help me resolve these 2 errors?

答:
1st image problem:

The url has index.html appended to the end. Your url is defined as /browse/7/

2nd image problem:

The namespace delimeter is : not /.

```<code>class ProjectDelete(DeleteView):
    ...
    success_url = reverse_lazy('mainapp:projs')
</code>```

Body:
The UpdateView and DeleteView not saving data back to model

views.py

class ProjectList(ListView):
    model = Project
    template_name = 'mainapp/browse_app.html'
    context_object_name = 'projs'

class ProjectUpdate(UpdateView):
    model = Project
    fields = ['pname','desc','emailID']
    template_name = 'mainapp/project_form_edit.html'

class ProjectDelete(DeleteView):
    model = Project
    fields = ['id','pname','desc','emailID','updated_on']
    template_name = 'mainapp/index.html'
    success_url = reverse_lazy('mainapp/projs')

def form_display(request):
    data = Project.objects.all()
    return render(request,'mainapp/browse_page.html',{'data':data})
...

browse_page.html: has an edit link and a delete button and it displays the project details of the project which is clicked

{% for i in data %}

      {{ i }}

        Edit
            <form method="POST" action="{% url 'project_del' pk=i.id %}">
                {% csrf_token %}<input type="submit" value="Delete">
            </form>
            {{ i.pname }}
            {{ i.id }}
            {{ i.updated_on }}

{% endfor %}

urls.py

from django.contrib import admin
from django.urls import path, include, re_path
from mainapp import views
from mainapp.views import ProjectUpdate, ProjectDelete

app_name = 'mainapp'
urlpatterns = [
    path('browse/',views.form_display,name="browse_page"),
    re_path(r'^browse/(?P<pk>\d+)/$', ProjectUpdate.as_view(), name='project_edit'),
    re_path(r'^browse/delete/(?P<pk>\d+)/$', ProjectDelete.as_view(), name='project_del'),
]

On submitting the edited form:
On clicking on delete button:

Can you help me resolve these 2 errors?

Body:
1st image problem:

The url has index.html appended to the end. Your url is defined as /browse/7/

2nd image problem:

The namespace delimeter is : not /.

class ProjectDelete(DeleteView):
    ...
    success_url = reverse_lazy('mainapp:projs')


来源: stackexchange

问:
Gatsby : image load then disapear on netlify. Works fine on my computer with gatsby develop and works fine on Zeit
I made a basic blog to test Gatsby and Netlify CMS.

I have a very strange problem.

The logo of the blog disappear when the page is fully loaded.
This happened only on Netlify.
With the "Gatsby Develop" command, there is no problems.

I tested to host the blog with Zeit, and the pictures doesn't disappear.

Netlify : https://wonderful-dubinsky-d2e0f3.netlify.com/
Zeit : https://recettes-ecru.now.sh/

Both website use the same Github repository.

答:
Finally i discovered that the problem was related to service worker.
I was using gatsby-plugin-offline. This plugin makes a Gatsby site work offline by using a service worker.

Browsers cache service workers for 24 hours by default, and don’t update them when you reload your page.

After unregistering my service worker, the problem was solved.

Useful reading here :
https://community.netlify.com/t/common-issue-understanding-unregistering-service-workers/145

How to uninstall a service worker :
https://love2dev.com/blog/how-to-uninstall-a-service-worker/

ContentLicense: CC BY-SA 4.0


问:
HHH10001002: Using Hibernate built-in connection pool (not for production use!)
While Deployment of my application i got this hibernate warning (twice):

```<code>WARN  org.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
</code>```

I don't want to use either these built-in connection pool from Hibernate, nor any other implementation like C3PO.

I tried a lot of things, but i was not able to use the connection pooling of my Weblogic Application Server.

My persistence.xml:

```<code><persistence...
<persistence-unit name="MY-PERSISTENCE-UNIT">
    <description>Hibernate JPA Configuration</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>some classes...</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.connection.datasource" value="jdbc/myDS"/>
        <property name="hibernate.hbm2ddl.auto" value="none"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect"/>
        <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="jndi.class" value="weblogic.jndi.WLInitialContextFactory"/>
    </properties>
</persistence-unit>
</persistence>
</code>```

weblogic.xml:

```<code>    ...
    <resource-description>
        <res-ref-name>jdbc/myDS</res-ref-name>
        <jndi-name>myDS</jndi-name>
    </resource-description>
    ...
</code>```

web.xml:

```<code>...
    <resource-ref>
       <res-ref-name>jdbc/myDS</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
    </resource-ref>
...
</code>```

PS:
I'm getting the Connection via the Entitymanager and i don't have any context.xml.

What can i do? Can anybody help?

答:
You shouldn't be setting the datasource using properties. There is and standard way to provide the datasource to the entity manager, using the <jta-data-source> element.

You only should need something like this:

```<code><persistence...
<persistence-unit name="MY-PERSISTENCE-UNIT">
    <description>Hibernate JPA Configuration</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <jta-data-source>jdbc/myDS</jta-data-source>

    <class>some classes...</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.hbm2ddl.auto" value="none"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect"/>
    </properties>
</persistence-unit>
</persistence>
</code>```

Body:
While Deployment of my application i got this hibernate warning (twice):

WARN  org.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)

I don't want to use either these built-in connection pool from Hibernate, nor any other implementation like C3PO.

I tried a lot of things, but i was not able to use the connection pooling of my Weblogic Application Server.

My persistence.xml:

<persistence...
<persistence-unit name="MY-PERSISTENCE-UNIT">
    <description>Hibernate JPA Configuration</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>some classes...</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.connection.datasource" value="jdbc/myDS"/>
        <property name="hibernate.hbm2ddl.auto" value="none"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect"/>
        <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="jndi.class" value="weblogic.jndi.WLInitialContextFactory"/>
    </properties>
</persistence-unit>
</persistence>

weblogic.xml:

    ...
    <resource-description>
        <res-ref-name>jdbc/myDS</res-ref-name>
        <jndi-name>myDS</jndi-name>
    </resource-description>
    ...

web.xml:

...
    <resource-ref>
       <res-ref-name>jdbc/myDS</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
    </resource-ref>
...

PS:
I'm getting the Connection via the Entitymanager and i don't have any context.xml.

What can i do? Can anybody help?

Body:
You shouldn't be setting the datasource using properties. There is and standard way to provide the datasource to the entity manager, using the <jta-data-source> element.

You only should need something like this:

<persistence...
<persistence-unit name="MY-PERSISTENCE-UNIT">
    <description>Hibernate JPA Configuration</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <jta-data-source>jdbc/myDS</jta-data-source>

    <class>some classes...</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.hbm2ddl.auto" value="none"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect"/>
    </properties>
</persistence-unit>
</persistence>


问:
How can i import a vector in rcpp?
Good afternoon ,

I created this rcpp function that returns a 3d matrix with dimensions K * K * L.

Rcpp Code :

```<code>#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]

NumericVector Test( int K , int L ){

  // calling some R functions

  Function f1("rnorm");
  Function f2("runif");
  Function f3("ceiling");
  Function f4("unique");
  Function f5("array");
  Function f6("unique.array");
  Function f7("print");

  // Creating a vector of normal law with length= K * K * L

  NumericVector rn = f5(f1(K*K*L, Named("sd")=1, _["mean"]=0), Named("dim")=NumericVector::create(K,K,L));

  // Reshaping the 1d vector  , the 3d matrix will be visible in R
  rn.attr("dim") = Dimension(K, K , L );
      return rn ;
    }

***Example of the obtained results :***  The function is called in Rstudio

    > Test(3,2)
    , , 1

            [,1]       [,2]        [,3]
[1,] -0.57144807 -0.1650806  0.07607133
[2,]  0.61278268 -0.5049861  0.37705107
[3,]  0.09037529  1.6185765 -0.68675536

, , 2

           [,1]       [,2]       [,3]
[1,] -0.5789173 -0.6630934  0.9961613
[2,] -0.4425025 -0.9083358 -1.4860523
[3,]  0.2150056 -0.3229108 -1.6536952
</code>```

My question :

Suppose that (K,L)=(3,2) like the example  , how can i extract in rcpp the second row / column in the second table of rn (indexed by [ , , 2 ] ) ?

Is it possible to store this extracted vector of length=K in a numericVector variable using the vector.import() method ?

Sorry but i didn't find an example that could help me !

Thank you a lot !

答:
A possible solution could be : </p>

```<code>NumericVector v1 ;
NumericVector v2=NumericVector::create(1,2,4,5,6,7,8) ;
v1= rd.import( v2.begin() , v2.begin()+ 6) ;
// return elements 1,2,4,5,6,7
</code>```

Title: How can i import a vector in rcpp?

Body:
Good afternoon ,

I created this rcpp function that returns a 3d matrix with dimensions K * K * L.

Rcpp Code :

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]

NumericVector Test( int K , int L ){

  // calling some R functions

  Function f1("rnorm");
  Function f2("runif");
  Function f3("ceiling");
  Function f4("unique");
  Function f5("array");
  Function f6("unique.array");
  Function f7("print");

  // Creating a vector of normal law with length= K * K * L

  NumericVector rn = f5(f1(K*K*L, Named("sd")=1, _["mean"]=0), Named("dim")=NumericVector::create(K,K,L));

  // Reshaping the 1d vector  , the 3d matrix will be visible in R
  rn.attr("dim") = Dimension(K, K , L );
      return rn ;
    }

***Example of the obtained results :***  The function is called in Rstudio

    > Test(3,2)
    , , 1

            [,1]       [,2]        [,3]
[1,] -0.57144807 -0.1650806  0.07607133
[2,]  0.61278268 -0.5049861  0.37705107
[3,]  0.09037529  1.6185765 -0.68675536

, , 2

           [,1]       [,2]       [,3]
[1,] -0.5789173 -0.6630934  0.9961613
[2,] -0.4425025 -0.9083358 -1.4860523
[3,]  0.2150056 -0.3229108 -1.6536952

My question :

Suppose that (K,L)=(3,2) like the example  , how can i extract in rcpp the second row / column in the second table of rn (indexed by [ , , 2 ] ) ?

Is it possible to store this extracted vector of length=K in a numericVector variable using the vector.import() method ?

Sorry but i didn't find an example that could help me !

Thank you a lot !

Body:
A possible solution could be :

NumericVector v1 ;
NumericVector v2=NumericVector::create(1,2,4,5,6,7,8) ;
v1= rd.import( v2.begin() , v2.begin()+ 6) ;
// return elements 1,2,4,5,6,7


问:
Analytics - active page - change url for group up
I have a custom dashboard where I have an real-time table.

This table shows what pages are seen by users which are now on website.

There are pages like /checkout/xxxxx.

If there are 2 users on /checkout/xxxxx1 and /checkout/xxxxx2. In table appear both pages.

I want to see just one, like /checkout and at count of users 2.

Here is an visual example:

答:
You can filter by regex ^\/checkouts and look at the row with the total values (which represents the aggregate of the pages that correspond to the regex).

However, it may be wrong to say that if page /checkouts/xxxxx1 was viewed by a user and page /checkouts/xxxxx2 was viewed by a user, the total of users is 2.

This is because it could be the same user, so the total could be 1 (so, you can know it look at the row with the total values).


问:
JQuery async .each returns empty promises
Problem

Hi friends,

I am having the problem that the object promises is returning me as empty []. While the console.log I have documented shows me the data.

If there is a way to solve the problem, I will appreciate it.

const getALLMovies = async(page: number = 1): Promise<IMovies[]> =>{
  const res = await axios.get(`${BASE_URL}peliculas/${page}`);
  const body = await res.data;
  const $ = load(body);
  const promises: IMovies[] = [];

$('body div div div div div div div div div div div div#default-tab-1 div.Posters a').each(async(index , element) =>{
    const $element = $(element);
    const id = $element.attr('href').replace(BASE_URL , '').trim();
    const title = $element.find('div.listing-content p').text().trim();
    const poster = $element.find('img').attr('src');
    const extra = await contentHandler(id);
    promises.push({
      //id: id || null,
      title: title || null,
      poster: poster || null,
      year:   extra[0].year || null,
      genres: extra[0].genres || null,
      rating: extra[0].rating || null,
      synopsis: extra[0].synopsis || null,
      authors:  extra[0].authors || null,
      director: extra[0].director || null,
      writers:  extra[0].writers || null,
      country:  extra[0].country || null,
      releaseDate: extra[0].releaseDate || null,
    })
    //console.log(JSON.stringify(promises , null , 2)) --> The data is shown here.

  });

  return Promise.all(promises);
};

getALLMovies()
  .then(res =>{
    console.log(res.map(x => x)) --> empty object
  })

```

答:
Thanks @Zze,

With your example I have managed to show all the data.

SOLUTION

const getALLMovies = async(page: number = 1) =>{
  const res = await axios.get(`${BASE_URL}peliculas/${page}`);
  const body = await res.data;
  const $ = load(body);
  const promises: IMovies[] = [];

  //const actual = page;
  //const lastPage = parseInt($('body div.app div.layout ul.pagination li').eq(4).find('a').attr('href').match(/\d/g).join("") , 10);
  //const pagination = {
  //  actual: actual,
  //  last: lastPage
  //}

  const promise = $('body div#default-tab-1 div.Posters a').map((index , element) => new Promise(async(resolve) =>{
    const $element = $(element);
    const id = $element.attr('href').replace(BASE_URL, '').trim();
    const title = $element.find('div.listing-content p').text().trim();
    const poster = $element.find('img').attr('src');
    const extra = await contentHandler(id);
    promises.push({
      //id: id || null,
      title: title || null,
      poster: poster || null,
      year: extra[0].year || null,
      genres: extra[0].genres || null,
      rating: extra[0].rating || null,
      synopsis: extra[0].synopsis || null,
      authors: extra[0].authors || null,
      director: extra[0].director || null,
      writers: extra[0].writers || null,
      country: extra[0].country || null,
      releaseDate: extra[0].releaseDate || null,
    });
    resolve(promises)
  }));

  return Promise.all(promise.toArray());
};

getALLMovies()
  .then(res =>{
    console.log(JSON.stringify(res , null , 2))
  })
```


问:
Receive broadcasts in stopped application
By default, an application which in stopped state (not yet run even once) could not receive broadcasts. There is a way to receive it if we add the flag FLAG_INCLUDE_STOPPED_PACKAGES to the broadcast intent.

My problem is that I need to receive system intent android.intent.action.MEDIA_MOUNTED (and I don't want to add that flag to it).

How can I receive it even in stopped application?

It seems to me that for sure it's possible because for example com.android.shell application is able to receive such intents even if it's force stopped. How it does it?

EDIT:

Just to clarify, because it appeared that this is not obvious:

Everything here is from the point of view of Android Open Source Project developer. I'm modifying the operating system source code and the application which I want to receive the broadcast could be preinstalled, signed with platform certificate, it can use hidden API, etc. Everything is permitted, even modifications of the system.

答:
If you are not referring to Force Stopped applications, but rather to closed applications that are in the stopped state, then look at these two links to find out how to implement a BroadcastReceiver that can be activated after the app is closed. Otherwise a custom ROM and or sys app is the way to go probably.

BroadcastReceiver 1

BroadcastReceiver 2

ContentLicense: CC BY-SA 3.0


问:
Bash echo output mix of string and character
I am taking an assessment and stumbled across the following sample question, but when I run the line it's none of the options?  Which is the correct answer?

答:
. is the string concatenation operator for PHP. In bash, you could just do echo Tomorrow will be January ${num}rd.

Both versions of the code output Tomorrow will be January 3rd.


问:
How do I compare a raw time in Java?
For example suppose I have

```<code>String endTime = "16:30:45";
</code>```

How would I determine whether right now is before this time?

答:
First, you need to parse this:

```<code>SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);
</code>```

Then you can create use a calendar to compare the time:

```<code>Calendar c = Calendar.getInstance();
c.setTime(date);
Calendar now = Calendar.getInstance();
if (now.get(Calendar.HOUR_OF_DAY) > c.get(Calendar.HOUR_OF_DAY) .. etc) { .. }
</code>```

Alternatively, you can create a calendar like now and set its HOUR, MINUTE and SECOND fields with the ones from the new calendar.

With joda-time you can do something similar.

```<code>new DateMidnight().withHour(..).widthMinute(..).isBefore(new DateTime())
</code>```

Title: How do I compare a raw time in Java?

Body:
For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time?

Body:
First, you need to parse this:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);

Then you can create use a calendar to compare the time:

Calendar c = Calendar.getInstance();
c.setTime(date);
Calendar now = Calendar.getInstance();
if (now.get(Calendar.HOUR_OF_DAY) > c.get(Calendar.HOUR_OF_DAY) .. etc) { .. }

Alternatively, you can create a calendar like now and set its HOUR, MINUTE and SECOND fields with the ones from the new calendar.

With joda-time you can do something similar.

new DateMidnight().withHour(..).widthMinute(..).isBefore(new DateTime())


问:
I Want to connect an HTML Element To a javascript Object
For every product's  element on the page, I want to create an associated JavaScript object with attributes of title, description and price.  When the  is clicked, it should show a modal based on a HTML template with the fields populated by these attributes.

Here is my current code:

document.getElementById("red").onclick = function() {functionRed()};
document.getElementById("yellow").onclick = function() {functionYellow()};
document.getElementById("blue").onclick = function() {functionBlue()};

// Create an object:
var Blue = {Title:"BlueIsTheNewBlack", Price:"500", Description:"This blue is the best color"}
var Yellow = {Title:"YellowIsTheNewBlack", Price:"900", Description:"This yellow is the best color"}
var Red = {Title:"RedIsTheNewBlack", Price:"100", Description:"This red is the best color"}

function functionRed() {
  document.getElementById('id01').style.display='block';
// Display some data from the object:
  document.getElementById("TitleModal").innerHTML = Red.Title;
  document.getElementById("PriceModal").innerHTML = Red.Price;
  document.getElementById("DescriptionModal").innerHTML = Red.Description;
}

function functionYellow() {
  document.getElementById('id01').style.display='block';
// Display some data from the object:
  document.getElementById("TitleModal").innerHTML = Yellow.Title;
  document.getElementById("PriceModal").innerHTML = Yellow.Price;
  document.getElementById("DescriptionModal").innerHTML = Yellow.Description;
}

function functionBlue() {
  document.getElementById('id01').style.display='block';
// Display some data from the object:
  document.getElementById("TitleModal").innerHTML = Blue.Title;
  document.getElementById("PriceModal").innerHTML = Blue.Price;
  document.getElementById("DescriptionModal").innerHTML = Blue.Description;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<div style="background-color:red; width:50px; height:50px; float: left;" id="red"></div>
<div style="background-color:blue; width:50px; height:50px; float: left;" id="blue"></div>
<div style="background-color:yellow; width:50px; height:50px; float: left;" id="yellow"></div>

  <div id="id01" class="w3-modal">
    <div class="w3-modal-content">
      <div class="w3-container">
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">×</span>
        <h2 id="TitleModal">Some text. Some text. Some text.</h2>
        <h2 id="PriceModal">Some text. Some text. Some text.</h2>
        <p id="DescriptionModal">Some text. Some text. Some text.</h2>
      </div>
    </div>
  </div>
</div></code>```

Thanks to everybody.

答:
Is that what you expect ?

const SquareColors
        = document.getElementById('ColorsChoices')
  ,   SquareMessage
        = { onRed    : { Title: 'RedIsTheNewBlack',    Price: '100', Description: 'This red is the best color'    }
          , onBlue   : { Title: 'BlueIsTheNewBlack',   Price: '500', Description: 'This blue is the best color'   }
          , onYellow : { Title: 'YellowIsTheNewBlack', Price: '900', Description: 'This yellow is the best color' }
          }
  ,   Modal_info
        = document.getElementById('idModal')
  ;
Modal_info.show=_=>Modal_info.classList.remove('noDisplay')
Modal_info.hide=_=>Modal_info.classList.add('noDisplay')

idModal.onclick=e=>
  {
  if (!e.target.matches('#close-button, #idModal')) return
  e.preventDefault()
  Modal_info.hide()
  }
const TitleModal      = document.getElementById('TitleModal')
  ,   PriceModal      = document.getElementById('PriceModal')
  ,  DescriptionModal = document.getElementById('DescriptionModal')
  ;
SquareColors.onclick=e=>
  {
  if (!e.target.matches('.colorButton')) return

  let inColor = e.target.id

  TitleModal.textContent       = SquareMessage[inColor].Title
  PriceModal.textContent       = SquareMessage[inColor].Price
  DescriptionModal.textContent = SquareMessage[inColor].Description

  Modal_info.show()
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav#ColorsChoices div {
  width : 50px;
  height: 50px;
  float : left;
}
#onRed    { background-color: red    }
#onBlue   { background-color: blue   }
#onYellow { background-color: yellow }

.noDisplay { display: none }

#idModal {
  z-index: 3;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color:   rgba(0,0,0,0.4);
}
#idModal > div {
  position: relative;
  display: block;
  width: 30em;
  margin: 5em auto;
  background-color: #fff;
  padding: 1em;
}
#close-button {
  position: absolute;
  top: 0;
  right: .3em;
  cursor: pointer;
  font-size: 2em;
  font-weight: bold;
}
#close-button:hover { color: crimson; }</code>```

    ×

Some text.

Some text.

Some text.

```

Body:
For every product's  element on the page, I want to create an associated JavaScript object with attributes of title, description and price.  When the  is clicked, it should show a modal based on a HTML template with the fields populated by these attributes.

Here is my current code:

document.getElementById("red").onclick = function() {functionRed()};
document.getElementById("yellow").onclick = function() {functionYellow()};
document.getElementById("blue").onclick = function() {functionBlue()};

// Create an object:
var Blue = {Title:"BlueIsTheNewBlack", Price:"500", Description:"This blue is the best color"}
var Yellow = {Title:"YellowIsTheNewBlack", Price:"900", Description:"This yellow is the best color"}
var Red = {Title:"RedIsTheNewBlack", Price:"100", Description:"This red is the best color"}

function functionRed() {
  document.getElementById('id01').style.display='block';
// Display some data from the object:
  document.getElementById("TitleModal").innerHTML = Red.Title;
  document.getElementById("PriceModal").innerHTML = Red.Price;
  document.getElementById("DescriptionModal").innerHTML = Red.Description;
}

function functionYellow() {
  document.getElementById('id01').style.display='block';
// Display some data from the object:
  document.getElementById("TitleModal").innerHTML = Yellow.Title;
  document.getElementById("PriceModal").innerHTML = Yellow.Price;
  document.getElementById("DescriptionModal").innerHTML = Yellow.Description;
}

function functionBlue() {
  document.getElementById('id01').style.display='block';
// Display some data from the object:
  document.getElementById("TitleModal").innerHTML = Blue.Title;
  document.getElementById("PriceModal").innerHTML = Blue.Price;
  document.getElementById("DescriptionModal").innerHTML = Blue.Description;
}

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

        ×

Some text. Some text. Some text.

Some text. Some text. Some text.

Some text. Some text. Some text.

Thanks to everybody.

Body:
Is that what you expect ?

const SquareColors
        = document.getElementById('ColorsChoices')
  ,   SquareMessage
        = { onRed    : { Title: 'RedIsTheNewBlack',    Price: '100', Description: 'This red is the best color'    }
          , onBlue   : { Title: 'BlueIsTheNewBlack',   Price: '500', Description: 'This blue is the best color'   }
          , onYellow : { Title: 'YellowIsTheNewBlack', Price: '900', Description: 'This yellow is the best color' }
          }
  ,   Modal_info
        = document.getElementById('idModal')
  ;
Modal_info.show=_=>Modal_info.classList.remove('noDisplay')
Modal_info.hide=_=>Modal_info.classList.add('noDisplay')

idModal.onclick=e=>
  {
  if (!e.target.matches('#close-button, #idModal')) return
  e.preventDefault()
  Modal_info.hide()
  }
const TitleModal      = document.getElementById('TitleModal')
  ,   PriceModal      = document.getElementById('PriceModal')
  ,  DescriptionModal = document.getElementById('DescriptionModal')
  ;
SquareColors.onclick=e=>
  {
  if (!e.target.matches('.colorButton')) return

  let inColor = e.target.id

  TitleModal.textContent       = SquareMessage[inColor].Title
  PriceModal.textContent       = SquareMessage[inColor].Price
  DescriptionModal.textContent = SquareMessage[inColor].Description

  Modal_info.show()
  }

nav#ColorsChoices div {
  width : 50px;
  height: 50px;
  float : left;
}
#onRed    { background-color: red    }
#onBlue   { background-color: blue   }
#onYellow { background-color: yellow }

.noDisplay { display: none }

#idModal {
  z-index: 3;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color:   rgba(0,0,0,0.4);
}
#idModal > div {
  position: relative;
  display: block;
  width: 30em;
  margin: 5em auto;
  background-color: #fff;
  padding: 1em;
}
#close-button {
  position: absolute;
  top: 0;
  right: .3em;
  cursor: pointer;
  font-size: 2em;
  font-weight: bold;
}
#close-button:hover { color: crimson; }

<nav id="ColorsChoices">
  <div class="colorButton" id="onRed"></div>
  <div class="colorButton" id="onBlue"></div>
  <div class="colorButton" id="onYellow"></div>
</nav>

<div id="idModal" class="noDisplay">
  <div>
    <span id="close-button">&times;</span>
    <h2 id="TitleModal">Some text. </h2>
    <h2 id="PriceModal">Some text. </h2>
    <p id="DescriptionModal">Some text. </h2>
  </div>
</div>


问:
Loop for two codes and two functions in r
I have two codes to be done for all of my samples.

```<code>cr1 = MEDIPS.seqCoverage(file = "1.bam", pattern = "CG", BSgenome = BSgenome, extend = extend, shift = shift, uniq = uniq)
MEDIPS.plotSeqCoverage(seqCoverageObj=cr1, type="pie", cov.level = c(0, 5, 10, 20, 30), main="cr1")
</code>```

Then,

```<code>cr2 = MEDIPS.seqCoverage(file = "2.bam", pattern = "CG", BSgenome = BSgenome, extend = extend, shift = shift, uniq = uniq)
MEDIPS.plotSeqCoverage(seqCoverageObj=cr2, type="pie", cov.level = c(0, 5, 10, 20, 30), main="cr2")
</code>```

I don't want to repeat the code again and again for 100 times. I tried some for loops but they are not working because " File i.bam  not found in ...". Well, I am not good at it at all. Does anyone can help me out?

So my code look like this:

```<code>for(i in 1:100){
  cr[i] = MEDIPS.seqCoverage(file = paste0(as.character(i),".bam"),
                             pattern = "CG", BSgenome = BSgenome, extend = extend,
                             shift = shift, uniq = uniq)
  MEDIPS.plotSeqCoverage(seqCoverageObj=cr[i], type="pie",
                         cov.level = c(0, 5, 10, 20, 30), main="cr",paste0(as.character(i)))
}
</code>```

Reading bam alignment 1.bam

Total number of imported short reads: 17254741

Extending reads...

Creating GRange Object...

Keep at most one 1 read mapping to the same genomic location.

Number of remaining reads: 11148075

Loading chromosome lengths for BSgenome.Hsapiens.UCSC.hg19...

Get genomic sequence pattern positions...

Number of identified  CG  pattern:  26752702

Calculating sequence pattern coverage...

Error: object 'cr' not found

答:
Be sure that your working directory is set correctly. The " File i.bam not found in ..." means that file is not in the same directory you are currently in.

```<code>getwd()
</code>```

will show you what directory you are currently in. If the file is in downloads, you can use

```<code>setwd()
</code>```

to change your directory to downloads to access the file.

Update from comment

```<code>for(i in 1:100){
cr[i] = MEDIPS.seqCoverage(file = cat(paste0(as.character(i),".bam")),
pattern = "CG", BSgenome = BSgenome, extend = extend,
shift = shift, uniq = uniq)

MEDIPS.plotSeqCoverage(seqCoverageObj=cr[i], type="pie",
cov.level = c(0, 5, 10, 20, 30), main=cr[i])
}
</code>```

Body:
I have two codes to be done for all of my samples.

cr1 = MEDIPS.seqCoverage(file = "1.bam", pattern = "CG", BSgenome = BSgenome, extend = extend, shift = shift, uniq = uniq)
MEDIPS.plotSeqCoverage(seqCoverageObj=cr1, type="pie", cov.level = c(0, 5, 10, 20, 30), main="cr1")

Then,

cr2 = MEDIPS.seqCoverage(file = "2.bam", pattern = "CG", BSgenome = BSgenome, extend = extend, shift = shift, uniq = uniq)
MEDIPS.plotSeqCoverage(seqCoverageObj=cr2, type="pie", cov.level = c(0, 5, 10, 20, 30), main="cr2")

I don't want to repeat the code again and again for 100 times. I tried some for loops but they are not working because " File i.bam  not found in ...". Well, I am not good at it at all. Does anyone can help me out?

So my code look like this:

for(i in 1:100){
  cr[i] = MEDIPS.seqCoverage(file = paste0(as.character(i),".bam"),
                             pattern = "CG", BSgenome = BSgenome, extend = extend,
                             shift = shift, uniq = uniq)
  MEDIPS.plotSeqCoverage(seqCoverageObj=cr[i], type="pie",
                         cov.level = c(0, 5, 10, 20, 30), main="cr",paste0(as.character(i)))
}

Reading bam alignment 1.bam

Total number of imported short reads: 17254741

Extending reads...

Creating GRange Object...

Keep at most one 1 read mapping to the same genomic location.

Number of remaining reads: 11148075

Loading chromosome lengths for BSgenome.Hsapiens.UCSC.hg19...

Get genomic sequence pattern positions...

Number of identified  CG  pattern:  26752702

Calculating sequence pattern coverage...

Error: object 'cr' not found

Body:
Be sure that your working directory is set correctly. The " File i.bam not found in ..." means that file is not in the same directory you are currently in.

getwd()

will show you what directory you are currently in. If the file is in downloads, you can use

setwd()

to change your directory to downloads to access the file.

Update from comment

for(i in 1:100){
cr[i] = MEDIPS.seqCoverage(file = cat(paste0(as.character(i),".bam")),
pattern = "CG", BSgenome = BSgenome, extend = extend,
shift = shift, uniq = uniq)

MEDIPS.plotSeqCoverage(seqCoverageObj=cr[i], type="pie",
cov.level = c(0, 5, 10, 20, 30), main=cr[i])
}


问:
Google PHP BigQueryClient returning Numeric Object instead of just the value for Numeric fields
When I run a bigquery select using PHP BiqQueryClient, the data returned for 'Numeric' fields is an object. The strings and integer fields are returned as values.

```<code><?php
use Google\Cloud\BigQuery\BigQueryClient;

$query = "SELECT customer_name, customer_number FROM mytable;";
$bigQuery = new BigQueryClient(['projectId' => $projectId]);
$queryJobConfig = $bigQuery->query($query);
$queryResults = $bigQuery->runQuery($queryJobConfig);
if($queryResults->isComplete()) {
    $rows = $queryResults->rows();
    foreach ($rows as $row) {
       print_r($row);
    }
}
?>
</code>```

Prints something like:

```<code>Array
([customer_number] => Google\Cloud\BigQuery\Numeric Object(
 [value:Google\Cloud\BigQuery\Numeric:private] => 18302117
))
</code>```

How can I simply get an numeric value returned?

答:
If you take a look at class implementation here: https://github.com/googleapis/google-cloud-php-bigquery/blob/master/src/Numeric.php it has a method get() that returns the value:

```<code>$customerNumber = $row['customer_number'];
print_r($customerNumber->get());
</code>```

Body:
When I run a bigquery select using PHP BiqQueryClient, the data returned for 'Numeric' fields is an object. The strings and integer fields are returned as values.

<?php
use Google\Cloud\BigQuery\BigQueryClient;

$query = "SELECT customer_name, customer_number FROM mytable;";
$bigQuery = new BigQueryClient(['projectId' => $projectId]);
$queryJobConfig = $bigQuery->query($query);
$queryResults = $bigQuery->runQuery($queryJobConfig);
if($queryResults->isComplete()) {
    $rows = $queryResults->rows();
    foreach ($rows as $row) {
       print_r($row);
    }
}
?>

Prints something like:

Array
([customer_number] => Google\Cloud\BigQuery\Numeric Object(
 [value:Google\Cloud\BigQuery\Numeric:private] => 18302117
))

How can I simply get an numeric value returned?

Body:
If you take a look at class implementation here: https://github.com/googleapis/google-cloud-php-bigquery/blob/master/src/Numeric.php it has a method get() that returns the value:

$customerNumber = $row['customer_number'];
print_r($customerNumber->get());


问:
Illegal vector component name "x" (metal)
with Metal, at runtime, when I try to compile my shader I receive the error

Error: Illegal vector component name 'x'

It's work well when In macos 10.14/10.15 but on macos 10.11 on old mac mini it's crash! any idea why ?

```<code>using namespace metal;

struct Vertex {
  packed_float3 position;
};

struct ProjectedVertex {
  float4 position [[position]];
};

vertex ProjectedVertex vertexShader(constant Vertex *vertexArray [[buffer(0)]],
                                    const unsigned int vertexId [[vertex_id]],
                                    constant float4x4 &MVPMatrix [[buffer(1)]]) {
  Vertex in = vertexArray[vertexId];
  ProjectedVertex out;
  out.position = float4(in.position.x, in.position.y, in.position.z, 1) * MVPMatrix;
  return out;
}
</code>```

答:
Prior to Metal 2.1, accessing the named components of a packed vector type is not permitted in Metal Shading Language.

To work around this, either access such elements via subscripting, or by creating a local variable of the corresponding non-packed type:

```<code>out.position = float4(in.position[0], in.position[1], in.position[2], 1) * MVPMatrix;

// OR:

float3 position = in.position;
out.position = float4(position.x, position.y, position.z, 1) * MVPMatrix;
</code>```

Body:
with Metal, at runtime, when I try to compile my shader I receive the error

Error: Illegal vector component name 'x'

It's work well when In macos 10.14/10.15 but on macos 10.11 on old mac mini it's crash! any idea why ?

using namespace metal;

struct Vertex {
  packed_float3 position;
};

struct ProjectedVertex {
  float4 position [[position]];
};

vertex ProjectedVertex vertexShader(constant Vertex *vertexArray [[buffer(0)]],
                                    const unsigned int vertexId [[vertex_id]],
                                    constant float4x4 &MVPMatrix [[buffer(1)]]) {
  Vertex in = vertexArray[vertexId];
  ProjectedVertex out;
  out.position = float4(in.position.x, in.position.y, in.position.z, 1) * MVPMatrix;
  return out;
}

Body:
Prior to Metal 2.1, accessing the named components of a packed vector type is not permitted in Metal Shading Language.

To work around this, either access such elements via subscripting, or by creating a local variable of the corresponding non-packed type:

out.position = float4(in.position[0], in.position[1], in.position[2], 1) * MVPMatrix;

// OR:

float3 position = in.position;
out.position = float4(position.x, position.y, position.z, 1) * MVPMatrix;


问:
on adding spring-data-rest-hal-browser dependency to my spring boot application(v 2.2.4) -my app failed to start .how to fix it?
Hi I am new to spring boot.
spring-boot-starter-actuator it works fine in the http://localhost:8080/actuator.

my spring boot version is 2.2.4

on adding

```<code>        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-browser</artifactId>
        </dependency>
</code>```

application failed to start .

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory.<init>(UnwrappingRepositoryInvokerFactory.java:57)

The following method did not exist:

    org.springframework.plugin.core.PluginRegistry.of(Ljava/util/List;)Lorg/springframework/plugin/core/PluginRegistry;

The method's class, org.springframework.plugin.core.PluginRegistry, is available from the following locations:enter code here

    jar:file:/C:/Users/SATHISH%20S/.m2/repository/org/springframework/plugin/spring-plugin-core/1.2.0.RELEASE/spring-plugin-core-1.2.0.RELEASE.jar!/org/springframework/plugin/core/PluginRegistry.class

It was loaded from the following location:

    file:/C:/Users/SATHISH%20S/.m2/repository/org/springframework/plugin/spring-plugin-core/1.2.0.RELEASE/spring-plugin-core-1.2.0.RELEASE.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.plugin.core.PluginRegistry
</code>```

and my pom.xml is

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>MysqlCrud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MysqlCrud</name>
    <description>Demo project for Spring Boot mysql crud</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-rest-hal-browser -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-browser</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

help me to fix this.

Thank you

答:
Spring Fox 2.9 is only compatible with version 1.2 of spring-plugin-core whereas the version of Spring Data REST included in Spring Boot 2.2 requires 2.0. Until a compatible version of SpringFox is released, you have a few options:

remove SpringFox from your app

remove Spring Data REST from your app

downgrade to Spring Boot 2.1.x

Body:
Hi I am new to spring boot.
spring-boot-starter-actuator it works fine in the http://localhost:8080/actuator.

my spring boot version is 2.2.4

on adding

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-browser</artifactId>
        </dependency>

application failed to start .

***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory.<init>(UnwrappingRepositoryInvokerFactory.java:57)

The following method did not exist:

    org.springframework.plugin.core.PluginRegistry.of(Ljava/util/List;)Lorg/springframework/plugin/core/PluginRegistry;

The method's class, org.springframework.plugin.core.PluginRegistry, is available from the following locations:enter code here

    jar:file:/C:/Users/SATHISH%20S/.m2/repository/org/springframework/plugin/spring-plugin-core/1.2.0.RELEASE/spring-plugin-core-1.2.0.RELEASE.jar!/org/springframework/plugin/core/PluginRegistry.class

It was loaded from the following location:

    file:/C:/Users/SATHISH%20S/.m2/repository/org/springframework/plugin/spring-plugin-core/1.2.0.RELEASE/spring-plugin-core-1.2.0.RELEASE.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.plugin.core.PluginRegistry

and my pom.xml is

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath />
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>MysqlCrud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MysqlCrud</name>
    <description>Demo project for Spring Boot mysql crud</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-browser</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

help me to fix this.

Thank you


问:
Connect and downlaod content with socket in iphone sdk
Hi I want to use socket programming for downlaoding HTML from the server.
Any body can give such a sample code.</p>

答:
```<code>-(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
</code>```

works for me.

Body:
-(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode

works for me.


问:
horizontally displayed JSON data react card
I am new to react ,I am fetching some json data and I would like to displayed them horizontally in bootstrap card,Whenever I tried ,it keeps displayed vertically .here is my code.

```<code><div className="row"  >
<div className="col-md-4" >
<div className="card" >
             <img className="card-img-top" src={user.picture.large? ( user.picture.large) : ("http://appalachiantrail.org/images/default-source/default-album/trailfocus.jpg?sfvrsn=2")} />
               <div className="card-body" >
                 <h1 className="card-title">{user.name.first}</h1>
                   <h2 className="card-text">{user.id.value} </h2>
                     <h4 className="card-text">{user.email} </h4>
                     </div>
<br>
                     </br>

   </div>
</div>
</code>```

this is what I want to achieve

See  code here of what I want to achieve,how do I replace those static column with my dynamic json response data ? Please advise

thanks

答:
This question is not specific enough.

The point of ReactJS is to serve data in an active state. Use Javascript to display and interact with the user.
In your situation you need to extract the display components from the example into your React.Component and utilize XHR(AJAX) request (probably using ext library axios).

Search for examples of these:

Axios

React.Component

React List and Keys

Body:
I am new to react ,I am fetching some json data and I would like to displayed them horizontally in bootstrap card,Whenever I tried ,it keeps displayed vertically .here is my code.

{user.name.first}

{user.id.value}

{user.email}

this is what I want to achieve

See  code here of what I want to achieve,how do I replace those static column with my dynamic json response data ? Please advise

thanks


问:
Convert int array to std::vector<int*>
I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.

I'm currently implementing this by doing the follow:

```<code>for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}
</code>```

Is it possible to implement this by using std::vector::insert() and std::being/end?

答:
std::transform is a useful algorithm in <algorithm> for copying values between containers that aren't implicitly compatible but for which you can provide a transformation function.

Here is an example of how you could populate a std::vector<int*> from a std::array<int, N>

```<code>int values[5] = { 1,2,3,4,5 };
std::vector<int*> v1;

std::transform(
    std::begin(values), std::end(values),   // Copy from
    std::back_inserter(v1),                 // Copy to
    [](auto& i) {                           // Transformation function
        return &i;
    });
</code>```

Edit : Changed std::array<int, 5> to int[5] to account for edits in the question.

Title: Convert int array to std::vector<int*>

Body:
I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.

I'm currently implementing this by doing the follow:

for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}

Is it possible to implement this by using std::vector::insert() and std::being/end?

Body:
std::transform is a useful algorithm in <algorithm> for copying values between containers that aren't implicitly compatible but for which you can provide a transformation function.

Here is an example of how you could populate a std::vector<int*> from a std::array<int, N>

int values[5] = { 1,2,3,4,5 };
std::vector<int*> v1;

std::transform(
    std::begin(values), std::end(values),   // Copy from
    std::back_inserter(v1),                 // Copy to
    [](auto& i) {                           // Transformation function
        return &i;
    });

Edit : Changed std::array<int, 5> to int[5] to account for edits in the question.


问:
Price adjustment on category and subcategorie - woocommerce
I found this piece of code and it works great. I would like to see that this also works on subcategories. I hope someone can help me with this.</p>

```<code>// Simple, grouped and external products
add_filter('woocommerce_product_get_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'conditional_custom_price', 99, 2 );
// Variable
add_filter('woocommerce_product_variation_get_regular_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'conditional_custom_price', 99, 2 );
function conditional_custom_price( $price, $product ) {
    global $post;
    if( has_term( 'test', 'product_cat', $post->ID )){
        // Delete product cached price  (if needed uncomment it)
        // wc_delete_product_transients($product->get_id());

        $price = $price * 2.1;
    }
    return $price;
}
</code>```

答:
Oke, found the answer.</p>

```<code>// Simple, grouped and external products
add_filter('woocommerce_product_get_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'conditional_custom_price', 99, 2 );
// Variable
add_filter('woocommerce_product_variation_get_regular_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'conditional_custom_price', 99, 2 );

function conditional_custom_price( $price, $product ) {
    $term_slug = 'test';
    $taxonomy  = 'product_cat';
    $term_id   = get_term_by( 'slug', $term_slug, $taxonomy )->term_id; // Get the term ID
    $child_ids = get_term_children( $term_id, $taxonomy ); // Get the children terms IDs
    $terms_ids = array_merge( $child_ids, [$term_id] ); // an array of all term IDs (main term Id and it's children)

    if ( has_term( $terms_ids, $taxonomy, $product->get_id() ) ) {
        // Delete product cached price  (if needed uncomment it)
        // wc_delete_product_transients($product->get_id());

        $price = $price * 2.1;
    }
    return $price;
}
</code>```

Body:
I found this piece of code and it works great. I would like to see that this also works on subcategories. I hope someone can help me with this.

// Simple, grouped and external products
add_filter('woocommerce_product_get_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'conditional_custom_price', 99, 2 );
// Variable
add_filter('woocommerce_product_variation_get_regular_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'conditional_custom_price', 99, 2 );
function conditional_custom_price( $price, $product ) {
    global $post;
    if( has_term( 'test', 'product_cat', $post->ID )){
        // Delete product cached price  (if needed uncomment it)
        // wc_delete_product_transients($product->get_id());

        $price = $price * 2.1;
    }
    return $price;
}

Body:
Oke, found the answer.

// Simple, grouped and external products
add_filter('woocommerce_product_get_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'conditional_custom_price', 99, 2 );
// Variable
add_filter('woocommerce_product_variation_get_regular_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'conditional_custom_price', 99, 2 );

function conditional_custom_price( $price, $product ) {
    $term_slug = 'test';
    $taxonomy  = 'product_cat';
    $term_id   = get_term_by( 'slug', $term_slug, $taxonomy )->term_id; // Get the term ID
    $child_ids = get_term_children( $term_id, $taxonomy ); // Get the children terms IDs
    $terms_ids = array_merge( $child_ids, [$term_id] ); // an array of all term IDs (main term Id and it's children)

    if ( has_term( $terms_ids, $taxonomy, $product->get_id() ) ) {
        // Delete product cached price  (if needed uncomment it)
        // wc_delete_product_transients($product->get_id());

        $price = $price * 2.1;
    }
    return $price;
}


问:
Is it possible to force smooth implicit scrolling for Flutter's accessibility focus system?
I'm currently adapting a Flutter app to work with Android TV devices. Documentation on this is sparse, but I've managed to feel my way through the process by using the accessibility focus system for directional navigation using the standard remote.

However, in one of my layouts I'm using a PageView containing some grids of items, the grid separated out into pages for better directional navigation ergonomics. As expected, creating a PageView with allowImplicitScrolling: true allows you to navigate between pages by moving the focus reticle off the side of the grid. However, implicit scrolling in any context never has any animation accompanying it, just transitioning to the next view position instantly. This ends up not looking very good. In reality, this same problem applies to all implicit scrolling, whether in a PageView, ListView, GridView, or any scrolling view at all.

Widget _buildPaginatedGrid(BuildContext build) {
    return SliverToBoxAdapter(
      child: Container(
        height: MediaQuery.of(build).size.height - gameHeroHeight(context),
        child: PageView(
          allowImplicitScrolling: true,
          controller: _pageController,
          children: [
            _buildRawGrid(build), //just display the same grid twice for testing
            _buildRawGrid(build)
          ]
        ),
      ),
    );
  }
```

<p>I know this sort of scrolling is driven by calls to <code>RenderObject.showOnScreen</code>, obviously with a duration of zero, so I attempted to create a <code>SingleChildRenderObjectWidget</code> with a subclass of <code>RenderProxyBox</code> that overrides the <code>RenderObject.showOnScreen</code> method to force a duration. Yet, no matter where I put this thing, around each individual grid item, around the grid, around the <code>PageView</code>, no animation ever shows during implicit scrolling, and in fact, my override method is never even called. It's like the call never propagates to it no matter where in the widget hierarchy it's placed.</p>

<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class RenderFocusSmoothScroll extends RenderProxyBox {
  RenderFocusSmoothScroll({RenderBox child}) : super(child);
  @override
  void showOnScreen({
    RenderObject descendant,
    Rect rect,
    Duration duration = Duration.zero,
    Curve curve = Curves.ease,
  }) {
    print("showOnScreen");
    super.showOnScreen(descendant: descendant, rect: rect, duration: Duration(milliseconds: 200), curve: Curves.ease);
  }
}

class FocusSmoothScroll extends SingleChildRenderObjectWidget {
  const FocusSmoothScroll({
    Key key,
    Widget child,
  })  : super(key: key, child: child);

  @override
  RenderFocusSmoothScroll createRenderObject(BuildContext context) {
    return RenderFocusSmoothScroll();
  }

  @override
  void updateRenderObject(BuildContext context, RenderFocusSmoothScroll renderObject) {

  }
}
</code>```

Documentation on implicit scrolling using the focus system is a bit lacking, as is documentation on properly overriding RenderObject methods to enforce custom handling of these propagating calls, so any assistance would be appreciated.

答:
Okay, I figured it out. Turns out the call to showOnScreen is actually in the framework's own FocusTraversalPolicy source code (lib/src/widgets/focus_traversal.dart). I never expected that, I thought the focus traversal policy was exclusively for establishing directionality relationships between widgets, not actually scrolling them onto the screen. I just needed to override the body of a particular function:

@protected
void _focusAndEnsureVisible(FocusNode node, {ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit}) {
  node.requestFocus();
  Scrollable.ensureVisible(node.context, alignment: 1.0, alignmentPolicy: alignmentPolicy);
}
```

<p>That call to <code>ensureVisible</code> includes no duration, hence, the target will instantly be scrolled to. I ended up needing to basically duplicate most of this module into my own project, since there's not any way to redirect the built-in <code>ReadingOrderTraversalPolicy</code> to use a different implementation of that module-private function. Not ideal of course, that function is obviously not intended to ever be overridden, but you absolutely can.</p>

<pre class="lang-dart prettyprint-override"><code>/// Overridden for smooth scrolling.
@protected
void _focusAndEnsureVisible(FocusNode node, {ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit}) {
  node.requestFocus();
  Scrollable.ensureVisible(
    node.context,
    alignment: 1.0,
    alignmentPolicy: alignmentPolicy,
    duration: Duration(milliseconds: 200),
    curve: Curves.ease,
  );
}
</code>```

So, duplicating the subclasses and mixins from that file and renaming ReadingOrderTraversalPolicy to SmoothReadingOrderTraversalPolicy, I ended up just sticking a DefaultFocusTraversal widget in the builder wrapper of my top level MaterialApp, as such:

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '...',
      theme: /* ... */,
      home: SplashView(),
      navigatorKey: Globals.rootNavigatorKey,
      initialRoute: '/splash',
      routes: <String, WidgetBuilder>{
        // ...
      },
      onGenerateRoute: _generateRoute,
      builder: (context, widget) => DefaultFocusTraversal(
        policy: SmoothReadingOrderTraversalPolicy(), //imported from my own copy
        child: Stack(children: [widget, /* ... */]),
      ),
    );
  }
```

And now implicit scrolling is smooth! If anybody else runs into this problem, I hope this will be helpful.

Thanks to @pskink for prompting me to look a bit deeper into where the method call was coming from, I was just stumped before I thought to look inside the traversal policy itself.

Body:
I'm currently adapting a Flutter app to work with Android TV devices. Documentation on this is sparse, but I've managed to feel my way through the process by using the accessibility focus system for directional navigation using the standard remote.

However, in one of my layouts I'm using a PageView containing some grids of items, the grid separated out into pages for better directional navigation ergonomics. As expected, creating a PageView with allowImplicitScrolling: true allows you to navigate between pages by moving the focus reticle off the side of the grid. However, implicit scrolling in any context never has any animation accompanying it, just transitioning to the next view position instantly. This ends up not looking very good. In reality, this same problem applies to all implicit scrolling, whether in a PageView, ListView, GridView, or any scrolling view at all.

Widget _buildPaginatedGrid(BuildContext build) {
    return SliverToBoxAdapter(
      child: Container(
        height: MediaQuery.of(build).size.height - gameHeroHeight(context),
        child: PageView(
          allowImplicitScrolling: true,
          controller: _pageController,
          children: [
            _buildRawGrid(build), //just display the same grid twice for testing
            _buildRawGrid(build)
          ]
        ),
      ),
    );
  }

I know this sort of scrolling is driven by calls to RenderObject.showOnScreen, obviously with a duration of zero, so I attempted to create a SingleChildRenderObjectWidget with a subclass of RenderProxyBox that overrides the RenderObject.showOnScreen method to force a duration. Yet, no matter where I put this thing, around each individual grid item, around the grid, around the PageView, no animation ever shows during implicit scrolling, and in fact, my override method is never even called. It's like the call never propagates to it no matter where in the widget hierarchy it's placed.

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class RenderFocusSmoothScroll extends RenderProxyBox {
  RenderFocusSmoothScroll({RenderBox child}) : super(child);
  @override
  void showOnScreen({
    RenderObject descendant,
    Rect rect,
    Duration duration = Duration.zero,
    Curve curve = Curves.ease,
  }) {
    print("showOnScreen");
    super.showOnScreen(descendant: descendant, rect: rect, duration: Duration(milliseconds: 200), curve: Curves.ease);
  }
}

class FocusSmoothScroll extends SingleChildRenderObjectWidget {
  const FocusSmoothScroll({
    Key key,
    Widget child,
  })  : super(key: key, child: child);

  @override
  RenderFocusSmoothScroll createRenderObject(BuildContext context) {
    return RenderFocusSmoothScroll();
  }

  @override
  void updateRenderObject(BuildContext context, RenderFocusSmoothScroll renderObject) {

  }
}

Documentation on implicit scrolling using the focus system is a bit lacking, as is documentation on properly overriding RenderObject methods to enforce custom handling of these propagating calls, so any assistance would be appreciated.

Body:
Okay, I figured it out. Turns out the call to showOnScreen is actually in the framework's own FocusTraversalPolicy source code (lib/src/widgets/focus_traversal.dart). I never expected that, I thought the focus traversal policy was exclusively for establishing directionality relationships between widgets, not actually scrolling them onto the screen. I just needed to override the body of a particular function:

@protected
void _focusAndEnsureVisible(FocusNode node, {ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit}) {
  node.requestFocus();
  Scrollable.ensureVisible(node.context, alignment: 1.0, alignmentPolicy: alignmentPolicy);
}

That call to ensureVisible includes no duration, hence, the target will instantly be scrolled to. I ended up needing to basically duplicate most of this module into my own project, since there's not any way to redirect the built-in ReadingOrderTraversalPolicy to use a different implementation of that module-private function. Not ideal of course, that function is obviously not intended to ever be overridden, but you absolutely can.

/// Overridden for smooth scrolling.
@protected
void _focusAndEnsureVisible(FocusNode node, {ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit}) {
  node.requestFocus();
  Scrollable.ensureVisible(
    node.context,
    alignment: 1.0,
    alignmentPolicy: alignmentPolicy,
    duration: Duration(milliseconds: 200),
    curve: Curves.ease,
  );
}

So, duplicating the subclasses and mixins from that file and renaming ReadingOrderTraversalPolicy to SmoothReadingOrderTraversalPolicy, I ended up just sticking a DefaultFocusTraversal widget in the builder wrapper of my top level MaterialApp, as such:

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '...',
      theme: /* ... */,
      home: SplashView(),
      navigatorKey: Globals.rootNavigatorKey,
      initialRoute: '/splash',
      routes: <String, WidgetBuilder>{
        // ...
      },
      onGenerateRoute: _generateRoute,
      builder: (context, widget) => DefaultFocusTraversal(
        policy: SmoothReadingOrderTraversalPolicy(), //imported from my own copy
        child: Stack(children: [widget, /* ... */]),
      ),
    );
  }

And now implicit scrolling is smooth! If anybody else runs into this problem, I hope this will be helpful.

Thanks to @pskink for prompting me to look a bit deeper into where the method call was coming from, I was just stumped before I thought to look inside the traversal policy itself.


问:
How can I enter time for time durations with specific timestamps into bins in python?
I am fairly new to python and I am looking for an efficient way to organize time in designated bins. I have a table with [start_time] and [duration]. I want to fill the time spent in each hourly interval based on this table.
Example: if I have this table,

```<code>start_time  duration
12:25         1:00
13:35         0:15
14:03         0:20
15:40         0:10
16:15         1:05
17:30         0:40
</code>```

then the expected output is

```<code>    bins          time
12:00 - 13:00     0:35
13:00 - 14:00     0:40
14:00 - 15:00     0:20
15:00 - 16:00     0:10
16:00 - 17:00     0:45
17:00 - 18:00     0:50
18:00 - 19:00     0:10
19:00 - 20:00     0:00
</code>```

I would appreciate any help on this task! :)

答:
The python-ranges library I wrote a while ago could be useful for this:

```<code>from ranges import Range, RangeSet
from datetime import datetime, timedelta
from functools import reduce

# times, transcribed from above
# and converted to datetimes (so that we can use timedelta math)
times = [
    (datetime(1, 1, 1, 12, 25), timedelta(hours=1)),     # (12:25, 1:00),
    (datetime(1, 1, 1, 13, 35), timedelta(minutes=15)),  # (13:35, 0:15),
    (datetime(1, 1, 1, 14, 3),  timedelta(minutes=20)),  # (14:03, 0:20),
    (datetime(1, 1, 1, 15, 40), timedelta(minutes=10)),  # (15:40, 0:10),
    (datetime(1, 1, 1, 16, 15), timedelta(minutes=65)),  # (16:15, 1:05),
    (datetime(1, 1, 1, 17, 30), timedelta(minutes=40)),  # (17:30, 0:40),
]

# make a RangeSet that encompasses the entire day
wholeDay = RangeSet(Range(datetime(1, 1, 1, 12, 00), datetime(1, 1, 1, 20, 00)))

# remove our times from the whole day
wholeDay -= [Range(start, start + duration) for (start, duration) in times]

# get a list of correspondences with timedeltas
bins = {}
for h in range(12, 20):
    # create the 1-hour-long range
    period = Range(datetime(1, 1, 1, h), datetime(1, 1, 1, h + 1))
    # compute number of minutes in this range *were consumed* during the whole day
    # which is the same as the number of minutes in this period that are not contained in wholeDay
    #   (in other words, the length of the set difference)
    # We have to do this roundabout counting-second method,
    #   because timedelta() doesn't work with sum() natively
    time_seconds = sum(rng.length().seconds for rng in period.difference(wholeDay))
    # finally, add to dict
    bins[period] = timedelta(seconds=time_seconds)
</code>```

This produces the following bins:

```<code>{Range[datetime.datetime(1, 1, 1, 12, 0), datetime.datetime(1, 1, 1, 13, 0)): datetime.timedelta(seconds=2100),
 Range[datetime.datetime(1, 1, 1, 13, 0), datetime.datetime(1, 1, 1, 14, 0)): datetime.timedelta(seconds=2400),
 Range[datetime.datetime(1, 1, 1, 14, 0), datetime.datetime(1, 1, 1, 15, 0)): datetime.timedelta(seconds=1200),
 Range[datetime.datetime(1, 1, 1, 15, 0), datetime.datetime(1, 1, 1, 16, 0)): datetime.timedelta(seconds=600),
 Range[datetime.datetime(1, 1, 1, 16, 0), datetime.datetime(1, 1, 1, 17, 0)): datetime.timedelta(seconds=2700),
 Range[datetime.datetime(1, 1, 1, 17, 0), datetime.datetime(1, 1, 1, 18, 0)): datetime.timedelta(seconds=3000),
 Range[datetime.datetime(1, 1, 1, 18, 0), datetime.datetime(1, 1, 1, 19, 0)): datetime.timedelta(seconds=600),
 Range[datetime.datetime(1, 1, 1, 19, 0), datetime.datetime(1, 1, 1, 20, 0)): datetime.timedelta(0)}
</code>```

which is your intended output, represented by datetimes.

Body:
I am fairly new to python and I am looking for an efficient way to organize time in designated bins. I have a table with [start_time] and [duration]. I want to fill the time spent in each hourly interval based on this table.
Example: if I have this table,

start_time  duration
12:25         1:00
13:35         0:15
14:03         0:20
15:40         0:10
16:15         1:05
17:30         0:40

then the expected output is

    bins          time
12:00 - 13:00     0:35
13:00 - 14:00     0:40
14:00 - 15:00     0:20
15:00 - 16:00     0:10
16:00 - 17:00     0:45
17:00 - 18:00     0:50
18:00 - 19:00     0:10
19:00 - 20:00     0:00

I would appreciate any help on this task! :)

Body:
The python-ranges library I wrote a while ago could be useful for this:

from ranges import Range, RangeSet
from datetime import datetime, timedelta
from functools import reduce

# times, transcribed from above
# and converted to datetimes (so that we can use timedelta math)
times = [
    (datetime(1, 1, 1, 12, 25), timedelta(hours=1)),     # (12:25, 1:00),
    (datetime(1, 1, 1, 13, 35), timedelta(minutes=15)),  # (13:35, 0:15),
    (datetime(1, 1, 1, 14, 3),  timedelta(minutes=20)),  # (14:03, 0:20),
    (datetime(1, 1, 1, 15, 40), timedelta(minutes=10)),  # (15:40, 0:10),
    (datetime(1, 1, 1, 16, 15), timedelta(minutes=65)),  # (16:15, 1:05),
    (datetime(1, 1, 1, 17, 30), timedelta(minutes=40)),  # (17:30, 0:40),
]

# make a RangeSet that encompasses the entire day
wholeDay = RangeSet(Range(datetime(1, 1, 1, 12, 00), datetime(1, 1, 1, 20, 00)))

# remove our times from the whole day
wholeDay -= [Range(start, start + duration) for (start, duration) in times]

# get a list of correspondences with timedeltas
bins = {}
for h in range(12, 20):
    # create the 1-hour-long range
    period = Range(datetime(1, 1, 1, h), datetime(1, 1, 1, h + 1))
    # compute number of minutes in this range *were consumed* during the whole day
    # which is the same as the number of minutes in this period that are not contained in wholeDay
    #   (in other words, the length of the set difference)
    # We have to do this roundabout counting-second method,
    #   because timedelta() doesn't work with sum() natively
    time_seconds = sum(rng.length().seconds for rng in period.difference(wholeDay))
    # finally, add to dict
    bins[period] = timedelta(seconds=time_seconds)

This produces the following bins:

{Range[datetime.datetime(1, 1, 1, 12, 0), datetime.datetime(1, 1, 1, 13, 0)): datetime.timedelta(seconds=2100),
 Range[datetime.datetime(1, 1, 1, 13, 0), datetime.datetime(1, 1, 1, 14, 0)): datetime.timedelta(seconds=2400),
 Range[datetime.datetime(1, 1, 1, 14, 0), datetime.datetime(1, 1, 1, 15, 0)): datetime.timedelta(seconds=1200),
 Range[datetime.datetime(1, 1, 1, 15, 0), datetime.datetime(1, 1, 1, 16, 0)): datetime.timedelta(seconds=600),
 Range[datetime.datetime(1, 1, 1, 16, 0), datetime.datetime(1, 1, 1, 17, 0)): datetime.timedelta(seconds=2700),
 Range[datetime.datetime(1, 1, 1, 17, 0), datetime.datetime(1, 1, 1, 18, 0)): datetime.timedelta(seconds=3000),
 Range[datetime.datetime(1, 1, 1, 18, 0), datetime.datetime(1, 1, 1, 19, 0)): datetime.timedelta(seconds=600),
 Range[datetime.datetime(1, 1, 1, 19, 0), datetime.datetime(1, 1, 1, 20, 0)): datetime.timedelta(0)}

which is your intended output, represented by datetimes.


问:
C++: How do I assign a value from a 2D dynamic array to another 2D dynamic array since 'temp[0][0] = array[0][0]' doesn't work?
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!</p>

```<code>    ...
    //initializing first 2D dynamic array
    int x=2;
    int y=2;
    int** array = new int*[x];
    for(int i=0; i<x; i++) array[i] = new int[y];

    //initializing second 2D dynamic array
    int new_x=3;
    int new_y=3;
    int** temp = new int*[new_x];
    for(int i=0; i<new_x; i++) temp[i] = new int[new_y];

    //assigning values
    array[0][0] = 1;
    cout << array[0][0] << endl; //output is 1

    //before assigning values to temp[0][0]
    cout << temp[0][0] << endl; //out is a huge random number

    temp[0][0] = array[0][0];
    cout << temp[0][0] << endl; //output is the same huge random number

    temp[0][0] = 2;
    cout << temp[0][0] << endl; //output is 2
    ...
</code>```

答: Memory under temp[0][0] is allocated dynamically, therefore that's why you're getting some random (garbage) stuff out of it before assigning 2. When you're assigning 2, the random garbage that's been there gets "overwritten" by a meaningful value, in your case 2 of int type</p>

Body:
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!

    ...
    //initializing first 2D dynamic array
    int x=2;
    int y=2;
    int** array = new int*[x];
    for(int i=0; i<x; i++) array[i] = new int[y];

    //initializing second 2D dynamic array
    int new_x=3;
    int new_y=3;
    int** temp = new int*[new_x];
    for(int i=0; i<new_x; i++) temp[i] = new int[new_y];

    //assigning values
    array[0][0] = 1;
    cout << array[0][0] << endl; //output is 1

    //before assigning values to temp[0][0]
    cout << temp[0][0] << endl; //out is a huge random number

    temp[0][0] = array[0][0];
    cout << temp[0][0] << endl; //output is the same huge random number

    temp[0][0] = 2;
    cout << temp[0][0] << endl; //output is 2
    ...


问:
pyspark cache() dataframe issue
I have program written in order to parallelize the process, cache has been applied after certain transformations on dataframe's. Lets say:

```<code>df1 = df.filter()
df3 = df1.join(df2, join_cond, "left")
df3.cache()    #ex: it has col1, col2, col3, col4 columns

After cache, we have some other steps to take care:
#1
df4 = df3.select(df3.col1, df3.col2)
df4.filter(df3.col1 > 500).show()
#2
df5 = df3.select(df3.col3, df3.col4)
df5.filter(df3.col4 > 2000)

df3.unpersist()
</code>```

So, in this process if any issue or error occurs we have to uncache the dataframe or the old cache will destroy automatically when we are rerunning the program.

Could you please help me how the cache() will work if there is any kind of failures in the program at a certain point of time.

Thanks

答:
cache persists the lazy evaluation result in memory, so after the cache, any transformation could directly from scanning the df in memory and start working.

action vs transformation, action leads to a non-rdd non-df object like in your code .show(), transformation leads to another rdd/spark df, like in your code .filter, .select, .join

just based on your code snippet, there is no problem, your df4's dependency is just scanned df3 -> df4 and there is just one action. But if you want to call df5.filter().show() or df4.show() again, it will become a problem. Because you unpersist df3, there is no data in memory, in order to regenerate df4, the spark application need to start from df1 -> df2 -> df3 -> df4.

Does unpersist break your code? no, but definitely influence your performance of your application. I will double-check whether a persisted df is no longer needed in any further downstream job, then unpersist it

Title: pyspark cache() dataframe issue

Body:
I have program written in order to parallelize the process, cache has been applied after certain transformations on dataframe's. Lets say:

df1 = df.filter()
df3 = df1.join(df2, join_cond, "left")
df3.cache()    #ex: it has col1, col2, col3, col4 columns

After cache, we have some other steps to take care:
#1
df4 = df3.select(df3.col1, df3.col2)
df4.filter(df3.col1 > 500).show()
#2
df5 = df3.select(df3.col3, df3.col4)
df5.filter(df3.col4 > 2000)

df3.unpersist()

So, in this process if any issue or error occurs we have to uncache the dataframe or the old cache will destroy automatically when we are rerunning the program.

Could you please help me how the cache() will work if there is any kind of failures in the program at a certain point of time.

Thanks


问:
Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?
I am trying to follow the docs on https://material.angular.io/components/component/dialog but I cannot understand why it has the below issue?

I added the below on my component:

@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: './dialog-result-example-dialog.html',
})
export class DialogResultExampleDialog {
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {}
}
```

<p>In my module I added </p>

<pre class="lang-js prettyprint-override"><code>import { HomeComponent,DialogResultExampleDialog } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    HomeComponent,
    DialogResultExampleDialog
  ],

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

Yet I get this error....

EXCEPTION: Error in ./HomeComponent class HomeComponent - inline template:53:0 caused by: No component factory found for DialogResultExampleDialog. Did you add it to @NgModule.entryComponents?
    ErrorHandler.handleError @ error_handler.js:50
    next @ application_ref.js:346
    schedulerFn @ async.js:91
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
    SafeSubscriber.next @ Subscriber.js:172
    Subscriber._next @ Subscriber.js:125
    Subscriber.next @ Subscriber.js:89
    Subject.next @ Subject.js:55
    EventEmitter.emit @ async.js:77
    NgZone.triggerError @ ng_zone.js:329
    onHandleError @ ng_zone.js:290
    ZoneDelegate.handleError @ zone.js:246
    Zone.runTask @ zone.js:154
    ZoneTask.invoke @ zone.js:345
    error_handler.js:52 ORIGINAL EXCEPTION: No component factory found for DialogResultExampleDialog. Did you add it to @NgModule.entryComponents?
    ErrorHandler.handleError @ error_handler.js:52
    next @ application_ref.js:346
    schedulerFn @ async.js:91
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
    SafeSubscriber.next @ Subscriber.js:172
    Subscriber._next @ Subscriber.js:125
    Subscriber.next @ Subscriber.js:89
    Subject.next @ Subject.js:55
    EventEmitter.emit @ async.js:77
    NgZone.triggerError @ ng_zone.js:329
    onHandleError @ ng_zone.js:290
    ZoneDelegate.handleError @ zone.js:246
    Zone.runTask @ zone.js:154
    ZoneTask.invoke @ zone.js:345
```

答:
If someone needs to call Dialog from services here is how to solve the issue.
I agree with some of above answer, my answer is for calling dialog in services if someone may face issues on.

Create a service for example DialogService then move your dialog function inside the services and add your dialogservice in the component you call like below code:

```<code> @Component({
  selector: "app-newsfeed",
  templateUrl: "./abc.component.html",
  styleUrls: ["./abc.component.css",],
  providers:[DialogService]
})
</code>```

otherwise you get error

Body:
I am trying to follow the docs on https://material.angular.io/components/component/dialog but I cannot understand why it has the below issue?

I added the below on my component:

@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: './dialog-result-example-dialog.html',
})
export class DialogResultExampleDialog {
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {}
}

In my module I added

import { HomeComponent,DialogResultExampleDialog } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    HomeComponent,
    DialogResultExampleDialog
  ],

// ...

Yet I get this error....

EXCEPTION: Error in ./HomeComponent class HomeComponent - inline template:53:0 caused by: No component factory found for DialogResultExampleDialog. Did you add it to @NgModule.entryComponents?
    ErrorHandler.handleError @ error_handler.js:50
    next @ application_ref.js:346
    schedulerFn @ async.js:91
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
    SafeSubscriber.next @ Subscriber.js:172
    Subscriber._next @ Subscriber.js:125
    Subscriber.next @ Subscriber.js:89
    Subject.next @ Subject.js:55
    EventEmitter.emit @ async.js:77
    NgZone.triggerError @ ng_zone.js:329
    onHandleError @ ng_zone.js:290
    ZoneDelegate.handleError @ zone.js:246
    Zone.runTask @ zone.js:154
    ZoneTask.invoke @ zone.js:345
    error_handler.js:52 ORIGINAL EXCEPTION: No component factory found for DialogResultExampleDialog. Did you add it to @NgModule.entryComponents?
    ErrorHandler.handleError @ error_handler.js:52
    next @ application_ref.js:346
    schedulerFn @ async.js:91
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
    SafeSubscriber.next @ Subscriber.js:172
    Subscriber._next @ Subscriber.js:125
    Subscriber.next @ Subscriber.js:89
    Subject.next @ Subject.js:55
    EventEmitter.emit @ async.js:77
    NgZone.triggerError @ ng_zone.js:329
    onHandleError @ ng_zone.js:290
    ZoneDelegate.handleError @ zone.js:246
    Zone.runTask @ zone.js:154
    ZoneTask.invoke @ zone.js:345

Body:
If someone needs to call Dialog from services here is how to solve the issue.
I agree with some of above answer, my answer is for calling dialog in services if someone may face issues on.

Create a service for example DialogService then move your dialog function inside the services and add your dialogservice in the component you call like below code:

 @Component({
  selector: "app-newsfeed",
  templateUrl: "./abc.component.html",
  styleUrls: ["./abc.component.css",],
  providers:[DialogService]
})

otherwise you get error


问:
CPLEX vs Constraint Programming Solution for a linearly constrained MIP with a nonlinear objective(division)
I am trying to solve an MIP with a non-linear objective such as sum(a(i)*x(i))/sum(b(i)*x(i)) where a(i) and b(i) are parameters. Since CPLEX cannot extract this expression, I tried using CP.

However, I have constraint stating that the decision variable x(i) should be a multiplier of 2.5, therefore a float. Since CP cannot handle floats, I set x to be an integer, and implied to be multiplier of 25. In every other constraint and expression I divided x by 10, so that the calculations remained the same.

First, I solved the model with the multiplier 5, I got a solution with a very small gap, which is fine. When I changed the multiplier to 25, the model cannot terminated within 2 hours (stucked with a gap of 90%). I believe this happened due to scaling, but still cannot figure it out, since I am not familiar with the CP algorithm.

I am still working to linearize the oblective but, any suggestion on both CPLEX and CP engine solutions will be highly appreciated.
Thanks in advance.

答:
have you tried to turn equalities into inequalities to allow some flexibility ?

For instance

```<code>using CP;

int scale=1000;
dvar int scalex in 0..2000;
dexpr float x=scalex/scale;

subject to
 {
   x*x==2;
 }
</code>```

gives no solution whereas

```<code>using CP;

float epsilon=0.001;

int scale=1000;
dvar int scalex in 0..2000;
dexpr float x=scalex/scale;

subject to
 {
   abs(x*x-2)<=epsilon;
 }
</code>```

gives

x=1.414

and

```<code>using CP;

{int} hm=asSet(1..4);
float epsilon=0.001;

dvar int scalex[1..card(hm)] in 0..20000;
int scale=10000;

dexpr float A[ i in 1..card(hm)]=scalex[i]/scale;
subject to
{
  forall(i in 1..card(hm))abs(A[i]*A[i]-2)<=epsilon;
}
</code>```

works fine too

Body:
have you tried to turn equalities into inequalities to allow some flexibility ?

For instance

using CP;

int scale=1000;
dvar int scalex in 0..2000;
dexpr float x=scalex/scale;

subject to
 {
   x*x==2;
 }

gives no solution whereas

using CP;

float epsilon=0.001;

int scale=1000;
dvar int scalex in 0..2000;
dexpr float x=scalex/scale;

subject to
 {
   abs(x*x-2)<=epsilon;
 }

gives

x=1.414

and

using CP;

{int} hm=asSet(1..4);
float epsilon=0.001;

dvar int scalex[1..card(hm)] in 0..20000;
int scale=10000;

dexpr float A[ i in 1..card(hm)]=scalex[i]/scale;
subject to
{
  forall(i in 1..card(hm))abs(A[i]*A[i]-2)<=epsilon;
}

works fine too