问:
How should I import Paper.js in Svelte?
I'm using the standard Svelte template with Rollup and have not been able to successfully import Paper.js.

I installed paper via:

```<code>npm install paper
</code>```

and I get this output trying to do npm run dev after importing Paper:

```<code>(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
acorn (guessing 'acorn')
</code>```

Acorn is a dependency of the paper-full.js disto, and I'm looking to map

```<code>import { paper } from "paper";
</code>```

to paper-core.js (although it would be very cool to get PaperScript from the full distro working in Svelte, but that's likely a whole other can of worms).

I'm wondering what kind of Rollup config I would need to add to resolve this.

Here's the repo I'm working on if you'd like some more context or a quick way to jump to exactly where I'm at.

答: UPDATE: Got it working! I had forgotten to install acorn as a dependency. I also switched to installing them both as devDependencies since rollup bundles everything. -- solution credit to Antony in the Svelte Discord</p>

Title: How should I import Paper.js in Svelte?

Body:
I'm using the standard Svelte template with Rollup and have not been able to successfully import Paper.js.

I installed paper via:

npm install paper

and I get this output trying to do npm run dev after importing Paper:

(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
acorn (guessing 'acorn')

Acorn is a dependency of the paper-full.js disto, and I'm looking to map

import { paper } from "paper";

to paper-core.js (although it would be very cool to get PaperScript from the full distro working in Svelte, but that's likely a whole other can of worms).

I'm wondering what kind of Rollup config I would need to add to resolve this.

Here's the repo I'm working on if you'd like some more context or a quick way to jump to exactly where I'm at.


来源: stackexchange

问:
Use jQuery to update cell values under a specific th to links
I need to use jquery to loop through the following table and turn the cell values under the "Account Name" th into hyperlinks.

```<code><table id="exampleTable">
 <tr>
     <th>Type</th>
     <th>Account Name</th>
 </tr>
 <tr>
      <td>Type 1</td>
      <td>Account Name 1</td>
 </tr>
 <tr>
      <td>Type 2</td>
      <td>Account Name 2</td>
 </tr>
  <tr>
      <td>Type 3</td>
      <td>Account Name 3</td>
 </tr>
 <tr>
      <td>Type 4</td>
      <td>Account Name 4</td>
 </tr>
 <tr>
      <td>Type 5</td>
      <td>Account Name 5</td>
 </tr>
 <tr>
      <td>Type 6</td>
      <td>Account Name 6</td>
 </tr>
</table>
</code>```

I'm currently using this Jquery code to get the index of the Account Name th and then loop through each table row to find the td that shares that index.

```<code> let title;
 $("th").each(function() {
   if ($.trim($(this).text()) == "Account Name") {
      title = $(this).index();
   }
 });
 $("tr").each(function() {
   let link = $.trim($(this).find("td:eq(" + title + ")").text());
   let anchor = "<a href='http://" + link + "'>" + link + "</a>";
   $(this).find("td:eq(" + title + ")").html(anchor);
 });
</code>```

The problem that I'm facing is that this table is paginated. The first two rows show up on page one and the next two so up on page 2 and so on. My current jQuery code is correctly changing the table cell text for Account Name 1 and Account Name 2 to a link on page 1, however these links are then duplicated on each successive page. Another words, on page two the Account Name 3 text and Account Name 4 text are being changed to links that say Account Name 1 and Account Name 2. This is occuring on every page.

I'm not sure if I need to add a third loop like

```<code> $("td").each(function() {

 });
</code>```

or if my current code just needs to be changed. Any help would be greatly appreciated.

```<code> <li ng-if="directionLinks" ng-class="{disabled: noPrevious() || ngDisabled
    }" class="ng-scope" style="">
     <a sp-focus-changer="#pageLink-1" sp-focus-changer-click="true" href=""
        aria-disabled="false" ng-click="selectPage(page - 1, $event)" aria-
        label="Previous Page" role="menuitem">
        <i class="fa fa-chevron-left" role="presentation"></i>
     </a>
 </li>
</code>```

答: You do not need an additional loop, your code works well with the example table you provided. There is some specific thing with the library you are using to create the pagination. Will be better if you provide a live example in codepen.</p>

ContentLicense: CC BY-SA 4.0

Body:
I need to use jquery to loop through the following table and turn the cell values under the "Account Name" th into hyperlinks.

     Type
     Account Name

      Type 1
      Account Name 1

      Type 2
      Account Name 2

      Type 3
      Account Name 3

      Type 4
      Account Name 4

      Type 5
      Account Name 5

      Type 6
      Account Name 6

I'm currently using this Jquery code to get the index of the Account Name th and then loop through each table row to find the td that shares that index.

 let title;
 $("th").each(function() {
   if ($.trim($(this).text()) == "Account Name") {
      title = $(this).index();
   }
 });
 $("tr").each(function() {
   let link = $.trim($(this).find("td:eq(" + title + ")").text());
   let anchor = "" + link + "";
   $(this).find("td:eq(" + title + ")").html(anchor);
 });

The problem that I'm facing is that this table is paginated. The first two rows show up on page one and the next two so up on page 2 and so on. My current jQuery code is correctly changing the table cell text for Account Name 1 and Account Name 2 to a link on page 1, however these links are then duplicated on each successive page. Another words, on page two the Account Name 3 text and Account Name 4 text are being changed to links that say Account Name 1 and Account Name 2. This is occuring on every page.

I'm not sure if I need to add a third loop like

 $("td").each(function() {

 });

or if my current code just needs to be changed. Any help would be greatly appreciated.


问:
Why long types are rounded in .NET Web API JSON response payload after 16 digits?
I am working with web api 2 which I coincidentally realized that it rounds the long type value in the response model if it is longer than 16 digits.

(simplifying the example for the sake of the question) Assume I have a web api method as "GetOrders" which returns list of orderVm model which is defined as below:

```<code>public class OrderVm{
    public int OrderID {get;set;}
    public long? OrderNumber {get;set;}
}
</code>```

What is happening is, if my order number value is

1234567890123459 there is no issue - total of 16 digits.

1234567890123499 there is no issue - total of 16 digits.

12345678901234599 this is the problematic one. total of 17 digits. It is rounding this to 12345678901234600

Below is my simplified example API Method:

```<code>        [HttpPost]
        [Route("get-orders/")]
        public IHttpActionResult GetOrders(PostedVm postedVm)
        {
              var orderDtoList = _orderManager.GetOrders(postedVm.Active); // I checked the value in orderDtoList and it is not rounded at this moment...
              var orderVmList  = MapDtoToVm(orderDtoList);
              return Ok(orderVmList);// I thought maybe something happens during the property mapping (which is just using simple reflection) but I checked the value in orderVmList and it is not rounded at this moment...
        }
</code>```

Even though right before returning the response, I checked that the values actually were not rounded.. But somehow on the client, it is coming as rounded. I thought maybe the browser does some magic (for some reason) but I checked my payload on postman and fiddler, it was showing that the value as rounded in the response payload.

This sounds something related to web api configuration but if so, how I can set it to not modify the data? And I am also curious about "why it is happening after 16 digits?"

Just in case I added my WebApiConfig class below:

```<code> public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        //GZip Compression
        GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.Routes.MapHttpRoute(
        name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
            id = RouteParameter.Optional
        });
    }
}
</code>```

答:
Thanks to Guy Incognito that he pointed me to the raw response of the JSON. In the raw response my values were not rounded. But when I parse the JSON the number was being too large for JavaScript and as floating point numbers don't have infinite precision, I was having this issue. I ended up changing my data type to string as I don't do any arithmetic operations with that anyways.

Thanks to Guy Incognito again, this SO post was also very helpful.

Body:
I am working with web api 2 which I coincidentally realized that it rounds the long type value in the response model if it is longer than 16 digits.

(simplifying the example for the sake of the question) Assume I have a web api method as "GetOrders" which returns list of orderVm model which is defined as below:

public class OrderVm{
    public int OrderID {get;set;}
    public long? OrderNumber {get;set;}
}

What is happening is, if my order number value is

1234567890123459 there is no issue - total of 16 digits.

1234567890123499 there is no issue - total of 16 digits.

12345678901234599 this is the problematic one. total of 17 digits. It is rounding this to 12345678901234600

Below is my simplified example API Method:

        [HttpPost]
        [Route("get-orders/")]
        public IHttpActionResult GetOrders(PostedVm postedVm)
        {
              var orderDtoList = _orderManager.GetOrders(postedVm.Active); // I checked the value in orderDtoList and it is not rounded at this moment...
              var orderVmList  = MapDtoToVm(orderDtoList);
              return Ok(orderVmList);// I thought maybe something happens during the property mapping (which is just using simple reflection) but I checked the value in orderVmList and it is not rounded at this moment...
        }

Even though right before returning the response, I checked that the values actually were not rounded.. But somehow on the client, it is coming as rounded. I thought maybe the browser does some magic (for some reason) but I checked my payload on postman and fiddler, it was showing that the value as rounded in the response payload.

This sounds something related to web api configuration but if so, how I can set it to not modify the data? And I am also curious about "why it is happening after 16 digits?"

Just in case I added my WebApiConfig class below:

 public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        //GZip Compression
        GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.Routes.MapHttpRoute(
        name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
            id = RouteParameter.Optional
        });
    }
}


问:
Can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
I am using javascript to connect websocket:

```<code><script>
    var socket;
    var host = "ws://localhost:8000/socket/server/startDaemon.php";
    var socket = new WebSocket(host);
</script>
</code>```

I got the error:

Can't establish a connection to the server at

```<code>var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);
</code>```

How can I solve this issue?

NOTE : I enabled websocket in mozilla to support web socket application.
       and when i run in chrome i got error:

```<code>   can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
</code>```

答:
Apparently firefox 4 has websockets disabled because of vulnerabilities. To quote From this article:

WebSocket disabled in Firefox 4

