问:
Halogen keyboard-input example and unsubsribing to the events?
How to unsubscribe to keyboard events from other actions than HandleKey in the  keyboard-input example? (The question is related to Halogen version 2.0.1 and purescript 0.11.4.)

In the example the enter/return works. I have a group of elements that can be collapsed with mouse by pressing close-button and Close-action takes care of it. Also, the enter/return can be used to collapse the elements and it works as it should.

```<code>Open next -> do
  st <- H.get
  if not st.open
    then do
      H.modify (_ { open = true })
      eval (H.action Init)
    else pure unit
  pure next

Close next -> do
  H.modify (_ { open = false })
  st <- H.get
  case st.unsubscribe of
    Nothing -> pure unit
    -- Just smth -> H.liftAff smth
    Just _ -> H.modify (_ { unsubscribe = Nothing}) -- H.liftAff us
  pure next

Init next -> do
  H.modify (_ { open = true})
  document <- H.liftEff $ DOM.window >>= DOM.document <#> DOM.htmlDocumentToDocument
  H.subscribe $ ES.eventSource'
    (K.onKeyUp document)
    (Just <<< H.request <<< HandleKey)
  -- H.modify (_ { unsubscribe = ??? })
  pure next
</code>```

The problem is that when I close (collapse) the elements with mouse, the event listener is not removed (not Done) and it will be still there. When I re-open the elements, the above code will establish a second (a third, fourth, etc) listener and then every keypress will be handled many times.

I was considering to create a keyboard event but it doesn't sound a correct way here.

So the questions are:

How to check if there is already a keyboard listener?

And then how to stop it at the Close -action?

Or is it possible to make the Done SubscribeStatus and send it to the keyboard listener at the Close -action?

Further questions:

The example has unsubscribe in the state. How to use it?

(I tried to put something into it at the Init -action and at the Close -action but it was pure guessing.)

Late edit:
This seems to be related to questions about dynamically attached event listeners and see also this, this and this.

One of the answers said that it is only possible to know about dynamic handlers through the use of states and that did the trick for my problem. Anyhow, I think that the questions stated here remain (how to remove handler  with Halogen and especially about the unsubscribe field in the example - is it somehow useable?)

答:
It took me a while to understand the eventSource' signature, but here's a breakdown that might help clarify what's going on.

This is the actual signature...

eventSource' :: forall f m a eff. MonadAff (avar :: AVAR | eff) m =>
  ((a -> Eff (avar :: AVAR | eff) Unit) -> Eff (avar :: AVAR | eff) (Eff (avar :: AVAR | eff) Unit)) ->
  (a -> Maybe (f SubscribeStatus)) ->
  EventSource f m
```

<p>If we use a sort of pseudocode to name the components of the signature...</p>

<pre class="lang-hs prettyprint-override"><code>type Callback a = (a -> Eff (avar :: AVAR | eff) Unit)
type MaybeQuery a = (a -> Maybe (f SubscribeStatus))
type RemoveEventListener = (Eff (avar :: AVAR | eff) Unit)
</code>```

We get...

eventSource' :: forall f m a eff.
  (Callback a -> Eff (avar :: AVAR | eff) RemoveEventListener) ->
  MaybeQuery a ->
  EventSource f m
```

<p>I think the part you're missing is the RemoveEventListener part.  Here's an example EventSource for onMouseUp on an HTMLDocument that doesn't use the foreign function interface (FFI) like the example you referenced.</p>

<pre class="lang-hs prettyprint-override"><code>import DOM.Event.Types as DET
import DOM.Event.EventTarget as DEET
import DOM.HTML.Event.EventTypes as EventTypes

onMouseUp :: forall e
   . DHT.HTMLDocument
  -> (DET.Event -> Eff (CompEffects e) Unit)
  -> Eff (CompEffects e) (Eff (CompEffects e) Unit)
onMouseUp doc callback = do
  let eventTarget = (DHT.htmlDocumentToEventTarget doc)

  -- Create an EventListener that will log a message
  -- and pass the event to the callback
  let listener =
        DEET.eventListener (\event -> do
          log "mouseUp"
          callback event
        )

  -- Add the EventListener to the
  -- document so it will fire on mouseup
  DEET.addEventListener
    EventTypes.mouseup
    listener true eventTarget

  -- Return the function that will later
  -- remove the event listener
  pure $ DEET.removeEventListener
    EventTypes.mouseup
    listener true eventTarget
</code>```

So the Callback will get the a event (In this case a generic Event).  Note that we have to create a reference to the listener, so we can pass the same reference to addEventListener as removeEventListener (the function reference acts like an id to determines which listener function is removed).

The MaybeQuery function will also be passed the a event, so Halogen can execute a query and you can decide if you should keep listening for events or not.  That query will need to be structured like this...

data YourQuery =
  | HandleEvent Event (SubscribeStatus -> a)

eval (HandleEvent event reply) =
  -- Decided if you want to keep listening
  -- or now.

  -- Keep listening...
  -- pure $ reply (H.Listening)

  -- Stop listening.  Halogen will call the removeEventListener
  -- function you returned from onMouseUp earlier
  -- pure $ reply (H.Done)
```

<p>And just show how to subscribe to the EventSource...</p>

<pre class="lang-hs prettyprint-override"><code>import DOM.HTML.Window as Win
import Halogen.Query.EventSource as HES

document <- H.liftEff $ (window >>= Win.document)
H.subscribe $ HES.eventSource'
  (onMouseUp document)
  (Just <<< H.request <<< HandleEvent)
</code>```

Body:
How to unsubscribe to keyboard events from other actions than HandleKey in the  keyboard-input example? (The question is related to Halogen version 2.0.1 and purescript 0.11.4.)

In the example the enter/return works. I have a group of elements that can be collapsed with mouse by pressing close-button and Close-action takes care of it. Also, the enter/return can be used to collapse the elements and it works as it should.

Open next -> do
  st <- H.get
  if not st.open
    then do
      H.modify (_ { open = true })
      eval (H.action Init)
    else pure unit
  pure next

Close next -> do
  H.modify (_ { open = false })
  st <- H.get
  case st.unsubscribe of
    Nothing -> pure unit
    -- Just smth -> H.liftAff smth
    Just _ -> H.modify (_ { unsubscribe = Nothing}) -- H.liftAff us
  pure next

Init next -> do
  H.modify (_ { open = true})
  document <- H.liftEff $ DOM.window >>= DOM.document <#> DOM.htmlDocumentToDocument
  H.subscribe $ ES.eventSource'
    (K.onKeyUp document)
    (Just <<< H.request <<< HandleKey)
  -- H.modify (_ { unsubscribe = ??? })
  pure next

The problem is that when I close (collapse) the elements with mouse, the event listener is not removed (not Done) and it will be still there. When I re-open the elements, the above code will establish a second (a third, fourth, etc) listener and then every keypress will be handled many times.

I was considering to create a keyboard event but it doesn't sound a correct way here.

So the questions are:

How to check if there is already a keyboard listener?

And then how to stop it at the Close -action?

Or is it possible to make the Done SubscribeStatus and send it to the keyboard listener at the Close -action?

Further questions:

The example has unsubscribe in the state. How to use it?

(I tried to put something into it at the Init -action and at the Close -action but it was pure guessing.)

Late edit:
This seems to be related to questions about dynamically attached event listeners and see also this, this and this.

One of the answers said that it is only possible to know about dynamic handlers through the use of states and that did the trick for my problem. Anyhow, I think that the questions stated here remain (how to remove handler  with Halogen and especially about the unsubscribe field in the example - is it somehow useable?)

Body:
It took me a while to understand the eventSource' signature, but here's a breakdown that might help clarify what's going on.

This is the actual signature...

eventSource' :: forall f m a eff. MonadAff (avar :: AVAR | eff) m =>
  ((a -> Eff (avar :: AVAR | eff) Unit) -> Eff (avar :: AVAR | eff) (Eff (avar :: AVAR | eff) Unit)) ->
  (a -> Maybe (f SubscribeStatus)) ->
  EventSource f m

If we use a sort of pseudocode to name the components of the signature...

type Callback a = (a -> Eff (avar :: AVAR | eff) Unit)
type MaybeQuery a = (a -> Maybe (f SubscribeStatus))
type RemoveEventListener = (Eff (avar :: AVAR | eff) Unit)

We get...

eventSource' :: forall f m a eff.
  (Callback a -> Eff (avar :: AVAR | eff) RemoveEventListener) ->
  MaybeQuery a ->
  EventSource f m

I think the part you're missing is the RemoveEventListener part.  Here's an example EventSource for onMouseUp on an HTMLDocument that doesn't use the foreign function interface (FFI) like the example you referenced.

import DOM.Event.Types as DET
import DOM.Event.EventTarget as DEET
import DOM.HTML.Event.EventTypes as EventTypes

onMouseUp :: forall e
   . DHT.HTMLDocument
  -> (DET.Event -> Eff (CompEffects e) Unit)
  -> Eff (CompEffects e) (Eff (CompEffects e) Unit)
onMouseUp doc callback = do
  let eventTarget = (DHT.htmlDocumentToEventTarget doc)

  -- Create an EventListener that will log a message
  -- and pass the event to the callback
  let listener =
        DEET.eventListener (\event -> do
          log "mouseUp"
          callback event
        )

  -- Add the EventListener to the
  -- document so it will fire on mouseup
  DEET.addEventListener
    EventTypes.mouseup
    listener true eventTarget

  -- Return the function that will later
  -- remove the event listener
  pure $ DEET.removeEventListener
    EventTypes.mouseup
    listener true eventTarget

So the Callback will get the a event (In this case a generic Event).  Note that we have to create a reference to the listener, so we can pass the same reference to addEventListener as removeEventListener (the function reference acts like an id to determines which listener function is removed).

