问:
How to get C# WebSocketClient to listen for messages in an ongoing capacity
I'm writing a program (really a game in Unity) which should act as a client to a Websocket server which is up and running separately.

I'm using the System.Net.Websockets ClientWebSocket. I have opened the connection, I can send messages, but unlike in a Javascript client where I would set up a callback function which would run each time the websocket client received a message I'm having a hard time understanding the intended flow for the C# API.

Here's a message handler that I've written:

public async Task HandleMessages() {
        using (var ms = new MemoryStream()) {
            var messageBuffer = WebSocket.CreateClientBuffer(8192, 8192);
            WebSocketReceiveResult result;
            do {
                result = await ws.ReceiveAsync(messageBuffer, CancellationToken.None);
                ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
            }
            while (!result.EndOfMessage);

            if (result.MessageType == WebSocketMessageType.Text) {
                var msgString = Encoding.UTF8.GetString(ms.ToArray());
                Debug.Log(msgString);
                var message = JsonConvert.DeserializeObject<Dictionary<String, String>>(msgString);
                if (message["roomCode"] == RoomCode.ToLower()) {
                    // Message was intended for us!
                    Debug.Log("[WS] Got a message of type " + message["messageType"]);
                }
            }
        }
    }
```

<p>So after opening my Websocket connection initially if I call this:</p>

<pre class="lang-cs prettyprint-override"><code>await Task.WhenAll(HandleMessages());
</code>```

then it will handle the first incoming message, but not any subsequent ones. I've tried many different things but I can't figure out how to get this task to run every time a message comes in.

Does anybody have any insight into the matter?

答:
It turns out that there was a good element of user-error in this situation, as always.

I didn't understand some basic concepts of websockets, so when I thought I was broadcasting messages from my server I was really only sending them to certain clients. With the improvements suggested by Marc Gravell and more hours of tinkering my C# client code now looks like this:

public async Task HandleMessages() {
        try {
            using (var ms = new MemoryStream()) {
                while (ws.State == WebSocketState.Open) {
                    WebSocketReceiveResult result;
                    do {
                        var messageBuffer = WebSocket.CreateClientBuffer(1024, 16);
                        result = await ws.ReceiveAsync(messageBuffer, CancellationToken.None);
                        ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
                    }
                    while (!result.EndOfMessage);

                    if (result.MessageType == WebSocketMessageType.Text) {
                        var msgString = Encoding.UTF8.GetString(ms.ToArray());
                        var message = JsonConvert.DeserializeObject<Dictionary<String, String>>(msgString);
                        if (message["roomCode"].ToLower() == RoomCode.ToLower()) {
                            Debug.Log("[WS] Got a message of type " + message["messageType"]);
                            // Message was intended for us!
                            switch (message["messageType"]) {
                                // handle messages here, unimportant to stackoverflow
                            }
                        }
                    }
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Position = 0;
                }
            }
        } catch (InvalidOperationException) {
            Debug.Log("[WS] Tried to receive message while already reading one.");
        }
    }
```

Once I configured the server to actually broadcast the messages I thought I was broadcasting (iterate over all clients and send the message), it now will read multiple messages. Thanks again for the help and hopefully this will help others in the future who are new to websockets have something to check for

Body:
I'm writing a program (really a game in Unity) which should act as a client to a Websocket server which is up and running separately.

I'm using the System.Net.Websockets ClientWebSocket. I have opened the connection, I can send messages, but unlike in a Javascript client where I would set up a callback function which would run each time the websocket client received a message I'm having a hard time understanding the intended flow for the C# API.

Here's a message handler that I've written:

public async Task HandleMessages() {
        using (var ms = new MemoryStream()) {
            var messageBuffer = WebSocket.CreateClientBuffer(8192, 8192);
            WebSocketReceiveResult result;
            do {
                result = await ws.ReceiveAsync(messageBuffer, CancellationToken.None);
                ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
            }
            while (!result.EndOfMessage);

            if (result.MessageType == WebSocketMessageType.Text) {
                var msgString = Encoding.UTF8.GetString(ms.ToArray());
                Debug.Log(msgString);
                var message = JsonConvert.DeserializeObject<Dictionary<String, String>>(msgString);
                if (message["roomCode"] == RoomCode.ToLower()) {
                    // Message was intended for us!
                    Debug.Log("[WS] Got a message of type " + message["messageType"]);
                }
            }
        }
    }

So after opening my Websocket connection initially if I call this:

await Task.WhenAll(HandleMessages());

then it will handle the first incoming message, but not any subsequent ones. I've tried many different things but I can't figure out how to get this task to run every time a message comes in.

Does anybody have any insight into the matter?

Body:
It turns out that there was a good element of user-error in this situation, as always.

I didn't understand some basic concepts of websockets, so when I thought I was broadcasting messages from my server I was really only sending them to certain clients. With the improvements suggested by Marc Gravell and more hours of tinkering my C# client code now looks like this:

public async Task HandleMessages() {
        try {
            using (var ms = new MemoryStream()) {
                while (ws.State == WebSocketState.Open) {
                    WebSocketReceiveResult result;
                    do {
                        var messageBuffer = WebSocket.CreateClientBuffer(1024, 16);
                        result = await ws.ReceiveAsync(messageBuffer, CancellationToken.None);
                        ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
                    }
                    while (!result.EndOfMessage);

                    if (result.MessageType == WebSocketMessageType.Text) {
                        var msgString = Encoding.UTF8.GetString(ms.ToArray());
                        var message = JsonConvert.DeserializeObject<Dictionary<String, String>>(msgString);
                        if (message["roomCode"].ToLower() == RoomCode.ToLower()) {
                            Debug.Log("[WS] Got a message of type " + message["messageType"]);
                            // Message was intended for us!
                            switch (message["messageType"]) {
                                // handle messages here, unimportant to stackoverflow
                            }
                        }
                    }
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Position = 0;
                }
            }
        } catch (InvalidOperationException) {
            Debug.Log("[WS] Tried to receive message while already reading one.");
        }
    }

Once I configured the server to actually broadcast the messages I thought I was broadcasting (iterate over all clients and send the message), it now will read multiple messages. Thanks again for the help and hopefully this will help others in the future who are new to websockets have something to check for


来源: stackexchange

问:
How to remove tombstones with a timestamp in the future
How can tombstones that were inserted with a timestamp set in the very distance future be removed?

Context:
There was a bug in some code that inserted entries with a timestamp in the distant future. The objects were manually deleted by created a tombstone further in the future.

Now inserts that have the same partition key are automatically deleted because of the future tombstone entry. These entries are not removed during compaction because of their timestamp. How can these future tombstones be removed so that entries with the same PKs can be inserted correctly?

答:
I reproduced the same issue by setting client server to +30 mins. I ran delete on a partition from the client. It created tombstone with future timestamp. All my update on source database server with correct time are being ignored because Cassandra only cares about most recent timestamp data.

I did these steps to clear tombstones on a table with this issue

1) Set table property gc_grace_seconds to 0

2) nodetool flush keyspace table

3) nodetool compact keyspace table

I have just one node. If you have multiple nodes then you need to do the above steps on all the nodes except setting table property

NOTE: Doing this will clear all the tombstones and also Compaction is resource intensive

ContentLicense: CC BY-SA 4.0


问:
targeting an enemy's direction towards a player game maker studio 2 DnD
I'm using game maker studio 2 to create a dungeon game as a programming experience, and I am trying to make an enemy target the player. since I don't understand the commands in the program, I'm using Drag and Drop to make it. I set its speed to 4 then it checks if an instance exists (since I have multiple types of player objects) then sets point direction to that player object, but it just starts going to the top left of the screen. does anyone have any idea how I can fix this? Thanks in advance!</p>

答:
Sounds like the X and Y values need to be updated to the instance of the targeted player's object. Im not sure with dnd but with gml you can access it from the object itself. For example if you wanted the player object's 'X' coordinate you could get it using something like this

```<code>objPlayer.x;
</code>```

You may need to use a global variable though if that wont work for you (be sure to update it in a STEP event though!). Also, something else to note is that if you have multiple player objects (which it sounds like you do) then you will need to know the instance ID for that player object. To do this you can use something like this:

```<code>players[i] = instance_create(xx, yy, objPlayer);
</code>```

Side note: I also agree with Steven though. I would recommend starting as simple as possible with this and add complexity to it as you get things working the way you want them to. It will save your sanity in the long run, trust me. ;)

Body:
Sounds like the X and Y values need to be updated to the instance of the targeted player's object. Im not sure with dnd but with gml you can access it from the object itself. For example if you wanted the player object's 'X' coordinate you could get it using something like this

objPlayer.x;

You may need to use a global variable though if that wont work for you (be sure to update it in a STEP event though!). Also, something else to note is that if you have multiple player objects (which it sounds like you do) then you will need to know the instance ID for that player object. To do this you can use something like this:

players[i] = instance_create(xx, yy, objPlayer);

Side note: I also agree with Steven though. I would recommend starting as simple as possible with this and add complexity to it as you get things working the way you want them to. It will save your sanity in the long run, trust me. ;)


问:
Spring Boot keeps crashing my pc...what is the best configuration for sts.ini file on Windows 10?
I'm using Spring Tool Suite IDE on a Windows 10 laptop with an i5 core processor.  Every time I try to run a Spring Boot App, STS hangs and crashes.  The same app works fine on my peers' computers.

Now, even when I run a simple program to practice some coding challenges such as reversing a string, STS will slow down a bit and is not as smooth as before.

These are my current sts.ini file configurations:

```<code>--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.1100.v20190907-0426
-startup
plugins/org.eclipse.equinox.launcher_1.5.600.v20191014-2022.jar
-product
org.springframework.boot.ide.branding.sts4
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
</code>```

I was considering changing my Xmx and Xms size. What should I increase this to for better STS performance.

答:
It depends on your Random Access Memory (RAM) of system.

As per your current sts.ini file,

-Xms256m

-Xmx1024m

which is generally set for 2GB RAM of system.

If you have more than 2GB RAM, for example 4GB RAM, please set:

-Xms512m

-Xmx2048m

Above settings indicates STS will occupy upto 2GB of your 4GB RAM of system, among all other open applications .

Thanks and Regards.

Body:
I'm using Spring Tool Suite IDE on a Windows 10 laptop with an i5 core processor.  Every time I try to run a Spring Boot App, STS hangs and crashes.  The same app works fine on my peers' computers.

Now, even when I run a simple program to practice some coding challenges such as reversing a string, STS will slow down a bit and is not as smooth as before.

These are my current sts.ini file configurations:

--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.1100.v20190907-0426
-startup
plugins/org.eclipse.equinox.launcher_1.5.600.v20191014-2022.jar
-product
org.springframework.boot.ide.branding.sts4
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM

I was considering changing my Xmx and Xms size. What should I increase this to for better STS performance.


问:
Scala, Swing and MVC
I found some informations about using Swing with Scala in Programming in Scala book. I also found some basic informations here: http://www.scala-lang.org/sid/8 . But there are no informations about how to build bigger application based on Swing. Than I found some informations in German (but code is in Scala;)): http://www.scalatutorial.de/topic123.html . And it is good... but still, it is good for small applications. I'm going to wrote something bigger. So I want to make not one, but few models, and few views for each, like in Ruby on Rails. Do you know some good tutorials or egsamples which may help me do it properly?</p>

答: here's a program using scala-swing: https://github.com/lrytz/pacman, also rather small though.</p>

ContentLicense: CC BY-SA 3.0

Title: Scala, Swing and MVC


问:
How to build NixOS/nixpkgs manuals?
How to build manuals for NixOS and nixpkgs?

I also get an error sometimes:

```<code>error: a 'aarch64-linux' with features {} is required to build '...options.xml.drv', but I am a 'x86_64-linux' with features {benchmark, big-parallel, kvm, nixos-test}
</code>```

答:
For NixOS:

$ nix-build nixos/release.nix -A manualHTML.x86_64-linux
```