Recent discoveries found that the protocol that Websocket works with is vulnerable to attacks. Adam Barth demonstrated some serious attacks against the protocol that could be used by an attacker to poison caches that sit in between the browser and the Internet.

ContentLicense: CC BY-SA 3.0

Body:
I am using javascript to connect websocket:

I got the error:

Can't establish a connection to the server at

var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);

How can I solve this issue?

NOTE : I enabled websocket in mozilla to support web socket application.
       and when i run in chrome i got error:

   can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);


问:
Show specific Quick Action for specific file extension
I am newbie with Applescript and Automator. I am trying to build a Quick Actions which will be able to propose different functions according to the type of file for example.
If the file is test.sh quick action will be a and b
If the file is document.pdf action will be c and d

I succeed in creating my actions but not to make them specific to file type. I don't know where to start as I don't see any possibility to make input conditional like if input = .sh do a and b.

Any help on how to proceed will be really appreciated.

Thank you,

答:
After looking at the image of your QuickAction, it is not at all useful for anything other then a selected PDF document in Finder.

The first action should be a Set Value of Variable action so its contents can be retrieved multiple times using Get Value of Variable with however many Filter Finder Items actions needed to process the different file types, followed by the appropriate actions for each file type.

You would also use Ignore this action's input checkbox under Options for this action  to detach it from the previous set of actions.

The image below shows a rough outline example of what I'm referring to:


问:
Move div down when parent div width changed
I have following page structure:

div_Menu  |  div_Stat1  div_Stat2  div_Stat3  div_Stat4

When page width is not enougth - 4 divs going under Menu div. If the width changed I want last div_Stat4 will go under div_Stat1.

Relevant part of the code:

```<code><div class="menu">...</div>
<div class="action">
<div class="title">...</div>
<div class="stat">...</div>
<div class="stat">...</div>
<div class="stat">...</div>
<div class="stat">...</div>
</div>
</code>```

css:

```<code>.menu {
float: left;
width: 200px;
height: 100%;
background-color: #006666;
color: #ffffff;
font-family: "Helvetica Neue",Georgia,Times,"Times New Roman",serif;
font-size: 2.0rem;
}
.action {
float: left;
padding-left: 60px;
}
.stat {
float: left;
background: #d8eacc;
padding: 10px;
border-color: azure;
border-style: solid;
text-align: center;
font-family: "Helvetica Neue",Georgia,Times,"Times New Roman",serif;
font-size: 1.6rem;
width: 200px;
margin-right: 10px;
}
</code>```

What should I change?

Correct display:

When browser width smaller:

答:
Try wrapping your menu and content in a flexbox:

...

...

...

...

...

...

```

<pre class="lang-css prettyprint-override"><code>.container {
    display: flex;
}
</code>```

That way, the .action will never go down.

Body:
I have following page structure:

div_Menu  |  div_Stat1  div_Stat2  div_Stat3  div_Stat4

When page width is not enougth - 4 divs going under Menu div. If the width changed I want last div_Stat4 will go under div_Stat1.

Relevant part of the code:

...

...

...

...

...

...

css:

.menu {
float: left;
width: 200px;
height: 100%;
background-color: #006666;
color: #ffffff;
font-family: "Helvetica Neue",Georgia,Times,"Times New Roman",serif;
font-size: 2.0rem;
}
.action {
float: left;
padding-left: 60px;
}
.stat {
float: left;
background: #d8eacc;
padding: 10px;
border-color: azure;
border-style: solid;
text-align: center;
font-family: "Helvetica Neue",Georgia,Times,"Times New Roman",serif;
font-size: 1.6rem;
width: 200px;
margin-right: 10px;
}

What should I change?

Correct display:

When browser width smaller:

Body:
Try wrapping your menu and content in a flexbox:

<div class="container">
    <div class="menu">...</div>
    <div class="action">
        <div class="title">...</div>
        <div class="stat">...</div>
        <div class="stat">...</div>
        <div class="stat">...</div>
        <div class="stat">...</div>
    </div>
</div>

.container {
    display: flex;
}

That way, the .action will never go down.


问:
React-Native Flatlist Load More with Firebase Realtime DB
I am trying to load more data from firebase when page is scrolled down, But its not working properly. There are lots of docs about doing it on cloudstore but not on realtime db so im stuck.

Problems:

At the beginning it runs onendreached,

When it works, After 3-4 scroll bottom; its not calling onEndReached no more.

Sometimes onEndReach not working

my functions:

retrieveNotifications = () => {
  var that = this
  database().ref('usernotifications/' + this.state.myuid).orderByChild('notificationDate').limitToLast(10).on('value', function(snapshot) {
    if (snapshot.val()) {
      that.setState({
        notifications: Object.values(snapshot.val())
      })
    } else {
      that.setState({
        notifications: null
      })
    }
  })
}

retrieveMoreNotifications = () => {
  console.log('retrieve more')
  this.setState({
    refreshingList: true
  })
  setTimeout(() => {
    var that = this
    database().ref('usernotifications/' + this.state.myuid).orderByChild('notificationDate').limitToLast(this.state.notifications.length + 5).once('value').then(function(snapshot) {
      if (snapshot.val()) {
        that.setState({
          notifications: Object.values(snapshot.val()),
          refreshingList: false
        })
      } else {
        that.setState({
          notifications: null
        })
      }
    })
  }, 1500);
}
```

<p>And Flatlist:</p>

```<FlatList
  ListFooterComponent={this.renderFooter}
  initialNumToRender = {1}
  onEndReachedThreshold = {0.1}
  onMomentumScrollBegin = {() => {this.onEndReachedCalledDuringMomentum = false;}}
  onEndReached = {() => {
    if (!this.onEndReachedCalledDuringMomentum) {
      this.retrieveMoreNotifications();    // LOAD MORE DATA
      this.onEndReachedCalledDuringMomentum = true;
    }
  }}
  style={{flexGrow:0, marginBottom: 0, backgroundColor:'#fff'}}
  keyExtractor={(item, index) => index.toString()}
  data={this.state.notifications.sort((a, b) => {
      return new Date(b.notificationDate) - new Date(a.notificationDate);
  })}

  renderItem={({ item }) =>
    <ListItem
      bottomDivider
      title={this.notificationTitleCreator(item)}
      titleStyle={{fontSize: 15,}}
      rightSubtitle={ Platform.OS =='ios' ?
      new Date(item.notificationDate).toLocaleString('tr-TR') :
      new Date(item.notificationDate).toLocaleDateString('tr-TR') + "\n" +
      new Date(item.notificationDate).toLocaleTimeString('tr-TR') }
      rightSubtitleStyle={{color:'#808080', fontSize: 16, marginTop: 5,}}
    />
  }
/>
```

So every scroll basicly i want to pull 5 more data from database than notification array length.

What am i doing wrong ?

答:
onMomentumScrollBegin is deprecated and not working. Deleted it and edited thresh hold as 0.01 solved my problem</p>

```<code>...

                          ListFooterComponent={this.renderFooter}
                          onEndReachedThreshold = {0.01}
                          onEndReached = {this.retrieveMoreNotifications}
                          style={{flexGrow:0, marginBottom: 0, backgroundColor:'#fff'}}
                          keyExtractor={(item, index) => index.toString()}

    ...
</code>```

Body:
I am trying to load more data from firebase when page is scrolled down, But its not working properly. There are lots of docs about doing it on cloudstore but not on realtime db so im stuck.

Problems:

At the beginning it runs onendreached,

When it works, After 3-4 scroll bottom; its not calling onEndReached no more.

Sometimes onEndReach not working

my functions:

retrieveNotifications = () => {
  var that = this
  database().ref('usernotifications/' + this.state.myuid).orderByChild('notificationDate').limitToLast(10).on('value', function(snapshot) {
    if (snapshot.val()) {
      that.setState({
        notifications: Object.values(snapshot.val())
      })
    } else {
      that.setState({
        notifications: null
      })
    }
  })
}

retrieveMoreNotifications = () => {
  console.log('retrieve more')
  this.setState({
    refreshingList: true
  })
  setTimeout(() => {
    var that = this
    database().ref('usernotifications/' + this.state.myuid).orderByChild('notificationDate').limitToLast(this.state.notifications.length + 5).once('value').then(function(snapshot) {
      if (snapshot.val()) {
        that.setState({
          notifications: Object.values(snapshot.val()),
          refreshingList: false
        })
      } else {
        that.setState({
          notifications: null
        })
      }
    })
  }, 1500);
}

And Flatlist:

<FlatList
  ListFooterComponent={this.renderFooter}
  initialNumToRender = {1}
  onEndReachedThreshold = {0.1}
  onMomentumScrollBegin = {() => {this.onEndReachedCalledDuringMomentum = false;}}
  onEndReached = {() => {
    if (!this.onEndReachedCalledDuringMomentum) {
      this.retrieveMoreNotifications();    // LOAD MORE DATA
      this.onEndReachedCalledDuringMomentum = true;
    }
  }}
  style={{flexGrow:0, marginBottom: 0, backgroundColor:'#fff'}}
  keyExtractor={(item, index) => index.toString()}
  data={this.state.notifications.sort((a, b) => {
      return new Date(b.notificationDate) - new Date(a.notificationDate);
  })}

  renderItem={({ item }) =>
    <ListItem
      bottomDivider
      title={this.notificationTitleCreator(item)}
      titleStyle={{fontSize: 15,}}
      rightSubtitle={ Platform.OS =='ios' ?
      new Date(item.notificationDate).toLocaleString('tr-TR') :
      new Date(item.notificationDate).toLocaleDateString('tr-TR') + "\n" +
      new Date(item.notificationDate).toLocaleTimeString('tr-TR') }
      rightSubtitleStyle={{color:'#808080', fontSize: 16, marginTop: 5,}}
    />
  }
/>

So every scroll basicly i want to pull 5 more data from database than notification array length.

What am i doing wrong ?

Body:
onMomentumScrollBegin is deprecated and not working. Deleted it and edited thresh hold as 0.01 solved my problem

...

                          ListFooterComponent={this.renderFooter}
                          onEndReachedThreshold = {0.01}
                          onEndReached = {this.retrieveMoreNotifications}
                          style={{flexGrow:0, marginBottom: 0, backgroundColor:'#fff'}}
                          keyExtractor={(item, index) => index.toString()}

    ...


问:
Firebase addOnSuccessListener callback running context throws `NetworkOnMainThreadException`
Suppose I have a repository class that defines a method to retrieve an image from Firebase Storage and defines a success listener that invokes a callback defined from a view model

```<code>fun getAdImg(imgId: String, callback: (stream: Bitmap?) -> Unit) {
        storage.child(FOLDER).child(imgId+EXTENSION).stream
            .addOnSuccessListener {
                callback(BitmapFactory.decodeStream(it.stream))
                Log.i(TAG, "getAdImg success")
            }
            .addOnCanceledListener {
                Log.e(TAG, "getAdImg canceled")
            }
            .addOnFailureListener {
                Log.e(TAG, "getAdImg failure")
            }

    }