The MaybeQuery function will also be passed the a event, so Halogen can execute a query and you can decide if you should keep listening for events or not.  That query will need to be structured like this...

data YourQuery =
  | HandleEvent Event (SubscribeStatus -> a)

eval (HandleEvent event reply) =
  -- Decided if you want to keep listening
  -- or now.

  -- Keep listening...
  -- pure $ reply (H.Listening)

  -- Stop listening.  Halogen will call the removeEventListener
  -- function you returned from onMouseUp earlier
  -- pure $ reply (H.Done)

And just show how to subscribe to the EventSource...

import DOM.HTML.Window as Win
import Halogen.Query.EventSource as HES

document <- H.liftEff $ (window >>= Win.document)
H.subscribe $ HES.eventSource'
  (onMouseUp document)
  (Just <<< H.request <<< HandleEvent)


来源: stackexchange

问:
How to tell if a string contains a certain character in JavaScript?
I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code.  I used maxlength to limit the user to entering 24 characters.

The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.

How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?

答:
If you have the text in variable foo:

```<code>if (! /^[a-zA-Z0-9]+$/.test(foo)) {
    // Validation failed
}
</code>```

This will test and make sure the user has entered at least one character, and has entered only alphanumeric characters.

ContentLicense: CC BY-SA 3.0

Body:
If you have the text in variable foo:

if (! /^[a-zA-Z0-9]+$/.test(foo)) {
    // Validation failed
}

This will test and make sure the user has entered at least one character, and has entered only alphanumeric characters.

ContentLicense: CC BY-SA 2.5


问:
Javascript script doesn't load in HTML
```<code><!DOCTYPE html>
<html>
  <head>
    <title>Breakout</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>

    <canvas width="900" height="450" class="canvas"></canvas>

    <script src="scripts/base.js"></script>
  </body>
</html>
</code>```

This is the index file

```<code>*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}
</code>```

This is the CSS file

```<code>var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();
</code>```

And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.

答:
Use fillRect instead of drawRect:

```<code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.fillRect(20,30,50,40);
ctx.endPath();

</script>
</code>```

Title: Javascript script doesn't load in HTML

Body:
<!DOCTYPE html>

    <title>Breakout</title>
    <link rel="stylesheet" href="css/style.css">

    <canvas width="900" height="450" class="canvas"></canvas>

This is the index file

*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}

This is the CSS file

var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();

And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.

Body:
Use fillRect instead of drawRect:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.fillRect(20,30,50,40);
ctx.endPath();

</script>


问:
Add affiliate URL query parameter to all links of a domain on a single page in Wordpress
I am preparing a page on my wordpress site where I will post coupons and product urls for a website I am an affiliate of.

Instead of creating affiliate links by hand on every URL, I would like to automatically add the affiliate query parameter on every URL of this particular domain.

The urls might be:

```<code>example.com
example.com/
example.com/cell-phones-c_11293/
example.com/cell-phones/pp_617010.html?wid=4
</code>```

The query parameter I want to add is ?lkid=12345678 (the same for every URL).

```<code>example.com?lkid=12345678
example.com/?lkid=12345678
example.com/cell-phones-c_11293/?lkid=12345678
example.com/cell-phones/pp_617010.html?wid=4&lkid=10823628
</code>```

I want this functionality only for this particular page, not for every post on Wordpress, so I wouldn't like to add the code to the functions.php, or install a plugin just for this single page.

Is it possible to add it as a header or body script to the page through the "Scripts" screen option at the editor?

I have found the following code from this answer,

```<code><script>
var $links = $('a'); // get all anchor tags

// loop through each anchor tag
$.each($links, function(index, item){
    var url = $(this).attr('href'); // var for value of href attribute
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                $(this).attr('href', url + '?lkid=12345678');
                // append ?lkid=12345678 if url contains example
});
</script>
</code>```

And the following code from this answer

```<code><script>
function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
</script>
</code>```

...but I unfortunately I don't know enough programming to make them work for my case.