<p>For Nixpkgs:</p>

<pre class="lang-sh prettyprint-override"><code>$ nix-build doc
</code>```

When building NixOS manual you get an error

```<code>error: a 'aarch64-linux' with features {} is required to build '...options.xml.drv', but I am a 'x86_64-linux' with features {benchmark, big-parallel, kvm, nixos-test}
</code>```

it means you forgot to specify .x86_64-linux attribute.

Title: How to build NixOS/nixpkgs manuals?

Body:
How to build manuals for NixOS and nixpkgs?

I also get an error sometimes:

error: a 'aarch64-linux' with features {} is required to build '...options.xml.drv', but I am a 'x86_64-linux' with features {benchmark, big-parallel, kvm, nixos-test}

Body:
For NixOS:

$ nix-build nixos/release.nix -A manualHTML.x86_64-linux

For Nixpkgs:

$ nix-build doc

When building NixOS manual you get an error

error: a 'aarch64-linux' with features {} is required to build '...options.xml.drv', but I am a 'x86_64-linux' with features {benchmark, big-parallel, kvm, nixos-test}

it means you forgot to specify .x86_64-linux attribute.


问:
Chrome extension: Extension button appears in extensions area but JS doesn't execute on click?
I'm dabbling a bit in making a chrome extension, and I followed the guide here (https://thoughtbot.com/blog/how-to-make-a-chrome-extension), which worked as expected. However, now that I'm changing it to work on other sites, it doesn't execute anything upon clicking the button. I feel like it's something obvious, but I don't know what.

Code:

manifest:

```<code>{
  "manifest_version": 2,
  "name": "extension_name",
  "version": "0.1",

  "description": "extension_description",
  "permissions": [
    "activeTab",
    "declarativeContent",
    "storage",
    "https://*/*",
    "http://*/*"
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

  "page_action": {
    "default_popup": "popup.html"
  }
}
</code>```

Popup:

```<code><!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="myButton">Scan</button>
  </body>
  <script src="popup.js"></script>
</html>
</code>```

Popup JS

```<code>'use strict';
let myBtn = document.getElementById('myButton');
peble.onclick = (element) => {
    console.log("You have hit the button.");
};
</code>```

Background JS

```<code>chrome.runtime.onInstalled.addListener(function() {
    chrome.storage.sync.set({color: '#3aa757'}, function() {
        console.log('Active.');
    });
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [
                new chrome.declarativeContent.PageStateMatcher({
                    pageUrl: {hostEquals: 'www.youtube.com'},
                })
            ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
      }]);
    });
});
</code>```

答: Per wOxxOm - The button has it's own html space - it isn't outputting to the same DOM console as the page.</p>

Body:
I'm dabbling a bit in making a chrome extension, and I followed the guide here (https://thoughtbot.com/blog/how-to-make-a-chrome-extension), which worked as expected. However, now that I'm changing it to work on other sites, it doesn't execute anything upon clicking the button. I feel like it's something obvious, but I don't know what.

Code:

manifest:

{
  "manifest_version": 2,
  "name": "extension_name",
  "version": "0.1",

  "description": "extension_description",
  "permissions": [
    "activeTab",
    "declarativeContent",
    "storage",
    "https://*/*",
    "http://*/*"
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

  "page_action": {
    "default_popup": "popup.html"
  }
}

Popup:

<!DOCTYPE html>

    <button id="myButton">Scan</button>

Popup JS

'use strict';
let myBtn = document.getElementById('myButton');
peble.onclick = (element) => {
    console.log("You have hit the button.");
};

Background JS

chrome.runtime.onInstalled.addListener(function() {
    chrome.storage.sync.set({color: '#3aa757'}, function() {
        console.log('Active.');
    });
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [
                new chrome.declarativeContent.PageStateMatcher({
                    pageUrl: {hostEquals: 'www.youtube.com'},
                })
            ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
      }]);
    });
});


问:
Minimum time quantum needed in nanosleep(), usleep() to yield the CPU
In concurrent code in my workplace, there are several occurrences of nanosleep() or usleep() with a non-zero constant to free up the CPU without relying on futex(), or a sleeping synchronization primitive to put the thread to sleep (for instance, when waiting for an element from a concurrent queue). The code claims to prevent pathological cases where threads consume CPU without doing any actual work when other threads are available to get scheduled on that CPU. This sounds reasonable by itself assuming the cooperation between the sleep functions and the kernel thread scheduler is correct.

Is there a concept in linux where a minimum duration passed to nanosleep(), usleep(), et al. is known to put the calling thread to sleep and run another thread in it's place on the same core when cores are oversubscribed? And if the duration is smaller than that, then the thread does not actually yield the CPU but continue spinning? This forms the basis of the constant passed to the sleep() functions in order to make it behave like a coarse-yield.

I realize that a sched_yield() is probably better suited for what the code is doing; but I just wanted to educate myself on the behavior of the linux sleep() functions before benchmarking a replacement or improvement on the existing code.

Thanks!

答:
The man page makes it clear that it no longer busy-waits.

In order to support applications requiring much more precise pauses
  (e.g., in order to control some time-critical hardware), nanosleep()
  would handle pauses of up to 2 milliseconds by busy waiting with
  microsecond precision when called from a thread scheduled under a
  real-time policy like SCHED_FIFO or SCHED_RR.  This special extension
  was removed in kernel 2.5.39, and is thus not available in Linux
  2.6.0 and later kernels.


问:
Cant Render React Componet, Error In my understanding or code?
So I have built a graph generator and have all the correct data on the props the problem is when I go to render the build component It logs

Object { "$$typeof": Symbol(react.element), type: createElement(), key: "1", ref: null, props: {…}, _owner: null, _store: {…}, … }

Here is the Code I am sure its something silly I am not understanding about the render.

i

```<code>mport React, { Component } from 'react'
import * as action from '../../actions'
import { connect } from 'react-redux'
import jsx from 'react-jsx'
import { bindActionCreators } from 'redux'
import {Modal} from './Modal'
@connect(
  (flux, props) => {

    return {
      filters: flux.FilterStore,
      ready: flux.FilterStore.ready,
      presets: flux.DataStore.preSelectList,
      graphs: flux.GraphStore.graphList
    }
  },
  (dispatch, props) => {
    dispatch(action.fetchGraphList())
    return {
      addDataReportGraphDetails: bindActionCreators(action.addDataReportGraphDetails, dispatch)
    }
  }
)

class RenderGraphPreview extends Component {
  constructor(props) {
    super(props)
    this.state = {
      running: {},
      show:false,
      graph:{}
    }
    this.data = 0;
  }

  //Error function for shorthand errors
  throwError = (string = "Error", err = null) => {
    throw new Error(`${string}:${err}`)
  }

  //simple print function to print objects and strings
  p = (string, variable) => {
    typeof variable === `object` ? variable = JSON.stringify(variable) : variable
    console.log(`${string}:${variable}`)
  }

  showModal = e => {
    this.state.show = true
    }