</code>```

The function in the view model that defines the callback and invokes the repository is the following

```<code>fun loadImage(imgId: String?) {
        imgId?.let { id ->
            if (_img.value == null) {
                viewModelScope.launch (context = IO) {
                    AdvertisementRepository.getInstance().getAdImg(id) { bitmap ->
                        _img.postValue(bitmap)
                    }
                }
            }
        }
    }
</code>```

I have a couple of questions:

What's the lifecycle of the listener defined by addOnSuccessListener in the repository class?

What's the scope from which the callback function is invoked in the listener?

When I try to run this code, BitmapFactory.decodeStream(it.stream) will throw a android.os.NetworkOnMainThreadException that seems like an exception due to the context in which the decodeStream function is invoked

答:
What's the lifecycle of the listener defined by addOnSuccessListener in the repository class?

The way you're using it here, it doesn't have a lifecycle.  The callback will persist indefinitely.

What's the scope from which the callback function is invoked in the listener?

It doesn't have a coroutine scope.  The callback will be invoked on the main thread whenever the result is ready.

When I try to run this code, BitmapFactory.decodeStream(it.stream) will throw a android.os.NetworkOnMainThreadException that seems like an exception due to the context in which the decodeStream function is invoked

Yes, since the callback is invoked on the main thread, and decodeStream does I/O, you will expect that it will throw an exception if strict mode is enabled to detect I/O on the main thread.  That's why the API documentation for getStream() says:

Asynchronously downloads the object at this StorageReference via a InputStream. The InputStream should be read on an OnSuccessListener registered to run on a background thread via addOnSuccessListener(Executor, OnSuccessListener)

The documentation suggsets that you arrange for the callback to be invoked on a thread other than the main thread using an Executor.  Alternatively, you could use a coroutine, but the API is not Kotlin-aware, so you will need to arrange for that yourself.  There is a library that helps convert Tasks for coroutine usage.

https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services

Body:
Suppose I have a repository class that defines a method to retrieve an image from Firebase Storage and defines a success listener that invokes a callback defined from a view model

fun getAdImg(imgId: String, callback: (stream: Bitmap?) -> Unit) {
        storage.child(FOLDER).child(imgId+EXTENSION).stream
            .addOnSuccessListener {
                callback(BitmapFactory.decodeStream(it.stream))
                Log.i(TAG, "getAdImg success")
            }
            .addOnCanceledListener {
                Log.e(TAG, "getAdImg canceled")
            }
            .addOnFailureListener {
                Log.e(TAG, "getAdImg failure")
            }

    }

The function in the view model that defines the callback and invokes the repository is the following

fun loadImage(imgId: String?) {
        imgId?.let { id ->
            if (_img.value == null) {
                viewModelScope.launch (context = IO) {
                    AdvertisementRepository.getInstance().getAdImg(id) { bitmap ->
                        _img.postValue(bitmap)
                    }
                }
            }
        }
    }

I have a couple of questions:

What's the lifecycle of the listener defined by addOnSuccessListener in the repository class?

What's the scope from which the callback function is invoked in the listener?

When I try to run this code, BitmapFactory.decodeStream(it.stream) will throw a android.os.NetworkOnMainThreadException that seems like an exception due to the context in which the decodeStream function is invoked


问:
Javascript error when sharing with LinkedIn Share API
I have the following code:

```<code> $(".btn_li").click(function() {
    window.open("http://www.linkedin.com/shareArticle?mini=true&url='+document.URL+'&title=Webpage Title;summary=Webpage Summary", "LinkedIn", "width=660,height=400,scrollbars=no;resizable=no");
try {
 _gaq.push(['_trackEvent', 'Social', 'LinkedIn', "Page URL"]);
 } catch(err){}
return false;
});
</code>```

and call this from:

```<code><div class="btn_li"></div>
</code>```

When this button is clicked, the LinkedIn error I receive is, "There was an unexpected problem that prevented us from completing your request." This tells me that the parameters are not being passed correctly.

Any advice?

NB: This is a new problem from my original question: Add Google Analytics Click (event) tracking code to Javascript window.open.

答:
You'll want to encode this correctly, for instance..

```<code>function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

$(".btn_li").click(function() {
    var url = fixedEncodeURIComponent('http://yourURL.com');
    window.open("https://www.linkedin.com/sharing/share-offsite/?url=" + url);
});
</code>```

The Microsoft Developer Network documentation says to never use encodeURIComponent() directly, but to use this function.  Take a look: MDN Web Documentation on encodeURIComponont().

I have also fixed your url, /share-offsite/ is the new standard, shareArticle? is the old standard that has been deprecated.  Source: LinkedIn Documentation: Share On LinkedIn, Section: "Customized URL".

Finally, the title, summary, and source arguments have all also been deprecated.  You can only use og: tags in the  block of your HTML source to fill these fields in.  For instance, this will look like...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Documentation: Making Your Website Shareable on LinkedIn.

Want to see if you got it right?  Test your own website at LinkedIn Post Inspector.

Body:
I have the following code:

 $(".btn_li").click(function() {
    window.open("http://www.linkedin.com/shareArticle?mini=true&url='+document.URL+'&title=Webpage Title;summary=Webpage Summary", "LinkedIn", "width=660,height=400,scrollbars=no;resizable=no");
try {
 _gaq.push(['_trackEvent', 'Social', 'LinkedIn', "Page URL"]);
 } catch(err){}
return false;
});

and call this from:

When this button is clicked, the LinkedIn error I receive is, "There was an unexpected problem that prevented us from completing your request." This tells me that the parameters are not being passed correctly.

Any advice?

NB: This is a new problem from my original question: Add Google Analytics Click (event) tracking code to Javascript window.open.

Body:
You'll want to encode this correctly, for instance..

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

$(".btn_li").click(function() {
    var url = fixedEncodeURIComponent('http://yourURL.com');
    window.open("https://www.linkedin.com/sharing/share-offsite/?url=" + url);
});

The Microsoft Developer Network documentation says to never use encodeURIComponent() directly, but to use this function.  Take a look: MDN Web Documentation on encodeURIComponont().

I have also fixed your url, /share-offsite/ is the new standard, shareArticle? is the old standard that has been deprecated.  Source: LinkedIn Documentation: Share On LinkedIn, Section: "Customized URL".

Finally, the title, summary, and source arguments have all also been deprecated.  You can only use og: tags in the <head> block of your HTML source to fill these fields in.  For instance, this will look like...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Documentation: Making Your Website Shareable on LinkedIn.

Want to see if you got it right?  Test your own website at LinkedIn Post Inspector.


问:
Keycloak in docker container + MySQL on host gives [org.keycloak.services] (ServerService Thread Pool -- 62) Failed to connect to database
New to KeyCloak.

Trying to run KeyCloak in a container that would be accessing MySQL on host machine (currently Windows 10, production would be Linux)

Followed steps in enter link description here and when both KeyCloak and MySQL are in their own containers, it works according to the documentation there.

When trying to connect existing MySQL database on the host and run KeyCloak docker container like this:

```<code>> docker run --name keycloak --network="host" -e DB_VENDOR=mysql -e DB_ADDR=host.docker.internal -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=sqlpass -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak
</code>```

or even

```<code>docker run --name keycloak --network=host -e DB_VENDOR=MYSQL -e DB_ADDR=<actual ip address of host> -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=sqlpass -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak
</code>```

Getting following error:

```<code>WFLYCTL0186:   Services which failed to start:      service org.wildfly.clustering.jgroups.channel.ee: java.lang.IllegalStateException: java.net.BindException: [UDP] /172.18.0.1 is not a valid address on any local network interface
</code>```

I think it's failing right after these messages...

```<code>19:33:30,381 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) WFLYSRV0027: Starting deployment of "keycloak-server.war" (runtime-name: "keycloak-server.war")
19:33:30,522 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-2) WFLYUT0006: Undertow HTTPS listener https listening on 0.0.0.0:8443
</code>```

Searched internet for the so called 'production ready' scenario where MySQL database would be on host and KeyCloak could be in Docker container, didn't find much help.

What am I doing wrong? Any help / pointers appreciated. Thank you.

Update:

When tried removing network - got different error.

```<code>docker run --rm --name keycloak  -e DB_VENDOR=MYSQL  -e DB_ADDR=docker.host.internal -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=sqlpass -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak
</code>```

More specific about not able to connect to the database:

```<code>20:14:28,844 FATAL [org.keycloak.services] (ServerService Thread Pool -- 62) java.lang.RuntimeException: Failed to connect to database
</code>```

答:
Got it. Turns out I needed to allow 'keycloak' user in MySQL instance to logon remotely (meaning not just from localhost but any other hosts).

I used following script to give access privileges for 'keycloak' user:

```<code>USE keycloak;

