问:
TypeError: Cannot read property 'prototype' of undefined React Express
I have a project uses Express and react, Everything was working fine,

I didn't make any changes to the code suddenly it starts to give this error.

In the previous days, I have upgraded node from 10.15.0 to 12.x and added Axios.

I tested after those changes and it works. now it does not, what this mean??

```<code>
TypeError: Cannot read property 'prototype' of undefined
(anonymous function)
C:/Desktop/ahmad/client/node_modules/express/lib/response.js:42
  39 |  * @public
  40 |  */
  41 |
> 42 | var res = Object.create(http.ServerResponse.prototype)
  43 |
  44 | /**
  45 |  * Module exports.
*/

View compiled
./node_modules/express/lib/response.js
http://localhost:3000/static/js/bundle.js:28181:30
__webpack_require__
C:/.../ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:678
  675 | };
  676 |
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 |
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
C:/.../ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled
./node_modules/express/lib/express.js
C:/.../Desktop/ahmad/client/node_modules/express/lib/express.js:22
  19 | var Route = require('./router/route');
  20 | var Router = require('./router');
  21 | var req = require('./request');
> 22 | var res = require('./response');
  23 |
  24 | /**
  25 |  * Expose `createApplication()`.
*/
View compiled
__webpack_require__
C:/.../Desktop/ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:678
  675 | };
  676 |
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 |
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
C:/.../Desktop/ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled
</code>```

答:
import response from { 'express' };
got imported
in your actions page by default by "vs code"</p>

Body:
I have a project uses Express and react, Everything was working fine,

I didn't make any changes to the code suddenly it starts to give this error.

In the previous days, I have upgraded node from 10.15.0 to 12.x and added Axios.

I tested after those changes and it works. now it does not, what this mean??

TypeError: Cannot read property 'prototype' of undefined
(anonymous function)
C:/Desktop/ahmad/client/node_modules/express/lib/response.js:42
  39 |  * @public
  40 |  */
  41 |
> 42 | var res = Object.create(http.ServerResponse.prototype)
  43 |
  44 | /**
  45 |  * Module exports.
*/

View compiled
./node_modules/express/lib/response.js
http://localhost:3000/static/js/bundle.js:28181:30
__webpack_require__
C:/.../ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:678
  675 | };
  676 |
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 |
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
C:/.../ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled
./node_modules/express/lib/express.js
C:/.../Desktop/ahmad/client/node_modules/express/lib/express.js:22
  19 | var Route = require('./router/route');
  20 | var Router = require('./router');
  21 | var req = require('./request');
> 22 | var res = require('./response');
  23 |
  24 | /**
  25 |  * Expose `createApplication()`.
*/
View compiled
__webpack_require__
C:/.../Desktop/ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:678
  675 | };
  676 |
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 |
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
C:/.../Desktop/ahmad/client/webpack/bootstrap 4501180ca3adc0d915c0:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled


来源: stackexchange

问:
Adding information to JWT token body using django rest framework jwt
Im using django rest framework and the djangorestframework-jwt package to creat JWT tokens for authorization.

On the frontend I can decode the token and get the username, email and user_id. However I would like to retrieve some extra information. For example it would be very convenient if I could get kind which is a field on our authorization model (user model).

I can ofcourse make a separate request to get the user info via a regular APIView. But I'm wondering if it's possible to add some extra params in the JWT body?

答:
Using the djangorestframework_simplejwt library

Specify in settings.py the USER_ID_FIELD and ALGORITHM

```<code>SIMPLE_JWT = {
    'USER_ID_FIELD': 'user_id',
    'ALGORITHM': 'HS512',
}
</code>```

Let's say you want to add fields to the body of TokenObtainPairView which has the following body

```<code>{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU5MDk5ODAwMSwianRpIjoiMjZhZThhYTU4YTJiNDU3M2JlMDgxNTMzMzU1ODg4ZmUiLCJ1c2VyX2lkIjoxMX0.-jUCnfpTF-RsqHnuoEgctPpHf1SfYNcYaPs8oo01RvrQBMcyhms5PfWipfYkaR0FlPHSTKncNeMxomwd4k7nyg",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTExOTAxLCJqdGkiOiI5NjZkOTFhNzEzNjg0NjMyOGUzYWU3NThiNzNiZmYxMyIsInVzZXJfaWQiOjExfQ.LiHrekmlHrM7_5187ghpIaA6mKcPCjDz4MDKPXHc4QAKVGvcJCJpCjrODCB4-pZn4Kuai5ht3YjWwYSirxpsXw"
}
</code>```

Add in your urls.py

```<code>path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'),
</code>```

Create the MyTokenObtainPairView

```<code>class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer`
</code>```

Create the MyTokenObtainPairSerializer

```<code>class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh)
        data.pop('refresh', None) # remove refresh from the payload
        data['access'] = str(refresh.access_token)

        # Add extra responses here
        data['user'] = self.user.username
        data['kind'] = self.user.kind
        data['date'] = datetime.date.today()
        return data
</code>```

This way when you post to /api/token/ you'll get in the body something like this

```<code>{
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNTc0LCJqdGkiOiIwM2Q5MzA1NTZmNzk0NmFjODU1MzJlNTYzNjUwZDY0MCIsInVzZXJfaWQiOjExfQ.H0huO84qtzdbo4OkKhsW_vtNTGwInG67gum6f138h1y66EiyZ1BvxaxbfEE2oPG4pB0XjiWQrXc5PlR9C6UvfQ",
    "user": "tiago",
    "kind": "whatever_this_has"
    "date": "2020-05-31"
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using the djangorestframework_simplejwt library

Specify in settings.py the USER_ID_FIELD and ALGORITHM

SIMPLE_JWT = {
    'USER_ID_FIELD': 'user_id',
    'ALGORITHM': 'HS512',
}

Let's say you want to add fields to the body of TokenObtainPairView which has the following body

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU5MDk5ODAwMSwianRpIjoiMjZhZThhYTU4YTJiNDU3M2JlMDgxNTMzMzU1ODg4ZmUiLCJ1c2VyX2lkIjoxMX0.-jUCnfpTF-RsqHnuoEgctPpHf1SfYNcYaPs8oo01RvrQBMcyhms5PfWipfYkaR0FlPHSTKncNeMxomwd4k7nyg",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTExOTAxLCJqdGkiOiI5NjZkOTFhNzEzNjg0NjMyOGUzYWU3NThiNzNiZmYxMyIsInVzZXJfaWQiOjExfQ.LiHrekmlHrM7_5187ghpIaA6mKcPCjDz4MDKPXHc4QAKVGvcJCJpCjrODCB4-pZn4Kuai5ht3YjWwYSirxpsXw"
}

Add in your urls.py

path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'),

Create the MyTokenObtainPairView

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer`

Create the MyTokenObtainPairSerializer

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh)
        data.pop('refresh', None) # remove refresh from the payload
        data['access'] = str(refresh.access_token)

        # Add extra responses here
        data['user'] = self.user.username
        data['kind'] = self.user.kind
        data['date'] = datetime.date.today()
        return data

This way when you post to /api/token/ you'll get in the body something like this

{
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNTc0LCJqdGkiOiIwM2Q5MzA1NTZmNzk0NmFjODU1MzJlNTYzNjUwZDY0MCIsInVzZXJfaWQiOjExfQ.H0huO84qtzdbo4OkKhsW_vtNTGwInG67gum6f138h1y66EiyZ1BvxaxbfEE2oPG4pB0XjiWQrXc5PlR9C6UvfQ",
    "user": "tiago",
    "kind": "whatever_this_has"
    "date": "2020-05-31"
}


问:
How to convert string into binary
I want to convert a string into binary codes, I try to use

```<code>test_str = "a"

res = ''.join(format(ord(i), 'b') for i in test_str)

</code>```

and I get 1100001, but I don't need the first two bits '11' which is used to distinguish capital and lower, I only need '00001', how can I do this?

答:
You can remove the first two digits like this</p>

```<code>res = res[2:]
</code>```

Title: How to convert string into binary

Body:
I want to convert a string into binary codes, I try to use

test_str = "a"

res = ''.join(format(ord(i), 'b') for i in test_str)

and I get 1100001, but I don't need the first two bits '11' which is used to distinguish capital and lower, I only need '00001', how can I do this?

Body:
You can remove the first two digits like this

res = res[2:]


问:
Why we actually need runtime polymorphism?
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.

Like, suppose this was a problem.

```<code>#include <bits/stdc++.h>
using namespace std;
class base{
    public:
        virtual void fun(){
            cout<<"base called"<<endl;
        }
};
class derived:public base{
    public:
        void fun(){
            cout<<"derived called"<<endl;
        }
};
int main() {

    base b,*b1;
    derived d;
    b1 = &d;
    b1->fun();
    // b.fun();
    // d.fun();
}
</code>```

suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism).
Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??

答:
Suppose you have a library which has a class and few methods which takes a pointer to that class.

```<code>class GameObject {
public:
    virtual void paint(void);

public:
    void print_to_display(void);

};

class Game {

public:
    void add_obj(GameObject *obj);
};
</code>```

Since, you just have the library (shared library and few header files) and you don't want to modify the libraries source code (as it may break existing method).

You can extend the class GameObject in your project and override it's print method to do something other than the default behavior.

```<code>class MyObject: public GameObject {

public:
    void paint(void) override;
};
</code>```

Body:
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.

Like, suppose this was a problem.

#include <bits/stdc++.h>
using namespace std;
class base{
    public:
        virtual void fun(){
            cout<<"base called"<<endl;
        }
};
class derived:public base{
    public:
        void fun(){
            cout<<"derived called"<<endl;
        }
};
int main() {

    base b,*b1;
    derived d;
    b1 = &d;
    b1->fun();
    // b.fun();
    // d.fun();
}

suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism).
Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??

Body:
Suppose you have a library which has a class and few methods which takes a pointer to that class.

class GameObject {
public:
    virtual void paint(void);

public:
    void print_to_display(void);

};

class Game {

public:
    void add_obj(GameObject *obj);
};

Since, you just have the library (shared library and few header files) and you don't want to modify the libraries source code (as it may break existing method).

You can extend the class GameObject in your project and override it's print method to do something other than the default behavior.

class MyObject: public GameObject {

public:
    void paint(void) override;
};


问:
How can be this if statement error removed?

name= input("Enter user name: ")
marks=float(input("Enter user's marks: "))
if marks>=75 :
    grade="Distinction"
elif 60<=marks<=75 :
    grade= "First Division"
elif 45<=marks<60:
    grade="Pass"
else:
    grade="Fail"
print("{} you have got {}!".format(name,grade))
```