  generateGraph = ({ presets, filters, graphDetails }) => {
    var reportProps = {
      wasRunning: true,
      companyName: filters.company_name,
      companyVertical: filters.company_vertical,
      graphTitle: jsx.client(`<div>${graphDetails.title}</div>`)(reportProps).props.children
    }
    this.data++

    if (typeof reportProps.graphTitle == "object") {

      reportProps.graphTitle = reportProps.graphTitle.join("")
    }
    if (!this.state.running) {
      reportProps.wasRunning = false
      this.state.running = true
    }
    if (graphDetails.graph) {
      var Graph = React.createFactory(require(`../graphs/${graphDetails.graph}`).default);
      var newGraphProps = {}
      var graphPropKeys = Object.keys(graphDetails.props || {})
      graphPropKeys.map((graphKey) => {

        if (graphDetails.props[graphKey] && graphDetails.props[graphKey].toString().length > 0)
          newGraphProps[graphKey] = graphDetails.props[graphKey]
      })
      if (graphDetails.timeframe) {
        newGraphProps[timeframe] = graphDetails[timeframe]
      }

      if (graphDetails.props.attackIndexFilterPreset) {
        let preset;
        for (let j = 0, jEnd = presets.length; j < jEnd; j++) {
          if (presets[j]._id == graphDetails.props.attackIndexFilterPreset) {
            return preset = presets[j]
          }
        }
        if (preset) {
          console.log(`In presents`)
          newGraphProps = { ...preset, ...newGraphProps }
        }
      }
    }
      // console.log(<Graph key={this.state.count++} isDocument={true} reportKey={graphDetails.key} onImageCreated={this.props.addDataReportGraphDetails} {...filters} {...reportProps} {...newGraphProps}/>)
    return (
      <Graph key={this.data} isDocument={true} reportKey={graphDetails.key} onImageCreated={this.props.addDataReportGraphDetails} {...filters} {...reportProps} {...newGraphProps}/>
    )
  }

    //Verifies we have the correct data to build the graph
    startGraphGeneration = async (e,{ props }) => {
      e.preventDefault()
      let require = this.props.filters && this.props.presets && props
      if (!require) {
        this.throwError()
      }
      let graphProps = {
        presets: this.props.presets,
        filters: this.props.filters,
        graphDetails: props,
      }
     let g = await this.generateGraph(graphProps)
      this.setState({
        graph: g
      });
     console.log(g)

    }

    render() {
      var x = this.state.graph
    return (

     <div>
       <button onClick={(e) => this.startGraphGeneration(e,this.props)}>Preview Graph</button>
        {this.state.graph ? <x/> : `Doing Noting`}
     </div>
    )

    }
  }

  export default connect()(RenderGraphPreview)
</code>```

答:
In your render method you use this.state.graph. You set this variable to the value returned from generateGraph function, which returns rendered node, not a component
. And then you try to render this node as a component(<x/>), which doesn't work. Also in
generateGraph function console.log(g) shows you rendered component. So just return x in you render method instead:

```<code> render() {
    var x = this.state.graph
    return (

     <div>
       <button onClick={(e) => this.startGraphGeneration(e,this.props)}>Preview Graph</button>
        {this.state.graph ? x : `Doing Noting`}
     </div>
    )
 }

</code>```

Body:
So I have built a graph generator and have all the correct data on the props the problem is when I go to render the build component It logs

Object { "$$typeof": Symbol(react.element), type: createElement(), key: "1", ref: null, props: {…}, _owner: null, _store: {…}, … }

Here is the Code I am sure its something silly I am not understanding about the render.

i

mport React, { Component } from 'react'
import * as action from '../../actions'
import { connect } from 'react-redux'
import jsx from 'react-jsx'
import { bindActionCreators } from 'redux'
import {Modal} from './Modal'
@connect(
  (flux, props) => {

    return {
      filters: flux.FilterStore,
      ready: flux.FilterStore.ready,
      presets: flux.DataStore.preSelectList,
      graphs: flux.GraphStore.graphList
    }
  },
  (dispatch, props) => {
    dispatch(action.fetchGraphList())
    return {
      addDataReportGraphDetails: bindActionCreators(action.addDataReportGraphDetails, dispatch)
    }
  }
)

class RenderGraphPreview extends Component {
  constructor(props) {
    super(props)
    this.state = {
      running: {},
      show:false,
      graph:{}
    }
    this.data = 0;
  }

  //Error function for shorthand errors
  throwError = (string = "Error", err = null) => {
    throw new Error(`${string}:${err}`)
  }

  //simple print function to print objects and strings
  p = (string, variable) => {
    typeof variable === `object` ? variable = JSON.stringify(variable) : variable
    console.log(`${string}:${variable}`)
  }

  showModal = e => {
    this.state.show = true
    }

  generateGraph = ({ presets, filters, graphDetails }) => {
    var reportProps = {
      wasRunning: true,
      companyName: filters.company_name,
      companyVertical: filters.company_vertical,
      graphTitle: jsx.client(`<div>${graphDetails.title}</div>`)(reportProps).props.children
    }
    this.data++

    if (typeof reportProps.graphTitle == "object") {

      reportProps.graphTitle = reportProps.graphTitle.join("")
    }
    if (!this.state.running) {
      reportProps.wasRunning = false
      this.state.running = true
    }
    if (graphDetails.graph) {
      var Graph = React.createFactory(require(`../graphs/${graphDetails.graph}`).default);
      var newGraphProps = {}
      var graphPropKeys = Object.keys(graphDetails.props || {})
      graphPropKeys.map((graphKey) => {

        if (graphDetails.props[graphKey] && graphDetails.props[graphKey].toString().length > 0)
          newGraphProps[graphKey] = graphDetails.props[graphKey]
      })
      if (graphDetails.timeframe) {
        newGraphProps[timeframe] = graphDetails[timeframe]
      }

      if (graphDetails.props.attackIndexFilterPreset) {
        let preset;
        for (let j = 0, jEnd = presets.length; j < jEnd; j++) {
          if (presets[j]._id == graphDetails.props.attackIndexFilterPreset) {
            return preset = presets[j]
          }
        }
        if (preset) {
          console.log(`In presents`)
          newGraphProps = { ...preset, ...newGraphProps }
        }
      }
    }
      // console.log(<Graph key={this.state.count++} isDocument={true} reportKey={graphDetails.key} onImageCreated={this.props.addDataReportGraphDetails} {...filters} {...reportProps} {...newGraphProps}/>)
    return (
      <Graph key={this.data} isDocument={true} reportKey={graphDetails.key} onImageCreated={this.props.addDataReportGraphDetails} {...filters} {...reportProps} {...newGraphProps}/>
    )
  }

    //Verifies we have the correct data to build the graph
    startGraphGeneration = async (e,{ props }) => {
      e.preventDefault()
      let require = this.props.filters && this.props.presets && props
      if (!require) {
        this.throwError()
      }
      let graphProps = {
        presets: this.props.presets,
        filters: this.props.filters,
        graphDetails: props,
      }
     let g = await this.generateGraph(graphProps)
      this.setState({
        graph: g
      });
     console.log(g)

    }

    render() {
      var x = this.state.graph
    return (

       <button onClick={(e) => this.startGraphGeneration(e,this.props)}>Preview Graph</button>
        {this.state.graph ? <x/> : `Doing Noting`}

    )

    }
  }

  export default connect()(RenderGraphPreview)

Body:
In your render method you use this.state.graph. You set this variable to the value returned from generateGraph function, which returns rendered node, not a component
. And then you try to render this node as a component(<x/>), which doesn't work. Also in
generateGraph function console.log(g) shows you rendered component. So just return x in you render method instead:

 render() {
    var x = this.state.graph
    return (

     <div>
       <button onClick={(e) => this.startGraphGeneration(e,this.props)}>Preview Graph</button>
        {this.state.graph ? x : `Doing Noting`}
     </div>
    )
 }


问:
telegram bot: how should i get user feedback after forcereply?
```<code>#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

from apikey import tgbottoken,authedchat
from telebot import types
import telebot,logging

bot =telebot.TeleBot(tgbottoken)
telebot.logger.setLevel(logging.DEBUG)

def extract_arg(arg):
    return arg.split()[1:]

@bot.message_handler(commands=['newmail'])
def mailwithsg(msg):
    cid = msg.chat.id
    sendto = types.ForceReply(selective=False)
    bot.send_message(cid, "Send me another word:", reply_markup=sendto)

bot.polling(none_stop=True)
</code>```

after I use the methods and send a reply markup message, how should I get user's reply text (like user feedback)? which method should I use?

I now use pyTelegramBotAPI as a Python Wrapper.

答:
use my method from php - i think you can translate it to python;</p>

```<code>switch($reply_to_message_text)
   case 'Send me another word:':
        $usersreply =  $message ;
        $this->db->addfeedback($user_id,$usersreply)

     --------->here you can send some text to user and say Thanks)
</code>```

Body:
#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

from apikey import tgbottoken,authedchat
from telebot import types
import telebot,logging

bot =telebot.TeleBot(tgbottoken)
telebot.logger.setLevel(logging.DEBUG)

def extract_arg(arg):
    return arg.split()[1:]

@bot.message_handler(commands=['newmail'])
def mailwithsg(msg):
    cid = msg.chat.id
    sendto = types.ForceReply(selective=False)
    bot.send_message(cid, "Send me another word:", reply_markup=sendto)

bot.polling(none_stop=True)

after I use the methods and send a reply markup message, how should I get user's reply text (like user feedback)? which method should I use?

I now use pyTelegramBotAPI as a Python Wrapper.

Body:
use my method from php - i think you can translate it to python;

switch($reply_to_message_text)
   case 'Send me another word:':
        $usersreply =  $message ;
        $this->db->addfeedback($user_id,$usersreply)

     --------->here you can send some text to user and say Thanks)


问:
How can I delay document.ready until a variable is set?
I am doing QUnit testing in an IFRAME and have a recursive JavaScript function that loads all of the scripts from the parent page into the IFRAME before starting QUnit.  This works great.  My problem is that some of our scripts use document.ready to make stuff start.

Something such as:

```<code>$(document).ready(function () {
    // blah
});
</code>```

to do do their work.  I'd prefer to not change production code just to account for tests and I don't want these production scripts to think the IFRAME document is "ready" until every scripts is loaded.

How I can delay "document.ready" itself?

Here is my pseudocode to give you an example to work from:

```<code>scripts[0] = "/foo/bar.js";
scripts[1] = "/blah/blah.js";