CREATE USER 'keycloak'@'localhost' IDENTIFIED WITH caching_sha2_password  BY 'password';
CREATE USER 'keycloak'@'<ip address of container>' IDENTIFIED WITH caching_sha2_password  BY 'password';

GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'localhost';
GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'<ip address of container>';
</code>```

Then use following command to run keycloak docker image as a daemon:

```<code>docker run --rm --name keycloak -d  -p 8080:8080 -e DB_VENDOR=MYSQL -e DB_ADDR=host.docker.internal -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=keycloak -e MYSQL_PASSWORD=password -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak
</code>```

Then go to http://localhost:8080/auth to access KeyCloak admin console and login using kc-admin user credentials defined previously.

To find out ip address of the container, used windows command line from this thread : How to get a Docker container's IP address from the host

Body:
New to KeyCloak.

Trying to run KeyCloak in a container that would be accessing MySQL on host machine (currently Windows 10, production would be Linux)

Followed steps in enter link description here and when both KeyCloak and MySQL are in their own containers, it works according to the documentation there.

When trying to connect existing MySQL database on the host and run KeyCloak docker container like this:

> docker run --name keycloak --network="host" -e DB_VENDOR=mysql -e DB_ADDR=host.docker.internal -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=sqlpass -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak

or even

docker run --name keycloak --network=host -e DB_VENDOR=MYSQL -e DB_ADDR=<actual ip address of host> -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=sqlpass -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak

Getting following error:

WFLYCTL0186:   Services which failed to start:      service org.wildfly.clustering.jgroups.channel.ee: java.lang.IllegalStateException: java.net.BindException: [UDP] /172.18.0.1 is not a valid address on any local network interface

I think it's failing right after these messages...

19:33:30,381 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) WFLYSRV0027: Starting deployment of "keycloak-server.war" (runtime-name: "keycloak-server.war")
19:33:30,522 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-2) WFLYUT0006: Undertow HTTPS listener https listening on 0.0.0.0:8443

Searched internet for the so called 'production ready' scenario where MySQL database would be on host and KeyCloak could be in Docker container, didn't find much help.

What am I doing wrong? Any help / pointers appreciated. Thank you.

Update:

When tried removing network - got different error.

docker run --rm --name keycloak  -e DB_VENDOR=MYSQL  -e DB_ADDR=docker.host.internal -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=sqlpass -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak

More specific about not able to connect to the database:

20:14:28,844 FATAL [org.keycloak.services] (ServerService Thread Pool -- 62) java.lang.RuntimeException: Failed to connect to database

Body:
Got it. Turns out I needed to allow 'keycloak' user in MySQL instance to logon remotely (meaning not just from localhost but any other hosts).

I used following script to give access privileges for 'keycloak' user:

USE keycloak;

CREATE USER 'keycloak'@'localhost' IDENTIFIED WITH caching_sha2_password  BY 'password';
CREATE USER 'keycloak'@'<ip address of container>' IDENTIFIED WITH caching_sha2_password  BY 'password';

GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'localhost';
GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'<ip address of container>';

Then use following command to run keycloak docker image as a daemon:

docker run --rm --name keycloak -d  -p 8080:8080 -e DB_VENDOR=MYSQL -e DB_ADDR=host.docker.internal -e MYSQL_DATABASE=keycloak -e MYSQL_USERNAME=keycloak -e MYSQL_PASSWORD=password -e KEYCLOAK_USER=kc-admin -e KEYCLOAK_PASSWORD=password jboss/keycloak

Then go to http://localhost:8080/auth to access KeyCloak admin console and login using kc-admin user credentials defined previously.

To find out ip address of the container, used windows command line from this thread : How to get a Docker container's IP address from the host


问:
How to have the ctime library read anywhere inside a switch
I am currently doing a supermarket management project for my uni, and one of the criteria is to have the sales timestamped with the system time when they are made. I am using the ctime library with the tm struct, and declaring it with

time_t now = time(0);
 tm *ltm = localtime(&now);

at the beggining of the main(), to read the system time from that moment when the variable is declared.

Problem is, if I try to put it inside the switch I'm using it gives me cross initialization error (example and error below). And as I have it on the very beginning of the program, if I let it idle for a few minutes and do a sale, the saved hour will be outdated, which I don't want. Does anyone know how to put this working inside a switch, or a workaround for it? Searched all over google but all I could find was how to define it. Thank you!

Example of intended behaviour:

#include <ctime>
int main(){
    *variables*
    //----------------------
    switch(menu1){
        case 1:
            *case code*
        break;
        case 2:
            time_t now = time(0);
            tm *ltm = localtime(&now);
            *case code*
        break;
        case 3:
            *case code*
        break;
        default:
            *case code*
        break
    }
    return;
}

Error im having with this implementation (it also seems to give me an error to every case below where it is implemented):
Error messages

答:
So, after taking a look at your errors, I found that someone had a similar problem in this question. I'd guess that you have some kind of similar error (I can't tell because you've hidden the content of the cases, sorry). As a result, you could fix your error by scoping your cases inside brackets so you eliminate the chance of using uninitialized variables.

For example:

This snippet won't work due to a redefinition of i:

#include <iostream>

int main()
{
    int foo = 1;
    switch(foo) {
      case 1:
        int i = 42;
        std::cout << i << '\n';
        break;
      case 2:
        int i = 33; // redefinition of i so the snippet doesn't compile
        std::cout << i * 2 << '\n';
    }
}
```

<p>This can be fixed by simply adding brackets so <code>i</code> goes out of scope before you redefine it:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <iostream>

int main()
{
    int foo = 1;
    switch(foo) {
      case 1: {
        int i = 42;
        std::cout << i << '\n';
        break;
      }
      case 2: {
        // i now can be defined since the previous one is out of scope
        int i = 33;
        std::cout << i * 2 << '\n';
      }
    }
}
</code>```

Hopefully, that makes sense, feel free to correct or clarify with me (I'm pretty new to this)

Body:
So, after taking a look at your errors, I found that someone had a similar problem in this question. I'd guess that you have some kind of similar error (I can't tell because you've hidden the content of the cases, sorry). As a result, you could fix your error by scoping your cases inside brackets so you eliminate the chance of using uninitialized variables.

For example:

This snippet won't work due to a redefinition of i:

#include <iostream>

int main()
{
    int foo = 1;
    switch(foo) {
      case 1:
        int i = 42;
        std::cout << i << '\n';
        break;
      case 2:
        int i = 33; // redefinition of i so the snippet doesn't compile
        std::cout << i * 2 << '\n';
    }
}

This can be fixed by simply adding brackets so i goes out of scope before you redefine it:

#include <iostream>

int main()
{
    int foo = 1;
    switch(foo) {
      case 1: {
        int i = 42;
        std::cout << i << '\n';
        break;
      }
      case 2: {
        // i now can be defined since the previous one is out of scope
        int i = 33;
        std::cout << i * 2 << '\n';
      }
    }
}

Hopefully, that makes sense, feel free to correct or clarify with me (I'm pretty new to this)


问:
Rails respond_to throw ActionController::UnknownFormat
So, I'm trying to respond to an action with a js file.

```<code>  def my_schedule
    respond_to do |format|
      format.js
    end
  end
</code>```

In my view, I have 'my_schedule.js.erb' but it's not even executed, rails broke in the controller and throw me an error : ActionController::UnknownFormat, where I have the respond_to.

I tried to add

```<code>respond_to :js, :json, :html
</code>```

at the beginning of my controller out of the actions but still not working.
Need help to debug this and understand how respond_to really works.

答:
format.js will only respond to an xhr request. You can't trigger this response by just navigating to the route that points to this controller and method.

You can test the js.erb execution by changing the respond_to block to

def my_schedule
  respond_to do |format|
    format.html
    format.js
  end
end
```

<p>Then create a my_schedule.html.erb file in the same view folder as the js.erb with the following contents</p>

<pre class="lang-rb prettyprint-override"><code><%= link_to 'Test', my_schedule_path, data: { remote: true } %>
</code>```

Note that you may need to adjust that path, I'm just guessing on that.

Then navigate to the same path you were trying to before. You should see a link which, when clicked, will fire the js response.

Body:
So, I'm trying to respond to an action with a js file.

  def my_schedule
    respond_to do |format|
      format.js
    end
  end

In my view, I have 'my_schedule.js.erb' but it's not even executed, rails broke in the controller and throw me an error : ActionController::UnknownFormat, where I have the respond_to.

I tried to add

respond_to :js, :json, :html

at the beginning of my controller out of the actions but still not working.
Need help to debug this and understand how respond_to really works.

Body:
format.js will only respond to an xhr request. You can't trigger this response by just navigating to the route that points to this controller and method.

You can test the js.erb execution by changing the respond_to block to

def my_schedule
  respond_to do |format|
    format.html
    format.js
  end
end

Then create a my_schedule.html.erb file in the same view folder as the js.erb with the following contents

<%= link_to 'Test', my_schedule_path, data: { remote: true } %>

Note that you may need to adjust that path, I'm just guessing on that.

Then navigate to the same path you were trying to before. You should see a link which, when clicked, will fire the js response.


问:
Not a single-group group function, with aggregate functions in select
I have the following query:

```<code>SELECT
    COUNT(*) AS "Number of Employees",
    EXTRACT(MONTH FROM hire_date) AS "Month Hired",
    AVG(salary)
FROM
    hr.employees;
</code>```

It gives me the error: ORA-00937: not a single-group group function. I have tried other resources and answers from other people, but they don't work in my case.

How do I fix this?

答:
Add a GROUP BY:

```<code>SELECT COUNT(*) AS "Number of Employees",
       EXTRACT(MONTH FROM hire_date) AS "Month Hired",
       AVG(salary)