答:
This code adds the parameter if it doesn't already have a query string, and will parse, add the parameter, and re-encode for links that already have a query string:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>></title>
    </head>
    <body>
        <a href="http://www.example.com">Test</a>
        <a href="//www.google.com?test=1">Test</a>
        <a href="http://www.example.com/?test=1">Test</a>
        <a href="www.example.com?test=1">Test</a>
        <a href="../?test=1&another=2">Test</a>
        <a href="?test=1&another=2">Test</a>
        <script>
            // parseQuery: Originally from StackOverflow of: https://stackoverflow.com/a/13419367/2529423
            function parseQuery(qstr) {
                var query = {};
                var a = (qstr[0] === '?' ? qstr.substr(1) : qstr).split('&');
                for (var i = 0; i < a.length; i++) {
                    var b = a[i].split('=');
                    query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
                }
                return query;
            }

            // encodeQuery originally from StackOverflow: https://stackoverflow.com/a/1714899/2529423
            function encodeQuery(obj) {
              var str = [];
              for(var p in obj)
                if (obj.hasOwnProperty(p)) {
                  str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
              return str.join("&");
            }

            function addQueryParameterToDomain(key, value, conditionDomain) {
                var links = document.querySelectorAll('a[href]'),
                    linksLength = links.length,
                    index,
                    queryIndex,
                    queryString,
                    query,
                    url,
                    domain,
                    colonSlashSlash;

                // Iterate through and add query paramter
                for(index = 0; index < linksLength; ++index) {
                    url = links[index].href,
                    queryIndex = url.indexOf('?'),
                    colonSlashSlash = url.indexOf('://');

                    domain = url.substring(colonSlashSlash + 3);
                    domain = domain.substring(0, domain.indexOf('/'));

                    if(domain !== conditionDomain) {
                        continue;
                    }

                    if(queryIndex === -1) {
                        url += '?' + key + '=' + value;
                    } else {
                        queryString = url.substring(queryIndex);
                        url = url.substring(0, queryIndex);
                        query = parseQuery(queryString);

                        query[key] = value;

                        url += '?' + encodeQuery(query);
                    }

                    links[index].href = url;
                }
            }

            jQuery(function() {
                addQueryParameterToDomain('lkid', '12345678', 'example.com');
                addQueryParameterToDomain('lkid', '12345678', 'www.example.com');
            });
        </script>
    </body>
</html>
</code>```

All you'll need to do is replace the script you have with the contents of the

Body:
I am preparing a page on my wordpress site where I will post coupons and product urls for a website I am an affiliate of.

Instead of creating affiliate links by hand on every URL, I would like to automatically add the affiliate query parameter on every URL of this particular domain.

The urls might be:

example.com
example.com/
example.com/cell-phones-c_11293/
example.com/cell-phones/pp_617010.html?wid=4

The query parameter I want to add is ?lkid=12345678 (the same for every URL).

example.com?lkid=12345678
example.com/?lkid=12345678
example.com/cell-phones-c_11293/?lkid=12345678
example.com/cell-phones/pp_617010.html?wid=4&lkid=10823628

I want this functionality only for this particular page, not for every post on Wordpress, so I wouldn't like to add the code to the functions.php, or install a plugin just for this single page.

Is it possible to add it as a header or body script to the page through the "Scripts" screen option at the editor?

I have found the following code from this answer,

And the following code from this answer

...but I unfortunately I don't know enough programming to make them work for my case.

Body:
This code adds the parameter if it doesn't already have a query string, and will parse, add the parameter, and re-encode for links that already have a query string:

<!DOCTYPE html>
<html>
    <head>
        <title>></title>
    </head>
    <body>
        <a href="http://www.example.com">Test</a>
        <a href="//www.google.com?test=1">Test</a>
        <a href="http://www.example.com/?test=1">Test</a>
        <a href="www.example.com?test=1">Test</a>
        <a href="../?test=1&another=2">Test</a>
        <a href="?test=1&another=2">Test</a>
        <script>
            // parseQuery: Originally from StackOverflow of: https://stackoverflow.com/a/13419367/2529423
            function parseQuery(qstr) {
                var query = {};
                var a = (qstr[0] === '?' ? qstr.substr(1) : qstr).split('&');
                for (var i = 0; i < a.length; i++) {
                    var b = a[i].split('=');
                    query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
                }
                return query;
            }

            // encodeQuery originally from StackOverflow: https://stackoverflow.com/a/1714899/2529423
            function encodeQuery(obj) {
              var str = [];
              for(var p in obj)
                if (obj.hasOwnProperty(p)) {
                  str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
              return str.join("&");
            }

            function addQueryParameterToDomain(key, value, conditionDomain) {
                var links = document.querySelectorAll('a[href]'),
                    linksLength = links.length,
                    index,
                    queryIndex,
                    queryString,
                    query,
                    url,
                    domain,
                    colonSlashSlash;

                // Iterate through and add query paramter
                for(index = 0; index < linksLength; ++index) {
                    url = links[index].href,
                    queryIndex = url.indexOf('?'),
                    colonSlashSlash = url.indexOf('://');

                    domain = url.substring(colonSlashSlash + 3);
                    domain = domain.substring(0, domain.indexOf('/'));

                    if(domain !== conditionDomain) {
                        continue;
                    }

                    if(queryIndex === -1) {
                        url += '?' + key + '=' + value;
                    } else {
                        queryString = url.substring(queryIndex);
                        url = url.substring(0, queryIndex);
                        query = parseQuery(queryString);

                        query[key] = value;

                        url += '?' + encodeQuery(query);
                    }

                    links[index].href = url;
                }
            }

            jQuery(function() {
                addQueryParameterToDomain('lkid', '12345678', 'example.com');
                addQueryParameterToDomain('lkid', '12345678', 'www.example.com');
            });
        </script>
    </body>
</html>

All you'll need to do is replace the script you have with the contents of the <script> tag above, and bob's your uncle.


问:
Can I run/convert a Docker-Compose project with/to CoreOS rkt?
Can I use CoreOS rkt, or some related tool, to run my Docker-Compose project?

And / or is there some way to convert a Docker-Compose project to something similar, for CoreOS and rkt?

My Docker-Compose project works fine on localhost and on the production servers. But I think I like CoreOS' and rkt's security model better — then I wouldn't have to run the containers with, in effect, root privileges, on my development machine (right?).

Here seems to be docs about how to run a single Docker container with rkt: https://coreos.com/rkt/docs/latest/running-docker-images.html — but I want Docker-Compose like functionality, not just a single container.

(I currently use an Ubuntu based Linux distro.)

答:
rkt-compose is a lightweight alternative to kubernetes and compose2fleet. rkt-compose supports a subset of the docker-compose file syntax and runs all services of a docker-compose file within a single pod in a wrapped rkt process without dependencies to other tools than rkt and docker (for build). To support service discovery and health checks Consul integration can be enabled optionally.

I have tested the current rkt-compose v0.1.0 release successfully against several of my old docker-compose projects.

Disclosure: I have developed rkt-compose while playing around with rkt and to learn golang.

Security annotation: As in docker rkt containers must also run as root. Running containers as unprivileged user is not supported. I am currently investigating runc: It is also shipped with CoreOS and in its current master state it allows you to truely run a container as unprivileged user with some workarounds and limitations but you still cannot run docker-compose files directly on it.


问:
After upgrading spring-jms from 4.0.2 to 4.3.8, we started facing communication related issues it seems
we just upgraded our spring jars from 4.0.2 to 4.3.8 and one of them was spring-jms.

Now, we started facing the login issue on our web apps where it has to communicate the user info with our security module through activemq (apache-activemq-5.13.0).

we have not touched our mq version. seems like the messages are getting delivered to the queue consumer with a long delay and this delay is random (as sometimes we don't see much of a delay).

Not sure whats going on, I replaced the spring-jms back to 4.0.2 and all login attempts just works fine like within 3 seconds.

Any ideas or suggestions what to look for ?

thanks.

答: Sorry for putting it late, but we figured out the issue which was the cache level on spring jms listener (DefaultMessageListenerContainer) was set as zero which means none but for some odd reason with jar 4.0.2 it was the caching of JMS objects still but when we used the upgraded jar 4.3.8 the cache was not there so it was creating/dropping jms objects and making it slower. After setting the right cache level the slowness went away.</p>


问:
node.js: readSync from stdin?
Is it possible to synchronously read from stdin in node.js? Because I'm writing a brainfuck to JavaScript compiler in JavaScript (just for fun). Brainfuck supports a read operation which needs to be implemented synchronously.

I tried this:

```<code>const fs = require('fs');
var c = fs.readSync(0,1,null,'utf-8');
console.log('character: '+c+' ('+c.charCodeAt(0)+')');
</code>```

But this only produces this output:

```<code>fs:189
  var r = binding.read(fd, buffer, offset, length, position);
              ^
Error: EAGAIN, Resource temporarily unavailable
    at Object.readSync (fs:189:19)
    at Object.<anonymous> (/home/.../stdin.js:3:12)
    at Module._compile (module:426:23)
    at Module._loadScriptSync (module:436:8)
    at Module.loadSync (module:306:10)
    at Object.runMain (module:490:22)
    at node.js:254:10
</code>```

答:
I wrote this module to read one line at a time from file or stdin. The module is named as line-reader which exposes an ES6 *Generator function to iterate over one line at a time. here is a code sample(in TypeScript) from readme.md.

```<code>import { LineReader } from "line-reader"

// FromLine and ToLine are optional arguments
const filePathOrStdin = "path-to-file.txt" || process.stdin
const FromLine: number = 1 // default is 0
const ToLine: number = 5 // default is Infinity
const chunkSizeInBytes = 8 * 1024 // default is 64 * 1024

const list: IterableIterator<string> = LineReader(filePathOrStdin, FromLine, ToLine, chunkSizeInBytes)

// Call list.next to iterate over lines in a file
list.next()

// Iterating using a for..of loop
for (const item of list) {
   console.log(item)
}
</code>```

Apart from above code, you can also take a look at src > tests folder in the repo.

Note:-

line-reader module doesn't read all stuff into memory instead it uses generator function to generate lines async or sync.

Title: node.js: readSync from stdin?

Body:
Is it possible to synchronously read from stdin in node.js? Because I'm writing a brainfuck to JavaScript compiler in JavaScript (just for fun). Brainfuck supports a read operation which needs to be implemented synchronously.

I tried this:

const fs = require('fs');
var c = fs.readSync(0,1,null,'utf-8');
console.log('character: '+c+' ('+c.charCodeAt(0)+')');

But this only produces this output:

fs:189
  var r = binding.read(fd, buffer, offset, length, position);
              ^
Error: EAGAIN, Resource temporarily unavailable
    at Object.readSync (fs:189:19)
    at Object.<anonymous> (/home/.../stdin.js:3:12)
    at Module._compile (module:426:23)
    at Module._loadScriptSync (module:436:8)
    at Module.loadSync (module:306:10)
    at Object.runMain (module:490:22)
    at node.js:254:10

Body:
I wrote this module to read one line at a time from file or stdin. The module is named as line-reader which exposes an ES6 *Generator function to iterate over one line at a time. here is a code sample(in TypeScript) from readme.md.

import { LineReader } from "line-reader"

// FromLine and ToLine are optional arguments
const filePathOrStdin = "path-to-file.txt" || process.stdin
const FromLine: number = 1 // default is 0
const ToLine: number = 5 // default is Infinity
const chunkSizeInBytes = 8 * 1024 // default is 64 * 1024

const list: IterableIterator<string> = LineReader(filePathOrStdin, FromLine, ToLine, chunkSizeInBytes)

// Call list.next to iterate over lines in a file
list.next()

// Iterating using a for..of loop
for (const item of list) {
   console.log(item)
}

Apart from above code, you can also take a look at src > tests folder in the repo.

Note:-

line-reader module doesn't read all stuff into memory instead it uses generator function to generate lines async or sync.


问:
Registering callbacks from text configuration file
I have a general problem where I have an array of function pointers.  The challenge is to bind the functions to locations in the array based on a text configuration file.  Is there a better way to do this than a gigantic if-else-else-...-else block?

Is it easier to implement functors and bind locations to instances of a type?

EDIT: For example, I might have:

```<code>void func1();
void func2();

void (*fptr[2])();
</code>```

I want to have an input configuration file that tells me that func1 goes in fptr[0] and func2 goes in fptr[1].

func1, 0
func2, 1

if-else means I stream the line in and I get a string fname = "func1", and a location_in_the_array, 0.  So I'll have a block:

```<code>if (fname.compare("func1"))
{
  fptr[location_in_the_array] = func1;
}
else if (...) {}
</code>```

A map is a good idea, and it has flitted in an out of my brain a couple of times, but I am a space cadet, and forgot it before I asked.

答:
Would indirection help?

For example, take your function pointers and at compile time assign them to a hash table by name, perhaps the identifier of function's name.

Then at runtime load the text file, which is a list of names.

Create an array by looking up the identifier, find its function pointer in the hash table, and fill the array.

Body:
I have a general problem where I have an array of function pointers.  The challenge is to bind the functions to locations in the array based on a text configuration file.  Is there a better way to do this than a gigantic if-else-else-...-else block?

Is it easier to implement functors and bind locations to instances of a type?

EDIT: For example, I might have:

void func1();
void func2();

void (*fptr[2])();

I want to have an input configuration file that tells me that func1 goes in fptr[0] and func2 goes in fptr[1].

func1, 0
func2, 1

if-else means I stream the line in and I get a string fname = "func1", and a location_in_the_array, 0.  So I'll have a block:

if (fname.compare("func1"))
{
  fptr[location_in_the_array] = func1;
}
else if (...) {}

A map is a good idea, and it has flitted in an out of my brain a couple of times, but I am a space cadet, and forgot it before I asked.


问:
How do you get the root namespace of an assembly?
Given an instance of System.Reflection.Assembly.

答:
Here as a rather simple way to get the root namespace for a website project.

```<code>''' <summary>
''' Returns the namespace of the currently running website
''' </summary>
Public Function GetWebsiteRootNamespace() As String
    For Each Asm In AppDomain.CurrentDomain.GetAssemblies()
        If Asm Is Nothing OrElse Asm.IsDynamic Then Continue For

        For Each Typ In Asm.GetTypes
            If Typ Is Nothing OrElse Typ.Name Is Nothing Then Continue For
            If Typ.Name = "MyProject" Then Return Typ.Namespace.Split("."c)(0)
        Next
    Next

    Return Nothing
End Function
</code>```

This simply checks all the loaded assemblies for the "MyProject" type and returns the root namespace for that type.  This is useful for logging when you have multiple web projects in a single solution sharing a log system.  Hope this helps someone.

OwnerDisplayName: Andrew

Body:
Here as a rather simple way to get the root namespace for a website project.

''' <summary>
''' Returns the namespace of the currently running website
''' </summary>
Public Function GetWebsiteRootNamespace() As String
    For Each Asm In AppDomain.CurrentDomain.GetAssemblies()
        If Asm Is Nothing OrElse Asm.IsDynamic Then Continue For

        For Each Typ In Asm.GetTypes
            If Typ Is Nothing OrElse Typ.Name Is Nothing Then Continue For
            If Typ.Name = "MyProject" Then Return Typ.Namespace.Split("."c)(0)
        Next
    Next

    Return Nothing
End Function

This simply checks all the loaded assemblies for the "MyProject" type and returns the root namespace for that type.  This is useful for logging when you have multiple web projects in a single solution sharing a log system.  Hope this helps someone.


问:
How can I tell if users are making repeated visits?
I have a javascript web application and I want to know if users are returning to it or just visiting it one time. Is there some identifier for each device (computer, phone, etc.) that I can record, so that I can check if a user has made repeated visits?

I do not want users to have to manually provide any information to me (like an email).

I can't record their IP address because that is not unique per device.

答: you can use cookies, or localStorage</p>

Body: you can use cookies, or localStorage


问:
laravel database pass data blade
I'm new to Laravel and trying to figure out why one of my pages is not pulling data from the database. Running locally using a setup based on the project in Laracasts. I'm on Laravel 5.4 running PHP 7 and MySQL on OS X Sierra.

I'm getting this error: Undefined Variable: hashtags (in my hashtags.blade.php file)

I have this code hashtags.blade.php, designed to pull entries from a database:

```<code><h2>Your Hashtags</h2>

    <table>
        <tr>
            <th>Hashtag</th>
            <th>List Name</th>
            <th>List Members Added</th>
        </tr>

    @foreach($hashtags as $hashtag)

        <tr>
            <td>{{ $hashtag -> tagname }}</td>
            <td>{{ $hashtag -> listname }}</td>
            <td>Count</td>
        </tr>

    @endforeach

    </table>
</code>```

In my web.php routes file:

```<code>Route::get('/hashtags', function () {

    $hashtags = DB::table('hashtags')->get();
    return view('hashtags');
});
</code>```

I have the database connected through the .env file and the overall connection in Laravel seems to be working, just not on this page. I was under the impression that the code in web.php defines the variable $hashtags and passes it to hashtags.blade.php. Apparently I'm missing something here.

I searched and found some other questions about passing data to the blade files, but nothing quite like this issue. Thanks!

答:
You need to Passed the variable in your web.php route file

Try this

```<code>Route::get('/hashtags', function () {
    $hashtags = DB::table('hashtags')->get();
    return view('hashtags',compact('hashtags'));
});
</code>```

Title: laravel database pass data blade

Body:
I'm new to Laravel and trying to figure out why one of my pages is not pulling data from the database. Running locally using a setup based on the project in Laracasts. I'm on Laravel 5.4 running PHP 7 and MySQL on OS X Sierra.

I'm getting this error: Undefined Variable: hashtags (in my hashtags.blade.php file)

I have this code hashtags.blade.php, designed to pull entries from a database:

Your Hashtags

            Hashtag
            List Name
            List Members Added

    @foreach($hashtags as $hashtag)

            {{ $hashtag -> tagname }}
            {{ $hashtag -> listname }}
            Count

    @endforeach

In my web.php routes file:

Route::get('/hashtags', function () {

    $hashtags = DB::table('hashtags')->get();
    return view('hashtags');
});

I have the database connected through the .env file and the overall connection in Laravel seems to be working, just not on this page. I was under the impression that the code in web.php defines the variable $hashtags and passes it to hashtags.blade.php. Apparently I'm missing something here.

I searched and found some other questions about passing data to the blade files, but nothing quite like this issue. Thanks!

Body:
You need to Passed the variable in your web.php route file

Try this

Route::get('/hashtags', function () {
    $hashtags = DB::table('hashtags')->get();
    return view('hashtags',compact('hashtags'));
});


问:
Tensorflow: tf.gradients between different paths of the graph
I am working on a DDPG implementation, which requires the computation of one network's (below: critic) gradients with respect to another network's (below: actor) output. My code already makes use of queues instead of feed dicts for the most part, but I could not do so for this specific part yet:

```<code>import tensorflow as tf
tf.reset_default_graph()

states = tf.placeholder(tf.float32, (None,))
actions = tf.placeholder(tf.float32, (None,))

actor = states * 1
critic = states * 1 + actions

grads_indirect = tf.gradients(critic, actions)
grads_direct = tf.gradients(critic, actor)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    act = sess.run(actor, {states: [1.]})
    print(act)  # -> [1.]
    cri = sess.run(critic, {states: [1.], actions: [2.]})
    print(cri)  # -> [3.]
    grad1 = sess.run(grads_indirect, {states: [1.], actions: act})
    print(grad1)  # -> [[1.]]
    grad2 = sess.run(grads_direct, {states: [1.], actions: [2.]})
    print(grad2)  # -> TypeError: Fetch argument has invalid type 'NoneType'
</code>```

grad1 here computes the gradients w.r.t. to the fed-in actions, which were previously computed by the actor. grad2 should do the same, but directly inside of the graph without the need for feeding the actions back in but by evaluating actor directly. The problem is that grads_direct is None:

```<code>print(grads_direct)  # [None]
</code>```

How can I achieve this? Is there a dedicated "evaluate this tensor" operation I could make use of? Thanks!

答:
In your example you don't use actor to compute critic so the gradient is None.

You should do:

```<code>actor = states * 1
critic = actor + actions  # change here

grads_indirect = tf.gradients(critic, actions)
grads_direct = tf.gradients(critic, actor)
</code>```

Body:
I am working on a DDPG implementation, which requires the computation of one network's (below: critic) gradients with respect to another network's (below: actor) output. My code already makes use of queues instead of feed dicts for the most part, but I could not do so for this specific part yet:

import tensorflow as tf
tf.reset_default_graph()

states = tf.placeholder(tf.float32, (None,))
actions = tf.placeholder(tf.float32, (None,))

actor = states * 1
critic = states * 1 + actions

grads_indirect = tf.gradients(critic, actions)
grads_direct = tf.gradients(critic, actor)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    act = sess.run(actor, {states: [1.]})
    print(act)  # -> [1.]
    cri = sess.run(critic, {states: [1.], actions: [2.]})
    print(cri)  # -> [3.]
    grad1 = sess.run(grads_indirect, {states: [1.], actions: act})
    print(grad1)  # -> [[1.]]
    grad2 = sess.run(grads_direct, {states: [1.], actions: [2.]})
    print(grad2)  # -> TypeError: Fetch argument has invalid type 'NoneType'

grad1 here computes the gradients w.r.t. to the fed-in actions, which were previously computed by the actor. grad2 should do the same, but directly inside of the graph without the need for feeding the actions back in but by evaluating actor directly. The problem is that grads_direct is None:

print(grads_direct)  # [None]

How can I achieve this? Is there a dedicated "evaluate this tensor" operation I could make use of? Thanks!

Body:
In your example you don't use actor to compute critic so the gradient is None.

You should do:

actor = states * 1
critic = actor + actions  # change here

grads_indirect = tf.gradients(critic, actions)
grads_direct = tf.gradients(critic, actor)


问:
SQL range conditions less than, greater than and between
What I would like to accomplish is; query if  'email ocr in' & 'universal production' rows in the "documents created column" field, total the same amount as "email OCR" 'documents_created. If not, pull that batch. finally if the attachment count is less than 7 entries after the email ocr in & universal production files are pulled then return said result

current query below:

```<code>use N
SELECT   id,
         type,
         NAME,
         log_time ,
         start_time ,
         documents_created ,
         pages_created,
         processed,
         processed_time

FROM     N_LF_OCR_LOG

WHERE

    -- Log time is current day
    log_time between  CONVERT(date, getdate()) AND CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00'

    -- Documents created is NULL or non zero
    AND (documents_created IS NULL OR documents_created <> 0)

  or  ( documents_created is null and log_time between  CONVERT(date, getdate()) AND CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00')

    -- Filter for specific types
    AND type IN ('Email OCR In',
            'Universal Production')

    -- Filter to rows where number of pages and documents created are not equal
    AND documents_created <2 and pages_created >2

ORDER BY log_time
,id asc
,processed_time asc
</code>```

any idea how to incorporate that? Im a novice. thanks

答:
When creating an index, you just specify the columns to be indexed. There is no difference in creating an index for a range query or an exact match. You can add multiple columns to the same index so all columns can benefit from the index, because only one index per table at the time can be selected to support a query.

You could create an index just covering your where-clause:

```<code>alter table N_LF_OCR_LOG add index test1(log_time, documents_created, type, pages_created);
</code>```

Or also add the required columns for the ordering into the index. The ordering of the columns in the index is important and must be the same as for the ordering in the query:

```<code>alter table N_LF_OCR_LOG add index test1(log_time, id, processed_time, documents_created, type, pages_created);
</code>```

Or add a covering index that also contains the returned columns so you do not have to load any values from your tables and can answer to complete query by just using the index. This gives the best response time for the query. But the index takes up more space on the disk.

```<code>alter table N_LF_OCR_LOG add index test1(log_time, id,  processed_time, documents_created, type, pages_created, NAME, start_time, processed);
</code>```

Use the explain keyword infront of your query to see how good your index performs.

Body:
What I would like to accomplish is; query if  'email ocr in' & 'universal production' rows in the "documents created column" field, total the same amount as "email OCR" 'documents_created. If not, pull that batch. finally if the attachment count is less than 7 entries after the email ocr in & universal production files are pulled then return said result

current query below:

use N
SELECT   id,
         type,
         NAME,
         log_time ,
         start_time ,
         documents_created ,
         pages_created,
         processed,
         processed_time

FROM     N_LF_OCR_LOG

WHERE

    -- Log time is current day
    log_time between  CONVERT(date, getdate()) AND CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00'

    -- Documents created is NULL or non zero
    AND (documents_created IS NULL OR documents_created <> 0)

  or  ( documents_created is null and log_time between  CONVERT(date, getdate()) AND CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00')

    -- Filter for specific types
    AND type IN ('Email OCR In',
            'Universal Production')

    -- Filter to rows where number of pages and documents created are not equal
    AND documents_created <2 and pages_created >2

ORDER BY log_time
,id asc
,processed_time asc

any idea how to incorporate that? Im a novice. thanks

Body:
When creating an index, you just specify the columns to be indexed. There is no difference in creating an index for a range query or an exact match. You can add multiple columns to the same index so all columns can benefit from the index, because only one index per table at the time can be selected to support a query.

You could create an index just covering your where-clause:

alter table N_LF_OCR_LOG add index test1(log_time, documents_created, type, pages_created);

Or also add the required columns for the ordering into the index. The ordering of the columns in the index is important and must be the same as for the ordering in the query:

alter table N_LF_OCR_LOG add index test1(log_time, id, processed_time, documents_created, type, pages_created);

Or add a covering index that also contains the returned columns so you do not have to load any values from your tables and can answer to complete query by just using the index. This gives the best response time for the query. But the index takes up more space on the disk.

alter table N_LF_OCR_LOG add index test1(log_time, id,  processed_time, documents_created, type, pages_created, NAME, start_time, processed);

Use the explain keyword infront of your query to see how good your index performs.


问:
How to enable serverside render support for servicestack angular 2 template?
with latest release of servicestack there is angular 2 template. How to enable serverside render?</p>

答: They don't support server side rendering, that would require using node.js to execute the JS on the server through something like JavaScriptServices which is only supported in .NET Core.</p>


问:
Non greedy (reluctant) regex matching in sed?
I'm trying to use sed to clean up lines of URLs to extract just the domain.

So from:

```<code>http://www.suepearson.co.uk/product/174/71/3816/
</code>```

I want:

```<code>http://www.suepearson.co.uk/
</code>```

(either with or without the trailing slash, it doesn't matter)

I have tried:

```<code> sed 's|\(http:\/\/.*?\/\).*|\1|'
</code>```

and (escaping the non-greedy quantifier)

```<code>sed 's|\(http:\/\/.*\?\/\).*|\1|'
</code>```

but I can not seem to get the non-greedy quantifier (?) to work, so it always ends up matching the whole string.

答:
Here is something you can do with a two step approach and awk:

```<code>A=http://www.suepearson.co.uk/product/174/71/3816/
echo $A|awk '
{
  var=gensub(///,"||",3,$0) ;
  sub(/\|\|.*/,"",var);
  print var
}'
</code>```

Output:
  http://www.suepearson.co.uk

Hope that helps!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use sed to clean up lines of URLs to extract just the domain.

So from:

http://www.suepearson.co.uk/product/174/71/3816/

I want:

http://www.suepearson.co.uk/

(either with or without the trailing slash, it doesn't matter)

I have tried:

 sed 's|\(http:\/\/.*?\/\).*|\1|'

and (escaping the non-greedy quantifier)

sed 's|\(http:\/\/.*\?\/\).*|\1|'

but I can not seem to get the non-greedy quantifier (?) to work, so it always ends up matching the whole string.

Body:
Here is something you can do with a two step approach and awk:

A=http://www.suepearson.co.uk/product/174/71/3816/
echo $A|awk '
{
  var=gensub(///,"||",3,$0) ;
  sub(/\|\|.*/,"",var);
  print var
}'

Output:
  http://www.suepearson.co.uk

Hope that helps!


答:
Probably the most popular way (without getting into creepy, borderline unethical types of big data tracking) is to simply store a cookie on their first visit. When they come back, check if they have the cookie. If they do, they've visited before. If not, they're either coming for the first time or have cleared their cookies (which would only be a small number of users).

Setting the cookie:

```<code>document.cookie = 'visited=1';
</code>```

Reading the cookie:

```<code>Boolean(document.cookie.split(';').filter(cookie => cookie === 'visited=1').length);
</code>```

When you set a cookie, you just set it on document.cookie. When you read them back, it gives you all cookies for the current domain, and you have to split them apart and check yourself.

There are more sophisticated, big data analyzing types of ways, but they are borderline unethical and illegal, not to mention super creepy and scumming, so I won't be diving into those methods. ;)

Title: How can I tell if users are making repeated visits?

Body:
I have a javascript web application and I want to know if users are returning to it or just visiting it one time. Is there some identifier for each device (computer, phone, etc.) that I can record, so that I can check if a user has made repeated visits?

I do not want users to have to manually provide any information to me (like an email).

I can't record their IP address because that is not unique per device.

Body:
Probably the most popular way (without getting into creepy, borderline unethical types of big data tracking) is to simply store a cookie on their first visit. When they come back, check if they have the cookie. If they do, they've visited before. If not, they're either coming for the first time or have cleared their cookies (which would only be a small number of users).

Setting the cookie:

document.cookie = 'visited=1';

Reading the cookie:

Boolean(document.cookie.split(';').filter(cookie => cookie === 'visited=1').length);

When you set a cookie, you just set it on document.cookie. When you read them back, it gives you all cookies for the current domain, and you have to split them apart and check yourself.

There are more sophisticated, big data analyzing types of ways, but they are borderline unethical and illegal, not to mention super creepy and scumming, so I won't be diving into those methods. ;)


问:
IS select top x reliable on large data sets in MSSQL
My question is to whether the following is reliable on a large dataset in MSSQL:

```<code>select top 1 * from table order by row_id
</code>```

I was wondering if there was some threshold that when met will return the top 1 from a set of data. For example if there was a table with millions of rows and the query above was ran if it was reliable that the row returned would indeed be the top row or if it would be top row of a subset of that data.

答: As long as there is an 'order by' clause, it's both consistent and reliable.</p>

Body:
My question is to whether the following is reliable on a large dataset in MSSQL:

select top 1 * from table order by row_id

I was wondering if there was some threshold that when met will return the top 1 from a set of data. For example if there was a table with millions of rows and the query above was ran if it was reliable that the row returned would indeed be the top row or if it would be top row of a subset of that data.


问:
Tkinter - Keyword arguement repeated
Tried searching around for this error, Currently making a resolution window before my friends program (Helping out with minor stuff) Currently have a problem with trying to use two commands in one line (Probably a easy fix knowing me), if anyone could help me out that would be epic!

Here's the code!

```<code>res1 = tkinter.Button(settings, text="800x600", fg="ghost white" , bg="grey10", font=(16), command=resolution1, command=close_window)
res2 = tkinter.Button(settings, text="1024x768", fg="ghost white" , bg="grey10", font=(16), command=resolution2, command=close_window)
res3 = tkinter.Button(settings, text="1280x720", fg="ghost white" , bg="grey10", font=(16), command=resolution3, command=close_window)
res4 = tkinter.Button(settings, text="1920x1080", fg="ghost white" , bg="grey10", font=(16), command=resolution4, command=close_window)
</code>```

If you need the full code just shout!

Many thanks!

答:
The best way to use commands with buttons is to have a button call a function. In that function you can do whatever you want, including calling multiple functions:

```<code>def do_resolution1():
    resolution1()
    close_window()

def do_resolution2():
    resolution2()
    close_widnow()
...
res1 = tkinter.Button(..., command=do_resolution1)
res2 = tkinter.Button(..., command=do_resolution2)
</code>```

You could also write a single function that takes another function as an argument, runs it, and then calls close_window. You can then use lambda to call that function with different arguments for each button:

I don't recommend this approach for beginners because lambda can be confusing.

```<code>def set_resolution(func):
    func()
    close_window()
...
res1 = tkinter.Button(..., command=lambda: set_resolution(resolution1))
res2 = tkinter.Button(..., command=lambda: set_resolution(resolution2))
...
</code>```

Title: Tkinter - Keyword arguement repeated

Body:
Tried searching around for this error, Currently making a resolution window before my friends program (Helping out with minor stuff) Currently have a problem with trying to use two commands in one line (Probably a easy fix knowing me), if anyone could help me out that would be epic!

Here's the code!

res1 = tkinter.Button(settings, text="800x600", fg="ghost white" , bg="grey10", font=(16), command=resolution1, command=close_window)
res2 = tkinter.Button(settings, text="1024x768", fg="ghost white" , bg="grey10", font=(16), command=resolution2, command=close_window)
res3 = tkinter.Button(settings, text="1280x720", fg="ghost white" , bg="grey10", font=(16), command=resolution3, command=close_window)
res4 = tkinter.Button(settings, text="1920x1080", fg="ghost white" , bg="grey10", font=(16), command=resolution4, command=close_window)

If you need the full code just shout!

Many thanks!

Body:
The best way to use commands with buttons is to have a button call a function. In that function you can do whatever you want, including calling multiple functions:

def do_resolution1():
    resolution1()
    close_window()

def do_resolution2():
    resolution2()
    close_widnow()
...
res1 = tkinter.Button(..., command=do_resolution1)
res2 = tkinter.Button(..., command=do_resolution2)

You could also write a single function that takes another function as an argument, runs it, and then calls close_window. You can then use lambda to call that function with different arguments for each button:

I don't recommend this approach for beginners because lambda can be confusing.

def set_resolution(func):
    func()
    close_window()
...
res1 = tkinter.Button(..., command=lambda: set_resolution(resolution1))
res2 = tkinter.Button(..., command=lambda: set_resolution(resolution2))
...


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
Interfaces are generally used when you want to define a behavior that objects can exhibit.

A good example of this in the .NET world is the IDisposable interface, which is used on any Microsoft classes that use system resources that must be manually released.  It requires that the class implementing it have a Dispose() method.

(The Dispose() method is also called by the using language construct for VB.NET and C#, which only works on IDisposables)

Keep in mind that you can check if an object implements a specific interface by using constructs such as TypeOf ... Is (VB.NET), is (C#), instanceof (Java), etc...

LastEditorDisplayName: ALassek

OwnerDisplayName: R. Bemrose


答:
Assuming a file format like

a

     c

     a

     b

this should parse it and put function pointers into a std::vector accordingly:

```<code>// Beware, untested code ahead!

typedef void (*func_t)();
typedef std::map<std::string, func_t>   func_map_t;
typedef func_map_t::value_type          func_map_entry_t;

void f1() {}
void f2() {}
void f3() {}

const func_map_entry_t func_map_entries[] = { func_map_entry_t("a", &f1)
                                            , func_map_entry_t("b", &f2)
                                            , func_map_entry_t("c", &f3) };

const func_map_t func_map( func_map_entries
                         , func_map_entries + sizeof(func_map_entries)
                                            / sizeof(func_map_entries[0]));

func_t read_line(std::istream& is)
{
    std::string token;
    if(!(is >> token)) throw "you need better error handling!";
    func_map_t::const_iterator found = func_map.find(token);
    if(found == func_map.end()) throw "you need better error handling!";
    return found->second;
}

std::vector<func_t> read_config(std::istream& is)
{
    std::vector<func_t> result;
    std::string line;
    while(std::getline(is,line))
    {
        std::istringstream iss(line);
        func_t func = read_line(iss);
        if(!func) throw "you need better error handling!";
        result.push_back(func);
    }
    if(is.eof()) throw "you need better error handling!";
    return result;
}
</code>```

Title: Registering callbacks from text configuration file

Body:
Assuming a file format like

a

     c

     a

     b

this should parse it and put function pointers into a std::vector accordingly:

// Beware, untested code ahead!

typedef void (*func_t)();
typedef std::map<std::string, func_t>   func_map_t;
typedef func_map_t::value_type          func_map_entry_t;

void f1() {}
void f2() {}
void f3() {}

const func_map_entry_t func_map_entries[] = { func_map_entry_t("a", &f1)
                                            , func_map_entry_t("b", &f2)
                                            , func_map_entry_t("c", &f3) };

const func_map_t func_map( func_map_entries
                         , func_map_entries + sizeof(func_map_entries)
                                            / sizeof(func_map_entries[0]));

func_t read_line(std::istream& is)
{
    std::string token;
    if(!(is >> token)) throw "you need better error handling!";
    func_map_t::const_iterator found = func_map.find(token);
    if(found == func_map.end()) throw "you need better error handling!";
    return found->second;
}

std::vector<func_t> read_config(std::istream& is)
{
    std::vector<func_t> result;
    std::string line;
    while(std::getline(is,line))
    {
        std::istringstream iss(line);
        func_t func = read_line(iss);
        if(!func) throw "you need better error handling!";
        result.push_back(func);
    }
    if(is.eof()) throw "you need better error handling!";
    return result;
}


问:
Moodle .doc to .pdf conversion doesn't work
When I go to grading and click to attribute a grade to a student, an interface opens: it has a comment section, grade field, etc. and a screen where it's printed "Generating PDF" where the student's homework should be. Except that the PDF is never ever generated, it just leaves a blank page. It happens when the uploaded file is a Word document - didn't test it with other kinds of submission.

Print:
An image is worth more than a thousand words

I've looked it up in Moodle's forum and it seems this issue's pretty common, but I can't really understand what they are saying, 'cause it seems their solutions are directed to those who have a server at home.

My moodle is hosted on a third-party server, I'm not a server owner, I'm merely the website administrator. I do have access to the web hosting account, but don't have enough permissions to install/change/delete server routines and stuff that requires access to a terminal.

Is there anything that I, as a website administrator can do?

To clarify: 1 - I do not know if this is the right place to ask this questions - there are so many "stackoverflow-sites" that I can't keep track. So, feel free to move my topic.

2 - I did search if there was a similar question here and found none. If there is one, it's well hidden and I would appreciate if anyone could provide me with the link to that.

答:
On moodle 3.2 and 3.1 you need unoconv and libreoffice installed on server, so if you can't install software on the server - it will not work.
On 3.3 it could use google services - didn't try it yet...</p>


问:
Firebase for A/B testing with remote config
I need to run A/B testing and I was thinking about using Firebase remote config. I could not find whether it is possible to updated the app keeping the value for the A/B config between versions. What I mean is that if I publish the app and I target 20% of the user with a new feature and then I need to make an hotfix, would I be able to publish a new version without breaking the A/B test I mean leaving the user that had got the new feature with the same config?</p>

答: Publishing a new version of the app will not change the way users are assigned into one of the groups created by Remote Config.</p>


答:
If you write up "Use a map" as an answer, I'll pick it.

Use a map.

More specifically, your text file contains the keys to the map, and the map maps keys to function pointers. Come up with a unique name for each function (could be the function name! perhaps plus argument types if you've got overloading), store it in the text file, and run each entry through the map to get the function pointer to store in the array.


问:
Connect refused in response to Django runserver
Working my way through a Django tutorial, I have run django-admin startproject mysite. Now I cannot get the next step to work.

```<code>$ python manage.py runserver

>>>
$
</code>```

where the blank line is where Ctrl-C was entered to break the loop.  The >>> was the prompt I defined for the virtualenv. In other words, no output.

Most importantly, I get a connection refused error when connecting to http://127.0.0.1:8000. I do not get the the "'Welcome to Django' page, in pleasant, light-blue pastel" as described in the tutorial.

For other commands python manage.py works correctly. For example:

```<code>$ python manage.py check
System check identified no issues (0 silenced).

$ python manage.py shell --command 'import sys; print(sys.version)'
3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)]

$/ python manage.py shell --command 'import django; print(django.__version__)'
1.11.2
</code>```

I am at loss for how explore further. I have tried:

Using multiple browsers

Varying the IP and port, including using LOCALHOST.

Turning off the proxy

Consulting other Stack Overflow, such as here and here

Rebooting my computer

Exploring Chrome's log's. Perhaps someone else can get something valueable out of these: Request Headers & Timing Diagram.

I am at loss for other steps to debug this problem.

答:
If you didn't change something in the settings.py you should enter the service in

localhost:8000

Using the same machine where you are runing the server.

If you want to enter from another computer in the same network you should use

```<code>$ python manage.py runserver 0.0.0.0:8000
</code>```

And change your "allowed hosts" to the ip of your computer or to *

Body:
Working my way through a Django tutorial, I have run django-admin startproject mysite. Now I cannot get the next step to work.

$ python manage.py runserver

>>>
$

where the blank line is where Ctrl-C was entered to break the loop.  The >>> was the prompt I defined for the virtualenv. In other words, no output.

Most importantly, I get a connection refused error when connecting to http://127.0.0.1:8000. I do not get the the "'Welcome to Django' page, in pleasant, light-blue pastel" as described in the tutorial.

For other commands python manage.py works correctly. For example:

$ python manage.py check
System check identified no issues (0 silenced).

$ python manage.py shell --command 'import sys; print(sys.version)'
3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)]

$/ python manage.py shell --command 'import django; print(django.__version__)'
1.11.2

I am at loss for how explore further. I have tried:

Using multiple browsers

Varying the IP and port, including using LOCALHOST.

Turning off the proxy

Consulting other Stack Overflow, such as here and here

Rebooting my computer

Exploring Chrome's log's. Perhaps someone else can get something valueable out of these: Request Headers & Timing Diagram.

I am at loss for other steps to debug this problem.

Body:
If you didn't change something in the settings.py you should enter the service in

localhost:8000

Using the same machine where you are runing the server.

If you want to enter from another computer in the same network you should use

$ python manage.py runserver 0.0.0.0:8000

And change your "allowed hosts" to the ip of your computer or to *


问:
Extract the provided text + whole paragraph where ever the text present in webpage python
I want to extract given text which is present, can be anywhere in the Webpage without using CssSelector, Xpath, ClassName, etc...

I have the following code:

```<code> keyword = raw_input("Please Enter The Keyword to Search : ")
 from selenium import webdriver
 driver = webdriver.Chrome()#path is already setuped
 driver.get(url)
 driver.implicitly_wait(5)
 # Not providing Expected output
 # dataa = driver.find_elements_by_xpath("//*[contains(text(), "+keyword+")]")
 dataa = driver.page_source
 driver.quit()
</code>```

Earlier I used this code to do the same text extraction process but with bs4 and that worked successfully.

```<code>soup = BeautifulSoup(data, "html.parser")
for da in soup.find_elements(text=re.compile(keyword)):
    print da.text
</code>```

Is there any method so that I can only extract paragraphs or description using the keyword?

答:
So what if you extract all text on page using 'goose' module, then iterate over everything and find keyword in given sentence, something like this:

```<code>from goose import Goose

keyword = 'I can only extract paragraphs'

g = Goose(config={'enable_image_fetching':False})
article = g.extract(url='https://stackoverflow.com/questions/44444456/extract-the-provided-text-whole-paragraph-where-ever-the-text-present-in-webpa')
text = article.cleaned_text
_sent = [sent for sent in text.split('\n') if keyword in sent]

print _sent
#[u'is there any method ?? so that ""I can only extract paragraphs or Description using the keyword""']
</code>```

UPDATE: extra module required: pyteaser. Function returns first 5 sents based on scoring for provided keyword

```<code>from pyteaser import Summarize
from goose import Goose

def teaser(title,text):
    summaries = Summarize(title,text)
    return summaries

g = Goose(config={'enable_image_fetching':False})
article = g.extract(url='http://en.wikipedia.org/wiki/Rahul_Dravid')
text = article.cleaned_text

print teaser('Dravid',text)
</code>```

Body:
I want to extract given text which is present, can be anywhere in the Webpage without using CssSelector, Xpath, ClassName, etc...

I have the following code:

 keyword = raw_input("Please Enter The Keyword to Search : ")
 from selenium import webdriver
 driver = webdriver.Chrome()#path is already setuped
 driver.get(url)
 driver.implicitly_wait(5)
 # Not providing Expected output
 # dataa = driver.find_elements_by_xpath("//*[contains(text(), "+keyword+")]")
 dataa = driver.page_source
 driver.quit()

Earlier I used this code to do the same text extraction process but with bs4 and that worked successfully.

soup = BeautifulSoup(data, "html.parser")
for da in soup.find_elements(text=re.compile(keyword)):
    print da.text

Is there any method so that I can only extract paragraphs or description using the keyword?

Body:
So what if you extract all text on page using 'goose' module, then iterate over everything and find keyword in given sentence, something like this:

from goose import Goose

keyword = 'I can only extract paragraphs'

g = Goose(config={'enable_image_fetching':False})
article = g.extract(url='https://stackoverflow.com/questions/44444456/extract-the-provided-text-whole-paragraph-where-ever-the-text-present-in-webpa')
text = article.cleaned_text
_sent = [sent for sent in text.split('\n') if keyword in sent]

print _sent
#[u'is there any method ?? so that ""I can only extract paragraphs or Description using the keyword""']

UPDATE: extra module required: pyteaser. Function returns first 5 sents based on scoring for provided keyword

from pyteaser import Summarize
from goose import Goose

def teaser(title,text):
    summaries = Summarize(title,text)
    return summaries

g = Goose(config={'enable_image_fetching':False})
article = g.extract(url='http://en.wikipedia.org/wiki/Rahul_Dravid')
text = article.cleaned_text

print teaser('Dravid',text)


问:
JQuery .addClass() not applying styles defined in JQuery
It's quite a simple question, but I'm (trying) to write a JQuery plugin, and I want to use only JQuery. The problem is, I have some styles set for the .active divs (via JQuery), and on clicking a
 it's given a class active - I know this, because I checked in the developer tools - but it's not given the styles. I tried hardcoding the class onto the
, and it worked fine. I also tried hardcoding the styles in CSS instead of JQuery, and again, it worked. Is there a way of updating the JQuery - onclick of the
 - so that the styles are applied when the
 is clicked?

$('div.active').css({
  'border-style':'solid',
 'border-width':'1px',
 'border-color':'black',
});
$('div').on('click',function(){
   $('div').removeClass('active');
    $(this).addClass('active');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">div 1</div>
<div class="div2">div 2</div>
<div class="div3">div 3</div>
<div class="div4">div 4</div></code>```

JSFiddle

Also, can you explain why this isn't working for me?

Thanks

答:
Aside explanation from others, put CSS seperately would work,

```<code>div.active {
    border: 1px solid red;
}

div {
    border: 1px solid green;
}
</code>```

A working demo for your question is here:
js fiddle

Body:
It's quite a simple question, but I'm (trying) to write a JQuery plugin, and I want to use only JQuery. The problem is, I have some styles set for the .active divs (via JQuery), and on clicking a
 it's given a class active - I know this, because I checked in the developer tools - but it's not given the styles. I tried hardcoding the class onto the
, and it worked fine. I also tried hardcoding the styles in CSS instead of JQuery, and again, it worked. Is there a way of updating the JQuery - onclick of the
 - so that the styles are applied when the
 is clicked?

$('div.active').css({
  'border-style':'solid',
 'border-width':'1px',
 'border-color':'black',
});
$('div').on('click',function(){
   $('div').removeClass('active');
    $(this).addClass('active');
});

div 1

div 2

div 3

div 4

JSFiddle

Also, can you explain why this isn't working for me?

Thanks

Body:
Aside explanation from others, put CSS seperately would work,

div.active {
    border: 1px solid red;
}

div {
    border: 1px solid green;
}

A working demo for your question is here:
js fiddle


问:
Getting current item ID in SharePoint Infopath form
Can we get the current item ID value while submitting the data in InfoPath form.

I need to use this and concatenate the ID with other field value. Tired "Max(@ID) + 1" function but it wouldn't solve the problem.

I know it can be done using calculated column or workflow.

It needs to be done using InfoPath form ? Is it possible ?

答:
You already figured it out yourself. Im assuming you are trying to use the ID in naming it.

Create a blank field.

Then add that field to your submission naming concat.

Create a receive data connection (assuming you havent) to that library.

On the Submit rule add the query action to that library and a set field action to set that new blank field with max(ID) + 1. Make sure Submit action is last.

That should do it unless Im missing something as I have used this many times!


问:
Using plist in a DetailView
I have this tableview in my app which has a particular item name such as "Apple". When the user taps on that selected item they are directed to a detailView that views an image and description of that selected item. I was thinking to use plist´s to do this, but I don't know how to. Please help me.

I looked at some sources such as iCodeBlog but they don´t really explain retrieving and saving so well. Maybe you people can also give reference to some links that describe this better.

Heres a plist that I have tried. Each of the items (Orange, Apple) have the data that I want to display in my detailView. I basically want to display the data shown.

答:
Here is an example view controller which will do what you want. I named the class DetailViewController and loaded the plist from Details.plist in the app's resources. Images are also located in the app's resources.

DetailViewController.h

```<code>#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController {
    UILabel *description;
    UIImageView *imageView;
    NSString *selectedItem;
}
@property (nonatomic, retain) IBOutlet UILabel *description;
@property (nonatomic, retain) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSString *selectedItem;
@end
</code>```

DetailViewController.m

```<code>#import "DetailViewController.h"
@implementation DetailViewController
@synthesize description, imageView, selectedItem;

- (void)viewDidLoad {
    NSDictionary *details = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Details" ofType:@"plist"]];
    details = [details objectForKey:self.selectedItem];
    self.description.text = [details objectForKey:@"description"];
    self.imageView.image = [UIImage imageNamed:[details objectForKey:@"image"]];
}
@end
</code>```

Then, all you have to do is update the selectedItem property before loading the view and create a NIB file with the description label and image view attached to their outlets.

Title: Using plist in a DetailView

Body:
Here is an example view controller which will do what you want. I named the class DetailViewController and loaded the plist from Details.plist in the app's resources. Images are also located in the app's resources.

DetailViewController.h

#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController {
    UILabel *description;
    UIImageView *imageView;
    NSString *selectedItem;
}
@property (nonatomic, retain) IBOutlet UILabel *description;
@property (nonatomic, retain) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSString *selectedItem;
@end

DetailViewController.m

#import "DetailViewController.h"
@implementation DetailViewController
@synthesize description, imageView, selectedItem;

- (void)viewDidLoad {
    NSDictionary *details = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Details" ofType:@"plist"]];
    details = [details objectForKey:self.selectedItem];
    self.description.text = [details objectForKey:@"description"];
    self.imageView.image = [UIImage imageNamed:[details objectForKey:@"image"]];
}
@end

Then, all you have to do is update the selectedItem property before loading the view and create a NIB file with the description label and image view attached to their outlets.


答:
join can only work on two files at a time, here comes

awk to the rescue!

```<code>$ awk -F, 'FNR==1 {c++; h=h sep $2; sep=FS; next}
                  {ks[$1]; a[$1,c]=$2}
           END    {print h;
                   for(k in ks)
                     {printf "%s", k;
                      for(i=1;i<=c;i++) printf "%s", FS a[k,i]+0;
                      print ""}}' files
</code>```

disclaimier: only if the data can fit in memory, also the order will be lost but if important there are ways to handle it.

Explanation Conceptually creating a table (aka 2D array, matrix) and filling up the entries.  THe rows are indexed by key and columns by file number.  Since awk array is hashing the keys we treat header separately to stay in place.  a[k,i]+0 is to convert missing elements to 0.

Title: How to merge multiple .csv files using the 1st column of one of them as a index (shell scripting)

Body:
How to merge multiple .csv files using the 1st column of one of them as an index (pref shell scripting - awk)

88 .csv files that look like this
input files names ZBND19X.csv

==> ZBND19X.csv <==
Gene,ZBND19X(26027342 pairs)
ENSTGUG00000013338 (GAPDH),984.31862471
ENSTGUG00000000915,862.597795025
ENSTGUG00000006651 (ARPP19),845.045872644
ENSTGUG00000005054 (CAMKV),823.404021741
ENSTGUG00000005949 (FTH1),585.628487964

and ZBND22V.csv

==> ZBND39X.csv <==
Gene,ZBND39X(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638
ENSTGUG00000000915,588.002298061

output file name RPKM_all.csv

Gene,ZBND19X(26027342 pairs),ZBND39X(26558640 pairs)
ENSTGUG00000013338 (GAPDH),984.31862471,971.678203888
ENSTGUG00000000915,862.597795025,588.002298061
ENSTGUG00000006651 (ARPP19),845.045872644,634.296191033
ENSTGUG00000005054 (CAMKV),823.404021741,687.81249397
ENSTGUG00000005949 (FTH1),585.628487964,0
ENSTGUG00000002582 (ITM2A),613.756010638,0

Adding the 0 when there is no corresponding value found.

Body:
join can only work on two files at a time, here comes

awk to the rescue!

$ awk -F, 'FNR==1 {c++; h=h sep $2; sep=FS; next}
                  {ks[$1]; a[$1,c]=$2}
           END    {print h;
                   for(k in ks)
                     {printf "%s", k;
                      for(i=1;i<=c;i++) printf "%s", FS a[k,i]+0;
                      print ""}}' files

disclaimier: only if the data can fit in memory, also the order will be lost but if important there are ways to handle it.

Explanation Conceptually creating a table (aka 2D array, matrix) and filling up the entries.  THe rows are indexed by key and columns by file number.  Since awk array is hashing the keys we treat header separately to stay in place.  a[k,i]+0 is to convert missing elements to 0.


答:
You can control based on variable as below:

```<code>declare @i int = 1
select top(@i) * from NumSeq order by col1
</code>```

Basedon variable @i it will return that number of records

Title: IS select top x reliable on large data sets in MSSQL

Body:
You can control based on variable as below:

declare @i int = 1
select top(@i) * from NumSeq order by col1

Basedon variable @i it will return that number of records


问:
UWP service for accessing SQL Server
RE: https://code.msdn.microsoft.com/How-to-access-data-from-5f2602ec

I'm hoping to clarify some points and concerns. When designing UWP for Windows 10 Microsoft, in my own thoughts, short-sightedly left SYSTEM.DATA out of the framework. This means that you must use a WCF web service as a middle man to access any data from SQL Server and return it to your application. Here's where I get confused:

When the app is run from Visual Studio and then stopped, the web service is still running in the background and can be accessed from any browser. You could easily find the address by using something like fiddler.

This concerns me for because anyone can then see your service and use it and I'm not sure how to obfuscate the service itself.

I'm also not sure how the service itself gets bundled and deployed. When creating the service reference, you reference a specific address and port. Does it always use that same port no matter where it's installed? Does the store app automatically deploy the web service as part of the UWP download/install?

Overall, I'm skeptical of the decision they made to exclude system.data and the ability to protect IP or secure your application when you can simply browse to the service address and review the function calls, profile, or decompile.

I hope I've been clear on my concerns and that some kind soul can entertain them.

答:
A service is a separate application that you typically deploy to some remote machine, for example in the cloud.

Your UWP client app connects to this service over the Internet but the service is not packaged and deployed together with your client application. It may serve several different kind of client applications simultaneously.

The client application obviously needs to know the address of the service to be able to connect to it at runtime.

So you basically create two different applications. One service application that reads from and writes to the database and one UWP client application that consumes the remote service application. The service application may be deployed to Azure and the UWP application to the Windows Store.

Title: UWP service for accessing SQL Server


问:
passing image and displaying it
So after studying, researching and outsoursing i couldnt figure my problem out :(. I am currently trying to get used to segue for view to view while passing values. So whats better then developing a simple app?

My app is like this... first page with one image array that randomly spits out an image when the view loads and one action buttonthat triggers the view segue to the next view using segue preform function.

the second page contains a dismiss button and an image view that should change depend on the randomly passed image from the previeous view image array.

Everything works fine except that I cannot see the randomly passed image.

Below is my code:

Page 1

```<code>import UIKit

class MainWelcomVC: UIViewController {

var ImageArr = [UIImageView]()

@IBOutlet weak var BackGround: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    for x in 0...2 {

        let image = UIImage(named: "char\(x).png")
        let imageview = (UIImageView(image: image))
        ImageArr.append(imageview)

    }

}

@IBAction func PlayButtonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
    let CharImage = ImageArr[randomIndex]

    performSegue(withIdentifier: "CharDisplayVC", sender: CharImage)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? CharDisplayVC{

        if let ImageFinal = sender as? UIImage {
            destination.ImageToDisplay = ImageFinal
        }
}

}
}
</code>```

page2

```<code>import UIKit

class CharDisplayVC: UIViewController {

private var _ImageToDisplay: UIImage!

var ImageToDisplay: UIImage {

    get {

        return _ImageToDisplay

    } set {

        _ImageToDisplay = newValue
    }

}

@IBOutlet weak var CharPicture: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    CharPicture.image = _ImageToDisplay

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func PlayAgainBtnPressed(_ sender: Any) {

    dismiss(animated: true, completion: nil)
}

}
</code>```

答:
That's not how I use the sender parameter in segues. Generally I call self since the UIViewController is making the performSegue call. Something like the following should work.

```<code>import UIKit

class MainWelcomVC: UIViewController {

    var ImageArr = [UIImageView]()
    var CharImage: UIImage?

    @IBOutlet weak var BackGround: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        for x in 0...2 {

            let image = UIImage(named: "char\(x).png")
            let imageview = (UIImageView(image: image))
            ImageArr.append(imageview)
        }
    }

    @IBAction func PlayButtonPressed(_ sender: Any) {

        let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
        self.CharImage = ImageArr[randomIndex].image

        performSegue(withIdentifier: "CharDisplayVC", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let destination = segue.destination as? CharDisplayVC {

            if let ImageFinal = self.CharImage as? UIImage {
                destination.ImageToDisplay = ImageFinal
            }
        }
    }
}
</code>```

Title: passing image and displaying it

Body:
So after studying, researching and outsoursing i couldnt figure my problem out :(. I am currently trying to get used to segue for view to view while passing values. So whats better then developing a simple app?

My app is like this... first page with one image array that randomly spits out an image when the view loads and one action buttonthat triggers the view segue to the next view using segue preform function.

the second page contains a dismiss button and an image view that should change depend on the randomly passed image from the previeous view image array.

Everything works fine except that I cannot see the randomly passed image.

Below is my code:

Page 1

import UIKit

class MainWelcomVC: UIViewController {

var ImageArr = [UIImageView]()

@IBOutlet weak var BackGround: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    for x in 0...2 {

        let image = UIImage(named: "char\(x).png")
        let imageview = (UIImageView(image: image))
        ImageArr.append(imageview)

    }

}

@IBAction func PlayButtonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
    let CharImage = ImageArr[randomIndex]

    performSegue(withIdentifier: "CharDisplayVC", sender: CharImage)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? CharDisplayVC{

        if let ImageFinal = sender as? UIImage {
            destination.ImageToDisplay = ImageFinal
        }
}

}
}

page2

import UIKit

class CharDisplayVC: UIViewController {

private var _ImageToDisplay: UIImage!

var ImageToDisplay: UIImage {

    get {

        return _ImageToDisplay

    } set {

        _ImageToDisplay = newValue
    }

}

@IBOutlet weak var CharPicture: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    CharPicture.image = _ImageToDisplay

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func PlayAgainBtnPressed(_ sender: Any) {

    dismiss(animated: true, completion: nil)
}

}

Body:
That's not how I use the sender parameter in segues. Generally I call self since the UIViewController is making the performSegue call. Something like the following should work.

import UIKit

class MainWelcomVC: UIViewController {

    var ImageArr = [UIImageView]()
    var CharImage: UIImage?

    @IBOutlet weak var BackGround: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        for x in 0...2 {

            let image = UIImage(named: "char\(x).png")
            let imageview = (UIImageView(image: image))
            ImageArr.append(imageview)
        }
    }

    @IBAction func PlayButtonPressed(_ sender: Any) {

        let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
        self.CharImage = ImageArr[randomIndex].image

        performSegue(withIdentifier: "CharDisplayVC", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let destination = segue.destination as? CharDisplayVC {

            if let ImageFinal = self.CharImage as? UIImage {
                destination.ImageToDisplay = ImageFinal
            }
        }
    }
}


问:
How to filter array of objects by object property in VueJS
I want to print out the movies that have time sessions that start after the hour 20 or the same day. Either way, I can't get it to work.

Component data structure:

```<code>day:"2017-06-08T18:34:27.211Z"
movies:Array[8]
0:Object
   Description:"orphan the becomes a famous magician "
   id:1
   movieName:"Harry Potter "
   time_session:Array[3]
     0:Object
       id:1
       pivot:Object
       time:"2017-06-14 00:00:00"
     1:Object
     2:Object
1:Object
2:Object
3:Object
4:Object
</code>```

Template:

```<code><template>
  <div>
    <li v-for="movie in filteration(movies)">{{movie.movieName}}</li>
  </div>
</template>
</code>```

How can I filter the movies so that the movies displayed depend on the time sessions in that same Object?

Here's what I've tried:

```<code><script>
  export default{
    data() {
      return {
        movies:[],
        day:moment()
      }
    },
    mounted(){
      axios.get("/fa")
        .then(response  => this.movies = response.data);
    },
    methods:{
      filteration(movie){
        return movie.filter(this.time);
      },
      time(movie){
        return moment(movie.time_session.time).hour() > 20;
        // return moment(movie.time_session.time).isSame(this.day,'day');
      }
    }
  }
</script>
</code>```

答:
The most likely reason you're having issues is that you are passing movie.time_session.time to moment. But, movie.time_session is an array of sessions and doesn't have a time property. You probably need to compare to the time of each element of the time_session array.

Generally, the best way to display an array of filtered data in Vue is to make a computed property that filters the data and returns it.

In your case you can make a computed property filteredMovies that returns the filtered movies and use that in your template instead:

```<code>computed: {
  filteredMovies() {
    return this.movies.filter((movie) => {
      return movie.time_session.reduce((acc, session) => {
        return acc || (moment(session.time).hour() > 20);
      }, false);
    });
  }
}
</code>```

Then, in your template, reference filteredMovies like so:

```<code><li v-for="movie in filteredMovies">{{movie.movieName}}</li>
</code>```

Body:
I want to print out the movies that have time sessions that start after the hour 20 or the same day. Either way, I can't get it to work.

Component data structure:

day:"2017-06-08T18:34:27.211Z"
movies:Array[8]
0:Object
   Description:"orphan the becomes a famous magician "
   id:1
   movieName:"Harry Potter "
   time_session:Array[3]
     0:Object
       id:1
       pivot:Object
       time:"2017-06-14 00:00:00"
     1:Object
     2:Object
1:Object
2:Object
3:Object
4:Object

Template:

<template>

{{movie.movieName}}

</template>

How can I filter the movies so that the movies displayed depend on the time sessions in that same Object?

Here's what I've tried:

Body:
The most likely reason you're having issues is that you are passing movie.time_session.time to moment. But, movie.time_session is an array of sessions and doesn't have a time property. You probably need to compare to the time of each element of the time_session array.

Generally, the best way to display an array of filtered data in Vue is to make a computed property that filters the data and returns it.

In your case you can make a computed property filteredMovies that returns the filtered movies and use that in your template instead:

computed: {
  filteredMovies() {
    return this.movies.filter((movie) => {
      return movie.time_session.reduce((acc, session) => {
        return acc || (moment(session.time).hour() > 20);
      }, false);
    });
  }
}

Then, in your template, reference filteredMovies like so:

<li v-for="movie in filteredMovies">{{movie.movieName}}</li>