<p>Error:</p>

```if marks>=75 :
             ^
SyntaxError: invalid syntax
```

I am not able to post this code in code segment, Please review the snapshot and suggest.

答:
That's because of the previous line.

You need to add a ) to the previous line.

marks = float(input("Enter user's mark"))
```

Body:
name= input("Enter user name: ")
marks=float(input("Enter user's marks: "))
if marks>=75 :
    grade="Distinction"
elif 60<=marks<=75 :
    grade= "First Division"
elif 45<=marks<60:
    grade="Pass"
else:
    grade="Fail"
print("{} you have got {}!".format(name,grade))

Error:

if marks>=75 :
             ^
SyntaxError: invalid syntax

I am not able to post this code in code segment, Please review the snapshot and suggest.


问:
How to create a DataFrame from two lists with multiple operations
I have two lists,

```<code>A=[a1, a2, a3, a4]
B=[b1, b2, b3, b4]
</code>```

I want to convert this to a dataframe C, where

```<code>C1      C2     C3     C4
a1*b1    0      0      0
a1*b2  a2*b1    0      0
a1*b3  a2*b2  a3*b1    0
a1*b4  a2*b3  a3*b2  a4*b1
</code>```

答:
Something like this should work</p>

```<code>import numpy as np
import pandas as pd

A = np.array(A)
B = np.array(B)

columns = ["C"+str(i) for i in range(1,len(A)+1)]

rows = []
for row in range(0,len(A)):
    if row == 0:
        rows += [A[row]*B]
    else:
        rows += [A[row]*np.array([0]*row + B[:-row].tolist())]

df = pd.DataFrame(np.array(rows).T, columns=columns)
</code>```

Body:
I have two lists,

A=[a1, a2, a3, a4]
B=[b1, b2, b3, b4]

I want to convert this to a dataframe C, where

C1      C2     C3     C4
a1*b1    0      0      0
a1*b2  a2*b1    0      0
a1*b3  a2*b2  a3*b1    0
a1*b4  a2*b3  a3*b2  a4*b1

Body:
Something like this should work

import numpy as np
import pandas as pd

A = np.array(A)
B = np.array(B)

columns = ["C"+str(i) for i in range(1,len(A)+1)]

rows = []
for row in range(0,len(A)):
    if row == 0:
        rows += [A[row]*B]
    else:
        rows += [A[row]*np.array([0]*row + B[:-row].tolist())]

df = pd.DataFrame(np.array(rows).T, columns=columns)


问:
Getting Java- and Javascript-generated charts to look similar
I'm having the following scenario: I'm displaying charts in the client side using the Javascript chart library Raphael. On clicking download I need to generate the same chart into pdf and display it to the user. I'm using JFreeChart to create charts on the server side. The problem is that since I'm using two different chart libraries, both look different. What is the solution for this?

The chart should be free for commercial use.

答:
4 options here :

Use Google Chart. http://code.google.com/apis/chart/

JQuery Chart. http://www.1stwebdesigner.com/css/top-jquery-chart-libraries-interactive-charts/

Create Applet, use your JFreeChart and put it on the applet. Then provide the data from javascript to the applet. (If you really insist to make a very similar UI)

On the servlet convert your chart to image, and store it in session. Later on, in your JSP, get the image from the session. check this link for the details. But this one won't exactly the same as option no 3.

ContentLicense: CC BY-SA 3.0


问:
Running a long rails console or rake task on Heroku
My rails application is hosted on Heroku. I'm trying to process data in my postgresql DB with a straightforward loop

```<code>  DocumentText.all.each do |t|
    if is_number? t.src
      puts t.src
      t.targ = t.src
      t.save
    end
  end
</code>```

The problem I have is my rails console will exit after running through some of my records (not all of them.) I have tried this as a rake task but same problem.

Why is this happening and what are my options?

答:
In your code snippet, you are running n update queries to the database which will take a lot of time and this is why your task is not fully running.

I would suggest running a single update query to the database. For that, add the following gem in your Gemfile

gem 'activerecord-import'

```<code>documents = []
DocumentText.all.each do |t|
  documents << t if is_number?(t.src)
end

# MySQL version
DocumentText.import(documents, on_duplicate_key_update: {targ: :src})

# PostgreSQL version (no shorthand version)
DocumentText.import([book], on_duplicate_key_update: {
  conflict_target: [:id], columns: {targ: :src}
})
</code>```

This should do the trick. If you have data in millions, then I would also recommend running this process in batches. Let me know if you need help with that.

Body:
My rails application is hosted on Heroku. I'm trying to process data in my postgresql DB with a straightforward loop

  DocumentText.all.each do |t|
    if is_number? t.src
      puts t.src
      t.targ = t.src
      t.save
    end
  end

The problem I have is my rails console will exit after running through some of my records (not all of them.) I have tried this as a rake task but same problem.

Why is this happening and what are my options?

Body:
In your code snippet, you are running n update queries to the database which will take a lot of time and this is why your task is not fully running.

I would suggest running a single update query to the database. For that, add the following gem in your Gemfile

gem 'activerecord-import'

documents = []
DocumentText.all.each do |t|
  documents << t if is_number?(t.src)
end

# MySQL version
DocumentText.import(documents, on_duplicate_key_update: {targ: :src})

# PostgreSQL version (no shorthand version)
DocumentText.import([book], on_duplicate_key_update: {
  conflict_target: [:id], columns: {targ: :src}
})

This should do the trick. If you have data in millions, then I would also recommend running this process in batches. Let me know if you need help with that.


问:
Passing data to searchstring parameter not working
I have issue when passing value as 'Text6=''locations''' to a parameter searchstring in C#.

It gives me error:

An expression of non-boolean type specified in a context where a condition is expected, near 'and'.

The problem is in the below function when passing value 'Text6=''locations''' to @searchstring it gives an error as shown.

```<code>{
"startdate": "2020-05-03T22:00:00Z",
"enddate": "2020-05-11T22:00:00Z",
"searchstring": "'Text6=''MFG'''",
"reportID": "2028"
}

public DataTable GetReportDetailsSearch(string ReportID, string FromDate, string ToDate, string SearchString)
      {

          List<SqlParameter> param = new List<SqlParameter>()
          {
              new SqlParameter("@ReportID", ReportID),
              new SqlParameter("@ReportDateFrom", FromDate),
              new SqlParameter("@ReportDateTo", ToDate),
              new SqlParameter("@SearchString",SearchString),

          };

  DataTable ReportDetailsSearch = SQLDAL.ReturnDataTableByProcedure("sp_ReportDetailsGetALL", param);
          return ReportDetailsSearch;
      }