FROM hr.employees
GROUP BY EXTRACT(MONTH FROM hire_date);
</code>```

There may be reasons why you are only interested in the hire month.  However, normally, you would also want the year.  In Oracle, this would commonly be accomplished using TO_CHAR():

```<code>SELECT TO_CHAR(hire_date, 'YYYY-MM') as month_hired,
       COUNT(*) AS num_empoyees,
       AVG(salary)
FROM hr.employees
GROUP BY TO_CHAR(hire_date, 'YYYY-MM')
ORDER BY month_hired;
</code>```

Body:
I have the following query:

SELECT
    COUNT(*) AS "Number of Employees",
    EXTRACT(MONTH FROM hire_date) AS "Month Hired",
    AVG(salary)
FROM
    hr.employees;

It gives me the error: ORA-00937: not a single-group group function. I have tried other resources and answers from other people, but they don't work in my case.

How do I fix this?

Body:
Add a GROUP BY:

SELECT COUNT(*) AS "Number of Employees",
       EXTRACT(MONTH FROM hire_date) AS "Month Hired",
       AVG(salary)
FROM hr.employees
GROUP BY EXTRACT(MONTH FROM hire_date);

There may be reasons why you are only interested in the hire month.  However, normally, you would also want the year.  In Oracle, this would commonly be accomplished using TO_CHAR():

SELECT TO_CHAR(hire_date, 'YYYY-MM') as month_hired,
       COUNT(*) AS num_empoyees,
       AVG(salary)
FROM hr.employees
GROUP BY TO_CHAR(hire_date, 'YYYY-MM')
ORDER BY month_hired;


问:
Problem with creating animations
I'm working with cocos2d 0.99.5. I need to create animations. I have 01.png in my resources and in my project. It's ok. I don't understand why I can't create a frame. I've got error SIGABRT.

```<code>CCSprite *frame = [CCSprite spriteWithSpriteFrameName:@"01.png"];
</code>```

I've tried to use this

```<code>CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache]
                        spriteFrameByName:@"01.png"];
</code>```

But I've got the same error.

答: That's because you must have your sprite in the spriteSheet. Here is the tutorial about creating animations: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:animation</p>

Title: Problem with creating animations

Body:
I'm working with cocos2d 0.99.5. I need to create animations. I have 01.png in my resources and in my project. It's ok. I don't understand why I can't create a frame. I've got error SIGABRT.

CCSprite *frame = [CCSprite spriteWithSpriteFrameName:@"01.png"];

I've tried to use this

CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache]
                        spriteFrameByName:@"01.png"];

But I've got the same error.


问:
Infinity loop after componentDidUpdate() in ReactJS
I have React JS app, which updating boostrap grid table with entries from ASP .NET Core Web API.

And I need to update the grid with new entries after inserting. I did that with help of componentDidUpdate() and using refreshList() function there, but I am getting an infinity loop of refreshList() function.

Any thoughts about how to update the grid without that loop?

import React, {Component} from 'react';
import {Table, Container} from 'react-bootstrap';
import {Button, ButtonToolbar} from 'react-bootstrap';

import {AddDepModal} from './AddDepModal';
import {EditDepModal} from './EditDepModal';

export class Department extends Component {

    constructor(props){
        super(props);
        this.state = {deps:[], addModalShow: false, editModalShow: false}
    }

    componentDidMount()
    {
        this.refreshList();
    }
    refreshList()
    {
       fetch("https://localhost:5001/api/departments")
       .then(response=> response.json())
       .then(data=> {
        this.setState({deps:data});
       });
    }

    componentDidUpdate()
    {
        this.refreshList();
    }

    render(){

     const {deps, depid, depname} = this.state;
     let addModalClose = () => this.setState({addModalShow:false})
     let editModalClose = () => this.setState({editModalShow:false})
    return (

            DepartmentID
            DepartmentName
            Options

        {deps.map(dep=>

            {dep.id}
            {dep.name}

                <ButtonToolbar>
                    <Button
                    className ="mr-2" variant ="info"
                    onClick = {() => this.setState({editModalShow:true, depid: dep.id, depname: dep.name})}
                    >
                        Edit
                    </Button>
                    <EditDepModal
                    show = {this.state.editModalShow}
                    onHide = {editModalClose}
                    depid = {depid}
                    depname = {depname}/>
                </ButtonToolbar>

            )}

     <ButtonToolbar>
    <Button variant = "primary" onClick = {() => this.setState({addModalShow: true})}>Add Department</Button>
    <AddDepModal
    show ={this.state.addModalShow}
    onHide ={addModalClose}/>
</ButtonToolbar>

    )
    }
}```

答:
Remove componentDidUpdate() because refreshData doesn't depend from props to fetch data and there aren't any checks with prevProps and newProps.

You can call refreshData method from Add or Save Button callback.

I image that you are saving data from modal code, add setState callback.

Modal save data, onhide set show state to false and call refreshData from once.

let addModalClose = () => this.setState({addModalShow:false}, this.refreshData)


问:
REST API url design
I have a REST API that has a database with table with two columns, product_id and server_id, that it serves product_ids to specific servers which request the data(based on the server_id from table).
Let's say I have three servers with server_ids 1,2 and 3.

My design is like this: /products/server_id/1 and with GET request I get json list of product_ids with server_id = 1, similarly /products/server_id/2 would output list of product_ids for server_id = 2.

Should I remove these routes and make a requirement to send POST request with instructions to receive product_ids for specific server_id in /products route only?

For example sending payload {"server_id":1} would yield a response of list of product_ids for server_id = 1.

答:
In REST APIs, POST requests should only be used in order to create new resource, so in order to retrieve data from server, the best practice is to perform a GET request.

If you want to load products 1,2,4,8 on server 9 for example, you can use this kind of request :

```<code>GET https://website/servers/9/products/1,2,4,8
</code>```

On server side, if products value contains a coma separated list, then return an array with all results, if not return just an array with only one item in order to keep consistency between calls.

In case you need to get all products, you can keep only the following url :

```<code>GET https://website/servers/9/products
</code>```

As there is no id provided in products parameter, then the server should return all existing products for requested server parameter.

Note : in case of big amount of results, they must by paginated.

Title: REST API url design

Body:
In REST APIs, POST requests should only be used in order to create new resource, so in order to retrieve data from server, the best practice is to perform a GET request.

If you want to load products 1,2,4,8 on server 9 for example, you can use this kind of request :

GET https://website/servers/9/products/1,2,4,8

On server side, if products value contains a coma separated list, then return an array with all results, if not return just an array with only one item in order to keep consistency between calls.

In case you need to get all products, you can keep only the following url :

GET https://website/servers/9/products

As there is no id provided in products parameter, then the server should return all existing products for requested server parameter.

Note : in case of big amount of results, they must by paginated.


问:
Creating a div by pressing a button
I was trying to create Divs by clicking a button but it just fill the button range with red.

```<code><div class="app">
  <button onclick="createDiv()">Make a cube</button>
</div>
<script>

  function createDiv ()
  {
  var boxEle = document.querySelector('.app');
  boxEle.style.width = 100;
  boxEle.style.height = 100;
  boxEle.style.backgroundColor = '#f00';

  }
</script>
</code>```

答:
Your not off by much.  You were selecting the div you already created in the html, and some of your js syntax is off.

Try this jsFiddle

```<code>function createDiv ()
  {
  var boxEle = document.createElement('div');
  var container = document.querySelector('.app');
  boxEle.style.width = '100px';
  boxEle.style.height = '100px';
  boxEle.style.backgroundColor = '#f00';
  container.appendChild(boxEle);
  }
</code>```

Title: Creating a div by pressing a button

Body:
I was trying to create Divs by clicking a button but it just fill the button range with red.

  <button onclick="createDiv()">Make a cube</button>

Body:
Your not off by much.  You were selecting the div you already created in the html, and some of your js syntax is off.

Try this jsFiddle

function createDiv ()
  {
  var boxEle = document.createElement('div');
  var container = document.querySelector('.app');
  boxEle.style.width = '100px';
  boxEle.style.height = '100px';
  boxEle.style.backgroundColor = '#f00';
  container.appendChild(boxEle);
  }


问:
Aquiring JWT-Token from AAD via Azure API Management Gateway
I have an API hosted in Azure (Web App). This API can't be accessed directory by every client (IP Restriction), and I am willing to use APIM to protect it.

Users will call the APIM-Gateway and the gateway should responds appropriately.

One big problem is authentication: I am protecting this API (The Backend API and not the APIM-Gateway endpoint) with AAD.
So users should authenticate themselves against AAD and access the resources with no direct access to the backend.

Is it possible to implement such a scenario?

答:
I have used below approach in my recent project and used jwt validation to validate oauth2 token in policy
Follow Microsoft document link https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad.

Here is a quick overview of the steps:

Register an application (backend-app) in Azure AD to represent the API.

Register another application (client-app) in Azure AD to represent a client application that needs to call the API.

In Azure AD, grant permissions to allow the client-app to call the backend-app.

Configure the Developer Console to call the API using OAuth 2.0 user authorization. (optional)

Add the validate-jwt policy to validate the OAuth token for every incoming request.


问:
Columns with mixed data
I have a set of data files that contain three different data set seach. These data sets are ordered as separate tables, each with its own columns. The data sets do not have a fixed length (i.e. rows).

I'm looking for a way to "clean" up the data and pour it into a new dataframe which will collect all three data sets (and will contain all of their columns, concatenated).

So basically what I've been trying to do is read each column header then pour its data into the corresponding column in the dataframe I created. However, the new column gets "fed" with all of the original column's data until the end of the file (including wrong data from the 2 data sets below the first).

Can someone advise on how to approach this issue?

Thanks!

e.g. I have a file that looks like this:

```<code>Column_Header A | Column_Header B | Column_Header C
Data1           | Data 2          | Data 3
Column_Header D | Column_Header E | Column_Header F
Data 4          | Data 5          | Data 6
</code>```