function RecursiveScriptStart(){
    // I want to set document.ready = false right here!
    if(scripts.length == 0) {
        QUnitStart();
        return;
    }
    RecursiveScriptLoader(0, scripts);
}

function RecursiveScriptLoader(currentScriptID, scripts) {
    $.getScript(scripts[currentScriptID], function () {
        if (currentScriptID == (scripts.length - 1)) {
            QUnitStart();
        }
        else {
            RecursiveScriptLoader(currentScriptID + 1, scripts);
        }
    });
}

function QUnitStart() {
        // I want to set document.ready = true right here!
        QUnit.stop();
        QUnit.start();
}
</code>```

The actual code is similar, but involves a jquery selector populating the array "scripts[]" with JavaScript tag "src" properties.

Thanks!

答: If you're using jQuery 1.6+ then you can use holdReady.  Just set $.holdReady(true) at the top of your script and then in the beginning of QUnitStart set $.holdReady(false).

Body:
I am doing QUnit testing in an IFRAME and have a recursive JavaScript function that loads all of the scripts from the parent page into the IFRAME before starting QUnit.  This works great.  My problem is that some of our scripts use document.ready to make stuff start.

Something such as:

$(document).ready(function () {
    // blah
});

to do do their work.  I'd prefer to not change production code just to account for tests and I don't want these production scripts to think the IFRAME document is "ready" until every scripts is loaded.

How I can delay "document.ready" itself?

Here is my pseudocode to give you an example to work from:

scripts[0] = "/foo/bar.js";
scripts[1] = "/blah/blah.js";

function RecursiveScriptStart(){
    // I want to set document.ready = false right here!
    if(scripts.length == 0) {
        QUnitStart();
        return;
    }
    RecursiveScriptLoader(0, scripts);
}

function RecursiveScriptLoader(currentScriptID, scripts) {
    $.getScript(scripts[currentScriptID], function () {
        if (currentScriptID == (scripts.length - 1)) {
            QUnitStart();
        }
        else {
            RecursiveScriptLoader(currentScriptID + 1, scripts);
        }
    });
}

function QUnitStart() {
        // I want to set document.ready = true right here!
        QUnit.stop();
        QUnit.start();
}

The actual code is similar, but involves a jquery selector populating the array "scripts[]" with JavaScript tag "src" properties.

Thanks!


问:
Encoding issue with csvhelper and html markup
I am using csvhelper 15.  My code looks like:

```<code>using (var reader = new StreamReader(_csvPath, Encoding.UTF8))
        {
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Configuration.MissingFieldFound = null;
                csv.Configuration.TrimOptions = TrimOptions.Trim;
                csv.Configuration.Encoding = Encoding.UTF8;

                profiles = csv.GetRecords<Profile>().ToList();
            }
        }
</code>```

In one of my fields in the csv i have html markup looks like:

```<code><p>Standard Chartered plc on its fully underwritten 2 for 7 rights issue to raise approximately £3.3 billion</p>
</code>```

The pound sign ends up at ? so looks like encoding, I am using utf8 however still an issue on the read.

Am i missing something?

答:
CsvHelper uses a TextReader and knows nothing about the encoding of the file. That is something that needs to be handled before passing the TextReader into `CsvHelper.

The CultureInfo that is required in the constructor is used for type conversions. When a string is converted into an int or DateTimeOffset, it uses the CultureInfo that is supplied.

In your case, the ? values are due to the encoding set on the TextReader that was supplied to CsvHelper.

Body:
I am using csvhelper 15.  My code looks like:

using (var reader = new StreamReader(_csvPath, Encoding.UTF8))
        {
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Configuration.MissingFieldFound = null;
                csv.Configuration.TrimOptions = TrimOptions.Trim;
                csv.Configuration.Encoding = Encoding.UTF8;

                profiles = csv.GetRecords<Profile>().ToList();
            }
        }

In one of my fields in the csv i have html markup looks like:

Standard Chartered plc on its fully underwritten 2 for 7 rights issue to raise approximately £3.3 billion

The pound sign ends up at ? so looks like encoding, I am using utf8 however still an issue on the read.

Am i missing something?


问:
HTML iframe shows scrollbar during animation and then disappears. CSS overflow property is set to hidden
I am building a Chrome extension which inserts an iframe onto the screen when activated. I have set the CSS property to hidden. The scrollbar is displaying during the animation (both ways), and it immediately disappears after the animation.

The animation wipes or scrolls the iframe onto the screen from the bottom edge of the browser window.

I am aware that the seamless property was removed from iframes in HTML5.

How can I prevent the scrollbar from displaying during the animations?

答:
Fixed by doing the following in javascript after creating the iframe.</p>

```<code>iFrame.scrolling = 'no';
</code>```

Body:
Fixed by doing the following in javascript after creating the iframe.

iFrame.scrolling = 'no';


问:
Exception in thread "main" java.lang.NoClassDefFoundError: gherkin/formatter/Formatter Cucumber 5.2.0
I am trying to setup my first Cucumber effort in Eclipse. I setup a basic feature file in the Features folder the way that the tutorial video suggested, but trying to execute as a cucumber feature, I get the following:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: gherkin/formatter/Formatter
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:821)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:719)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:642)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:600)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at cucumber.runtime.formatter.PluginFactory$1.<init>(PluginFactory.java:53)
    at cucumber.runtime.formatter.PluginFactory.<clinit>(PluginFactory.java:52)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:70)
    at cucumber.api.cli.Main.run(Main.java:31)
    at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.ClassNotFoundException: gherkin.formatter.Formatter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 14 more
</code>```

I have followed all the steps listed by the tutorial video I am watching, but no success. I have the following installed:

Eclipse 2019-12, Java SE 13

I downloaded and installed all the jar files locally. I have read that the potential for conflicts can arise with a large number of jar files that could interfere with one another so I updated all my jar files to the latest versions. Still no help. I then eliminated installed jars one at a time and attempted to run again until I got down to the bare necessities. The issue still persists.

Here is a snippet of my setup:

Snapshot of my project in Eclipse

I'm open to any help that others can provide

答:
I downloaded and installed all the jar files locally. I have read that the potential for conflicts can arise with a large number of jar files that could interfere with one another so I updated all my jar files to the latest versions. Still no help. I then eliminated installed jars one at a time and attempted to run again until I got down to the bare necessities. The issue still persists.

If you follow the 10 minute tutorial you'll get an introduction that uses Maven dependency management.

In addition to this tutorial I would strongly urge you to invest time in learning either Maven or Gradle along with Cucumber. Amongst other things these tools will automate your dependency management and this can make your life much easier.

For example:

If you want to use Cucumber with JUnit 4 and annotation based step definitions you would declare this minimal set of dependencies in a Maven pom.xml file.

```<code>    <properties>
        <cucumber.version>5.2.0</cucumber.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

By telling Maven what your dependencies are Maven can calculate your transitive dependencies i.e: the dependencies of your dependencies.

This has many advantages. One example would be using the mvn dependency:tree command to will list all dependencies. This is much faster and much less error prone then downloading jar files by hand and hoping that you have the right ones.

```<code>$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< cucumber:cucumber-java-skeleton >-------------------
[INFO] Building Cucumber-Java Skeleton 0.0.1
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ cucumber-java-skeleton ---
[INFO] cucumber:cucumber-java-skeleton:jar:0.0.1
[INFO] +- io.cucumber:cucumber-java:jar:5.2.0:test
[INFO] |  +- io.cucumber:cucumber-core:jar:5.2.0:test
[INFO] |  |  +- io.cucumber:cucumber-gherkin:jar:5.2.0:test
[INFO] |  |  +- io.cucumber:cucumber-gherkin-vintage:jar:5.2.0:test
[INFO] |  |  +- io.cucumber:tag-expressions:jar:2.0.4:test
[INFO] |  |  +- io.cucumber:cucumber-expressions:jar:8.3.1:test
[INFO] |  |  +- io.cucumber:datatable:jar:3.3.0:test
[INFO] |  |  +- io.cucumber:cucumber-plugin:jar:5.2.0:test
[INFO] |  |  \- io.cucumber:docstring:jar:5.2.0:test
[INFO] |  \- org.apiguardian:apiguardian-api:jar:1.1.0:test
[INFO] +- io.cucumber:cucumber-junit:jar:5.2.0:test
[INFO] \- junit:junit:jar:4.13:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.781 s
[INFO] Finished at: 2020-02-10T23:00:14+01:00
[INFO] ------------------------------------------------------------------------
</code>```

Body:
I am trying to setup my first Cucumber effort in Eclipse. I setup a basic feature file in the Features folder the way that the tutorial video suggested, but trying to execute as a cucumber feature, I get the following:

Exception in thread "main" java.lang.NoClassDefFoundError: gherkin/formatter/Formatter
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:821)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:719)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:642)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:600)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at cucumber.runtime.formatter.PluginFactory$1.<init>(PluginFactory.java:53)
    at cucumber.runtime.formatter.PluginFactory.<clinit>(PluginFactory.java:52)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:70)
    at cucumber.api.cli.Main.run(Main.java:31)
    at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.ClassNotFoundException: gherkin.formatter.Formatter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 14 more

I have followed all the steps listed by the tutorial video I am watching, but no success. I have the following installed:

Eclipse 2019-12, Java SE 13

I downloaded and installed all the jar files locally. I have read that the potential for conflicts can arise with a large number of jar files that could interfere with one another so I updated all my jar files to the latest versions. Still no help. I then eliminated installed jars one at a time and attempted to run again until I got down to the bare necessities. The issue still persists.