</code>```

web API asp.net core 2.2

```<code>[Route("ReportDetailsSearch")]
       [HttpPost]
       public IActionResult GetSearchedData([FromBody] dynamic DataObjectSearch)
       {

           try
           {
               string ReportId = DataObjectSearch.reportID;
               string FromDate = DataObjectSearch.startdate;
               string StartDate = FromDate.Substring(0, 10);
               string todate = DataObjectSearch.enddate;
               string EndDate = todate.Substring(0, 10);
               string Searchdata = DataObjectSearch.searchstring;

               var PostSearch = _reportservice.GetReportDetailsSearch(ReportId, StartDate, EndDate, Searchdata);

               return Ok(PostSearch);

       }
</code>```

But on SQL Server it works successfully:

```<code> exec [dbo].[sp_ReportDetailsGetALL] "2028","2020-05-03","2020-05-11", 'Text6=''locations'''
</code>```

Procedure as below:

```<code>declare @ColumnName Nvarchar(max) = (SELECT 'select ' + STUFF((SELECT ',' + 'Text'+CONVERT(varchar(20),ReportHeaderIndex) + ' '+ '['+ReportHeader +']'
FROM ReportHeaders where ReportID=@ReportID order by ReportHeaderIndex
FOR XML PATH('')) ,1,1,'') + ' , convert(nvarchar(20),[ReportDate]) ReportDate From ReportDetails R where ReportDate >= ''' +@ReportDateFrom+''' and ReportDate <= '''+ @ReportDateTo +''' and R.ReportID =' + @ReportID + ' and '+@SearchString+' and IsHistory=0 order by reportdate desc ' + @SortingColumns AS Txt )
exec (@ColumnName)
</code>```

答:
my issue solved by pass data from front end to web API as below :</p>

```<code>searchstring = "Text6='MFG'"
</code>```

Body:
I have issue when passing value as 'Text6=''locations''' to a parameter searchstring in C#.

It gives me error:

An expression of non-boolean type specified in a context where a condition is expected, near 'and'.

The problem is in the below function when passing value 'Text6=''locations''' to @searchstring it gives an error as shown.

{
"startdate": "2020-05-03T22:00:00Z",
"enddate": "2020-05-11T22:00:00Z",
"searchstring": "'Text6=''MFG'''",
"reportID": "2028"
}

public DataTable GetReportDetailsSearch(string ReportID, string FromDate, string ToDate, string SearchString)
      {

          List<SqlParameter> param = new List<SqlParameter>()
          {
              new SqlParameter("@ReportID", ReportID),
              new SqlParameter("@ReportDateFrom", FromDate),
              new SqlParameter("@ReportDateTo", ToDate),
              new SqlParameter("@SearchString",SearchString),

          };

  DataTable ReportDetailsSearch = SQLDAL.ReturnDataTableByProcedure("sp_ReportDetailsGetALL", param);
          return ReportDetailsSearch;
      }

web API asp.net core 2.2

[Route("ReportDetailsSearch")]
       [HttpPost]
       public IActionResult GetSearchedData([FromBody] dynamic DataObjectSearch)
       {

           try
           {
               string ReportId = DataObjectSearch.reportID;
               string FromDate = DataObjectSearch.startdate;
               string StartDate = FromDate.Substring(0, 10);
               string todate = DataObjectSearch.enddate;
               string EndDate = todate.Substring(0, 10);
               string Searchdata = DataObjectSearch.searchstring;

               var PostSearch = _reportservice.GetReportDetailsSearch(ReportId, StartDate, EndDate, Searchdata);

               return Ok(PostSearch);

       }

But on SQL Server it works successfully:

 exec [dbo].[sp_ReportDetailsGetALL] "2028","2020-05-03","2020-05-11", 'Text6=''locations'''

Procedure as below:

declare @ColumnName Nvarchar(max) = (SELECT 'select ' + STUFF((SELECT ',' + 'Text'+CONVERT(varchar(20),ReportHeaderIndex) + ' '+ '['+ReportHeader +']'
FROM ReportHeaders where ReportID=@ReportID order by ReportHeaderIndex
FOR XML PATH('')) ,1,1,'') + ' , convert(nvarchar(20),[ReportDate]) ReportDate From ReportDetails R where ReportDate >= ''' +@ReportDateFrom+''' and ReportDate <= '''+ @ReportDateTo +''' and R.ReportID =' + @ReportID + ' and '+@SearchString+' and IsHistory=0 order by reportdate desc ' + @SortingColumns AS Txt )
exec (@ColumnName)

Body:
my issue solved by pass data from front end to web API as below :

searchstring = "Text6='MFG'"


问:
Multiple adress parameters in single page application
Sorry for the long post. My code is corrected by a bot and I get an error returned that I can't seem to work my way around.

In my code, I want to make so that you can you can visit #two-adress, followed two separate parameters like this: #/two/hello/world which generates
helloworld
.

This is my Vue code:

```<code>let One = Vue.component('one', {
  template: '<h1>One {{ $route.params.user }} </h1>'
})

let Two = Vue.component('two', {
  template: '<h1>Two</h1>'
})

let router = new VueRouter({
  routes: [{
    component: One,
    path: '/one/:user'
  }, {
    component: One,
    path: '/one'
  },
  {
    component: Two,
    path: '/two/'
  },
]})

new Vue({
  el: '#app',
  router: router
})
</code>```

My HTML:

```<code><div id="app">
      <nav>
        <ul>
          <li><router-link to="/one/test">test</router-link></li>
          <li><router-link to="two/hello/world">helloworld</router-link></li>
        </ul>
      </nav>
      <router-view></router-view>
    </div>
</code>```

I get returned this output from the bot:

```<code>index.html
    ✓ exists
  index.js
    ✓ exists
    ✓ is valid JavaScript
  index.html and index.js
    ✓ constant or variable One has the name "one"
    ✓ constant or variable Two has the name "two"
    ✓ navigating to #/ does not render "One"
    ✓ navigating to #/ does not render "Two"
    ✓ navigating to #/one renders "One"
    ✓ navigating to #/one does not render "Two"
    ✓ navigating to #/two renders "Two"
    ✓ navigating to #/two does not render "One"
    ✓ navigating to #/one/test renders "test"
    ✓ navigating to some other "one" address renders something else
    ✓ navigating to #/two/hello/world renders "helloworld"
    FAIL) navigating to some other "two" address renders something else
</code>```

The last line/error is the problem. What's wrong with my code? I've tried to clone the two-component but I get the same output...

答:
It appears that you want to use dynamic segments in your route, where the data in the route is passed along as data to your component. You can take a look at the Vue Router documentation for dynamic route matching here.

In short, you need to redefine your route:

```<code>let router = new VueRouter({
  routes: [
  // other routes
  {
    component: Two,
    path: '/two/:first/:second'
  },
]})
</code>```

Note that :first and :second can be anything you'd like. It could just as easily be:

```<code>  {
    component: Two,
    path: '/two/:zebra/:canteloupe'
  },
</code>```

However you choose to name those dynamic route segments, Vue router will pass them along as params to your identified component, which in this case is the Two component.

So, in your Two template, you could do something like...

```<code><template>
  <div>
    {{$route.params.first}}{{$route.params.second}}
  <div>
<template>
</code>```

Body:
Sorry for the long post. My code is corrected by a bot and I get an error returned that I can't seem to work my way around.

In my code, I want to make so that you can you can visit #two-adress, followed two separate parameters like this: #/two/hello/world which generates
helloworld
.

This is my Vue code:

let One = Vue.component('one', {
  template: '
One {{ $route.params.user }}
'
})

let Two = Vue.component('two', {
  template: '
Two
'
})

let router = new VueRouter({
  routes: [{
    component: One,
    path: '/one/:user'
  }, {
    component: One,
    path: '/one'
  },
  {
    component: Two,
    path: '/two/'
  },
]})

new Vue({
  el: '#app',
  router: router
})

My HTML:

<router-link to="/one/test">test</router-link>

<router-link to="two/hello/world">helloworld</router-link>

      <router-view></router-view>

I get returned this output from the bot:

index.html
    ✓ exists
  index.js
    ✓ exists
    ✓ is valid JavaScript
  index.html and index.js
    ✓ constant or variable One has the name "one"
    ✓ constant or variable Two has the name "two"
    ✓ navigating to #/ does not render "One"
    ✓ navigating to #/ does not render "Two"
    ✓ navigating to #/one renders "One"
    ✓ navigating to #/one does not render "Two"
    ✓ navigating to #/two renders "Two"
    ✓ navigating to #/two does not render "One"
    ✓ navigating to #/one/test renders "test"
    ✓ navigating to some other "one" address renders something else
    ✓ navigating to #/two/hello/world renders "helloworld"
    FAIL) navigating to some other "two" address renders something else

The last line/error is the problem. What's wrong with my code? I've tried to clone the two-component but I get the same output...

Body:
It appears that you want to use dynamic segments in your route, where the data in the route is passed along as data to your component. You can take a look at the Vue Router documentation for dynamic route matching here.

In short, you need to redefine your route:

let router = new VueRouter({
  routes: [
  // other routes
  {
    component: Two,
    path: '/two/:first/:second'
  },
]})

Note that :first and :second can be anything you'd like. It could just as easily be:

  {
    component: Two,
    path: '/two/:zebra/:canteloupe'
  },

However you choose to name those dynamic route segments, Vue router will pass them along as params to your identified component, which in this case is the Two component.

So, in your Two template, you could do something like...

<template>
  <div>
    {{$route.params.first}}{{$route.params.second}}
  <div>
<template>


问:
Can an Outlook macro trigger its built-in import functionality?
I'm trying to automate Outlook to automatically load an iCalendar file (.ics) when it starts. I'm aware of the hooks I need to use to arrange the timing already, I just haven't been able to find quality information about what sort of automation is possible.

Since Outlook already has the ability to import iCalendar files well enough for my purposes, I'd prefer to trigger that functionality rather than write my own parsing code. Is that possible?

答:
Depending on what you want, the answer is you cannot do it.

If you want to "import" the ics file you cannot do it alone, you would need for example redemption see here Visual Studio Forum  Because MS moves their links often here is a quote from there

“Outlook has no built-in methods to import an ICS file into a calendar item using code. However, a 3rd party library called Redemption (www.dimastr.com/redemption) does have that ability. The SafeAppointmentItem.Import function is called with a file path and item type. So if it's called with the file path where you saved the attachment and a type of  7 (olVCal) you can do what you want. “ Original link is:http://groups.google.co.uk/group/microsoft.public.office.developer.outlook.vba/browse_thread/thread/e4656ad0c5b68b89/d356ce07aeae783d?hl=en&lnk=st&q=import+.ics+file+into+outlook+by+codes#d356ce07aeae783d

So what are you options or what else can you do.

First I assume you are working in something like the application_startup event.

you could "shell" the file - which would have the same effect as double clicking on it.

see here MSDN shell with examples  For this you would need the path to your ics file.

But for me in your position, I would be first trying to get the person or thing generating the ics file to change OR I would be just treating it like a text file, parsing the information (which should not be too hard given it is an expected format) and creating my own calendar item in outlook.


问:
Node.js - getting a value from MySQL and assigning it to a variable
My query:

```<code>pool.query("SELECT MAX(ID) FROM `games` WHERE status IN('0','1') LIMIT 1", (err, row) => {
    if(err) return console.log("err getting the game.");
    currentGame = row[0];
    console.log(currentGame);
});
</code>```

Current Result:

```<code>RowDataPacket { 'MAX(ID)': 1 }
</code>```

Desired Result:

1

How do I get just the value and not include the other stuff?

答:
Try adding an alias to your count query, and then access it:

```<code>pool.query("SELECT MAX(ID) AS max_id FROM games WHERE status IN ('0','1')", (err, row) => {
    if(err) return console.log("err getting the game.");
    currentGame = row[0].max_id;
    console.log(currentGame);
});
</code>```

Note: A max query by definition will always return only a single record result set (in the absence of GROUP BY), so there is no need for LIMIT 1.

Body:
My query:

pool.query("SELECT MAX(ID) FROM `games` WHERE status IN('0','1') LIMIT 1", (err, row) => {
    if(err) return console.log("err getting the game.");
    currentGame = row[0];
    console.log(currentGame);
});

Current Result:

RowDataPacket { 'MAX(ID)': 1 }

Desired Result:

1

How do I get just the value and not include the other stuff?

Body:
Try adding an alias to your count query, and then access it:

pool.query("SELECT MAX(ID) AS max_id FROM games WHERE status IN ('0','1')", (err, row) => {
    if(err) return console.log("err getting the game.");
    currentGame = row[0].max_id;
    console.log(currentGame);
});

Note: A max query by definition will always return only a single record result set (in the absence of GROUP BY), so there is no need for LIMIT 1.


答: You could use res[2:] which will clip off the first two characters.</p>

Title: How to convert string into binary


问:
Is it possible to set the max duration of voice record time using speech_recognition module in Python?
I'm using the speech_recognition module in Python.  I have it use adjust_for_ambient_noise() before recording audio with listen().  The problem is sometimes it just tries to record seemingly forever, and then when it finally finishes it eats bandwidth transfering the large audio file it recorded to Google for transcription.

Is there a way for me to specify a maximum record time of like 5 seconds?

Setting timeout=5 is only the amount of time it will wait to detect a starting audio signal.

```<code>import speech_recognition

def listen(rec, mic):
  with mic as source:
    print('adjusting mic for ambient noise..')
    rec.adjust_for_ambient_noise(source)
    print('listening..')
    # timeout is not max record time but max time it will wait for audio to start
    audio = rec.listen(source, timeout=5)
    try:
      print('sending audio to google..')
      outputString = rec.recognize_google(audio).lower()
    except speech_recognition.UnknownValueError:
      print('google was not able to transcribe the audio')
      return None
    except speech_recognition.RequestError:
      print('google API unreachable')
      return None
    except speech_recognition.WaitTimeoutError:
      print('timout expired while waiting for audio command to start')
      return None
    print('transcription \'' + outputString + '\'')
    return outputString

rec = sr.Recognizer()
mic = sr.Microphone()
outputString = listen(rec, mic)
</code>```

答: You can use (source, phrase_time_limit=5) instead of (source, timeout=5)

Body:
I'm using the speech_recognition module in Python.  I have it use adjust_for_ambient_noise() before recording audio with listen().  The problem is sometimes it just tries to record seemingly forever, and then when it finally finishes it eats bandwidth transfering the large audio file it recorded to Google for transcription.

Is there a way for me to specify a maximum record time of like 5 seconds?

Setting timeout=5 is only the amount of time it will wait to detect a starting audio signal.

import speech_recognition

def listen(rec, mic):
  with mic as source:
    print('adjusting mic for ambient noise..')
    rec.adjust_for_ambient_noise(source)
    print('listening..')
    # timeout is not max record time but max time it will wait for audio to start
    audio = rec.listen(source, timeout=5)
    try:
      print('sending audio to google..')
      outputString = rec.recognize_google(audio).lower()
    except speech_recognition.UnknownValueError:
      print('google was not able to transcribe the audio')
      return None
    except speech_recognition.RequestError:
      print('google API unreachable')
      return None
    except speech_recognition.WaitTimeoutError:
      print('timout expired while waiting for audio command to start')
      return None
    print('transcription \'' + outputString + '\'')
    return outputString

rec = sr.Recognizer()
mic = sr.Microphone()
outputString = listen(rec, mic)


问:
Flutter - How to make dynamic dropdown from static list?
I have a method called getBreed() that depending of the species filled in another widget, returns the list of dog or cat breeds to populate a dynamic dropdown of breeds. But this method is not working well, an error occurs:

The method 'map' was called on null. Tried calling: map > (Closure: (String) => DropdownMenuItem )

However, if I call the method that returns the list directly it works, example:

```<code>//instead of this
DropdownContent.getBreed(widget.pet.specie).map<DropdownMenuItem<String>>((String value) {
//i put this
DropdownContent.listOfDogBreeds().map<DropdownMenuItem<String>>((String value) {
</code>```

Why is this happening? Bellow is my full code:

```<code>new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new DropdownButton<String>(
              value: widget.pet.breed == null
                  ? dropdownInitialValue
                  : widget.pet.breed,
              icon: Icon(Icons.arrow_downward),
              iconSize: 15,
              elevation: 16,
              style: TextStyle(color: Colors.black, fontSize: 14),
              underline: Container(
                height: 2,
                color: Colors.grey,
              ),
              onChanged: (String newValue) {
                setState(() {
                  dropdownInitialValue = newValue;
                  widget.pet.breed = newValue;
                });
              },
              items: DropdownContent.getBreed(widget.pet.specie).map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            )
          ])

class DropdownContent {
  static List<String> listOfDogBreeds() {
    return [
      'Select',
      'Australian Cattle',
      'Basset Hound',
      'Chihuahua',
      'Chow Chow'
    ];
  }

  static List<String> listOfCatBreeds() {
    return <String>[
      'Select',
      'American Shorthair',
      'Bengal',
      'Maine Coon',
      'Sphynx'
    ];
  }

  static getBreed(String specie) {
    if (specie.contains('dog')) {
      listOfDogBreeds();
    }
    if (specie.contains('cat')) {
      listOfCatBreeds();
    }
  }
}
</code>```

答: The word  return  is missing in the "getBreed" method

Body:
I have a method called getBreed() that depending of the species filled in another widget, returns the list of dog or cat breeds to populate a dynamic dropdown of breeds. But this method is not working well, an error occurs:

The method 'map' was called on null. Tried calling: map > (Closure: (String) => DropdownMenuItem )

However, if I call the method that returns the list directly it works, example:

//instead of this
DropdownContent.getBreed(widget.pet.specie).map<DropdownMenuItem<String>>((String value) {
//i put this
DropdownContent.listOfDogBreeds().map<DropdownMenuItem<String>>((String value) {

Why is this happening? Bellow is my full code:

new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new DropdownButton<String>(
              value: widget.pet.breed == null
                  ? dropdownInitialValue
                  : widget.pet.breed,
              icon: Icon(Icons.arrow_downward),
              iconSize: 15,
              elevation: 16,
              style: TextStyle(color: Colors.black, fontSize: 14),
              underline: Container(
                height: 2,
                color: Colors.grey,
              ),
              onChanged: (String newValue) {
                setState(() {
                  dropdownInitialValue = newValue;
                  widget.pet.breed = newValue;
                });
              },
              items: DropdownContent.getBreed(widget.pet.specie).map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            )
          ])

class DropdownContent {
  static List<String> listOfDogBreeds() {
    return [
      'Select',
      'Australian Cattle',
      'Basset Hound',
      'Chihuahua',
      'Chow Chow'
    ];
  }

  static List<String> listOfCatBreeds() {
    return <String>[
      'Select',
      'American Shorthair',
      'Bengal',
      'Maine Coon',
      'Sphynx'
    ];
  }

  static getBreed(String specie) {
    if (specie.contains('dog')) {
      listOfDogBreeds();
    }
    if (specie.contains('cat')) {
      listOfCatBreeds();
    }
  }
}


问:
How to update the Strapi GraphQL cache, after creating new data?

How to update the cache, after creating new data?

Error message from Apollo

Store error: the application attempted to write an object with no provided id but the store already contains an id of UsersPermissionsUser:1 for this object. The selectionSet that was trying to be written is:

{
  "kind": "Field",
  "name": { "kind": "Name", "value": "user" },
  "arguments": [],
  "directives": [],
  "selectionSet": {
    "kind": "SelectionSet",
    "selections": [
      { "kind": "Field", "name": { "kind": "Name", "value": "username" }, "arguments": [], "directives": [] },

      { "kind": "Field", "name": { "kind": "Name", "value": "__typename" } }
    ]
  }
}

```
<h2>Nativescript-vue Front-end Details</h2>
<p><img src="https://i.stack.imgur.com/R8I55.png" alt="enter image description here" /></p>
<p>1- <strong>Watch Book Mobile app in action</strong> on YouTube: https://youtu.be/sBM-ErjXWuw</p>
<p>2- <strong>Watch Question video for details</strong> on YouTube: https://youtu.be/wqvrcBRQpZg</p>
<p><strong>{N}</strong>-vue  <strong>AddBook.vue file</strong></p>
<pre class="lang-js prettyprint-override"><code>apolloClient
        .mutate({
          // Query
          mutation: mutations.CREATE_BOOK,
          // Parameters
          variables: {
            name: this.book.name,
            year: this.book.year,
          },
           // HOW TO UPDATE
          update: (store, { data }) => {
            console.log("data   ::::>> ", data.createBook.book);
            const bookQuery = {
              query: queries.ALL_BOOKS,
            };
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
            const bookData:any = store.readQuery(bookQuery);
            console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
            bookData.books.push(data.createBook.book);
            store.writeQuery({ ...bookQuery, data: bookData })
          },
        })
        .then((data) => {
          // I can even see ID in Result
          console.log("new data.data id  ::::: :>> ", data.data.createBook.book.id);
          this.$navigateTo(App);
        })
        .catch((error) => {
          // Error
          console.error(error);
        });
</code>```

What are these "Book:9": { lines in the cache?

console.log store  turns out:

```<code>"Book:9": {
        "id": "9",
        "name": "Hadi",
        "year": "255",
        "__typename": "Book"
      },
      "$ROOT_MUTATION.createBook({\"input\":{\"data\":{\"name\":\"Hadi\",\"year\":\"255\"}}})": {
</code>```

You can see all front-end GitHub repo here

Download Android apk file

Our goal is to update the cache. Add Book Method is in here:
https://github.com/kaanguru/mutate-question/blob/c199f8dcc8e80e83abdbcde4811770b766befcb5/nativescript-vue/app/components/AddBook.vue#L39

Back-end details

However, this is a frontend question a running Strapi GraphQL Server is here: https://polar-badlands-01357.herokuapp.com/admin/

GraphQL Playground

USER: admin

PASSWORD: passw123

You can see GraphQL documentation

I have so much simple Strapi GrapQL Scheme:

If you want to test it using postman or insomnia you can use;

POST GraphQL Query URL: https://polar-badlands-01357.herokuapp.com/graphql

Bearer Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTkwODI3MzE0LCJleHAiOjE1OTM0MTkzMTR9.WIK-f4dkwVAyIlP20v1PFoflpwGmRYgRrsQiRFgGdqg

NOTE: Don't get confused with $navigateTo() it's just a custom method of nativescript-vue.

答:
It turns out;

all code was correct accept bookData.push(createBook);

          // HOW TO UPDATE
          update: (store, { data }) => {
            console.log("data   ::::>> ", data.createBook.book);
            const bookQuery = {
              query: queries.ALL_BOOKS,
            };
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
            const bookData:any = store.readQuery(bookQuery);
            console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
            bookData.books.push(data.createBook.book);
            store.writeQuery({ ...bookQuery, data: bookData })
          },
        })
```

Typescipt was helping

The point is; I shouldn't trust TypeScript errors, or at least I should read more about what it really says.

Typescript just asked me to be more specific while saying: Property 'push' does not exist on type 'unknown'

TypeScript was trying to tell me I need to be more specific while calling ROOT_MUTATION data. It said: Cannot find name 'createBook' But again I ignored it.

Solution Github Branch

https://github.com/kaanguru/mutate-question/tree/solution

Sources

how to update cache

Create interface for object Typescript

Body:
How to update the cache, after creating new data?

Error message from Apollo

Store error: the application attempted to write an object with no provided id but the store already contains an id of UsersPermissionsUser:1 for this object. The selectionSet that was trying to be written is:

{
  "kind": "Field",
  "name": { "kind": "Name", "value": "user" },
  "arguments": [],
  "directives": [],
  "selectionSet": {
    "kind": "SelectionSet",
    "selections": [
      { "kind": "Field", "name": { "kind": "Name", "value": "username" }, "arguments": [], "directives": [] },

      { "kind": "Field", "name": { "kind": "Name", "value": "__typename" } }
    ]
  }
}

Nativescript-vue Front-end Details

1- Watch Book Mobile app in action on YouTube: https://youtu.be/sBM-ErjXWuw

2- Watch Question video for details on YouTube: https://youtu.be/wqvrcBRQpZg

{N}-vue  AddBook.vue file

apolloClient
        .mutate({
          // Query
          mutation: mutations.CREATE_BOOK,
          // Parameters
          variables: {
            name: this.book.name,
            year: this.book.year,
          },
           // HOW TO UPDATE
          update: (store, { data }) => {
            console.log("data   ::::>> ", data.createBook.book);
            const bookQuery = {
              query: queries.ALL_BOOKS,
            };
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
            const bookData:any = store.readQuery(bookQuery);
            console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
            bookData.books.push(data.createBook.book);
            store.writeQuery({ ...bookQuery, data: bookData })
          },
        })
        .then((data) => {
          // I can even see ID in Result
          console.log("new data.data id  ::::: :>> ", data.data.createBook.book.id);
          this.$navigateTo(App);
        })
        .catch((error) => {
          // Error
          console.error(error);
        });

What are these "Book:9": { lines in the cache?

console.log store  turns out:

"Book:9": {
        "id": "9",
        "name": "Hadi",
        "year": "255",
        "__typename": "Book"
      },
      "$ROOT_MUTATION.createBook({\"input\":{\"data\":{\"name\":\"Hadi\",\"year\":\"255\"}}})": {

You can see all front-end GitHub repo here

Download Android apk file

Our goal is to update the cache. Add Book Method is in here:
https://github.com/kaanguru/mutate-question/blob/c199f8dcc8e80e83abdbcde4811770b766befcb5/nativescript-vue/app/components/AddBook.vue#L39

Back-end details

However, this is a frontend question a running Strapi GraphQL Server is here: https://polar-badlands-01357.herokuapp.com/admin/

GraphQL Playground

USER: admin

PASSWORD: passw123

You can see GraphQL documentation

I have so much simple Strapi GrapQL Scheme:

If you want to test it using postman or insomnia you can use;

POST GraphQL Query URL: https://polar-badlands-01357.herokuapp.com/graphql

Bearer Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTkwODI3MzE0LCJleHAiOjE1OTM0MTkzMTR9.WIK-f4dkwVAyIlP20v1PFoflpwGmRYgRrsQiRFgGdqg

NOTE: Don't get confused with $navigateTo() it's just a custom method of nativescript-vue.

Body:
It turns out;

all code was correct accept bookData.push(createBook);

          // HOW TO UPDATE
          update: (store, { data }) => {
            console.log("data   ::::>> ", data.createBook.book);
            const bookQuery = {
              query: queries.ALL_BOOKS,
            };
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
            const bookData:any = store.readQuery(bookQuery);
            console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
            bookData.books.push(data.createBook.book);
            store.writeQuery({ ...bookQuery, data: bookData })
          },
        })

Typescipt was helping

The point is; I shouldn't trust TypeScript errors, or at least I should read more about what it really says.

Typescript just asked me to be more specific while saying: Property 'push' does not exist on type 'unknown'

TypeScript was trying to tell me I need to be more specific while calling ROOT_MUTATION data. It said: Cannot find name 'createBook' But again I ignored it.

Solution Github Branch

https://github.com/kaanguru/mutate-question/tree/solution

Sources

how to update cache

Create interface for object Typescript


问:
preferences-systems tries to write a lock file at a location where "normal" users have no write permissions on Linux
I am using system prefrences for  testing  my code i observed some peculiar things on java 1.5

```<code>private void loadEmptyPreferences() throws IOException,
            InvalidPreferencesFormatException, BackingStoreException {
        ClassLoader contextClassLoader = Thread.currentThread()
                .getContextClassLoader();
        InputStream stream = contextClassLoader
                .getResourceAsStream("example.xml");
        if (stream == null) {
            fail("Could not load preferences file");
        }
        Preferences pref = Preferences.systemRoot().node("test");
        pref.removeNode();
        Preferences.importPreferences(stream);
    }
</code>```

I get

java.lang.SecurityException: Could not lock System prefs.Lock file access denied.
    at java.util.prefs.FileSystemPreferences.checkLockFile0ErrorCode(FileSystemPreferences.java:919)
    at java.util.prefs.FileSystemPreferences.lockFile(FileSystemPreferences.java:908)
    at java.util.prefs.FileSystemPreferences.removeNode(FileSystemPreferences.java:656)

The reason is that the preferences-systems tries to write a lock file at a location where "normal" users have no write permissions on Linux  (/opt/j2se/linux/ix86/j2se_1.5.0_22/jre/.systemPrefs/.system.lock)

How to solve this?Should we use properties?

答:
Preferences.systemRoot() returns the system-wide (i.e. root only) preferences. They can't be changed by non-privileged users.

If you need to change settings for normal users, try using userRoot() instead.

Body:
I am using system prefrences for  testing  my code i observed some peculiar things on java 1.5

private void loadEmptyPreferences() throws IOException,
            InvalidPreferencesFormatException, BackingStoreException {
        ClassLoader contextClassLoader = Thread.currentThread()
                .getContextClassLoader();
        InputStream stream = contextClassLoader
                .getResourceAsStream("example.xml");
        if (stream == null) {
            fail("Could not load preferences file");
        }
        Preferences pref = Preferences.systemRoot().node("test");
        pref.removeNode();
        Preferences.importPreferences(stream);
    }

I get

java.lang.SecurityException: Could not lock System prefs.Lock file access denied.
    at java.util.prefs.FileSystemPreferences.checkLockFile0ErrorCode(FileSystemPreferences.java:919)
    at java.util.prefs.FileSystemPreferences.lockFile(FileSystemPreferences.java:908)
    at java.util.prefs.FileSystemPreferences.removeNode(FileSystemPreferences.java:656)

The reason is that the preferences-systems tries to write a lock file at a location where "normal" users have no write permissions on Linux  (/opt/j2se/linux/ix86/j2se_1.5.0_22/jre/.systemPrefs/.system.lock)

How to solve this?Should we use properties?


问:
Problems using Rooms on Android Studios
I'm doing an app for final project and I have a strange case using rooms.

When I was uninstall the aplication and I install again the app the database is the same at before, it didn't clean all the information of database. But when I cleaned the information by the manual way (on options of android) it works with a new database.

If anyone can know the problem, this database works very good yesterday.

Thanks.

答:
In manifest, inside application tag make the allowBackup false.

```<code>android:allowBackup="false"
</code>```

It is issue due to backup i think.

Title: Problems using Rooms on Android Studios

Body:
In manifest, inside application tag make the allowBackup false.

android:allowBackup="false"

It is issue due to backup i think.


问:
Alert on Browser Back button click or page refresh
I have seen the same function is multiple sites including SO. I am also trying to achieve this.
Here is the code so far.

```<code> <script>
            var myEvent = window.attachEvent || window.addEventListener;
            var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';

            myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                var confirmationMessage = ' ';
                (e || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            });
        </script>
</code>```

The problem is above code is working fine in chrome and IE but when I tried to test in on Firefox it is not working. I checked firebug but there is no error.
I updated the firefox and version are 47.0.1.

But issue not fixed.

Any advice would be helpful.

Guys if you have code better than this then it would be also helpful.

答:
It's work for me by this code.</p>

```<code>window.onbeforeunload = function () {
    return 'Are you sure? Your work will be lost. ';
};
</code>```

Body:
I have seen the same function is multiple sites including SO. I am also trying to achieve this.
Here is the code so far.

The problem is above code is working fine in chrome and IE but when I tried to test in on Firefox it is not working. I checked firebug but there is no error.
I updated the firefox and version are 47.0.1.

But issue not fixed.

Any advice would be helpful.

Guys if you have code better than this then it would be also helpful.

Body:
It's work for me by this code.

window.onbeforeunload = function () {
    return 'Are you sure? Your work will be lost. ';
};


问:
jupyter note book error because of unknown reason
```<code>from scipy.io import wavfile

train_audio_path = 'E:\'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))
</code>```

this is my code and I have two problems.
when i keep using this code, an error

```<code>  File "<ipython-input-7-ebdfbc596537>", line 3
    train_audio_path = "E:\"
                            ^
SyntaxError: EOL while scanning string literal
</code>```

comes out

and when i use / instead of \,

```<code>FileNotFoundError                         Traceback (most recent call last)
<ipython-input-10-cd74bbc41446> in <module>
      3 train_audio_path = 'E:/'
      4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
      6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
    262         mmap = False
    263     else:
--> 264         fid = open(filename, 'rb')
    265
    266     try:

FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'
</code>```

this error comes out. what is wrong in my code? I can't find at all..

答:
The antislash character is special in python.

Try train_audio_path = 'E:\\'
print(train_audio_path)
output: E:\

Body:
from scipy.io import wavfile

train_audio_path = 'E:\'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

this is my code and I have two problems.
when i keep using this code, an error

  File "<ipython-input-7-ebdfbc596537>", line 3
    train_audio_path = "E:\"
                            ^
SyntaxError: EOL while scanning string literal

comes out

and when i use / instead of \,

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-10-cd74bbc41446> in <module>
      3 train_audio_path = 'E:/'
      4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
      6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
    262         mmap = False
    263     else:
--> 264         fid = open(filename, 'rb')
    265
    266     try:

FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'

this error comes out. what is wrong in my code? I can't find at all..


问:
Spark SQL encapsulation of data sources
I have a Dataset where 98% (older than one day ) of its data would be in Parquet file and 2% (the current day - real time feed) of data would be in HBase, i always need to union them to get final data set for that particular table or entity.

So i would like my clients use the data seamlessly like below in any language they use for accessing spark or via spark shell or any BI tools

```<code>spark.read.format("my.datasource").load("entity1")
</code>```

internally i will read entity1's data from parquet and hbase then union them and return it.

I googled and got few examples on extending DatasourceV2, most of them says you need to develop reader, but here i do not need new reader, but need to make use the existing ones (parquet and HBase).

as i am not introducing any new datasource as such, do i need to create new datasource?  or is there any higher level abstraction/hook available?

答:
You have to implement a new datasource per se "parquet+hbase", in the implementation you will make use of existing readers of parquet and hbase, may be extending your classes with both of them and union them etc

For your reference here are some links, which can help you implementing new DataSource.

spark "bigquery" datasource implementation

https://github.com/GoogleCloudDataproc/spark-bigquery-connector

Implementing custom datasource

https://michalsenkyr.github.io/2017/02/spark-sql_datasource

Title: Spark SQL encapsulation of data sources

Body:
I have a Dataset where 98% (older than one day ) of its data would be in Parquet file and 2% (the current day - real time feed) of data would be in HBase, i always need to union them to get final data set for that particular table or entity.

So i would like my clients use the data seamlessly like below in any language they use for accessing spark or via spark shell or any BI tools

spark.read.format("my.datasource").load("entity1")

internally i will read entity1's data from parquet and hbase then union them and return it.

I googled and got few examples on extending DatasourceV2, most of them says you need to develop reader, but here i do not need new reader, but need to make use the existing ones (parquet and HBase).

as i am not introducing any new datasource as such, do i need to create new datasource?  or is there any higher level abstraction/hook available?


问:
CSS not loading since adding new id element to div class
First off what changed is I added two new divs and assigned it an id class of "order" and one "menuOutput".  Ever since then my CSS within the div id="menuOutput" has disappeared.  How do I get my CSS styles back whilst not changing how my js code works?  I know the new additions of the div are the problem but please tell me how to keep my styles with the new code?  </p>

```<code><body>
<div id="order"></div>
<div id="menuOutput">
<h1 class="menu">Menu</h1>
  <div class="grid">
    <div class="two">
      <h2>Pizza by the slice ($2)</h2>
      <input type="number" id="qty_slice of pizza">
      <h2>Toppings</h2>
      <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
      <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
      <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
      <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
    </div>

    <div class="one">
      <h2>Sides</h2>
      <p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
      <p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
      <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
      <p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
    </div>

    <div class="three">
        <h2>Drinks</h2>
        <div>

          <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
          <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
          <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
        </div><hr>
      <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
      <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

    </div>
 </div><br>
 </div>
<div class="button">
  <button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<script src="./run.js"></script>
</body>

 ------------------------------------JS---------------------------
 //get menu from api
 var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status == 200) {
    callback(null, xhr.response);
  } else {
    callback(status);
  }
};
xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
 },
 "sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
  },
  "drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
   },
  "juice": "2.00",
  "water": "1.25"
  }
 }
 }
*/

 getJSON('https://mm214.com/menu.php', function(err, data) {
 if (err != null) {
 alert('Something went wrong: ' + err);
 } else {

 var content = '';

 for (x in data.menu){
 if (typeof(data.menu[x]) == 'object'){
    for (y in data.menu[x]) {
        if (typeof(data.menu[x][y]) == 'object'){
            for (z in data.menu[x][y]) {
      content +=  z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
            }
          }
            else {
      content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
            }
        }//closes y in data

  }
  else
  {
  content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';

  }//else for data.menu[x] if not an object
  }
  }//closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order',JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order){
  }

  });

  function storeOrder(){
   var pizzaqty = document.getElementById('qty_slice of pizza').value;
   localStorage.setItem('pizza',pizzaqty);
   var price  = pizzaqty * 2;

  }

  function retrieveOrder(){
    var pizzaordered = localStorage.getItem('pizza');

  }

  //output html
  //
  //document.getElementById("menuOutput").innerHTML = "Here is the menu: <br>" + data.menu;
  //why in't this working?

  //style menu for ordering
  //save order as json string
  //save in local storage
  //your order button

  //onclick: show order
  document.getElementById('order').innerHTML = localStorage.getItem('order1');

------------------CSS------------------------------

 @import url('https://fonts.googleapis.com/css2?
 family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');

 .grid {
 display: grid;
 grid-template-areas:
    "one two three"
    "one two three"
    "one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
 }

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}

input[type="number"] {
width: 40px;
}

.menu {
text-align: center;
}

.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
 }

.titles {
font-family: 'Bree Serif', serif;
}

.pizza {
text-align: center;
color: tomato;
background-color: teal;
}

.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}

.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}

.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}

h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
</code>```

答:
The issue, I suspect is this line:

document.getElementById("menuOutput").innerHTML = content;

This basically says everything between the div with id "menuOutput" should now be the html in your content variable.

But nowhere in your content variable are you specifying the .grid, .one, .two, .three div classes.

Inspect the source code of the page: does
 exist?

Body:
First off what changed is I added two new divs and assigned it an id class of "order" and one "menuOutput".  Ever since then my CSS within the div id="menuOutput" has disappeared.  How do I get my CSS styles back whilst not changing how my js code works?  I know the new additions of the div are the problem but please tell me how to keep my styles with the new code?

Menu

Pizza by the slice ($2)

      <input type="number" id="qty_slice of pizza">

Toppings

Per Pepperoni($0.25):
 <input type="number" id="qty_pepperoni">

Per Meatball($0.35):
 <input type="number" id="qty_meatballs">

Per Mushhroom($0.40):
 <input type="number" id="qty_mushrooms">

Per Olive($0.20):
 <input type="number" id="qty_olives">

Sides

Potato Salad($1.25):
 <input type="number" id="qty_potato salad">

Humus($2.50):
 <input type="number" id="qty_hummus">

Caesar Salad($3.50):
 <input type="number" id="qty_caesar salad">

Garden Salad($2.25):
 <input type="number" id="qty_garden salad">

Drinks

Small Soda($1.95):
 <input type="number" id="qty_small">

Medium Soda($2.20):
 <input type="number" id="qty_medium">

Large Soda($2.50):
 <input type="number" id="qty_large">

Juice($2.00):
 <input type="number" id="qty_juice">

Water($1.25):
 <input type="number" id="qty_water">

  <button type class="button" id="submitOrder">Review Order</button>

 ------------------------------------JS---------------------------
 //get menu from api
 var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status == 200) {
    callback(null, xhr.response);
  } else {
    callback(status);
  }
};
xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
 },
 "sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
  },
  "drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
   },
  "juice": "2.00",
  "water": "1.25"
  }
 }
 }
*/

 getJSON('https://mm214.com/menu.php', function(err, data) {
 if (err != null) {
 alert('Something went wrong: ' + err);
 } else {

 var content = '';

 for (x in data.menu){
 if (typeof(data.menu[x]) == 'object'){
    for (y in data.menu[x]) {
        if (typeof(data.menu[x][y]) == 'object'){
            for (z in data.menu[x][y]) {
      content +=  z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '">
';
            }
          }
            else {
      content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '">
';
            }
        }//closes y in data

  }
  else
  {
  content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '">
';

  }//else for data.menu[x] if not an object
  }
  }//closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order',JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order){
  }

  });

  function storeOrder(){
   var pizzaqty = document.getElementById('qty_slice of pizza').value;
   localStorage.setItem('pizza',pizzaqty);
   var price  = pizzaqty * 2;

  }

  function retrieveOrder(){
    var pizzaordered = localStorage.getItem('pizza');

  }

  //output html
  //
  //document.getElementById("menuOutput").innerHTML = "Here is the menu:
" + data.menu;
  //why in't this working?

  //style menu for ordering
  //save order as json string
  //save in local storage
  //your order button

  //onclick: show order
  document.getElementById('order').innerHTML = localStorage.getItem('order1');

------------------CSS------------------------------

 @import url('https://fonts.googleapis.com/css2?
 family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');

 .grid {
 display: grid;
 grid-template-areas:
    "one two three"
    "one two three"
    "one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
 }

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}

input[type="number"] {
width: 40px;
}

.menu {
text-align: center;
}

.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
 }

.titles {
font-family: 'Bree Serif', serif;
}

.pizza {
text-align: center;
color: tomato;
background-color: teal;
}

.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}

.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}

.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}

h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}

Body:
The issue, I suspect is this line:

document.getElementById("menuOutput").innerHTML = content;

This basically says everything between the div with id "menuOutput" should now be the html in your content variable.

But nowhere in your content variable are you specifying the .grid, .one, .two, .three div classes.

Inspect the source code of the page: does <div class="two"> exist?


问:
How take a picture automatic after 3 seconds in Flutter?
I'm developing a punch clock in a tablet with Flutter Application and I need this functionality.

I know how to make the camera show and the user make a screenshot, but I searched everywhere how to make an automatic self screenshot after 3 seconds and don't find anything.

Someone has an example, tutorial, or experience to make something like this?

答:
You can use Timer class to do some action after certain time duration as shown below

```<code>Timer(Duration(milliseconds: 3000), () {
    //after 3 seconds this will be called,
    //once this is called take picture or whatever function you need to do
    takeScreenshot();
  });
</code>```

And if you want,use this code below to take screenshot as mentioned in this answer Take Screenshot Stackoverflow answer

```<code>takeScreenShot() async{
   RenderRepaintBoundary boundary =
      previewContainer.currentContext.findRenderObject();
   ui.Image image = await boundary.toImage();
   final directory = (await getApplicationDocumentsDirectory()).path;
   ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
   Uint8List pngBytes = byteData.buffer.asUint8List();
   print(pngBytes);
   File imgFile =new File('$directory/screenshot.png');
   imgFile.writeAsBytes(pngBytes);
  }
</code>```

Hope this helps!

Body:
You can use Timer class to do some action after certain time duration as shown below

Timer(Duration(milliseconds: 3000), () {
    //after 3 seconds this will be called,
    //once this is called take picture or whatever function you need to do
    takeScreenshot();
  });

And if you want,use this code below to take screenshot as mentioned in this answer Take Screenshot Stackoverflow answer

takeScreenShot() async{
   RenderRepaintBoundary boundary =
      previewContainer.currentContext.findRenderObject();
   ui.Image image = await boundary.toImage();
   final directory = (await getApplicationDocumentsDirectory()).path;
   ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
   Uint8List pngBytes = byteData.buffer.asUint8List();
   print(pngBytes);
   File imgFile =new File('$directory/screenshot.png');
   imgFile.writeAsBytes(pngBytes);
  }

Hope this helps!


问:
Having troubles with CVX's DCP for R
I am facing the following challenge for which I don't seem to find a solution:

Basically, I want to program some code for StoNED - Stochastic non-smooth envelopment of data.

I started with this:

```<code># dim(G) is 35x15
# dim(X) is 5x15
# dim(y) is 5x1
# dim(h) is 15x1

# y is a vector of output, x a matrix of input,
h a vector of zeros, G a matrix of constraint parameters, betaa shall be estimated

library(CVXR)
betaa <- Variable(15,1)
target <- cvxr_norm(log(y)-log(X%*%betaa))
obj <- Minimize(target)
constr <- list(G%*%betaa>=h)
prob <- Problem(obj,constr)
result <- solve(prob)
print(result$getValue(betaa))
</code>```

Since this didn't work, I tried transforming the problem to this:

```<code>library(CVXR)
library(MASS)

#betaa <- Variable((15,1)
test <- Variable(5,1)
target <- cvxr_norm(log(y)-test)
obj <- Minimize(target)
constr <- list(G%*%(ginv(X)%*%exp(test))>=h)
prob <- Problem(obj,constr)
result <- solve(prob)
print(result$getValue(ginv(X)%*%exp(test)))
</code>```

Through this I shifted the DCP error from the problem expression to the constraint expression. I really don't have a clue how to get around this. Does anyone have a proper solution? Thanks in advance!

答:
Here is the rest of the code for testing</p>

```<code>input = 2
xmin = 5
xmax = 15
n=5

X <- cbind(runif(n, xmin, xmax))
if (input>=2){
  for (i in 2:input){
    Xi <-runif(n, xmin, xmax)
    X <- cbind(X,Xi)
  }
}

exponent=1
Y <- cbind(X[,1]^(exponent/ncol(X)))
if (input >=2){
  for (i in 2:input){
    Y <- Y*X[,i]^(exponent/ncol(X))
  }
}

u <- exp(-abs(rnorm(n, 0, 1.0877)))
v <- exp(rnorm(n, 0, 2*0.1361))

Y_mod <- Y*u*v

COST = 0
MULT = 1
inter = 1
x=X
y=Y_mod
RTS = "VRS"

n <- nrow(as.matrix(x))  # No DMUs
m <- ncol(as.matrix(x))  # No Inputs

x <- as.matrix(x)
estimator <- "MM"

ifelse (RTS=="CRS",inter <- 0,inter <- 1) #
if (is.null(estimator)==TRUE){estimator <- "MM"; print("Moment estimator used
if not specified")}
if (RTS=="CRS") MULT <- 1
if (RTS=="DRS") MULT <- 1
if (RTS=="IRS") MULT <- 1
if (RTS=="CRS" | RTS=="IRS" | RTS=="DRS") paste("Multiplicative model induced
for this scale assumption")

if (MULT==1){
  if (inter==1){
    X <- diag(n);
    for (i in (1:m)){
      X<- cbind(X,diag(n)*as.matrix(x)[,i])
    }
  }

  if (inter==0){
    X <- diag(n)*as.matrix(x)[,1]
    if (m>1){
      for (i in (2:m)){X<- cbind(X,diag(n)*as.matrix(x)[,i])}}}
  B <- log(y)
}

if (MULT==0){
  if (inter==1){
    X <- diag(n);
    for (i in (1:m)){X<- cbind(X,diag(n)*as.matrix(x)[,i])}}

  if (inter==0){
    X <- diag(n)*as.matrix(x)[,1]
    if (m>1){
      for (i in (2:m)){X<- cbind(X,diag(n)*as.matrix(x)[,i])}}}
  B <- y
}

###############################################
###### Create non-neg constraints
###############################################

non_neg_beta <- cbind(matrix(0,nrow=m*n,ncol=n),diag(m*n))
if(COST==0){
  if (inter==1){
    if (RTS=="VRS") {sign_cons <- non_neg_beta}
    if (RTS=="DRS"){RTS_cons <- cbind(1*diag(n),matrix(0,nrow=n,ncol=m*n));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
    if (RTS=="IRS"){RTS_cons <- cbind(-1*diag(n),matrix(0,nrow=n,ncol=m*n));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
  }
}
if(COST==1){
  if (inter==1){
    if (RTS=="VRS") {sign_cons <- non_neg_beta}
    if (RTS=="DRS"){RTS_cons <- cbind(-1*diag(n),matrix(0,nrow=n,ncol=n*m));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
    if (RTS=="IRS"){RTS_cons <- cbind(1*diag(n),matrix(0,nrow=n,ncol=n*m));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
  }
}

if (inter==0){
  sign_cons <- diag(m*n)}

###############################################
###### Create concavity constraints
###############################################
alpha_matlist <- list()
beta_matlist <- list()

for (i in 1:n){
  a_matr <- diag(n);
  a_matr[,i] <- a_matr[,i]-1
  alpha_matlist[[i]] <- a_matr

  # Create beta
  b_matr <-matrix(0,ncol=m*n,nrow=n);

  for (j in 1:m){
    b_matr[,i+n*(j-1)] <- -x[i,j]

    for (k in 1:n){
      b_matr[k,k+(j-1)*n] <- b_matr[k,k+(j-1)*n]+x[i,j]}
  }

  beta_matlist[[i]] <- b_matr}

if (inter==1){sspot_cons <-
cbind(do.call(rbind,alpha_matlist),do.call(rbind,beta_matlist))}
if (inter==0){sspot_cons <- cbind(do.call(rbind,beta_matlist))}
#####################################
# !!!!!!!!! Cost function !!!!!!!!!
#####################################
if (COST==1){sspot_cons <- -1*sspot_cons}

#####################################
### Getting the constraints together
#####################################
G <- rbind(sign_cons,sspot_cons)
h <- rep(0,nrow(sign_cons)+nrow(sspot_cons))
</code>```

Title: Having troubles with CVX's DCP for R

Body:
I am facing the following challenge for which I don't seem to find a solution:

Basically, I want to program some code for StoNED - Stochastic non-smooth envelopment of data.

I started with this:

# dim(G) is 35x15
# dim(X) is 5x15
# dim(y) is 5x1
# dim(h) is 15x1

# y is a vector of output, x a matrix of input,
h a vector of zeros, G a matrix of constraint parameters, betaa shall be estimated

library(CVXR)
betaa <- Variable(15,1)
target <- cvxr_norm(log(y)-log(X%*%betaa))
obj <- Minimize(target)
constr <- list(G%*%betaa>=h)
prob <- Problem(obj,constr)
result <- solve(prob)
print(result$getValue(betaa))

Since this didn't work, I tried transforming the problem to this:

library(CVXR)
library(MASS)

#betaa <- Variable((15,1)
test <- Variable(5,1)
target <- cvxr_norm(log(y)-test)
obj <- Minimize(target)
constr <- list(G%*%(ginv(X)%*%exp(test))>=h)
prob <- Problem(obj,constr)
result <- solve(prob)
print(result$getValue(ginv(X)%*%exp(test)))

Through this I shifted the DCP error from the problem expression to the constraint expression. I really don't have a clue how to get around this. Does anyone have a proper solution? Thanks in advance!

Body:
Here is the rest of the code for testing

input = 2
xmin = 5
xmax = 15
n=5

X <- cbind(runif(n, xmin, xmax))
if (input>=2){
  for (i in 2:input){
    Xi <-runif(n, xmin, xmax)
    X <- cbind(X,Xi)
  }
}

exponent=1
Y <- cbind(X[,1]^(exponent/ncol(X)))
if (input >=2){
  for (i in 2:input){
    Y <- Y*X[,i]^(exponent/ncol(X))
  }
}

u <- exp(-abs(rnorm(n, 0, 1.0877)))
v <- exp(rnorm(n, 0, 2*0.1361))

Y_mod <- Y*u*v

COST = 0
MULT = 1
inter = 1
x=X
y=Y_mod
RTS = "VRS"

n <- nrow(as.matrix(x))  # No DMUs
m <- ncol(as.matrix(x))  # No Inputs

x <- as.matrix(x)
estimator <- "MM"

ifelse (RTS=="CRS",inter <- 0,inter <- 1) #
if (is.null(estimator)==TRUE){estimator <- "MM"; print("Moment estimator used
if not specified")}
if (RTS=="CRS") MULT <- 1
if (RTS=="DRS") MULT <- 1
if (RTS=="IRS") MULT <- 1
if (RTS=="CRS" | RTS=="IRS" | RTS=="DRS") paste("Multiplicative model induced
for this scale assumption")

if (MULT==1){
  if (inter==1){
    X <- diag(n);
    for (i in (1:m)){
      X<- cbind(X,diag(n)*as.matrix(x)[,i])
    }
  }

  if (inter==0){
    X <- diag(n)*as.matrix(x)[,1]
    if (m>1){
      for (i in (2:m)){X<- cbind(X,diag(n)*as.matrix(x)[,i])}}}
  B <- log(y)
}

if (MULT==0){
  if (inter==1){
    X <- diag(n);
    for (i in (1:m)){X<- cbind(X,diag(n)*as.matrix(x)[,i])}}

  if (inter==0){
    X <- diag(n)*as.matrix(x)[,1]
    if (m>1){
      for (i in (2:m)){X<- cbind(X,diag(n)*as.matrix(x)[,i])}}}
  B <- y
}

###############################################
###### Create non-neg constraints
###############################################

non_neg_beta <- cbind(matrix(0,nrow=m*n,ncol=n),diag(m*n))
if(COST==0){
  if (inter==1){
    if (RTS=="VRS") {sign_cons <- non_neg_beta}
    if (RTS=="DRS"){RTS_cons <- cbind(1*diag(n),matrix(0,nrow=n,ncol=m*n));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
    if (RTS=="IRS"){RTS_cons <- cbind(-1*diag(n),matrix(0,nrow=n,ncol=m*n));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
  }
}
if(COST==1){
  if (inter==1){
    if (RTS=="VRS") {sign_cons <- non_neg_beta}
    if (RTS=="DRS"){RTS_cons <- cbind(-1*diag(n),matrix(0,nrow=n,ncol=n*m));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
    if (RTS=="IRS"){RTS_cons <- cbind(1*diag(n),matrix(0,nrow=n,ncol=n*m));
    sign_cons <- rbind(non_neg_beta, RTS_cons)}
  }
}

if (inter==0){
  sign_cons <- diag(m*n)}

###############################################
###### Create concavity constraints
###############################################
alpha_matlist <- list()
beta_matlist <- list()

for (i in 1:n){
  a_matr <- diag(n);
  a_matr[,i] <- a_matr[,i]-1
  alpha_matlist[[i]] <- a_matr

  # Create beta
  b_matr <-matrix(0,ncol=m*n,nrow=n);

  for (j in 1:m){
    b_matr[,i+n*(j-1)] <- -x[i,j]

    for (k in 1:n){
      b_matr[k,k+(j-1)*n] <- b_matr[k,k+(j-1)*n]+x[i,j]}
  }

  beta_matlist[[i]] <- b_matr}

if (inter==1){sspot_cons <-
cbind(do.call(rbind,alpha_matlist),do.call(rbind,beta_matlist))}
if (inter==0){sspot_cons <- cbind(do.call(rbind,beta_matlist))}
#####################################
# !!!!!!!!! Cost function !!!!!!!!!
#####################################
if (COST==1){sspot_cons <- -1*sspot_cons}

#####################################
### Getting the constraints together
#####################################
G <- rbind(sign_cons,sspot_cons)
h <- rep(0,nrow(sign_cons)+nrow(sspot_cons))


问:
How to create carousel items based on item count using React-Bootstrap
How can I loop through an array and based on the item count create new <Carousel.Item> and insert a <Card> component inside of it.

Let's say I have the following array with some image sources:

```<code>const items = [
   {
     src: 'http://somerandomimage.com'
   },
   {
     src: 'http://somerandomimage.com'
   },
   {
     src: 'http://somerandomimage.com'
   },
   {
     src: 'http://somerandomimage.com'
   }
]
</code>```

I would like to map through this array and add two <Card> per <Carousel.Item>
So each <Carousel.Item> would look like this:

```<code><Carousel.Item>
   <Row>
        <Col lg="3">
           <Card>
               <Card.Img variant="top" src={item.src}/>
                <Card.Body>
                    <Card.Title>Title</Card.Title>
                    <Card.Text>
                      Nisi voluptate ex enim eiusmod pariatur eiusmod non aute
                      cupidatat cillum pariatur.
                    </Card.Text>
                 </Card.Body>
           </Card>
       </Col>
       <Col lg="3">
           <Card>
               <Card.Img variant="top" src={item.src}/>
                <Card.Body>
                    <Card.Title>Title</Card.Title>
                    <Card.Text>
                      Nisi voluptate ex enim eiusmod pariatur eiusmod non aute
                      cupidatat cillum pariatur.
                    </Card.Text>
                 </Card.Body>
           </Card>
       </Col>
  </Row>
</code>```

答:
First use array chunk to split that array into smaller chunks.

```<code>Array.prototype.chunk = function(size) {
  const result = [];

  while (this.length) {
    result.push(this.splice(0, size));
  }

  return result;
};
</code>```

Then map that to render 2 <Carousel.Item> with two items in each like below, array chunk will return [[{},{}], [{},{}]]

```<code>{items.chunk(2).map((chunk, idx) => (
        <Carousel.Item key={idx} className={idx === 0 ? "active" : ""}>
          <Row>
            {chunk.map((item, idx2) => (
              <Col lg="3" key={idx2}>
                <Card>
                  <Card.Img variant="top" style={{width: "50px"}} src={item.src} />
                  <Card.Body>
                    <Card.Title>Title</Card.Title>
                    <Card.Text>
                      Nisi voluptate ex enim eiusmod pariatur eiusmod non aute
                      cupidatat cillum pariatur.
                    </Card.Text>
                  </Card.Body>
                </Card>
              </Col>
            ))}
          </Row>
        </Carousel.Item>
      ))}
</code>```

Demo https://codesandbox.io/s/spring-pine-fdtg5?file=/src/App.js

Body:
How can I loop through an array and based on the item count create new <Carousel.Item> and insert a <Card> component inside of it.

Let's say I have the following array with some image sources:

const items = [
   {
     src: 'http://somerandomimage.com'
   },
   {
     src: 'http://somerandomimage.com'
   },
   {
     src: 'http://somerandomimage.com'
   },
   {
     src: 'http://somerandomimage.com'
   }
]

I would like to map through this array and add two <Card> per <Carousel.Item>
So each <Carousel.Item> would look like this:

<Carousel.Item>
   <Row>
        <Col lg="3">
           <Card>
               <Card.Img variant="top" src={item.src}/>
                <Card.Body>
                    <Card.Title>Title</Card.Title>
                    <Card.Text>
                      Nisi voluptate ex enim eiusmod pariatur eiusmod non aute
                      cupidatat cillum pariatur.
                    </Card.Text>
                 </Card.Body>
           </Card>
       </Col>
       <Col lg="3">
           <Card>
               <Card.Img variant="top" src={item.src}/>
                <Card.Body>
                    <Card.Title>Title</Card.Title>
                    <Card.Text>
                      Nisi voluptate ex enim eiusmod pariatur eiusmod non aute
                      cupidatat cillum pariatur.
                    </Card.Text>
                 </Card.Body>
           </Card>
       </Col>
  </Row>

Body:
First use array chunk to split that array into smaller chunks.

Array.prototype.chunk = function(size) {
  const result = [];

  while (this.length) {
    result.push(this.splice(0, size));
  }

  return result;
};

Then map that to render 2 <Carousel.Item> with two items in each like below, array chunk will return [[{},{}], [{},{}]]

{items.chunk(2).map((chunk, idx) => (
        <Carousel.Item key={idx} className={idx === 0 ? "active" : ""}>
          <Row>
            {chunk.map((item, idx2) => (
              <Col lg="3" key={idx2}>
                <Card>
                  <Card.Img variant="top" style={{width: "50px"}} src={item.src} />
                  <Card.Body>
                    <Card.Title>Title</Card.Title>
                    <Card.Text>
                      Nisi voluptate ex enim eiusmod pariatur eiusmod non aute
                      cupidatat cillum pariatur.
                    </Card.Text>
                  </Card.Body>
                </Card>
              </Col>
            ))}
          </Row>
        </Carousel.Item>
      ))}

Demo https://codesandbox.io/s/spring-pine-fdtg5?file=/src/App.js


答:
First of all, remember you can't have two identical ids in one page so you have to remove one of divs with id=order (I removed the one at the top). second, it seems you have added your classes in id attribute. we have two attributes for each element, id and class. you can add multiple classes for one element (e.g class="green blue red"), but you must have only one id which is unique in your page and can't include white spaces. (e.g id="blue_red"). at the end, I edited your code and removed the pizza from id and add it to the class and also corrected the values you have assigned to the elements and your css works fine again. you can run the snippet to see the result. wish it helps you:)

@import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');

.grid {
    display: grid;
    grid-template-areas:
        "one two three"
        "one two three"
        "one two three";
    grid-template-columns: 1fr 2fr 1fr;
    grid-template-rows: repeat(3, 165px);
}

.title {
    font-family: 'Chelsea Market', cursive;
    font-size: 30px;
    text-align: center;
    color: teal;
}

input[type="number"] {
    width: 40px;
}

.menu {
    text-align: center;
}

.button {
    text-align: center;
    font-family: 'Bangers', cursive;
    font-size: 25px;
}

.titles {
    font-family: 'Bree Serif', serif;
}

.pizza {
    text-align: center;
    color: tomato;
    background-color: teal;
}

.one {
    grid-area: one;
    background-color: #008c45;
    text-align: center;
}

.two {
    text-align: center;
    grid-area: two;
    background-color: #f4f5f0;
    color: black;
}

.three {
    grid-area: three;
    text-align: center;
    background-color: #cd212a;
}

h2 {
    font-size: 30px;
    font-family: 'Oswald', sans-serif;
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menuOutput">
    <h1 class="menu">Menu</h1>
    <div class="grid">
        <div class="two">
            <h2>Pizza by the slice ($2)</h2>
            <input type="number" class="pizza" id="qty_slice_of_pizza">
            <h2>Toppings</h2>
            <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
            <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
            <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
            <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
        </div>

        <div class="one">
            <h2>Sides</h2>
            <p class="titles">Potato Salad($1.25):</p> <input type="number" class="salad" id="qty_potato_salad">
            <p class="titles">Humus($2.50):</p> <input type="number" class="salad" id="qty_hummus">
            <p class="titles">Caesar Salad($3.50):</p> <input type="number" class="salad" id="qty_caesar_salad">
            <p class="titles">Garden Salad($2.25):</p> <input type="number" class="salad" id="qty_garden_salad">
        </div>

        <div class="three">
            <h2>Drinks</h2>
            <div>

                <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
                <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
                <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
            </div>
            <hr/>
            <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
            <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

        </div>
    </div>

    <br/>
</div>
<div class="button">
  <button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div></code>```

Title: CSS not loading since adding new id element to div class

Body:
First of all, remember you can't have two identical ids in one page so you have to remove one of divs with id=order (I removed the one at the top). second, it seems you have added your classes in id attribute. we have two attributes for each element, id and class. you can add multiple classes for one element (e.g class="green blue red"), but you must have only one id which is unique in your page and can't include white spaces. (e.g id="blue_red"). at the end, I edited your code and removed the pizza from id and add it to the class and also corrected the values you have assigned to the elements and your css works fine again. you can run the snippet to see the result. wish it helps you:)

@import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');

.grid {
    display: grid;
    grid-template-areas:
        "one two three"
        "one two three"
        "one two three";
    grid-template-columns: 1fr 2fr 1fr;
    grid-template-rows: repeat(3, 165px);
}

.title {
    font-family: 'Chelsea Market', cursive;
    font-size: 30px;
    text-align: center;
    color: teal;
}

input[type="number"] {
    width: 40px;
}

.menu {
    text-align: center;
}

.button {
    text-align: center;
    font-family: 'Bangers', cursive;
    font-size: 25px;
}

.titles {
    font-family: 'Bree Serif', serif;
}

.pizza {
    text-align: center;
    color: tomato;
    background-color: teal;
}

.one {
    grid-area: one;
    background-color: #008c45;
    text-align: center;
}

.two {
    text-align: center;
    grid-area: two;
    background-color: #f4f5f0;
    color: black;
}

.three {
    grid-area: three;
    text-align: center;
    background-color: #cd212a;
}

h2 {
    font-size: 30px;
    font-family: 'Oswald', sans-serif;
    text-align: center;
}

<div id="menuOutput">
    <h1 class="menu">Menu</h1>
    <div class="grid">
        <div class="two">
            <h2>Pizza by the slice ($2)</h2>
            <input type="number" class="pizza" id="qty_slice_of_pizza">
            <h2>Toppings</h2>
            <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
            <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
            <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
            <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
        </div>

        <div class="one">
            <h2>Sides</h2>
            <p class="titles">Potato Salad($1.25):</p> <input type="number" class="salad" id="qty_potato_salad">
            <p class="titles">Humus($2.50):</p> <input type="number" class="salad" id="qty_hummus">
            <p class="titles">Caesar Salad($3.50):</p> <input type="number" class="salad" id="qty_caesar_salad">
            <p class="titles">Garden Salad($2.25):</p> <input type="number" class="salad" id="qty_garden_salad">
        </div>

        <div class="three">
            <h2>Drinks</h2>
            <div>

                <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
                <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
                <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
            </div>
            <hr/>
            <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
            <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

        </div>
    </div>

    <br/>
</div>
<div class="button">
  <button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>