And need the data frame to look like this

```<code>Column_Header A | Column_Header B| Column_Header C | Column_Header D | Column_Header E| Column_Header F
Data1           | Data2          | Data3           |                 |                |
                |                |                 | Data4           | Data5          |Data6
</code>```

My code currently looks like this:

```<code># Gather the files
files = [file for file in os.listdir('C:/Users/user/Downloads/Inventory data/Raw')]

# Create dataframe
all_files_data = pd.DataFrame()

# Add file data to dataframe
for file in files:
    df = pd.read_excel("C:/Users/user/Downloads/Inventory data/Raw/"+file)
    all_files_data = pd.concat([all_files_data, df])

# Add columns to dataframe
all_files_data['Entry_Month'] = ''
all_files_data['Currency'] = ''
all_files_data['Notes'] = ''
</code>```

However the values for entry month, currency and notes are jammed into the wrong columns (namely supplier name, purchase date and then value).
I need some way to create the separation and I've no idea how to approach this...

答:
read_excel has a parameter nrows and skiprows. The idea here is you first read n rows until the second header (nrows=n, skiprows=0), then the remaining m rows (nrows=m, skiprows=n). If you don't know this value in advance you can check each row individually until one contains the second header.

Afterwards you can combine the columns with the concat function.

Title: Columns with mixed data

Body:
I have a set of data files that contain three different data set seach. These data sets are ordered as separate tables, each with its own columns. The data sets do not have a fixed length (i.e. rows).

I'm looking for a way to "clean" up the data and pour it into a new dataframe which will collect all three data sets (and will contain all of their columns, concatenated).

So basically what I've been trying to do is read each column header then pour its data into the corresponding column in the dataframe I created. However, the new column gets "fed" with all of the original column's data until the end of the file (including wrong data from the 2 data sets below the first).

Can someone advise on how to approach this issue?

Thanks!

e.g. I have a file that looks like this:

Column_Header A | Column_Header B | Column_Header C
Data1           | Data 2          | Data 3
Column_Header D | Column_Header E | Column_Header F
Data 4          | Data 5          | Data 6

And need the data frame to look like this

Column_Header A | Column_Header B| Column_Header C | Column_Header D | Column_Header E| Column_Header F
Data1           | Data2          | Data3           |                 |                |
                |                |                 | Data4           | Data5          |Data6

My code currently looks like this:

# Gather the files
files = [file for file in os.listdir('C:/Users/user/Downloads/Inventory data/Raw')]

# Create dataframe
all_files_data = pd.DataFrame()

# Add file data to dataframe
for file in files:
    df = pd.read_excel("C:/Users/user/Downloads/Inventory data/Raw/"+file)
    all_files_data = pd.concat([all_files_data, df])

# Add columns to dataframe
all_files_data['Entry_Month'] = ''
all_files_data['Currency'] = ''
all_files_data['Notes'] = ''

However the values for entry month, currency and notes are jammed into the wrong columns (namely supplier name, purchase date and then value).
I need some way to create the separation and I've no idea how to approach this...


问:
pandas rolling window effective add new rows
I have a pretty big dataset (around 5 million rows) with several calculated columns like lags (1 and 7) and rolling windows (7, 30, 90 with several values each, like mean, std, min, max and so on). Now I need to add one or more rows to the df and I was wondering the most effective way to (re)calculate those features. Recalculating the whole df would take too much time, but I cannot simply apply the functions to the new added row.

For the lags it's not a big issue, I can simply, for example for lag 1,

```<code>df.iloc[-1, -2] = df.iloc[-2, -2]
</code>```

and this should solve the problem (the same for lag 7), but what about rolling windows? The same approach won't work and I cannot afford to (re)run the rolling windows on the whole dataframe. Shall I make the calculations by hand? Any other way?

Python 3.7.7 and pandas 1.0.3

答:
If I'm interpreting the question correctly, you have a large DataFrame, with one or more source data columns and then multiple columns with windowed summary statistics based on the source columns. You're trying to update the bottom of the windowed summary columns after appending new rows to your source data columns without re-calculating the entire summary column.

The way to approach this will depend on a number of things, including whether you're using centered windows or not. But hopefully this gets you started.

I'll start with a toy version of your problem, with a single source column and two windowed means:

In [2]: df = pd.DataFrame({'source': np.arange(0, 20, 2)})

In [3]: for window in [3, 5]:
   ...:     df[f'rolling_mean_{window}'] = (
   ...:         df.source.rolling(window, center=True).mean())
   ...:
```

<p>Then we append a new row to the bottom:</p>

<pre class="lang-py prettyprint-override"><code>In [4]: df = df.append(pd.Series({'source': 100}), ignore_index=True)

In [5]: df
Out[5]:
    source  rolling_mean_3  rolling_mean_5
0      0.0             NaN             NaN
1      2.0             2.0             NaN
2      4.0             4.0             4.0
3      6.0             6.0             6.0
4      8.0             8.0             8.0
5     10.0            10.0            10.0
6     12.0            12.0            12.0
7     14.0            14.0            14.0
8     16.0            16.0             NaN
9     18.0             NaN             NaN
10   100.0             NaN             NaN
</code>```

The amount of data we have to update depends on the length of the window. For example, for to update rolling_mean_3 we need to update the last two rows, using information from the last five rows. To be safe, we can re-calculate the last 2*window rows plus the number of rows you added:

In [6]: df.source.iloc[-(2*window+1):].rolling(window, center=True).mean()
Out[6]:
4           NaN
5     10.000000
6     12.000000
7     14.000000
8     16.000000
9     44.666667
10          NaN
Name: source, dtype: float64
```

<p>This has the correct data for rows 5-10. Note that row 4 is not correct in this version (it's now <code>NaN</code>), but we can use this result to only update the last <code>[-(window+1):]</code> rows. Here's the full solution:</p>

<pre class="lang-py prettyprint-override"><code>In [7]: updated_rows = 1
In [8]: for window in [3, 5]:
   ...:     update_column_name = f'rolling_mean_{window}'
   ...:     update_column_index = df.columns.get_loc(update_column_name)
   ...:     df.iloc[-(window+updated_rows):, update_column_index] = (
   ...:         df.source
   ...:         .iloc[-(window*2+updated_rows):]
   ...:         .rolling(window, center=True).mean()
   ...:         .iloc[-(window+updated_rows):]
   ...:     )

In [9]: df
Out[9]:
    source  rolling_mean_3  rolling_mean_5
0      0.0             NaN             NaN
1      2.0        2.000000             NaN
2      4.0        4.000000             4.0
3      6.0        6.000000             6.0
4      8.0        8.000000             8.0
5     10.0       10.000000            10.0
6     12.0       12.000000            12.0
7     14.0       14.000000            14.0
8     16.0       16.000000            32.0
9     18.0       44.666667             NaN
10   100.0             NaN             NaN
</code>```

This now has been updated to have a correctly computed tail.

Technically, for a centered rolling operation, you only need to update the last floor(window/2)+updated_rows rows, drawing from the last window+updated_rows rows of the dataframe. So you could do this to really optimize things.

If you're producing rolling statistics that aren't centered, the approach should be the same, but don't include the centered flag.

Body:
I have a pretty big dataset (around 5 million rows) with several calculated columns like lags (1 and 7) and rolling windows (7, 30, 90 with several values each, like mean, std, min, max and so on). Now I need to add one or more rows to the df and I was wondering the most effective way to (re)calculate those features. Recalculating the whole df would take too much time, but I cannot simply apply the functions to the new added row.

For the lags it's not a big issue, I can simply, for example for lag 1,

df.iloc[-1, -2] = df.iloc[-2, -2]

and this should solve the problem (the same for lag 7), but what about rolling windows? The same approach won't work and I cannot afford to (re)run the rolling windows on the whole dataframe. Shall I make the calculations by hand? Any other way?

Python 3.7.7 and pandas 1.0.3

Body:
If I'm interpreting the question correctly, you have a large DataFrame, with one or more source data columns and then multiple columns with windowed summary statistics based on the source columns. You're trying to update the bottom of the windowed summary columns after appending new rows to your source data columns without re-calculating the entire summary column.

The way to approach this will depend on a number of things, including whether you're using centered windows or not. But hopefully this gets you started.

I'll start with a toy version of your problem, with a single source column and two windowed means:

In [2]: df = pd.DataFrame({'source': np.arange(0, 20, 2)})

In [3]: for window in [3, 5]:
   ...:     df[f'rolling_mean_{window}'] = (
   ...:         df.source.rolling(window, center=True).mean())
   ...:

Then we append a new row to the bottom:

In [4]: df = df.append(pd.Series({'source': 100}), ignore_index=True)

In [5]: df
Out[5]:
    source  rolling_mean_3  rolling_mean_5
0      0.0             NaN             NaN
1      2.0             2.0             NaN
2      4.0             4.0             4.0
3      6.0             6.0             6.0
4      8.0             8.0             8.0
5     10.0            10.0            10.0
6     12.0            12.0            12.0
7     14.0            14.0            14.0
8     16.0            16.0             NaN
9     18.0             NaN             NaN
10   100.0             NaN             NaN

The amount of data we have to update depends on the length of the window. For example, for to update rolling_mean_3 we need to update the last two rows, using information from the last five rows. To be safe, we can re-calculate the last 2*window rows plus the number of rows you added:

In [6]: df.source.iloc[-(2*window+1):].rolling(window, center=True).mean()
Out[6]:
4           NaN
5     10.000000
6     12.000000
7     14.000000
8     16.000000
9     44.666667
10          NaN
Name: source, dtype: float64