Here is a snippet of my setup:

Snapshot of my project in Eclipse

I'm open to any help that others can provide

Body:
I downloaded and installed all the jar files locally. I have read that the potential for conflicts can arise with a large number of jar files that could interfere with one another so I updated all my jar files to the latest versions. Still no help. I then eliminated installed jars one at a time and attempted to run again until I got down to the bare necessities. The issue still persists.

If you follow the 10 minute tutorial you'll get an introduction that uses Maven dependency management.

In addition to this tutorial I would strongly urge you to invest time in learning either Maven or Gradle along with Cucumber. Amongst other things these tools will automate your dependency management and this can make your life much easier.

For example:

If you want to use Cucumber with JUnit 4 and annotation based step definitions you would declare this minimal set of dependencies in a Maven pom.xml file.

    <properties>
        <cucumber.version>5.2.0</cucumber.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

By telling Maven what your dependencies are Maven can calculate your transitive dependencies i.e: the dependencies of your dependencies.

This has many advantages. One example would be using the mvn dependency:tree command to will list all dependencies. This is much faster and much less error prone then downloading jar files by hand and hoping that you have the right ones.

$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< cucumber:cucumber-java-skeleton >-------------------
[INFO] Building Cucumber-Java Skeleton 0.0.1
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ cucumber-java-skeleton ---
[INFO] cucumber:cucumber-java-skeleton:jar:0.0.1
[INFO] +- io.cucumber:cucumber-java:jar:5.2.0:test
[INFO] |  +- io.cucumber:cucumber-core:jar:5.2.0:test
[INFO] |  |  +- io.cucumber:cucumber-gherkin:jar:5.2.0:test
[INFO] |  |  +- io.cucumber:cucumber-gherkin-vintage:jar:5.2.0:test
[INFO] |  |  +- io.cucumber:tag-expressions:jar:2.0.4:test
[INFO] |  |  +- io.cucumber:cucumber-expressions:jar:8.3.1:test
[INFO] |  |  +- io.cucumber:datatable:jar:3.3.0:test
[INFO] |  |  +- io.cucumber:cucumber-plugin:jar:5.2.0:test
[INFO] |  |  \- io.cucumber:docstring:jar:5.2.0:test
[INFO] |  \- org.apiguardian:apiguardian-api:jar:1.1.0:test
[INFO] +- io.cucumber:cucumber-junit:jar:5.2.0:test
[INFO] \- junit:junit:jar:4.13:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.781 s
[INFO] Finished at: 2020-02-10T23:00:14+01:00
[INFO] ------------------------------------------------------------------------


问:
Upload zero size final part to Google Cloud Storage resumable upload
A common problem when using resumable upload's is that the final size of the upload is not known when it is started. Google has solved this problem through allowing the user to (credit to this SO answer):

(a) send a chunk that is not a multiple of 256kB (the required chunk size of
GCS), or

(b) sending a chunk with bytes NNN-MMM/(MMM+1). That is, the
last chunk contains the total size for the upload and indicates that
it contains the last byte

The problem I am having is with the edge case of sending the last chunk that is a multiple of 256kB and not knowing it is the last chunk until after it has already been sent to the GCS API. I thought I would be able to get around this by sending a zero byte chunk with headers of Content-Length: 0 and Content-Range: NNN-MMM/(MMM+1), e.g (Content-Range: 262143-262143/262144). This does not appear to work though, and I get a 408 timeout response and the object is not finalized.

What can I do to solve this problem and tell the GCS API that my upload is finished after I have already uploaded all the data?

答:
The issue with a packet of length 0 at the end is a known issue which is being tracked on This Github Channel It is still an open issue.

The issue seems to be that the server treats it as a 0 byte upload and returns that the previous chunks were uploaded but the client continues waiting for the confirmation of the last chunk.

As a work around you can be reading for the current chunk and following chunk, and when detect that following chunk length is 0 you can divide current chunk in two chunks.


问:
Using number as "index" (JSON)
Recently started digging in to JSON, and I'm currently trying to use a number as "identifier", which doesn't work out too well. foo:"bar" works fine, while 0:"bar" doesn't.

```<code>var Game = {
    status: [
                {
                    0:"val",
                    1:"val",
                    2:"val"
                },
                {
                    0:"val",
                    1:"val",
                    2:"val"
                }
           ]
}

alert(Game.status[0].0);
</code>```

Is there any way to do it the following way? Something like Game.status[0].0 Would make my life way easier. Of course there's other ways around it, but this way is preferred.

答:
JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.

The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

Title: Using number as "index" (JSON)

Body:
Recently started digging in to JSON, and I'm currently trying to use a number as "identifier", which doesn't work out too well. foo:"bar" works fine, while 0:"bar" doesn't.

var Game = {
    status: [
                {
                    0:"val",
                    1:"val",
                    2:"val"
                },
                {
                    0:"val",
                    1:"val",
                    2:"val"
                }
           ]
}

alert(Game.status[0].0);

Is there any way to do it the following way? Something like Game.status[0].0 Would make my life way easier. Of course there's other ways around it, but this way is preferred.


问:
Is there a fast and non-fancy C# code/algorithm to compress a string of comma separated digits close to maximum info density?
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

```<code>select SumKeys(id), name from SomeTable where name='multiple rows named this'
</code>```

and I get something like:

```<code>SumKeys         name
--------        ---------
1,4,495         multiple rows named this
</code>```

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?

答: How about a hexadecimal representation, where every digit represents a 4-bit half of a character byte (a nibble), with 0xa used as the comma? You will only get a 50% compression, but it is fast and simple.

Body:
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

select SumKeys(id), name from SomeTable where name='multiple rows named this'

and I get something like:

SumKeys         name
--------        ---------
1,4,495         multiple rows named this

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?


问:
Can't bind angular-mentions in contenteditable in angular 8
I am using contenteditable in the div element in an Angular 8 project. I tried using angular-mentions in my project. I have used npm to include that mention in my project. While doing that [mention] tag is not at all recognized.

I am using this https://github.com/dmacfarlane/angular-mentions

```<code>npm install angular-mentions
</code>```

Here is the error I am getting in the console:

Can't bind to 'mention' since it isn't a known property of 'div'. ][mention]="items" id="rteditor" class="scrollbox-content"
  contenteditable="true" placeholder="Type a "):

Here is the div element where I am using the mention

```<code><div [mention]="items" id="rteditor" class="scrollbox-content" contenteditable="true" placeholder="Type a message here..."></div>
</code>```

This is the angular mention version I am using:

```<code>"angular-mentions": "^1.1.2",
</code>```

I also have imported the module in the app.module.ts before using it in my component:

```<code>@NgModule({ imports: [ BrowserModule, MentionModule]})
</code>```

I have followed the below demo and implemented the same, still it didn't work.

https://stackblitz.com/edit/angular-mentions?file=app%2Fapp.component.html

Note:

I have also tried with the latest version (1.1.3) of angular-mention. Still the issue persists.

I have removed the angular-mention package completely and installed it again.

I have Googled and tried various ways to fix this issue, but ended up with no solution.

Could anyone please help me on this? Thanks in advance.

答:
Answer:

Changed the angular-mentions import statement as below. It worked!

```<code>import { MentionModule } from 'angular-mentions/';
</code>```

Body:
I am using contenteditable in the div element in an Angular 8 project. I tried using angular-mentions in my project. I have used npm to include that mention in my project. While doing that [mention] tag is not at all recognized.

I am using this https://github.com/dmacfarlane/angular-mentions

npm install angular-mentions

Here is the error I am getting in the console:

Can't bind to 'mention' since it isn't a known property of 'div'. ][mention]="items" id="rteditor" class="scrollbox-content"
  contenteditable="true" placeholder="Type a "):

Here is the div element where I am using the mention

This is the angular mention version I am using:

"angular-mentions": "^1.1.2",

I also have imported the module in the app.module.ts before using it in my component:

@NgModule({ imports: [ BrowserModule, MentionModule]})

I have followed the below demo and implemented the same, still it didn't work.

https://stackblitz.com/edit/angular-mentions?file=app%2Fapp.component.html

Note:

I have also tried with the latest version (1.1.3) of angular-mention. Still the issue persists.

I have removed the angular-mention package completely and installed it again.

I have Googled and tried various ways to fix this issue, but ended up with no solution.

Could anyone please help me on this? Thanks in advance.

Body:
Answer:

Changed the angular-mentions import statement as below. It worked!

import { MentionModule } from 'angular-mentions/';


问:
generating GeoTIFF colormaps
I am generating 2D statistical maps and would like to also generate and save the image colormaps.  The mean-size image has a data type of float32.  The following example modified from online sources:

```<code>with rasterio.open(name,'w',**profile) as dst:
    dst.write(data.astype(np.float32), 1)
    dst.write_colormap(
        1, {
            0: (255, 0, 0, 255),
            255: (0, 0, 255, 255) })
    cmap = dst.colormap(1)
    print (cmp)
</code>```

Does not work, and the call to colormap(1) returns a NULL table and terminates the program.

Changing the data type to uint8 or uint16, it works after a fashion, but I have been unable to find examples on how to change the color tables and maps for floating point and integer data types.

Could someone provide a snippet that shows how to generate different colormaps, colorinterps and/or color pallets for floating point images? While I am currently using rasterio, I can also convert this GDAL if someone can post a solution.

答:
The reason why your program crashes is almost certainly because you are reading the file while it is still open. The format and syntax of your color table is correct. The following code will exit the first context manager to close the file, then reopen. Please try:</p>