This has the correct data for rows 5-10. Note that row 4 is not correct in this version (it's now NaN), but we can use this result to only update the last [-(window+1):] rows. Here's the full solution:

In [7]: updated_rows = 1
In [8]: for window in [3, 5]:
   ...:     update_column_name = f'rolling_mean_{window}'
   ...:     update_column_index = df.columns.get_loc(update_column_name)
   ...:     df.iloc[-(window+updated_rows):, update_column_index] = (
   ...:         df.source
   ...:         .iloc[-(window*2+updated_rows):]
   ...:         .rolling(window, center=True).mean()
   ...:         .iloc[-(window+updated_rows):]
   ...:     )

In [9]: df
Out[9]:
    source  rolling_mean_3  rolling_mean_5
0      0.0             NaN             NaN
1      2.0        2.000000             NaN
2      4.0        4.000000             4.0
3      6.0        6.000000             6.0
4      8.0        8.000000             8.0
5     10.0       10.000000            10.0
6     12.0       12.000000            12.0
7     14.0       14.000000            14.0
8     16.0       16.000000            32.0
9     18.0       44.666667             NaN
10   100.0             NaN             NaN

This now has been updated to have a correctly computed tail.

Technically, for a centered rolling operation, you only need to update the last floor(window/2)+updated_rows rows, drawing from the last window+updated_rows rows of the dataframe. So you could do this to really optimize things.

If you're producing rolling statistics that aren't centered, the approach should be the same, but don't include the centered flag.


问:
How to send subarray of 2d Boost.MultiArray via Boost.MPI?
I need to send reference to a subarray of 2d of Boost.MultiArray with Boost.MPI.
Now I have the following code:

matrix_type::array_view<2>::type
                    current_process_batch = matrix[boost::indices[range(bias, finish_line)][range(0, width)]];
world.send(rank, BEGIN_TAG, current_process_batch);

```

<p>But also I have following error trying to execute it:</p>

```/usr/local/include/boost/serialization/access.hpp:116:11: error: no member named 'serialize' in 'boost::detail::multi_array::multi_array_view<double, 2>'
        t.serialize(ar, file_version);
```

Can anyone help me to send it to another process?

答:
You need to implement serialization.

Here's a general multi_array<T. Dims> serializer:

```<code>namespace boost::serialization {
    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::multi_array<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape)
               & make_nvp("data", make_array(ma.data(), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            ar & make_nvp("shape", shape);

            ma.resize(shape);
            ar & make_nvp("data", make_array(const_cast<T*>(ma.data()), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }
}
</code>```

See it Live On Coliru

```<code>auto make_multi_array() {
    boost::multi_array<int, 2> ma(boost::extents[7][4]);
    std::iota(ma.data(), ma.data() + ma.num_elements(), 10);
    return ma;
}

int main() {
    auto const original = make_multi_array();

    {
        std::ofstream os("array.txt");
        boost::archive::text_oarchive oa(os);

        oa << original;
    }

    std::cout << std::ifstream("array.txt").rdbuf() << "\n";

    {
        std::ifstream is("array.txt");
        boost::archive::text_iarchive ia(is);

        boost::multi_array<int, 2> restored;
        ia >> restored;

        assert(restored == original);
    }
}
</code>```

Prints

```<code>22 serialization::archive 17 0 0 0 0 2 7 4 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
</code>```

UPDATE: VIEWS

Mmm. Already accepted? Noticing late that I didn't actually read your question that well. You wanted to serialize a view. You can't, really. You can't "deserialize a view".

The most you can do is deserialize INTO a view.

Note also that

serializing the whole array could be (much) more efficient if the size difference isn't huge

the view types are not public interface for the library, i.e. it may break in future versions of Boost. If in doubt, serialize the arrays themselves

Here's some more machinery:

adds support for detail::multi_array::multi_array_view<...> in the sense that it can deserialize INTO an existing view of matching shape only

adds support for detail::multi_array::const_multi_array_view<...>  only for serializing. Said view can be deserialized into a non-const view only, for obvious reasons.

extends the demo with a sub-view that patches the initial array after serializing, so we can verify that reading the patch into an equivalent view of the restored array has the same effect as on the original (after checking that the patch created the expected mismatch 20 != 999).

Live On Coliru

```<code>#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/array_wrapper.hpp>
#include <boost/multi_array.hpp>
#include <iostream>
#include <fstream>

namespace boost::serialization {
    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::detail::multi_array::const_multi_array_view<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape);

            for (auto i = 0; i < shape[0]; ++i) {
                for (auto j = 0; j < shape[1]; ++j) {
                    ar & make_nvp("item", ma[i][j]);
                }
            }
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar&, boost::detail::multi_array::const_multi_array_view<T, Dims>&, unsigned) {
            static_assert(not Ar::is_loading::value, "const_multi_array_view immutable");
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::detail::multi_array::const_multi_array_view<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }

    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::detail::multi_array::multi_array_view<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape);

            for (auto i = 0; i < shape[0]; ++i) {
                for (auto j = 0; j < shape[1]; ++j) {
                    ar & make_nvp("item", ma[i][j]);
                }
            }
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar& ar, boost::detail::multi_array::multi_array_view<T, Dims>& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            ar & make_nvp("shape", shape);

            if (!std::equal(begin(shape), end(shape), ma.shape()))
                throw std::logic_error("multi_array_view shape mismatch");

            for (auto i = 0; i < shape[0]; ++i) {
                for (auto j = 0; j < shape[1]; ++j) {
                    ar & make_nvp("item", ma[i][j]);
                }
            }
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::detail::multi_array::multi_array_view<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }

    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::multi_array<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape)
               & make_nvp("data", make_array(ma.data(), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            ar & make_nvp("shape", shape);

            ma.resize(shape);
            ar & make_nvp("data", make_array(const_cast<T*>(ma.data()), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }
}

auto make_multi_array() {
    boost::multi_array<int, 2> ma(boost::extents[7][4]);
    std::iota(ma.data(), ma.data() + ma.num_elements(), 10);
    return ma;
}

int main() {
    using range = boost::multi_array_types::index_range;
    auto original = make_multi_array();
    auto const SLICE = boost::indices[range(1,3)][range(1,3)];

    {
        std::ofstream os("array.txt");
        boost::archive::text_oarchive oa(os);

        // only serialize initial array:
        oa << original;

        // modify through a sub-view
        auto sub = original[SLICE];
        original[2][2] = 999;

        // serialize the patch
        oa << sub;

        auto const& const_original = original;
        auto const_sub = const_original[SLICE];
        oa << const_sub; // compiles
    }

    std::cout << std::ifstream("array.txt").rdbuf() << "\n";

    {
        std::ifstream is("array.txt");
        boost::archive::text_iarchive ia(is);

        // only deserialize initial array:
        boost::multi_array<int, 2> restored;
        ia >> restored;

        assert(restored != original); // entry overwritten with 999

        assert(restored.num_elements() == original.num_elements());
        auto [o_2_2, r_2_2] = std::mismatch(
                original.data(), original.data()+original.num_elements(),
                restored.data());

        assert(*o_2_2 == 999);
        assert(*r_2_2 == 20);

        // now patch in the sub array at the same sub-view:
        auto sub = restored[SLICE];
        ia >> sub;

        // now everything is equal
        assert(restored == original); // now matches!
        assert(*r_2_2 == 999);

        auto const& const_restored = restored;
        auto const_sub = const_restored[SLICE];
        //ia >> const_sub; // WON'T COMPILE
    }
}
</code>```

Body:
I need to send reference to a subarray of 2d of Boost.MultiArray with Boost.MPI.
Now I have the following code:

matrix_type::array_view<2>::type
                    current_process_batch = matrix[boost::indices[range(bias, finish_line)][range(0, width)]];
world.send(rank, BEGIN_TAG, current_process_batch);

But also I have following error trying to execute it:

/usr/local/include/boost/serialization/access.hpp:116:11: error: no member named 'serialize' in 'boost::detail::multi_array::multi_array_view<double, 2>'
        t.serialize(ar, file_version);

Can anyone help me to send it to another process?

Body:
You need to implement serialization.

Here's a general multi_array<T. Dims> serializer:

namespace boost::serialization {
    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::multi_array<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape)
               & make_nvp("data", make_array(ma.data(), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            ar & make_nvp("shape", shape);

            ma.resize(shape);
            ar & make_nvp("data", make_array(const_cast<T*>(ma.data()), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }
}

See it Live On Coliru

auto make_multi_array() {
    boost::multi_array<int, 2> ma(boost::extents[7][4]);
    std::iota(ma.data(), ma.data() + ma.num_elements(), 10);
    return ma;
}

int main() {
    auto const original = make_multi_array();

    {
        std::ofstream os("array.txt");
        boost::archive::text_oarchive oa(os);

        oa << original;
    }

    std::cout << std::ifstream("array.txt").rdbuf() << "\n";

    {
        std::ifstream is("array.txt");
        boost::archive::text_iarchive ia(is);

        boost::multi_array<int, 2> restored;
        ia >> restored;

        assert(restored == original);
    }
}

Prints

22 serialization::archive 17 0 0 0 0 2 7 4 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

UPDATE: VIEWS

Mmm. Already accepted? Noticing late that I didn't actually read your question that well. You wanted to serialize a view. You can't, really. You can't "deserialize a view".

The most you can do is deserialize INTO a view.

Note also that

serializing the whole array could be (much) more efficient if the size difference isn't huge

the view types are not public interface for the library, i.e. it may break in future versions of Boost. If in doubt, serialize the arrays themselves

Here's some more machinery:

adds support for detail::multi_array::multi_array_view<...> in the sense that it can deserialize INTO an existing view of matching shape only

adds support for detail::multi_array::const_multi_array_view<...>  only for serializing. Said view can be deserialized into a non-const view only, for obvious reasons.

extends the demo with a sub-view that patches the initial array after serializing, so we can verify that reading the patch into an equivalent view of the restored array has the same effect as on the original (after checking that the patch created the expected mismatch 20 != 999).

Live On Coliru

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/array_wrapper.hpp>
#include <boost/multi_array.hpp>
#include <iostream>
#include <fstream>

namespace boost::serialization {
    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::detail::multi_array::const_multi_array_view<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape);

            for (auto i = 0; i < shape[0]; ++i) {
                for (auto j = 0; j < shape[1]; ++j) {
                    ar & make_nvp("item", ma[i][j]);
                }
            }
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar&, boost::detail::multi_array::const_multi_array_view<T, Dims>&, unsigned) {
            static_assert(not Ar::is_loading::value, "const_multi_array_view immutable");
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::detail::multi_array::const_multi_array_view<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }

    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::detail::multi_array::multi_array_view<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape);

            for (auto i = 0; i < shape[0]; ++i) {
                for (auto j = 0; j < shape[1]; ++j) {
                    ar & make_nvp("item", ma[i][j]);
                }
            }
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar& ar, boost::detail::multi_array::multi_array_view<T, Dims>& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            ar & make_nvp("shape", shape);

            if (!std::equal(begin(shape), end(shape), ma.shape()))
                throw std::logic_error("multi_array_view shape mismatch");

            for (auto i = 0; i < shape[0]; ++i) {
                for (auto j = 0; j < shape[1]; ++j) {
                    ar & make_nvp("item", ma[i][j]);
                }
            }
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::detail::multi_array::multi_array_view<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }

    template <typename Ar, typename T, size_t Dims>
        void save(Ar& ar, boost::multi_array<T, Dims> const& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            std::copy_n(ma.shape(), Dims, shape.begin());
            ar & make_nvp("shape", shape)
               & make_nvp("data", make_array(ma.data(), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void load(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned /*version*/) {
            std::array<int, Dims> shape;
            ar & make_nvp("shape", shape);

            ma.resize(shape);
            ar & make_nvp("data", make_array(const_cast<T*>(ma.data()), ma.num_elements()));
        }

    template <typename Ar, typename T, size_t Dims>
        void serialize(Ar& ar, boost::multi_array<T, Dims>& ma, unsigned version) {
            split_free(ar, ma, version);
        }
}

auto make_multi_array() {
    boost::multi_array<int, 2> ma(boost::extents[7][4]);
    std::iota(ma.data(), ma.data() + ma.num_elements(), 10);
    return ma;
}

int main() {
    using range = boost::multi_array_types::index_range;
    auto original = make_multi_array();
    auto const SLICE = boost::indices[range(1,3)][range(1,3)];

    {
        std::ofstream os("array.txt");
        boost::archive::text_oarchive oa(os);

        // only serialize initial array:
        oa << original;

        // modify through a sub-view
        auto sub = original[SLICE];
        original[2][2] = 999;

        // serialize the patch
        oa << sub;

        auto const& const_original = original;
        auto const_sub = const_original[SLICE];
        oa << const_sub; // compiles
    }

    std::cout << std::ifstream("array.txt").rdbuf() << "\n";

    {
        std::ifstream is("array.txt");
        boost::archive::text_iarchive ia(is);

        // only deserialize initial array:
        boost::multi_array<int, 2> restored;
        ia >> restored;

        assert(restored != original); // entry overwritten with 999

        assert(restored.num_elements() == original.num_elements());
        auto [o_2_2, r_2_2] = std::mismatch(
                original.data(), original.data()+original.num_elements(),
                restored.data());

        assert(*o_2_2 == 999);
        assert(*r_2_2 == 20);

        // now patch in the sub array at the same sub-view:
        auto sub = restored[SLICE];
        ia >> sub;

        // now everything is equal
        assert(restored == original); // now matches!
        assert(*r_2_2 == 999);

        auto const& const_restored = restored;
        auto const_sub = const_restored[SLICE];
        //ia >> const_sub; // WON'T COMPILE
    }
}


问:
Why doesn't EOF (ctrl+d) execute in function code? And only ctrl+z
I have some code below that works fine but only exits out when I do ctrl+z on Linux but not ctrl+d (EOF)? Does it have something to do with ncurses? What should I use instead (ERR?) and why?

```<code>
#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = -1;
         }
    }

    // to close curses terminal
    endwin();
}
</code>```

Thank you.

答:
"Why doesn't EOF (CTRL + D) execute in function code?"

Because you commented out the cbreak() option and with that the terminal is in raw mode.

Quotes from the Linux man pages (emphasize mine):

The raw and noraw routines place the terminal into or out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences are that in raw mode, the interrupt, quit, suspend, and flow control characters are all passed through uninterpreted, instead of generating a signal.

Source: https://linux.die.net/man/3/raw

Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly. Most interactive programs using curses set the cbreak mode. Note that cbreak overrides raw.

Source: https://linux.die.net/man/3/cbreak

As the quotes says, In raw mode the interrupt, quit, suspend, and flow control characters are passed through uninterpreted and do not generate the respective signals.

cbreak() overrides raw mode. Remove the // preceding cbreak() to uncomment cbreak() and it shall work as desired.

Beside that, you always should call either cbreak() or nocbreak() explicitly because it isn´t determined in what mode the terminal is at program startup.

Body:
I have some code below that works fine but only exits out when I do ctrl+z on Linux but not ctrl+d (EOF)? Does it have something to do with ncurses? What should I use instead (ERR?) and why?

#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = -1;
         }
    }

    // to close curses terminal
    endwin();
}

Thank you.


问:
Cannot clone object keras.wrappers
```<code>      def try_and_error(layers, activation):
         model = Sequential()
         for i, nodes in enumerate(layers):
            if i==0:
                model.add(Dense(nodes,input_dim=train_X.shape[1]))#input layers

                model.add(Activation(activation)) #Activation layer
            else:
                model.add(Dense(nodes))# Hidden Layers
                model.add(Activation(activation))#Activation Layers
          model.add(Dense(1)) # output layer

     model.compile(optimizer='adam', loss='binary_crossentropy',metrics=['accuracy'])
    return model

    layers=[[150], [160,100], [140,100,500]]
    activations = ['sigmoid', 'relu']
    param_grid = dict(layers=layers, activation=activations, batch_size=
    [500,800,1000])
    grid =
    RandomizedSearchCV(
                      estimator=KerasClassifier(build_fn=try_and_error
                                                ,epochs=100,verbose=0),
                      param_distributions =param_grid)

     grid_result= grid.fit(train_X,train_y)}

</code>```

and this is the error encountered even I have tried this with gridsearchcv result still the same.
RuntimeError: Cannot clone object <keras.wrappers.scikit_learn.KerasClassifier object at 0x7f3d7959c390>, as the constructor either does not set or modifies parameter layers

答:
change the layers to this :
layers=[(150,), (160,100), (140,100,500)]

Also , Dont forget to add (,) in (150,) otherwise it will throw an error like : TypeError: 'int' object is not iterable
This is because single tuple without comma(,) is treated as int.

Title: Cannot clone object keras.wrappers

Body:
      def try_and_error(layers, activation):
         model = Sequential()
         for i, nodes in enumerate(layers):
            if i==0:
                model.add(Dense(nodes,input_dim=train_X.shape[1]))#input layers

                model.add(Activation(activation)) #Activation layer
            else:
                model.add(Dense(nodes))# Hidden Layers
                model.add(Activation(activation))#Activation Layers
          model.add(Dense(1)) # output layer

     model.compile(optimizer='adam', loss='binary_crossentropy',metrics=['accuracy'])
    return model

    layers=[[150], [160,100], [140,100,500]]
    activations = ['sigmoid', 'relu']
    param_grid = dict(layers=layers, activation=activations, batch_size=
    [500,800,1000])
    grid =
    RandomizedSearchCV(
                      estimator=KerasClassifier(build_fn=try_and_error
                                                ,epochs=100,verbose=0),
                      param_distributions =param_grid)

     grid_result= grid.fit(train_X,train_y)}

and this is the error encountered even I have tried this with gridsearchcv result still the same.
RuntimeError: Cannot clone object <keras.wrappers.scikit_learn.KerasClassifier object at 0x7f3d7959c390>, as the constructor either does not set or modifies parameter layers


问:
Accessing member variables with getters C++
If I have this private map of scenes in my header file

```<code>std::map<std::string, Scene> scenes;
</code>```

Should my public getter be like so?

```<code>std::map<std::string, Scene>* getScenes() { return &scenes; }
</code>```

Still getting my head around pointers in c++ so apologies if it seems like a dumb question

答:
Using a pointer is rarely a good idea, considering you can return by reference.

```<code>std::map<std::string, Scene>& getScenes() { return scenes; }
</code>```

This however is also not very good and defeats the purpose of making the member variable private, as does returning a pointer to it.

To access the member variable to view the data and not change it, which lends some sense to having a getter of a private member variable, you should return a const reference:

```<code>const std::map<std::string, Scene>& getScenes() const { return scenes; }
</code>```

I'll just add that some defend that getters and setters are just clutter and you shoud just go ahead and make the member variable public if need be.

Others defend that it should be used with parsimony.

Others still, that they sholud be used but only because they're the lesser o two evils.

Body:
If I have this private map of scenes in my header file

std::map<std::string, Scene> scenes;

Should my public getter be like so?

std::map<std::string, Scene>* getScenes() { return &scenes; }

Still getting my head around pointers in c++ so apologies if it seems like a dumb question

Body:
Using a pointer is rarely a good idea, considering you can return by reference.

std::map<std::string, Scene>& getScenes() { return scenes; }

This however is also not very good and defeats the purpose of making the member variable private, as does returning a pointer to it.

To access the member variable to view the data and not change it, which lends some sense to having a getter of a private member variable, you should return a const reference:

const std::map<std::string, Scene>& getScenes() const { return scenes; }

I'll just add that some defend that getters and setters are just clutter and you shoud just go ahead and make the member variable public if need be.

Others defend that it should be used with parsimony.

Others still, that they sholud be used but only because they're the lesser o two evils.