```<code>with rasterio.open(name,'w',**profile) as dst:
    dst.write(data.astype(np.float32), 1)
    dst.write_colormap(
        1, {
            0: (255, 0, 0, 255),
            255: (0, 0, 255, 255) })

with rasterio.open(name) as dst:
    cmap = dst.colormap(1)
    print (cmp)
</code>```

Title: generating GeoTIFF colormaps

Body:
I am generating 2D statistical maps and would like to also generate and save the image colormaps.  The mean-size image has a data type of float32.  The following example modified from online sources:

with rasterio.open(name,'w',**profile) as dst:
    dst.write(data.astype(np.float32), 1)
    dst.write_colormap(
        1, {
            0: (255, 0, 0, 255),
            255: (0, 0, 255, 255) })
    cmap = dst.colormap(1)
    print (cmp)

Does not work, and the call to colormap(1) returns a NULL table and terminates the program.

Changing the data type to uint8 or uint16, it works after a fashion, but I have been unable to find examples on how to change the color tables and maps for floating point and integer data types.

Could someone provide a snippet that shows how to generate different colormaps, colorinterps and/or color pallets for floating point images? While I am currently using rasterio, I can also convert this GDAL if someone can post a solution.

Body:
The reason why your program crashes is almost certainly because you are reading the file while it is still open. The format and syntax of your color table is correct. The following code will exit the first context manager to close the file, then reopen. Please try:

with rasterio.open(name,'w',**profile) as dst:
    dst.write(data.astype(np.float32), 1)
    dst.write_colormap(
        1, {
            0: (255, 0, 0, 255),
            255: (0, 0, 255, 255) })

with rasterio.open(name) as dst:
    cmap = dst.colormap(1)
    print (cmp)


问:
SQL Query To Obtain Value that Occurs more than once
I need to query my database to show the records inside my table where lastname occurs more than three times. Example: in my Students Table, there are 3 people with Lastname 'Smith', 4 with 'Johnson', and 1 with 'Potter'. My query should show the records of those with the lastnames Smith, and Johnson since these values occur more than or equal to 3 times.

Can anyone point me to this? I was thinking of using COUNT() but I can't seem to think how to apply it?

答:
I think this answer can also work (it may require a little bit of modification though) :</p>

```<code>SELECT * FROM Students AS S1 WHERE EXISTS(SELECT Lastname, count(*) FROM Students AS S2 GROUP BY Lastname HAVING COUNT(*) > 3 WHERE S2.Lastname = S1.Lastname)
</code>```

Body:
I think this answer can also work (it may require a little bit of modification though) :

SELECT * FROM Students AS S1 WHERE EXISTS(SELECT Lastname, count(*) FROM Students AS S2 GROUP BY Lastname HAVING COUNT(*) > 3 WHERE S2.Lastname = S1.Lastname)


问:
How to add the sum of cubes using a function in python?
I can get the answer of cubes but I don't really know where to go from here to get the function to return back the answer and keep adding it to a sum! What do I have to do to make it keep adding to get a total?</p>

```<code>def sumNCubes(n):
    for i in range(n)
    return (n-1)**3
def main():
    number = int(raw_input("What number do you want to find the sum of cubes for?"))
    n = number + 1
    for i in range(number):
        n = n - 1
    print "The result of the sums is:", sumNCubes(n)
main()
</code>```

答:
Without using n**3

```<code>def sum_cubes (n):
    b, c, sum = 1, 0, 0
    for a in range(0, 6*n, 6):
        sum += (c := c + (b := b + a))
    return sum
</code>```

Without a loop

```<code> def sum_cubes (n):
     return (n*(n+1)//2)**2
</code>```

Body:
I can get the answer of cubes but I don't really know where to go from here to get the function to return back the answer and keep adding it to a sum! What do I have to do to make it keep adding to get a total?

def sumNCubes(n):
    for i in range(n)
    return (n-1)**3
def main():
    number = int(raw_input("What number do you want to find the sum of cubes for?"))
    n = number + 1
    for i in range(number):
        n = n - 1
    print "The result of the sums is:", sumNCubes(n)
main()

Body:
Without using n**3

def sum_cubes (n):
    b, c, sum = 1, 0, 0
    for a in range(0, 6*n, 6):
        sum += (c := c + (b := b + a))
    return sum

Without a loop

 def sum_cubes (n):
     return (n*(n+1)//2)**2


问:
JavaScript sort a dictionary array
I have a question about sorting a dictionary object is JS es6. I am trying to filter the array but still keep the structure of an array in each month's object. Here is a mock of the data:

```<code>"soldListings": {
    "Jan - 2020": [
        {
            "id": 159,
            "user_id": 1,
            "type_id": 1,
        },
        {
            "id": 173,
            "user_id": 1,
            "type_id": 1,
        },
        {
            "id": 563,
            "user_id": 1,
            "type_id": 2,
        }
    ],
    "Dec - 2019": [
        {
            "id": 183,
            "user_id": 1,
            "type_id": 1,
        }
    ],
    "Oct - 2019": [
        {
            "id": 176,
            "user_id": 1,
            "type_id": 1,
        }
    ]
}
</code>```

If it were a flat array of objects i would do something like:

```<code>typeFilter = data.filter((listing) => {
            if(listing.type_id){
                return listing.type_id == this.state.soldListTypeFilter ;
            }
        });
</code>```

UPDATE

I need the output to be in the same format as the input. For example if i were to filter the object by type_id = 2 it would return this:

```<code>"soldListings": {
"Jan - 2020": [
    {
        "id": 563,
        "user_id": 1,
        "type_id": 2,
    }
],
"Dec - 2019": [

],
"Oct - 2019": [

]
</code>```

}

答:
Use keySort function for this problem, for un-integer keys
Read https://stackoverflow.com/a/23202095/7146552

keySort( object, sortfn? )

function keySort(obj, sort) {
  var keys = Object.keys(obj);
  keys = keys.sort(sort);
  var sortedObject = {};
  for (var i = 0; i < keys.length; i++) {
    sortedObject[keys[i]] = obj[keys[i]]
  }
  return sortedObject;
}

// Using
var obj = {
  "z:": "Zvalue",
  "a": "AValue"
};
console.log(obj);
obj = keySort(obj);
// or
obj = keySort(obj, (a, b) => {
  return a > b ? 1 : -1
});
console.log(obj)```
</div>
</div>
</p>

<h1>On your Question Test</h1>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function keySort(obj, sort) {
  var keys = Object.keys(obj);
  keys = keys.sort(sort);
  var sortedObject = {};
  for (var i = 0; i < keys.length; i++) {
    sortedObject[keys[i]] = obj[keys[i]]
  }
  return sortedObject;
}
data = {
  "Jan - 2020": [{
      "id": 159,
      "user_id": 1,
      "type_id": 1,
    },
    {
      "id": 173,
      "user_id": 1,
      "type_id": 1,
    },
    {
      "id": 563,
      "user_id": 1,
      "type_id": 2,
    }
  ],
  "Dec - 2019": [{
    "id": 183,
    "user_id": 1,
    "type_id": 1,
  }],
  "Oct - 2019": [{
    "id": 176,
    "user_id": 1,
    "type_id": 1,
  }]
}

data = keySort(data,function(a,b){
  adate = new Date(a);
  bdate = new Date(b);
  return adate>bdate ? 1 : -1;
})
console.log(data);</code>```

Title: JavaScript sort a dictionary array

Body:
I have a question about sorting a dictionary object is JS es6. I am trying to filter the array but still keep the structure of an array in each month's object. Here is a mock of the data:

"soldListings": {
    "Jan - 2020": [
        {
            "id": 159,
            "user_id": 1,
            "type_id": 1,
        },
        {
            "id": 173,
            "user_id": 1,
            "type_id": 1,
        },
        {
            "id": 563,
            "user_id": 1,
            "type_id": 2,
        }
    ],
    "Dec - 2019": [
        {
            "id": 183,
            "user_id": 1,
            "type_id": 1,
        }
    ],
    "Oct - 2019": [
        {
            "id": 176,
            "user_id": 1,
            "type_id": 1,
        }
    ]
}

If it were a flat array of objects i would do something like:

typeFilter = data.filter((listing) => {
            if(listing.type_id){
                return listing.type_id == this.state.soldListTypeFilter ;
            }
        });

UPDATE

I need the output to be in the same format as the input. For example if i were to filter the object by type_id = 2 it would return this:

"soldListings": {
"Jan - 2020": [
    {
        "id": 563,
        "user_id": 1,
        "type_id": 2,
    }
],
"Dec - 2019": [

],
"Oct - 2019": [

]

}

Body:
Use keySort function for this problem, for un-integer keys
Read https://stackoverflow.com/a/23202095/7146552

keySort( object, sortfn? )

function keySort(obj, sort) {
  var keys = Object.keys(obj);
  keys = keys.sort(sort);
  var sortedObject = {};
  for (var i = 0; i < keys.length; i++) {
    sortedObject[keys[i]] = obj[keys[i]]
  }
  return sortedObject;
}

// Using
var obj = {
  "z:": "Zvalue",
  "a": "AValue"
};
console.log(obj);
obj = keySort(obj);
// or
obj = keySort(obj, (a, b) => {
  return a > b ? 1 : -1
});
console.log(obj)

On your Question Test

function keySort(obj, sort) {
  var keys = Object.keys(obj);
  keys = keys.sort(sort);
  var sortedObject = {};
  for (var i = 0; i < keys.length; i++) {
    sortedObject[keys[i]] = obj[keys[i]]
  }
  return sortedObject;
}
data = {
  "Jan - 2020": [{
      "id": 159,
      "user_id": 1,
      "type_id": 1,
    },
    {
      "id": 173,
      "user_id": 1,
      "type_id": 1,
    },
    {
      "id": 563,
      "user_id": 1,
      "type_id": 2,
    }
  ],
  "Dec - 2019": [{
    "id": 183,
    "user_id": 1,
    "type_id": 1,
  }],
  "Oct - 2019": [{
    "id": 176,
    "user_id": 1,
    "type_id": 1,
  }]
}

data = keySort(data,function(a,b){
  adate = new Date(a);
  bdate = new Date(b);
  return adate>bdate ? 1 : -1;
})
console.log(data);


问:
How to Highlight GTKTreeView Row in C as if was selected with mouse
I've either looking too deep or or something. I have a simple GTKTreeVew that is populated from a file. The number of rows is determined by the number of lines in a CSV file.

I can get get data from each line in a loop, but can seem to grasp how to highlight the row. I can select it getting it's path and printf the row number, but don't know how to highlight it in code...

```<code>selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(gtk_tree_view));
if (gtk_tree_selection_get_selected(selection, &model, &iter))
{
    path = gtk_tree_model_get_path (model, &iter);
    path_string = gtk_tree_path_to_string (path);
    row = atoi(path_string);
    set_active_test_row_single(row);

    printf("\nSelected ROW is %d\n", row);

}
</code>```

Thanks for any links, feedback etc. Can't seem to find function to "highlight" the row number. The same "highlight" that happens when a row is clicked on with the mouse.

答:
I finally figured it out with googleing for about a week and seeing other similar examples in other languages.</p>

```<code>void single_button_clicked_cb(GtkWidget *widget, gpointer data)
{
    static int         index = 0;
    GtkTreeIter iter;
    char buf[9];
    GtkTreeModel *model;
    GtkAdjustment *vadjustment;
    int i;

    printf("\nScroll Active test row to %d\n",index);

    sprintf(buf,"%d",index);

    gtk_widget_grab_focus (GTK_WIDGET(gtk_tree_view));

    GtkTreePath *path = gtk_tree_path_new_from_string(buf);

    gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW (gtk_tree_view),path, NULL,FALSE, 0.0, 0.0);

    gtk_tree_view_set_cursor (gtk_tree_view,path,NULL,FALSE); // works but doesn't scroll

    gtk_tree_path_free(path);

    index++;
}
</code>```

Body:
I've either looking too deep or or something. I have a simple GTKTreeVew that is populated from a file. The number of rows is determined by the number of lines in a CSV file.

I can get get data from each line in a loop, but can seem to grasp how to highlight the row. I can select it getting it's path and printf the row number, but don't know how to highlight it in code...

selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(gtk_tree_view));
if (gtk_tree_selection_get_selected(selection, &model, &iter))
{
    path = gtk_tree_model_get_path (model, &iter);
    path_string = gtk_tree_path_to_string (path);
    row = atoi(path_string);
    set_active_test_row_single(row);

    printf("\nSelected ROW is %d\n", row);

}

Thanks for any links, feedback etc. Can't seem to find function to "highlight" the row number. The same "highlight" that happens when a row is clicked on with the mouse.

Body:
I finally figured it out with googleing for about a week and seeing other similar examples in other languages.

void single_button_clicked_cb(GtkWidget *widget, gpointer data)
{
    static int         index = 0;
    GtkTreeIter iter;
    char buf[9];
    GtkTreeModel *model;
    GtkAdjustment *vadjustment;
    int i;

    printf("\nScroll Active test row to %d\n",index);

    sprintf(buf,"%d",index);

    gtk_widget_grab_focus (GTK_WIDGET(gtk_tree_view));

    GtkTreePath *path = gtk_tree_path_new_from_string(buf);

    gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW (gtk_tree_view),path, NULL,FALSE, 0.0, 0.0);

    gtk_tree_view_set_cursor (gtk_tree_view,path,NULL,FALSE); // works but doesn't scroll

    gtk_tree_path_free(path);

    index++;
}


问:
How can we do object filtering in Entity Framework?
When defining an object context, using code first in entity framework, for example:

```<code>public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}
</code>```

We all know that you can query "News" doing something like (for example, to get all news that were published today):

```<code>var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)
</code>```

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?

答:
I don't believe there's a way to add a filter to the DbSet<News> object as you're suggesting. But what you should be able to do is just write another function:

```<code>public virtual IEnumerable<News> TodaysNews
{
    get { return News.WHere(n => n.PublishDate == DateTime.Today); }
}
</code>```

And then, I think, if you did a query on top of that somewhere else, like:

```<code>var todaysGoodNews = from n in ctx.TodaysNews
                     where n.IsGood == true
                     select n;
</code>```

then it would combine the queries when it sent it to the server rather than making it two separate queries. I'm not positive if that works when you use IEnumerable<> or if you need to return something else (IQueryable<>, perhaps?).

Edit:

I just saw your response to the other poster below. I guess I took too long to type/format. I don't know of any way to apply a filter like that, but aren't our solutions effectively doing that? You could even make TodaysNews be the only way to directly access that object through the context or something.

Body:
When defining an object context, using code first in entity framework, for example:

public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}

We all know that you can query "News" doing something like (for example, to get all news that were published today):

var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?

Body:
I don't believe there's a way to add a filter to the DbSet<News> object as you're suggesting. But what you should be able to do is just write another function:

public virtual IEnumerable<News> TodaysNews
{
    get { return News.WHere(n => n.PublishDate == DateTime.Today); }
}

And then, I think, if you did a query on top of that somewhere else, like:

var todaysGoodNews = from n in ctx.TodaysNews
                     where n.IsGood == true
                     select n;

then it would combine the queries when it sent it to the server rather than making it two separate queries. I'm not positive if that works when you use IEnumerable<> or if you need to return something else (IQueryable<>, perhaps?).

Edit:

I just saw your response to the other poster below. I guess I took too long to type/format. I don't know of any way to apply a filter like that, but aren't our solutions effectively doing that? You could even make TodaysNews be the only way to directly access that object through the context or something.


问:
How do I create an IoT Edge Module for an existing docker container from Azure Cognitive Services?
I currently have public preview access for the Azure Cognitive Services for Speech-To-Text as a docker container.  This allows the container to be run on an IoT Edge device, rather than accessing the cloud to perform this service.  This public preview came with installation instructions that show I can download an existing docker image of one of the containers and run it from a CLI using "docker run".

But I don't want to have to run the docker container manually on my IoT Edge devices.  I want it to be automatically deployed to my IoT Edge devices and automatically start running.  In order to do this, I believe that it needs to exist as an IoT Edge Module.  Is my understanding correct?

So my question is more of an instructional question.  Do I need to create my own IoT Edge Module that utilizes this ACS docker container, or is there some other way to automatically deploy it to my IoT Edge Device and have it start running automatically?

I was unable to find any documentation or examples online of deploying an existing docker container to an IoT Edge device.  Any guidance would be greatly appreciated!

答:
OK, after much digging, I found a solution.  Whatever you do, don't search online for "create iot module from docker container" or anything COMPLETELY MEANINGFUL like that.  Instead, I had to search for something very specific to the Azure Cognitive Service's EULA acceptance on the docker run (i.e. I had to search for "iot edge module docker \"eula\""). Note the quotation marks around eula to ensure it is in the search result.  I came across this article.

Using the article's guidance, I will repeat in detail what I did here in case the link ever goes stale.

In VS Code, create a new IoT Edge Solution

In your solution, add a new IoT Edge Module
a. When prompted for the type of Module to create, select "Choose Existing Module (Enter Full URL)"

If you look inside your deployment.template.json file, you will now see a new element for "registryCredentials" that got added to your edgeAgent details.  Fill out the address, username, and password accordingly.

If you haven't done so yet, create your Cognitive Services resource online to obtain an Endpoint URL and an ApiKey.  Take note of these values.

In the deployment.template.json file, under your new module's configuration settings, add the following.

```<code>"settings": {
  "image": "containerpreview.azurecr.io/microsoft/cognitive-services-speech-to-text:latest",
  "createOptions":
  {
    "Cmd": [
        "Eula=accept",
      "Billing={enter-your-EndpointURL}",
        "ApiKey={enter-your-ApiKey}"
    ],
    "HostConfig": {
      "PortBindings": {
      "5000/tcp": [
      {
        "HostPort": "5000"
      }
      ]
      }
      }
    }
</code>```

This will be equivalent to running "docker run" from the command line with parameters like this:

    docker run --rm -it -p 5000:5000 --memory 4g --cpus 1 \
    containerpreview.azurecr.io/microsoft/cognitive-services-recognize-text \
    Eula=accept \
    Billing={BILLING_ENDPOINT_URI} \
    ApiKey={BILLING_KEY}

Now "Build and Push your IoT Edge Solution", followed by "Create Deployment for Single Device".  On your target IoT Edge device, you should now see the module installed and running via CLI "iotedge list".

Update: 2020/05/01

After submitting a request for better documentation from MSFT, they updated their docs site to include information on how to modify the deployment.template.json file to match the docker command line arguments: https://learn.microsoft.com/en-us/azure/iot-edge/how-to-use-create-options

Body:
OK, after much digging, I found a solution.  Whatever you do, don't search online for "create iot module from docker container" or anything COMPLETELY MEANINGFUL like that.  Instead, I had to search for something very specific to the Azure Cognitive Service's EULA acceptance on the docker run (i.e. I had to search for "iot edge module docker \"eula\""). Note the quotation marks around eula to ensure it is in the search result.  I came across this article.

Using the article's guidance, I will repeat in detail what I did here in case the link ever goes stale.

In VS Code, create a new IoT Edge Solution

In your solution, add a new IoT Edge Module
a. When prompted for the type of Module to create, select "Choose Existing Module (Enter Full URL)"

If you look inside your deployment.template.json file, you will now see a new element for "registryCredentials" that got added to your edgeAgent details.  Fill out the address, username, and password accordingly.

If you haven't done so yet, create your Cognitive Services resource online to obtain an Endpoint URL and an ApiKey.  Take note of these values.

In the deployment.template.json file, under your new module's configuration settings, add the following.

"settings": {
  "image": "containerpreview.azurecr.io/microsoft/cognitive-services-speech-to-text:latest",
  "createOptions":
  {
    "Cmd": [
        "Eula=accept",
      "Billing={enter-your-EndpointURL}",
        "ApiKey={enter-your-ApiKey}"
    ],
    "HostConfig": {
      "PortBindings": {
      "5000/tcp": [
      {
        "HostPort": "5000"
      }
      ]
      }
      }
    }

This will be equivalent to running "docker run" from the command line with parameters like this:

    docker run --rm -it -p 5000:5000 --memory 4g --cpus 1 \
    containerpreview.azurecr.io/microsoft/cognitive-services-recognize-text \
    Eula=accept \
    Billing={BILLING_ENDPOINT_URI} \
    ApiKey={BILLING_KEY}

Now "Build and Push your IoT Edge Solution", followed by "Create Deployment for Single Device".  On your target IoT Edge device, you should now see the module installed and running via CLI "iotedge list".

Update: 2020/05/01

After submitting a request for better documentation from MSFT, they updated their docs site to include information on how to modify the deployment.template.json file to match the docker command line arguments: https://learn.microsoft.com/en-us/azure/iot-edge/how-to-use-create-options


问:
Sequences in SAS Tables
I'm looking to add a sequence column to my sas dataset, but according to ids and transaction dates. To illustrate, below is the table I'm referring to:

```<code>ID   |   TXN_DT    |
01   |  01JAN2020  |
01   |  01JAN2020  |
01   |  02JAN2020  |
01   |  03JAN2020  |
02   |  01JAN2020  |
02   |  02JAN2020  |
02   |  02JAN2020  |
02   |  03JAN2020  |
02   |  03JAN2020  |
</code>```

and I want to add a sequence like so:

```<code>ID   |   TXN_DT    |   SEQ  |
01   |  01JAN2020  |    1   |
01   |  01JAN2020  |    1   |
01   |  02JAN2020  |    2   |
01   |  03JAN2020  |    3   |
02   |  01JAN2020  |    1   |
02   |  02JAN2020  |    2   |
02   |  02JAN2020  |    2   |
02   |  03JAN2020  |    3   |
02   |  03JAN2020  |    3   |
</code>```

I'm trying to run the following code, but it seems to jump a row up and not copying the previous' row's value, and instead skips to 2 rows above.

```<code>data want;
set have;
by id;
if first.id then seq=1;
else seq+1;
if txn_dt=lag(txn_dt) then seq = lag(seq);
keep id seq txn_dt;
run;
</code>```

any help? Thanks in advance!

答:
```<code>data want;
set have;
by id txn_dt;
if first.id then seq=1;
else if first.txn_dt then seq+1;
run;
</code>```

I think that should do it.

Title: Sequences in SAS Tables

Body:
I'm looking to add a sequence column to my sas dataset, but according to ids and transaction dates. To illustrate, below is the table I'm referring to:

ID   |   TXN_DT    |
01   |  01JAN2020  |
01   |  01JAN2020  |
01   |  02JAN2020  |
01   |  03JAN2020  |
02   |  01JAN2020  |
02   |  02JAN2020  |
02   |  02JAN2020  |
02   |  03JAN2020  |
02   |  03JAN2020  |

and I want to add a sequence like so:

ID   |   TXN_DT    |   SEQ  |
01   |  01JAN2020  |    1   |
01   |  01JAN2020  |    1   |
01   |  02JAN2020  |    2   |
01   |  03JAN2020  |    3   |
02   |  01JAN2020  |    1   |
02   |  02JAN2020  |    2   |
02   |  02JAN2020  |    2   |
02   |  03JAN2020  |    3   |
02   |  03JAN2020  |    3   |

I'm trying to run the following code, but it seems to jump a row up and not copying the previous' row's value, and instead skips to 2 rows above.

data want;
set have;
by id;
if first.id then seq=1;
else seq+1;
if txn_dt=lag(txn_dt) then seq = lag(seq);
keep id seq txn_dt;
run;

any help? Thanks in advance!

Body:
data want;
set have;
by id txn_dt;
if first.id then seq=1;
else if first.txn_dt then seq+1;
run;

I think that should do it.


问:
How do I reverse this string properly in c#?
Problem:
I have many strings/equations in this format or one similar:
-4x^2 + 6x^5 -12y + 3xy

BUT I need them in the following order (the reverse - descending instead of ascending powers):
3xy - 12y + 6x^5 - 4x^2

Current attempt (gets close):

```<code>string str ="-4x^2 + 6x^5 -12y + 3xy";

var reverseString = string.Join(" ", str.Split(' ').Reverse());
//This returns: 3xy + 12y - 6x^5 + -4x^2
//Desired rtrn: 3xy - 12y + 6x^5 - 4x^2
</code>```

Issues with current attempt:

"+" and "-" are not reordered correctly.

In the case of negative numbers "+ -" should just be " - ". (e.g 2x + -3x should be 2x - 3x).

In the circumstance the equation starts with a negative number or
is inside a bracket opening, this needs to still remain as "-2x" or
"(-2x ...) (no space) for example not become "- 2x" with a space.

Question:

How would I get the string and +/- in the correct order and fix the issues with my current attempt?

Should I try again after learning regex? (If that's more suitable).

Thank you for any help.

答:
The question is hardly understandable, but i think i got it right that you need just to reverse parts of equation, or they should be sorted by the power as well?

```<code>string str = "4x^2 + 6x^5 -12y + 3xy";

string strCopy = str;

if (str.Length != 0 && str[0] != '-') // covers case when first member is positive, if it is not enough you can use str.TrimStart()[0]
{
    strCopy = "+" + str;
}

var reverseString = string.Join(" ", strCopy
    .Replace(" ", "") // remove all spaces because they kind of random now
    .Replace("+", " +") // add space to signs to keep them with their value
    .Replace("-", " -")
    .Split(' ')
    .Reverse()
)
.TrimStart('+') // remove plus if positive number on the right
.Replace(" +", " + ") // fix spaces back
.Replace(" -", " - ");

Console.WriteLine(strCopy);
Console.WriteLine(reverseString);
Console.ReadKey();
</code>```

Result

Body:
Problem:
I have many strings/equations in this format or one similar:
-4x^2 + 6x^5 -12y + 3xy

BUT I need them in the following order (the reverse - descending instead of ascending powers):
3xy - 12y + 6x^5 - 4x^2

Current attempt (gets close):

string str ="-4x^2 + 6x^5 -12y + 3xy";

var reverseString = string.Join(" ", str.Split(' ').Reverse());
//This returns: 3xy + 12y - 6x^5 + -4x^2
//Desired rtrn: 3xy - 12y + 6x^5 - 4x^2

Issues with current attempt:

"+" and "-" are not reordered correctly.

In the case of negative numbers "+ -" should just be " - ". (e.g 2x + -3x should be 2x - 3x).

In the circumstance the equation starts with a negative number or
is inside a bracket opening, this needs to still remain as "-2x" or
"(-2x ...) (no space) for example not become "- 2x" with a space.

Question:

How would I get the string and +/- in the correct order and fix the issues with my current attempt?

Should I try again after learning regex? (If that's more suitable).

Thank you for any help.

Body:
The question is hardly understandable, but i think i got it right that you need just to reverse parts of equation, or they should be sorted by the power as well?

string str = "4x^2 + 6x^5 -12y + 3xy";

string strCopy = str;

if (str.Length != 0 && str[0] != '-') // covers case when first member is positive, if it is not enough you can use str.TrimStart()[0]
{
    strCopy = "+" + str;
}

var reverseString = string.Join(" ", strCopy
    .Replace(" ", "") // remove all spaces because they kind of random now
    .Replace("+", " +") // add space to signs to keep them with their value
    .Replace("-", " -")
    .Split(' ')
    .Reverse()
)
.TrimStart('+') // remove plus if positive number on the right
.Replace(" +", " + ") // fix spaces back
.Replace(" -", " - ");

Console.WriteLine(strCopy);
Console.WriteLine(reverseString);
Console.ReadKey();

Result


问:
is there a simple way to add the dplyr summarize function result to every row?
The following is a simple version of my data:

I want to create a flag for each group if they at least have one item in Column1.
I know I can do this in dplyr and then merge it with my original data but I was wondering if there is an easier way.

For example, I can do this:

```<code>df_column <- df %>% filter(!is.na(Column1)) %>% group_by(Group)%>%
  summarize(n=n_distinct(Column1))
</code>```

and then I can merge this with the original data and create a flag.

答:
Just a riff on the previous answer using ifelse which may be easier to understand if you're coming from Excel (which it looks like you may be):

```<code>library(dplyr)

df %>%
    group_by(Group) %>%
    mutate(flag = ifelse(
        is.na(column1),
        "flag",
        "dont_flag"
    ))
</code>```

Body:
The following is a simple version of my data:

I want to create a flag for each group if they at least have one item in Column1.
I know I can do this in dplyr and then merge it with my original data but I was wondering if there is an easier way.

For example, I can do this:

df_column <- df %>% filter(!is.na(Column1)) %>% group_by(Group)%>%
  summarize(n=n_distinct(Column1))

and then I can merge this with the original data and create a flag.

Body:
Just a riff on the previous answer using ifelse which may be easier to understand if you're coming from Excel (which it looks like you may be):

library(dplyr)

df %>%
    group_by(Group) %>%
    mutate(flag = ifelse(
        is.na(column1),
        "flag",
        "dont_flag"
    ))