问:
Setting up dotenv in firebase functions
I am trying to move the tiny node-express app I made into firebase functions.

The file have dotenv variables. Earlier I thought If I just deploy and put dotenv in dependency, It will work but that didn't happen so..

So, I went to environment configuration article of firebase to understand how I can set .env

Which states to set things by doing something like this

```<code>firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
</code>```

But I have so many environment configuration and doing that some what seems to be cumbersome task.

So let's say this is environment file

```<code># App port Address
PORT = 8080

# Google Secret
GOOGLE_CALLBACK_URL =   http://localhost:8080/auth/google/callback
GOOGLE_CLIENT_ID = 4048108-bssbfjohpu69vl6jhpgs1ne0.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET = lTQHpjzY57oQpO

# Client Address
CLIENT_ADDRESS = http://localhost:3000/

# Meetup Secret
MEETUP_CALLBACK_URL = http://localhost:8080/auth/meetup/callback
MEETUP_CLIENT_ID = ef6i9f7m6k0jp33m9olgt
MEETUP_CLIENT_SECRET = sk3t5lnss2sdl1kgnt

#EventBrite Secret
EVENTBRITE_CALLBACK_URL = http://localhost:8080/auth/eventbrite/callback
EVENTBRITE_CLIENT_ID = UU2FXKGYHJRNHLN
EVENTBRITE_CLIENT_SECRET = NA55QG52FAOF6GDMLKSJBKYOPIGQU4R46HHEU4
</code>```

How Can I best set up so that when I do firebase firebase serve --only functions,hosting it doesn't throw any errors such as

OAuth2Strategy requires a clientID option

答:
UPDATED 2019-06-04

I'm very sorry. This solution is wrong.

I found the correct way.

https://stackoverflow.com/a/45064266/1872674

You should put a .runtimeconfig.json into the functions directory. Your dotenv variables move to .runtimeconfig.json with json format.

This is my solution.

```<code>const functionConfig = () => {
    if (process.env.RUN_LOCALLY) {
        const fs = require('fs');
        return JSON.parse(fs.readFileSync('.env.json'));
    } else {
      return functions.config();
    }
};
</code>```

The functionConfig() was called by your Firebase Function.

```<code>exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("someservice id is: " + functionConfig().someservice.id);
});
</code>```

.env.json is like:

```<code>{
  "someservice": {
    "key":"THE API KEY",
    "id":"THE CLIENT ID"
  }
}
</code>```

Finally, run the command with the RUN_LOCALLY variable.

```<code>RUN_LOCALLY=1 firebase serve
</code>```

When we will deploy functions,
don't forget to update the environment configuration in Firebase using the .env.json.

Title: Setting up dotenv in firebase functions

Body:
I am trying to move the tiny node-express app I made into firebase functions.

The file have dotenv variables. Earlier I thought If I just deploy and put dotenv in dependency, It will work but that didn't happen so..

So, I went to environment configuration article of firebase to understand how I can set .env

Which states to set things by doing something like this

firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"

But I have so many environment configuration and doing that some what seems to be cumbersome task.

So let's say this is environment file

# App port Address
PORT = 8080

# Google Secret
GOOGLE_CALLBACK_URL =   http://localhost:8080/auth/google/callback
GOOGLE_CLIENT_ID = 4048108-bssbfjohpu69vl6jhpgs1ne0.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET = lTQHpjzY57oQpO

# Client Address
CLIENT_ADDRESS = http://localhost:3000/

# Meetup Secret
MEETUP_CALLBACK_URL = http://localhost:8080/auth/meetup/callback
MEETUP_CLIENT_ID = ef6i9f7m6k0jp33m9olgt
MEETUP_CLIENT_SECRET = sk3t5lnss2sdl1kgnt

#EventBrite Secret
EVENTBRITE_CALLBACK_URL = http://localhost:8080/auth/eventbrite/callback
EVENTBRITE_CLIENT_ID = UU2FXKGYHJRNHLN
EVENTBRITE_CLIENT_SECRET = NA55QG52FAOF6GDMLKSJBKYOPIGQU4R46HHEU4

How Can I best set up so that when I do firebase firebase serve --only functions,hosting it doesn't throw any errors such as

OAuth2Strategy requires a clientID option

Body:
UPDATED 2019-06-04

I'm very sorry. This solution is wrong.

I found the correct way.

https://stackoverflow.com/a/45064266/1872674

You should put a .runtimeconfig.json into the functions directory. Your dotenv variables move to .runtimeconfig.json with json format.

This is my solution.

const functionConfig = () => {
    if (process.env.RUN_LOCALLY) {
        const fs = require('fs');
        return JSON.parse(fs.readFileSync('.env.json'));
    } else {
      return functions.config();
    }
};

The functionConfig() was called by your Firebase Function.

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("someservice id is: " + functionConfig().someservice.id);
});

.env.json is like:

{
  "someservice": {
    "key":"THE API KEY",
    "id":"THE CLIENT ID"
  }
}

Finally, run the command with the RUN_LOCALLY variable.

RUN_LOCALLY=1 firebase serve

When we will deploy functions,
don't forget to update the environment configuration in Firebase using the .env.json.


来源: stackexchange

问:
ContextVars across modules
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

```<code>from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)
</code>```

then I try to import number.py

```<code>(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200
</code>```

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?

答:
You are reassigning the value of number.  Directly call the variable from the module, e.g. example.number.get().

A simple application is substituting a global variable.

Given

```<code>import random
import contextvars as cv
</code>```

Code

Here we'll imitate a random walk.  Like a global variable, we are able to share state between functions:

```<code>move = cv.ContextVar("move", default="")

def go_left():
    value = move.get()
    move.set(value + "L")

def go_right():
    value = move.get()
    move.set(value + "R")

def random_walk(steps):
    directions = [go_left, go_right]
    while steps:
        random.choice(directions)()
        steps -= 1
    return move.get()
</code>```

Demo

The ContextVar acts as a global variable that is updated by random events:

```<code>random_walk(1)
# 'R'
random_walk(2)
# 'RLL'
random_walk(3)
# 'RLLLRL'
</code>```

Beyond a regular global variable, ContextVar:

permits default values

works with context managers

works with coroutines

ContentLicense: CC BY-SA 4.0

Title: ContextVars across modules

Body:
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)

then I try to import number.py

(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?

Body:
You are reassigning the value of number.  Directly call the variable from the module, e.g. example.number.get().

A simple application is substituting a global variable.

Given

import random
import contextvars as cv

Code

Here we'll imitate a random walk.  Like a global variable, we are able to share state between functions:

move = cv.ContextVar("move", default="")

def go_left():
    value = move.get()
    move.set(value + "L")

def go_right():
    value = move.get()
    move.set(value + "R")

def random_walk(steps):
    directions = [go_left, go_right]
    while steps:
        random.choice(directions)()
        steps -= 1
    return move.get()

Demo

The ContextVar acts as a global variable that is updated by random events:

random_walk(1)
# 'R'
random_walk(2)
# 'RLL'
random_walk(3)
# 'RLLLRL'

Beyond a regular global variable, ContextVar:

permits default values

works with context managers

works with coroutines


问:
Guarding resources with Singleton?
I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:

Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).

Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).

My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Is my choice of making this class a singleton class a bad decision?

答:
Singletons are considered a smell because:

They are the moral equivalent of global variables, and thus their use hides dependencies in code rather than revealing them through interfaces.

They promote tight coupling because your code depends on a specific instance of a specific type.  What if you wanted your UI to operate against a different camera manager some day?

They make unit testing difficult because they carry state with them for the entire lifetime of the program.  When state is carried across from test to test, it can make tests state-dependent, which is a very big smell.

ContentLicense: CC BY-SA 3.0

Title: Guarding resources with Singleton?


问:
Haskell with emacs org-mode: Variable not in scope
After wandering off in frustration from before, I've decided to try Haskell in Emacs org-mode again. I'm using Haskell stack-ghci (8.6.3), Emacs 26.2, org-mode 9.2.3 set up with intero. This code block

```<code>#+begin_src haskell :results raw :session *haskell*
pyth2 :: Int -> [(Int, Int, Int)]
pyth2 n =
  [ (x, y, z)
  | x <- [1 .. n]
  , y <- [x .. n]
  , z <- [y .. n]
  , x ^ 2 + y ^ 2 == z ^ 2
  ]
#+end_src
</code>```

produces this RESULTS:

```<code>*Main| *Main| *Main| *Main| *Main|
<interactive>:59:16: error: Variable not in scope: n
<interactive>:60:16: error: Variable not in scope: n
<interactive>:61:16: error: Variable not in scope: n
</code>```

However, this

```<code>#+begin_src haskell :results raw
tripleMe x = x + x + x
#+end_src
</code>```

works fine. I've added the :set +m to both ghci.conf and the individual code block to no effect. This code works fine in a separate hs file run in a separate REPL. The pyth2 code in a separate file also can be called from the org-mode started REPL and run just fine as well. Not sure how to proceed. Can include Emacs init info if necessary.

答:
This is a GHCi issue.

The same error occurs when your code is copied directly into GHCi, which also gives a parse error when it encounters the new line after the equal sign. This first error isn't showing up here because org-babel only shows the value of the last expression (in this case, the error caused by the list comprehension).

I'm not entirely familiar with how Haskell-mode sends the code to GHCi, but it looks like it involves loading in the buffer into GHCi as a file, which may be why you didn't have this problem working from the hs file.

There are a few options to fix this, none of which are completely ideal:

Move some portion of the list into the first line (e.g. the first line could be pyth2 n =  [).

Wrap the entire function definition with :{ and :}.

Write an Elisp function to modify what is being sent to GHCi and then changes it back after it is evaluated.

The first two options require you to format your code in a form that the GHCi will accept. In your example case, the first option may not be too bad, but this won't always be so trivial for all multi-line declarations (e.g. pattern-matching function declarations). The downside to the second option is that it requires adding brackets to the code that shouldn't be there in real source code.

To fix the issue of extraneous brackets being added, I've written an Elisp command (my-org-babel-execute-haskell-blocks) that places these brackets around code blocks that it finds, evaluates the region, and then deletes the brackets. Note that this function requires that blocks be separated from all other code with at least one empty line.

Calling my-org-babel-execute-haskell-blocks on your example declares the function without any errors.

EDIT: The previous function I gave failed to work on pattern matching declarations. I've rewritten the function to fix this issue as well as to be comment aware. This new function should be significantly more useful. However, it's worth noting that I didn't handle multi-line comments in a sophisticated manner, so code blocks with multi-line comments may not be wrapped properly.

```<code>(defun my-org-babel-execute-haskell-blocks ()
  "Wraps :{ and :} around all multi-line blocks and then evaluates the source block.
Multi-line blocks are those where all non-indented, non-comment lines are declarations using the same token."
  (interactive)
  (save-excursion
    ;; jump to top of source block
    (my-org-jump-to-top-of-block)
    (forward-line)
    ;; get valid blocks
    (let ((valid-block-start-ends (seq-filter #'my-haskell-block-valid-p (my-get-babel-blocks))))
      (mapcar #'my-insert-haskell-braces valid-block-start-ends)
      (org-babel-execute-src-block)
      (mapcar #'my-delete-inserted-haskell-braces (reverse valid-block-start-ends)))))

(defun my-get-blocks-until (until-string)
  (let ((block-start nil)
        (block-list nil))
    (while (not (looking-at until-string))
      (if (looking-at "[[:space:]]*\n")
          (when (not (null block-start))
            (setq block-list (cons (cons block-start (- (point) 1))
                                   block-list)
                  block-start nil))
        (when (null block-start)
          (setq block-start (point))))
      (forward-line))
    (when (not (null block-start))
      (setq block-list (cons (cons block-start (- (point) 1))
                             block-list)))))

(defun my-get-babel-blocks ()
  (my-get-blocks-until "#\\+end_src"))

(defun my-org-jump-to-top-of-block ()
  (forward-line)
  (org-previous-block 1))

(defun my-empty-line-p ()
  (beginning-of-line)
  (= (char-after) 10))

(defun my-haskell-type-declaration-line-p ()
  (beginning-of-line)
  (and (not (looking-at "--"))
       (looking-at "^.*::.*$")))

(defun my-insert-haskell-braces (block-start-end)
  (let ((block-start (car block-start-end))
        (block-end (cdr block-start-end)))
    (goto-char block-end)
    (insert "\n:}")
    (goto-char block-start)
    (insert ":{\n")))

(defun my-delete-inserted-haskell-braces (block-start-end)
  (let ((block-start (car block-start-end))
        (block-end (cdr block-start-end)))
    (goto-char block-start)
    (delete-char 3)
    (goto-char block-end)
    (delete-char 3)))

(defun my-get-first-haskell-token ()
  "Gets all consecutive non-whitespace text until first whitespace"
  (save-excursion
    (beginning-of-line)
    (let ((starting-point (point)))
      (re-search-forward ".*?[[:blank:]\n]")
      (goto-char (- (point) 1))
      (buffer-substring-no-properties starting-point (point)))))

(defun my-haskell-declaration-line-p ()
  (beginning-of-line)
  (or (looking-at "^.*=.*$")  ;; has equals sign
      (looking-at "^.*\n[[:blank:]]*|")
      (looking-at "^.*where[[:blank:]]*$")))

(defun my-haskell-block-valid-p (block-start-end)
  (let ((block-start (car block-start-end))
        (block-end (cdr block-start-end))
        (line-count 0))
        (save-excursion
          (goto-char block-start)
          (let ((token 'nil)
                (is-valid t))
            ;; eat top comments
            (while (or (looking-at "--")
                       (looking-at "{-"))
              (forward-line))
            (when (my-haskell-type-declaration-line-p)
              (progn
                (setq token (my-get-first-haskell-token)
                      line-count 1)
                (forward-line)))
            (while (<= (point) block-end)
              (let ((current-token (my-get-first-haskell-token)))
                (cond ((string= current-token "") ; line with indentation
                       (when (null token) (setq is-valid nil))
                       (setq line-count (+ 1 line-count)))
                      ((or (string= (substring current-token 0 2) "--") ;; skip comments
                           (string= (substring current-token 0 2) "{-"))
                       '())
                      ((and (my-haskell-declaration-line-p)
                            (or (null token) (string= token current-token)))
                       (setq token current-token
                             line-count (+ 1 line-count)))
                      (t (setq is-valid nil)
                         (goto-char (+ 1 block-end))))
                (forward-line)))
            (and is-valid (> line-count 1))))))
</code>```

Body:
After wandering off in frustration from before, I've decided to try Haskell in Emacs org-mode again. I'm using Haskell stack-ghci (8.6.3), Emacs 26.2, org-mode 9.2.3 set up with intero. This code block

#+begin_src haskell :results raw :session *haskell*
pyth2 :: Int -> [(Int, Int, Int)]
pyth2 n =
  [ (x, y, z)
  | x <- [1 .. n]
  , y <- [x .. n]
  , z <- [y .. n]
  , x ^ 2 + y ^ 2 == z ^ 2
  ]
#+end_src

produces this RESULTS:

*Main| *Main| *Main| *Main| *Main|
<interactive>:59:16: error: Variable not in scope: n
<interactive>:60:16: error: Variable not in scope: n
<interactive>:61:16: error: Variable not in scope: n

However, this

#+begin_src haskell :results raw
tripleMe x = x + x + x
#+end_src

works fine. I've added the :set +m to both ghci.conf and the individual code block to no effect. This code works fine in a separate hs file run in a separate REPL. The pyth2 code in a separate file also can be called from the org-mode started REPL and run just fine as well. Not sure how to proceed. Can include Emacs init info if necessary.

Body:
This is a GHCi issue.

The same error occurs when your code is copied directly into GHCi, which also gives a parse error when it encounters the new line after the equal sign. This first error isn't showing up here because org-babel only shows the value of the last expression (in this case, the error caused by the list comprehension).

I'm not entirely familiar with how Haskell-mode sends the code to GHCi, but it looks like it involves loading in the buffer into GHCi as a file, which may be why you didn't have this problem working from the hs file.

There are a few options to fix this, none of which are completely ideal:

Move some portion of the list into the first line (e.g. the first line could be pyth2 n =  [).

Wrap the entire function definition with :{ and :}.

Write an Elisp function to modify what is being sent to GHCi and then changes it back after it is evaluated.

The first two options require you to format your code in a form that the GHCi will accept. In your example case, the first option may not be too bad, but this won't always be so trivial for all multi-line declarations (e.g. pattern-matching function declarations). The downside to the second option is that it requires adding brackets to the code that shouldn't be there in real source code.

To fix the issue of extraneous brackets being added, I've written an Elisp command (my-org-babel-execute-haskell-blocks) that places these brackets around code blocks that it finds, evaluates the region, and then deletes the brackets. Note that this function requires that blocks be separated from all other code with at least one empty line.

Calling my-org-babel-execute-haskell-blocks on your example declares the function without any errors.

EDIT: The previous function I gave failed to work on pattern matching declarations. I've rewritten the function to fix this issue as well as to be comment aware. This new function should be significantly more useful. However, it's worth noting that I didn't handle multi-line comments in a sophisticated manner, so code blocks with multi-line comments may not be wrapped properly.

(defun my-org-babel-execute-haskell-blocks ()
  "Wraps :{ and :} around all multi-line blocks and then evaluates the source block.
Multi-line blocks are those where all non-indented, non-comment lines are declarations using the same token."
  (interactive)
  (save-excursion
    ;; jump to top of source block
    (my-org-jump-to-top-of-block)
    (forward-line)
    ;; get valid blocks
    (let ((valid-block-start-ends (seq-filter #'my-haskell-block-valid-p (my-get-babel-blocks))))
      (mapcar #'my-insert-haskell-braces valid-block-start-ends)
      (org-babel-execute-src-block)
      (mapcar #'my-delete-inserted-haskell-braces (reverse valid-block-start-ends)))))

(defun my-get-blocks-until (until-string)
  (let ((block-start nil)
        (block-list nil))
    (while (not (looking-at until-string))
      (if (looking-at "[[:space:]]*\n")
          (when (not (null block-start))
            (setq block-list (cons (cons block-start (- (point) 1))
                                   block-list)
                  block-start nil))
        (when (null block-start)
          (setq block-start (point))))
      (forward-line))
    (when (not (null block-start))
      (setq block-list (cons (cons block-start (- (point) 1))
                             block-list)))))

(defun my-get-babel-blocks ()
  (my-get-blocks-until "#\\+end_src"))

(defun my-org-jump-to-top-of-block ()
  (forward-line)
  (org-previous-block 1))

(defun my-empty-line-p ()
  (beginning-of-line)
  (= (char-after) 10))

(defun my-haskell-type-declaration-line-p ()
  (beginning-of-line)
  (and (not (looking-at "--"))
       (looking-at "^.*::.*$")))

(defun my-insert-haskell-braces (block-start-end)
  (let ((block-start (car block-start-end))
        (block-end (cdr block-start-end)))
    (goto-char block-end)
    (insert "\n:}")
    (goto-char block-start)
    (insert ":{\n")))

(defun my-delete-inserted-haskell-braces (block-start-end)
  (let ((block-start (car block-start-end))
        (block-end (cdr block-start-end)))
    (goto-char block-start)
    (delete-char 3)
    (goto-char block-end)
    (delete-char 3)))

(defun my-get-first-haskell-token ()
  "Gets all consecutive non-whitespace text until first whitespace"
  (save-excursion
    (beginning-of-line)
    (let ((starting-point (point)))
      (re-search-forward ".*?[[:blank:]\n]")
      (goto-char (- (point) 1))
      (buffer-substring-no-properties starting-point (point)))))

(defun my-haskell-declaration-line-p ()
  (beginning-of-line)
  (or (looking-at "^.*=.*$")  ;; has equals sign
      (looking-at "^.*\n[[:blank:]]*|")
      (looking-at "^.*where[[:blank:]]*$")))

(defun my-haskell-block-valid-p (block-start-end)
  (let ((block-start (car block-start-end))
        (block-end (cdr block-start-end))
        (line-count 0))
        (save-excursion
          (goto-char block-start)
          (let ((token 'nil)
                (is-valid t))
            ;; eat top comments
            (while (or (looking-at "--")
                       (looking-at "{-"))
              (forward-line))
            (when (my-haskell-type-declaration-line-p)
              (progn
                (setq token (my-get-first-haskell-token)
                      line-count 1)
                (forward-line)))
            (while (<= (point) block-end)
              (let ((current-token (my-get-first-haskell-token)))
                (cond ((string= current-token "") ; line with indentation
                       (when (null token) (setq is-valid nil))
                       (setq line-count (+ 1 line-count)))
                      ((or (string= (substring current-token 0 2) "--") ;; skip comments
                           (string= (substring current-token 0 2) "{-"))
                       '())
                      ((and (my-haskell-declaration-line-p)
                            (or (null token) (string= token current-token)))
                       (setq token current-token
                             line-count (+ 1 line-count)))
                      (t (setq is-valid nil)
                         (goto-char (+ 1 block-end))))
                (forward-line)))
            (and is-valid (> line-count 1))))))


问:
Click on the Checkbox inside the Label or Div
I want to create the two methods, one for clicking on the specific checkbox and second for de-selecting the same checkbox.
I was trying to using the XPath and ID but unable to do so.
Please tell me how it can be done. Here is the HTML:

```<code>IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
            js.ExecuteScript("window.scrollBy(200,document.body.scrollHeight)", "");
            var mileageTextbox = driver.FindElement(By.Id("VehicleMileageMax"));
            mileageTextbox.SendKeys("9500");
            var checkBox = driver.FindElement(By.XPath("//label[text()='financial-check-all-8']::input[@type='checkbox'"));
            Thread.Sleep(2000);
            checkBox.Click();
</code>```

Element is not visible

HTML code :

```<code><input id="financial-check-all-8" type="checkbox" selected="filter.isDisabled" ng-model="filter.isDisabled" ng-change="vm.emptyFilterValue(filter);" class="ng-pristine ng-untouched ng-valid ng-empty" aria-invalid="false" tabindex="44"> <label for="financial-check-all-8" id="enabled-8" class="form-checkbox-label"></label>
</code>```

答:
You can try with this code :

```<code>//input[starts-with(@id,'financial-check-all') and @ng-model='filter.isDisabled']
</code>```

Code :

```<code>var checkBox = driver.FindElement(By.XPath("//input[starts-with(@id,'financial-check-all') and @ng-model='filter.isDisabled']"));
checkBox.Click();
</code>```

EDIT :
As per the Shared HTML you can use this xpath:
try to wait also before clicking on it, Just try with Thread.Sleep(4000); , If that works then we can easily replace that with webdriverwait.

```<code>//label[@for='VehicleMileageMax']/../preceding-sibling::div/descendant::input
</code>```

or with this xpath :

```<code>//label[@for='VehicleMileageMax']/../preceding-sibling::div/descendant::label
</code>```

Body:
I want to create the two methods, one for clicking on the specific checkbox and second for de-selecting the same checkbox.
I was trying to using the XPath and ID but unable to do so.
Please tell me how it can be done. Here is the HTML:

IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
            js.ExecuteScript("window.scrollBy(200,document.body.scrollHeight)", "");
            var mileageTextbox = driver.FindElement(By.Id("VehicleMileageMax"));
            mileageTextbox.SendKeys("9500");
            var checkBox = driver.FindElement(By.XPath("//label[text()='financial-check-all-8']::input[@type='checkbox'"));
            Thread.Sleep(2000);
            checkBox.Click();

Element is not visible

HTML code :

<input id="financial-check-all-8" type="checkbox" selected="filter.isDisabled" ng-model="filter.isDisabled" ng-change="vm.emptyFilterValue(filter);" class="ng-pristine ng-untouched ng-valid ng-empty" aria-invalid="false" tabindex="44">

Body:
You can try with this code :

//input[starts-with(@id,'financial-check-all') and @ng-model='filter.isDisabled']

Code :

var checkBox = driver.FindElement(By.XPath("//input[starts-with(@id,'financial-check-all') and @ng-model='filter.isDisabled']"));
checkBox.Click();

EDIT :
As per the Shared HTML you can use this xpath:
try to wait also before clicking on it, Just try with Thread.Sleep(4000); , If that works then we can easily replace that with webdriverwait.

//label[@for='VehicleMileageMax']/../preceding-sibling::div/descendant::input

or with this xpath :

//label[@for='VehicleMileageMax']/../preceding-sibling::div/descendant::label


答:
Here's a solution that uses a "drill-down" and therefore rather tedious approach:

```<code>["#text", "@x", "@y"],
( .document.page[]
  | .row[]?
  | .column
  | (if type == "array" then .[] else . end)
  | .text
  | objects
  | [.["#text", "@x", "@y"]]
)
| @tsv
</code>```

This would be used in conjunction with the -r command-line option.

I've used @tsv as this produces output that resembles the given expected output.  As mentioned elsewhere on this page, there are other alternatives, e.g. using join/1.

Title: Parsing Json file with jq tool

Body:
I Have the following nested json file which I want to parse with jq tool and print in table form like I show at the end

The input.json structure is like this:

{
 "document":{
  "page":[
     {
        "@index":"0",
        "image":{
           "@data":"ABC",
           "@format":"png",
           "@height":"620.00",
           "@type":"base64encoded",
           "@width":"450.00",
           "@x":"85.00",
           "@y":"85.00"
        }
     },
     {
        "@index":"1",
        "row":[
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text1",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"71.04",
                       "@x":"121.10",
                       "@y":"83.42"
                    }
                 }
              ]
           },
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text2",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"101.07",
                       "@x":"121.10",
                       "@y":"124.82"
                    }
                 }
              ]
           }
        ]
     },
     {
        "@index":"2",
        "row":[
           {
              "column":{
                 "text":{
                    "#text":"Text3",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"363.44",
                    "@x":"85.10",
                    "@y":"69.62"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text4",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"382.36",
                    "@x":"85.10",
                    "@y":"83.42"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text5",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"435.05",
                    "@x":"85.10",
                    "@y":"97.22"
                 }
              }
           }
        ]
     },
     {
        "@index":"3"
     }
  ]
 }
}

Following the answers of the following question (Parsing nested json with jq) I've tried this code but doesn't work

$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv

The output I'm trying to get is:

#text @x     @y
Text1 121.10 83.42
Text2 121.10 124.82
Text3 65.10  69.62
Text4 85.10  83.42
Text5 85.10  97.22

How can achieve this?

Thanks

UPDATE

Thanks so much for the help. I've tried with a real file a bit longer.

I was able to adapt the first peak's solution like below:

["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
( ..
| objects
| select(has("#text","@data"))
| [.["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
)
| @tsv

and with new input I get this table:

+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| #text         | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
|               | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ä 1      |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ¢76      |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text % 5      |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 7Ç8      |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text • 2 Wñ79 |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text          |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
|   » 1 A\\\\CÓ |       |           |           |         |         |               |        |        |        |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 12       |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 82       |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 31       |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

If possible, how to add the follwing 3 columns (counter, page and row) to know the corresponding page and row for each line?

The expected output would be like this:

+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| counter | page | row | #text             | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 1     | 0    |     |                   | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 2     | 1    | 0   | Text ä 1          |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 3     | 1    | 1   | Text ¢76          |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 4     | 1    | 1   | Text % 5          |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 5     | 2    | 2   | Text 7Ç8          |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 6     | 2    | 0   | Text • 2 Wñ79     |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 7     | 2    | 1   | Text  » 1 A\\\\CÓ |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 8     | 2    | 1   | Text 12           |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 9     | 2    | 2   | Text 82           |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 10    | 2    | 2   | Text 31           |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

This is new more representative input file input2.json.

And seeing the Json structure in image below gives and idea about page number and row number present in json file and values within them.

Body:
Here's a solution that uses a "drill-down" and therefore rather tedious approach:

["#text", "@x", "@y"],
( .document.page[]
  | .row[]?
  | .column
  | (if type == "array" then .[] else . end)
  | .text
  | objects
  | [.["#text", "@x", "@y"]]
)
| @tsv

This would be used in conjunction with the -r command-line option.

I've used @tsv as this produces output that resembles the given expected output.  As mentioned elsewhere on this page, there are other alternatives, e.g. using join/1.


问:
Capturing CancelKeyPress to stop an async console app at a safe point
I'm working on a small utility console app, built in C# 7.1 (which has async Main support).

The app takes one of several input commands and then starts a long-running process which iterates through tens of thousands of items, processing each.

I want to be able to cancel this process at any time (using CTRL+C), although the program should not immediately cancel but instead should finish the current iteration, then stop.

Here's a shortened version of what I have so far.

```<code>private static bool _cancel;

private static async Task Main(string[] args)
{
    Console.CancelKeyPress += (sender, eventArgs) =>
                                      {
                                          eventArgs.Cancel = true;                                              _logger("Migration will be stopped after the current record has been completed.\n");
                                          _cancel = true;
                                      };

    while (!_cancel)
    {
        var input = Console.ReadLine();

        // handle the various input commands
    }
}
</code>```

Inside the methods which run the (optional) long-running process there is logic which checks for this global _cancel variable:

```<code>private static async Task RunPersonMigration(Order order)
{
    var nextPerson = // ...
    while (nextPerson.IsValid)
    {
        // business logic

        if (_cancel)
        {
            _logger("Person migration stopped by user.\n");
            return;
        }

        nextPerson = // ...
    }
}
</code>```

However, whenever I hit CTRL+C the Visual Studio debugger asks me to locate an assembly, and it's usually a different assembly each time. For example, I've been asked to locate waithandle.cs and thread.cs. Because I'm unable to locate such files, the running debug process abruptly stops.

I can never see which line is causing the problem, and no amount of breakpoints helps.

Basically, I'm trying to use CTRL+C to exit a long-running process without exiting the console app.

Can anyone tell me how I should correctly handle cancelling a long-running console process at a point of my choosing?

UPDATE:

If I update my CancelKeyPress delegate...

```<code>Console.CancelKeyPress += (sender, eventArgs) =>
                                  {
                                      **eventArgs.Cancel = true;**                                              _logger("Migration will be stopped after the current record has been completed.\n");
                                      _cancel = true;
                                  };
</code>```

then this stops the program from crashing to a close, but I'd still like to be able to trap CTRL+C and use it as a means of exiting the long-running process without exiting the console app itself. Is this even possible?

答:
A working example using a CancellationToken, which can be passed down to lower levels:

```<code>using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        // Cancellation Tokens - https://learn.microsoft.com/en-us/previous-versions/dd997289(v=vs.110)
        private static readonly CancellationTokenSource canToken = new CancellationTokenSource();

        static async Task Main(string[] args)
        {
            Console.WriteLine("Application has started. Ctrl-C to end");

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Cancel event triggered");
                canToken.Cancel();
                eventArgs.Cancel = true;
            };

            await Worker();

            Console.WriteLine("Now shutting down");
            await Task.Delay(1000);
        }

        async static Task Worker()
        {
            while (!canToken.IsCancellationRequested)
            {
                // do work
                Console.WriteLine("Worker is working");
                await Task.Delay(1000); // arbitrary delay
            }
        }
    }
}
</code>```

Body:
I'm working on a small utility console app, built in C# 7.1 (which has async Main support).

The app takes one of several input commands and then starts a long-running process which iterates through tens of thousands of items, processing each.

I want to be able to cancel this process at any time (using CTRL+C), although the program should not immediately cancel but instead should finish the current iteration, then stop.

Here's a shortened version of what I have so far.

private static bool _cancel;

private static async Task Main(string[] args)
{
    Console.CancelKeyPress += (sender, eventArgs) =>
                                      {
                                          eventArgs.Cancel = true;                                              _logger("Migration will be stopped after the current record has been completed.\n");
                                          _cancel = true;
                                      };

    while (!_cancel)
    {
        var input = Console.ReadLine();

        // handle the various input commands
    }
}

Inside the methods which run the (optional) long-running process there is logic which checks for this global _cancel variable:

private static async Task RunPersonMigration(Order order)
{
    var nextPerson = // ...
    while (nextPerson.IsValid)
    {
        // business logic

        if (_cancel)
        {
            _logger("Person migration stopped by user.\n");
            return;
        }

        nextPerson = // ...
    }
}

However, whenever I hit CTRL+C the Visual Studio debugger asks me to locate an assembly, and it's usually a different assembly each time. For example, I've been asked to locate waithandle.cs and thread.cs. Because I'm unable to locate such files, the running debug process abruptly stops.

I can never see which line is causing the problem, and no amount of breakpoints helps.

Basically, I'm trying to use CTRL+C to exit a long-running process without exiting the console app.

Can anyone tell me how I should correctly handle cancelling a long-running console process at a point of my choosing?

UPDATE:

If I update my CancelKeyPress delegate...

Console.CancelKeyPress += (sender, eventArgs) =>
                                  {
                                      **eventArgs.Cancel = true;**                                              _logger("Migration will be stopped after the current record has been completed.\n");
                                      _cancel = true;
                                  };

then this stops the program from crashing to a close, but I'd still like to be able to trap CTRL+C and use it as a means of exiting the long-running process without exiting the console app itself. Is this even possible?

Body:
A working example using a CancellationToken, which can be passed down to lower levels:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        // Cancellation Tokens - https://learn.microsoft.com/en-us/previous-versions/dd997289(v=vs.110)
        private static readonly CancellationTokenSource canToken = new CancellationTokenSource();

        static async Task Main(string[] args)
        {
            Console.WriteLine("Application has started. Ctrl-C to end");

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Cancel event triggered");
                canToken.Cancel();
                eventArgs.Cancel = true;
            };

            await Worker();

            Console.WriteLine("Now shutting down");
            await Task.Delay(1000);
        }

        async static Task Worker()
        {
            while (!canToken.IsCancellationRequested)
            {
                // do work
                Console.WriteLine("Worker is working");
                await Task.Delay(1000); // arbitrary delay
            }
        }
    }
}


问:
Is %$var dereferencing a Perl hash?
I'm sending a subroutine a hash, and fetching it with my($arg_ref) = @_;

But what exactly is %$arg_ref? Is %$ dereferencing the hash?

答:
Since it's somewhat clear this construct is being used to provide a hash reference as a list of named arguments to a sub it should also be noted that this

```<code>sub foo {
  my ($arg_ref) = @_;
  # do something with $arg_ref->{keys}
}
</code>```

may be overkill as opposed to just unpacking @_

```<code>sub bar {
  my ($a, $b, $c) = @_;
  return $c / ( $a * $b );
}
</code>```

Depending on how complex the argument list is.

OwnerDisplayName: Stian S

LastEditorDisplayName: brian d foy

ContentLicense: CC BY-SA 2.5

Title: Is %$var dereferencing a Perl hash?

Body:
Since it's somewhat clear this construct is being used to provide a hash reference as a list of named arguments to a sub it should also be noted that this

sub foo {
  my ($arg_ref) = @_;
  # do something with $arg_ref->{keys}
}

may be overkill as opposed to just unpacking @_

sub bar {
  my ($a, $b, $c) = @_;
  return $c / ( $a * $b );
}

Depending on how complex the argument list is.

OwnerDisplayName: mnology


问:
How to run react in different Host
```<code>    "scripts": {
        "start": "HOST=`0.0.0.0` react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },
</code>```

How to run reactjs in different host;

I am trying to run react inside docker so,
How can i run react on 0.0.0.0:8000

PLease have a look

答:
Expose 8080 port first when you run your container docker run -p 8080:8080.

Add port set in your package.json file, { start: PORT=8080 react-scripts start }

Title: How to run react in different Host

Body:
    "scripts": {
        "start": "HOST=`0.0.0.0` react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },

How to run reactjs in different host;

I am trying to run react inside docker so,
How can i run react on 0.0.0.0:8000

PLease have a look


问:
Counting words with more than x characters in a string in C# using lambda expressions
I wrote a program to count words in a sentence that have x number of matching characters. The input string is a multi line string and I need to consider only alternate lines based on given criteria. Also in those filtered lines, I need to further select alternate words and then check if those filtered words match the characters for intersection.

E.g. let's say I have a input string as below and need to find words with 2 or more vowels in them:

```<code>string myString = "1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";
</code>```

now let's say I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these
 matching words.

E.g. with criteria of selecting every 2nd line, filtered lines will be {2, 4, 6}. Similarly every 3rd word in these filtered line will be line 2: {"the", "Wars"}, for line 4: {"of", "before"} and for line 6: {"be", "after"}.

For these filtered words, matching words with 2 or more vowels will be {"before"} in line number 4 and word {"after"} in line 6. So the final output will be wordCount = 2 and since these words are from line 4 and 6 so total lineCount = 2.

I wrote the below code using nested for loops that produces the desired output.

```<code>public static void Main(string[] args)
    {
        int vowelCount = 2; // match words with 2 or more vowels
        int skipWord = 3; // Consider every 3rd word only
        int skipLine = 2; // Consider every 2nd line only
        int wordCount = 0;
        int lineCount = 0;

        string myString = @"1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";";

        List<string> myList = myString.Split(Environment.NewLine).ToList();
        List<string> lineWords = new List<string>();
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

        for (int i = skipLine; i <= myList.Count; i += skipLine)
        {
            int origWordCount = wordCount;
            lineWords = myList[i - 1].Split(' ').ToList();
            for (int j = skipWord; j <= lineWords.Count; j += skipWord)
            {
                char[] wordArr = lineWords[j-1].ToLower().ToCharArray();
                int match = vowels.Intersect(wordArr).Count();
                if (match >= vowelCount)
                    wordCount++;
            }
            if (wordCount > origWordCount)
                lineCount++;
        }

        Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);
</code>```

Above code works great but wondering if there is a way to do it without nested loops. I read about linq and lambda expressions but not sure how to use them here.

All comments are appreciated.

答:
First filter the lines using a 'predicate' in the 'where' clause like this to get every 2nd line:

```<code>List<string> lines = myString.Split(Environment.NewLine).Where((l,index) => index % 2 != 0).ToList();
</code>```

Then you can get the results as below:

```<code>foreach (var line in lines)
{
    // Get every 3rd word in the line
    var thirdWords = line.Split(' ').Where((w,index) => index % 3 == 2).ToList();

    // Get words with 2 or more vowels in it.
    // Have you tested words that have same vowel twice?
    var matchWords = thirdWords.Where(w => w.Intersect(vowels).Count() >= vowelCount).ToList();

    //if words with vowels found, update 'wordCount' and 'lineCount'
    if (matchWords.Any()) {
        wordCount = wordCount + matchWords.Count;
        lineCount++;
    }
}
Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);
</code>```

Body:
I wrote a program to count words in a sentence that have x number of matching characters. The input string is a multi line string and I need to consider only alternate lines based on given criteria. Also in those filtered lines, I need to further select alternate words and then check if those filtered words match the characters for intersection.

E.g. let's say I have a input string as below and need to find words with 2 or more vowels in them:

string myString = "1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";

now let's say I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these
 matching words.

E.g. with criteria of selecting every 2nd line, filtered lines will be {2, 4, 6}. Similarly every 3rd word in these filtered line will be line 2: {"the", "Wars"}, for line 4: {"of", "before"} and for line 6: {"be", "after"}.

For these filtered words, matching words with 2 or more vowels will be {"before"} in line number 4 and word {"after"} in line 6. So the final output will be wordCount = 2 and since these words are from line 4 and 6 so total lineCount = 2.

I wrote the below code using nested for loops that produces the desired output.

public static void Main(string[] args)
    {
        int vowelCount = 2; // match words with 2 or more vowels
        int skipWord = 3; // Consider every 3rd word only
        int skipLine = 2; // Consider every 2nd line only
        int wordCount = 0;
        int lineCount = 0;

        string myString = @"1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";";

        List<string> myList = myString.Split(Environment.NewLine).ToList();
        List<string> lineWords = new List<string>();
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

        for (int i = skipLine; i <= myList.Count; i += skipLine)
        {
            int origWordCount = wordCount;
            lineWords = myList[i - 1].Split(' ').ToList();
            for (int j = skipWord; j <= lineWords.Count; j += skipWord)
            {
                char[] wordArr = lineWords[j-1].ToLower().ToCharArray();
                int match = vowels.Intersect(wordArr).Count();
                if (match >= vowelCount)
                    wordCount++;
            }
            if (wordCount > origWordCount)
                lineCount++;
        }

        Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);

Above code works great but wondering if there is a way to do it without nested loops. I read about linq and lambda expressions but not sure how to use them here.

All comments are appreciated.

Body:
First filter the lines using a 'predicate' in the 'where' clause like this to get every 2nd line:

List<string> lines = myString.Split(Environment.NewLine).Where((l,index) => index % 2 != 0).ToList();

Then you can get the results as below:

foreach (var line in lines)
{
    // Get every 3rd word in the line
    var thirdWords = line.Split(' ').Where((w,index) => index % 3 == 2).ToList();

    // Get words with 2 or more vowels in it.
    // Have you tested words that have same vowel twice?
    var matchWords = thirdWords.Where(w => w.Intersect(vowels).Count() >= vowelCount).ToList();

    //if words with vowels found, update 'wordCount' and 'lineCount'
    if (matchWords.Any()) {
        wordCount = wordCount + matchWords.Count;
        lineCount++;
    }
}
Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);


问:
VS 2017 Metadata file '.dll could not be found
I know there is another question with exact the same problem, but I went trough all those answers, and none helped me. :( (This was the question.)

I just created a new ASP.NET MVC project and joined a few '.dll's in the solution. Now when I try to build the project I get the error message shown below on 3 of the 5 libraries.

```<code>Error   CS0006  Metadata file 'C:\Users\...\source\Database\bin\Debug\DataAccessLayer.dll' could not be found   Logic   C:\Users\...\source\Logic\CSC   1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\Logic\bin\Debug\Logic.dll' could not be found    PTS2-MVC    C:\Users\...\source\PTS2-MVC\CSC    1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\PTS2-MVC\bin\PTS2-MVC.dll' could not be found    PTS2-MVC.Tests  C:\Users\...\source\PTS2-MVC.Tests\CSC  1   Active
</code>```

When I go to the bin\debug folder of that .dll, I see that it is empty, and the other .dll where I do not get an error message, is not empty. But I am clueless how to fix this or what I did to make this happen.

The most common answer is to go to the properties of the solution and go to configuration and uncheck -> apply -> check and apply again, but that didn't work

答:
I had the same problem and i tried solutions from
Metadata file '.dll' could not be found

but none of these worked.

So after trial and error i fixed it by unloading and reloading the project doing this reset the configuration file and fixed the issue.

Body:
I know there is another question with exact the same problem, but I went trough all those answers, and none helped me. :( (This was the question.)

I just created a new ASP.NET MVC project and joined a few '.dll's in the solution. Now when I try to build the project I get the error message shown below on 3 of the 5 libraries.

Error   CS0006  Metadata file 'C:\Users\...\source\Database\bin\Debug\DataAccessLayer.dll' could not be found   Logic   C:\Users\...\source\Logic\CSC   1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\Logic\bin\Debug\Logic.dll' could not be found    PTS2-MVC    C:\Users\...\source\PTS2-MVC\CSC    1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\PTS2-MVC\bin\PTS2-MVC.dll' could not be found    PTS2-MVC.Tests  C:\Users\...\source\PTS2-MVC.Tests\CSC  1   Active

When I go to the bin\debug folder of that .dll, I see that it is empty, and the other .dll where I do not get an error message, is not empty. But I am clueless how to fix this or what I did to make this happen.

The most common answer is to go to the properties of the solution and go to configuration and uncheck -> apply -> check and apply again, but that didn't work


问:
I need to analyse many audio WAV files for characteristic noise, ideas?
I need to be able to analyze (search thru) hundreds of WAV files and detect but not remove static noise. As done currently now, I must listen to each conversation and find the characteristic noise/static manually, which takes too much time. Ideally, I would need a program that can read each new WAV file and be able to detect characteristic signatures of the static noise such as periods of bursts of white noise or full audio band, high amplitude noise (like AM radio noise over phone conversation such as a wall of white noise) or bursts of peek high frequency high amplitude (as in crackling on the phone line) in a background of normal voice. I do not need to remove the noise but simply detect it and flag the recording for further troubleshooting. Ideas?

I can listen to the recordings and find the static or crackling but this takes time. I need an automated or batch process that can run on its own and flag the troubled call recordings (WAV files for a phone PBX). These are SIP and analog conversations depending on the leg of the conversation so RTSP/SIP packet analysis might be an option, but the raw WAV file is the simplest. I can use Audacity, but this still requires opening each file and looking at the visual representation of the audio spectrometry and is only a little faster than listening to each call but still cumbersome.

I currently have no code or methods for this task. I simply listen to each call wav file to find the noise.

I need a batch Wav file search that can render wav file recordings that contain the characteristic noise or static or crackling over the recording phone conversation.

答:
Unless you can tell the program how the noise looks like, it's going to be challenging to run any sort of batch processing. I was facing a similar challenge and that prompted me to develop (free and open source) software to help user in audio exploration, analysis and signal separation:

App: https://audioexplorer.online/

Docs: https://tracek.github.io/audio-explorer/

Source code: https://github.com/tracek/audio-explorer

Essentially, it visualises audio as a 2d scatter plot rather than only "linear", as in waveform or spectrogram. When you upload audio the following happens:

Onsets are detected (based on high-frequency content algorithm from aubio) according to the threshold you set. Set it to None if you want all.

Per each audio fragment, calculate audio features based on your selection. There's no universal best set of features, all depends on the application. You might try for starter with e.g. Pitch statistics. Consider setting proper values for bandpass filter and sample length (that's the length of audio fragment we're going to use). Sample length could be in future established dynamically. Check docs for more info.

The result is that for each fragment you have many features, e.g. 6 or 60. That means we have then k-dimensional (where k is number of features) structure, which we then project to 2d space with dimensionality reduction algorithm of your selection. Uniform Manifold Approximation and Projection is a sound choice.

In theory, the resulting embedding should be such that similar sounds (according to features we have selected) are closely together, while different further apart. Your noise should be now separated from your "not noise" and form cluster.

When you hover over the graph, in right-upper corner a set of icons appears. One is lasso selection. Use it to mark points, inspect spectrogram and e.g. download table with features that describe that signal. At that moment you can also reduce the noise (extra button appears) in a similar way to Audacity - it analyses the spectrum and reduces these frequencies with some smoothing.

It does not completely solve your problem right now, but could severely cut the effort. Going through hundreds of wavs could take better part of the day, but you will be done. Want it automated? There's CLI (command-line interface) that I am developing at the same time. In not-too-distant future it should take what you have labelled as noise and signal and then use supervised machine learning to go through everything in batch mode.

Suggestions / feedback? Drop an issue on GitHub.


问:
How to return total number of records with TOP * select
I have over 300 000 rows, I would like to return total number of the records even if I pick only 20/50/100 records using TOP * statement.

Is it possible to filter select like

select top 50 * from table where rule1=rule1 and rule=rule2

Let's say that total number of records if database is 300 000 and select above would return 4 000 records. But physically it will return only 50 records, I need to know how manu is there in database using this where statement (it would return 4000).

Thanks

答:
You could do:

```<code>select top 50 *, (select count(*) from table)
from table
where rule1=rule1 and rule=rule2
</code>```

This will give you the total number of rows as an extra column against each row returned by the main query. Not sure of the performance implications on this though...

Wasn't clear from your question if you need the count to be based on the filtered number of rows or not, but if so:

```<code>select top 50 *, (select count(*) from table where rule1=rule1 and rule=rule2)
from table
where rule1=rule1 and rule=rule2
</code>```

Body:
You could do:

select top 50 *, (select count(*) from table)
from table
where rule1=rule1 and rule=rule2

This will give you the total number of rows as an extra column against each row returned by the main query. Not sure of the performance implications on this though...

Wasn't clear from your question if you need the count to be based on the filtered number of rows or not, but if so:

select top 50 *, (select count(*) from table where rule1=rule1 and rule=rule2)
from table
where rule1=rule1 and rule=rule2


问:
"How to convert String Builder to Array ?"
What kind of mistake did I make in my code?

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_activity);

etEname = findViewById(R.id.etEname);
etSalary = findViewById(R.id.etSalary);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);
cbWork = findViewById(R.id.cbWork);
spEno = findViewById(R.id.spEno);
//creation
helper = new DBHelper(this);
Cursor cursor = helper.readAll();
String arr [] = new String[0];

StringBuilder builder=new StringBuilder();

    while(cursor.moveToNext()){
        builder.append(cursor.getString(0)+"   "+cursor.getString(1));
    }
    try {
    for (int i = 0 ; i < cursor.getCount(); i++)
        arr[i] = builder.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this, R.layout.custom, R.id.textView2,arr );
// Add adapter to spinner
spEno.setAdapter(adapter);
}
</code>```

Simply put, I want to add specific data from the database name and id to spinner, what way?

答:
Change this Line :

```<code>String arr [] = new String[cursor.getCount()];
builder.append(cursor.getString(0)+"   "+cursor.getString(1));
</code>```

to

```<code>int i =0;
arr[i] = cursor.getString(0)+"   "+cursor.getString(1);
i++;
</code>```

And Remove this things :

```<code>try {
for (int i = 0 ; i < cursor.getCount(); i++)
    arr[i] = builder.toString();
</code>```

Body:
What kind of mistake did I make in my code?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_activity);

etEname = findViewById(R.id.etEname);
etSalary = findViewById(R.id.etSalary);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);
cbWork = findViewById(R.id.cbWork);
spEno = findViewById(R.id.spEno);
//creation
helper = new DBHelper(this);
Cursor cursor = helper.readAll();
String arr [] = new String[0];

StringBuilder builder=new StringBuilder();

    while(cursor.moveToNext()){
        builder.append(cursor.getString(0)+"   "+cursor.getString(1));
    }
    try {
    for (int i = 0 ; i < cursor.getCount(); i++)
        arr[i] = builder.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this, R.layout.custom, R.id.textView2,arr );
// Add adapter to spinner
spEno.setAdapter(adapter);
}

Simply put, I want to add specific data from the database name and id to spinner, what way?

Body:
Change this Line :

String arr [] = new String[cursor.getCount()];
builder.append(cursor.getString(0)+"   "+cursor.getString(1));

to

int i =0;
arr[i] = cursor.getString(0)+"   "+cursor.getString(1);
i++;

And Remove this things :

try {
for (int i = 0 ; i < cursor.getCount(); i++)
    arr[i] = builder.toString();


问:
Angular2 angular-datatables is not working

ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };
    this.allservice.getUrl(this.listUserUrl)
    .subscribe(data=>{
      this.listUser=data.responseContents

    });
  }

  ## angular.json:
    "styles": [
              "src/styles.css",
              "node_modules/datatables.net-dt/css/jquery.dataTables.css"

            ],
            "scripts": [

 "node_modules/jquery/dist/jquery.js",
              "node_modules/datatables.net/js/jquery.dataTables.js"

            ]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table datatable  [dtOptions]="dtOptions" class="row-border hover">
  <thead>
    <tr>
        <th class="text-center width-10"> Name
       </th>
      <th class="text-center"> User Name

      </th>

    </tr>
  </thead>
  <tbody>
    <tr  *ngFor = "let i = index ; let x of listUser ">
          <td class="text-center">{{x.name}}</td>
      <td>{{x.username}}</td>

    </tr>
  </tbody>
</table></code>```

In this Iam trying to use datatable on first loading Im getting the data in table but If I do any sort r filter,pagenation it showing No data Found.I dont no where Im making mistake can any one help to solve this problem.

答:
I was getting no data found even if rows were loaded above that message. I got it solved using dtTrigger as explained below.

Make sure you are putting [dtTrigger]="dtTrigger" inside table tag in template. dtTrigger: Subject<any> = new Subject(); as component property. And after calling service put this.dtTrigger.next(); to tigger datatable rendering.

Body:
ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };
    this.allservice.getUrl(this.listUserUrl)
    .subscribe(data=>{
      this.listUser=data.responseContents

    });
  }

  ## angular.json:
    "styles": [
              "src/styles.css",
              "node_modules/datatables.net-dt/css/jquery.dataTables.css"

            ],
            "scripts": [

 "node_modules/jquery/dist/jquery.js",
              "node_modules/datatables.net/js/jquery.dataTables.js"

            ]

         Name

       User Name

          {{x.name}}
      {{x.username}}

In this Iam trying to use datatable on first loading Im getting the data in table but If I do any sort r filter,pagenation it showing No data Found.I dont no where Im making mistake can any one help to solve this problem.


问:
flash effect with jquery
I want fadeIn and fadeout backgroud-color using jQuery, I tried below code, It's affect the full div content , I need to add flash effect only for backgroud-color.

```<code>   $('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800)
    .fadeout("fast");
<div class="countbox">checkout</div>
</code>```

I tried this on also but it's not working!

```<code>$('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800).css("background-color","#FFFFFF");
</code>```

What's the problem anyone can help me !

Edit

oops!
my answer not applying to all window. Which one only giving flash effect for current window but I need to get the flash effect for all window.
for example :-
When I click on button, it should give me flash effect for div  for all windows, exactly like in this website.

答:
to do this in separate windows as you're mentioning in your comments, you will need to have some sort of postback to a server to signal when this will happen.

extending omerkirk's answer (which is the correct way to do this IMO).

do an setInterval(function(){.get();}); that periodicially gets information from some background server that stores the current state (per user probably...). When the current state changes, you do the .animate(); on the current window's background to match that of the background server...

This can get very tricky and problematic if you have multiple 'driving' windows instead of just one master window and x client ones...

Really this is a bad idea IMO...

Title: flash effect with jquery

Body:
I want fadeIn and fadeout backgroud-color using jQuery, I tried below code, It's affect the full div content , I need to add flash effect only for backgroud-color.

   $('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800)
    .fadeout("fast");

checkout

I tried this on also but it's not working!

$('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800).css("background-color","#FFFFFF");

What's the problem anyone can help me !

Edit

oops!
my answer not applying to all window. Which one only giving flash effect for current window but I need to get the flash effect for all window.
for example :-
When I click on button, it should give me flash effect for div  for all windows, exactly like in this website.


问:
Is it possible to have Netbeans format keep the @FXML annotation inline with fields?
I want to have my @FXML annotations inline with my field declarations, and still be able to use the Netbeans format option (shift + ^ + F).  However, it always reformats them to be on the line above my declaration wasting space as depicted in before and after examples below.  Does anyone know how to do this in Netbeans?

This is the code in the format that I like and want to keep.

```<code>public class LoginController implements Initializable {

    @FXML private TextField usernameTextField;
    @FXML private TextField visiblePasswordTextField;
    @FXML private PasswordField passwordField;
    @FXML private CheckBox showPasswordCheckBox;
    @FXML private Button login;
</code>```

This is the code after running format option in Netbeans.

```<code>public class LoginController implements Initializable {

    @FXML
    private TextField usernameTextField;
    @FXML
    private TextField visiblePasswordTextField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private CheckBox showPasswordCheckBox;
    @FXML
    private Button login;
</code>```

答:
There is a configuration setting in NetBeans which does exactly what you want:

Select Tools > Options > Editor, then click the Formatting tab.

Select Java from the Language drop list, then Wrapping from the Category drop list.

Locate the Annotations option in the left column, then change its default setting of Always to Never:

Click the Apply button and then close the Options window.

Once that is done you can place annotations on the same line as code and reformatting will not force them onto a separate line.

I didn't specifically test @FXML, but I verified this with some trivial code which has a couple of method annotations:

```<code>package javaapplication10;

public class JavaApplication10 {

    public static void main(String[] args) {

        Foo foo = new Foo();
        System.out.println("Foo.dummy() = " + foo.dummy());

    }

    @Deprecated public int dummy() {
        return 42;
    }

}

class Foo extends JavaApplication10 {

    @Override public int dummy() {
        return 41;
    }

}
</code>```

There is also an Annotation Arguments option (shown in the screen shot above), though since it has a default setting of Never you would probably never want to change it.

Body:
I want to have my @FXML annotations inline with my field declarations, and still be able to use the Netbeans format option (shift + ^ + F).  However, it always reformats them to be on the line above my declaration wasting space as depicted in before and after examples below.  Does anyone know how to do this in Netbeans?

This is the code in the format that I like and want to keep.

public class LoginController implements Initializable {

    @FXML private TextField usernameTextField;
    @FXML private TextField visiblePasswordTextField;
    @FXML private PasswordField passwordField;
    @FXML private CheckBox showPasswordCheckBox;
    @FXML private Button login;

This is the code after running format option in Netbeans.

public class LoginController implements Initializable {

    @FXML
    private TextField usernameTextField;
    @FXML
    private TextField visiblePasswordTextField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private CheckBox showPasswordCheckBox;
    @FXML
    private Button login;

Body:
There is a configuration setting in NetBeans which does exactly what you want:

Select Tools > Options > Editor, then click the Formatting tab.

Select Java from the Language drop list, then Wrapping from the Category drop list.

Locate the Annotations option in the left column, then change its default setting of Always to Never:

Click the Apply button and then close the Options window.

Once that is done you can place annotations on the same line as code and reformatting will not force them onto a separate line.

I didn't specifically test @FXML, but I verified this with some trivial code which has a couple of method annotations:

package javaapplication10;

public class JavaApplication10 {

    public static void main(String[] args) {

        Foo foo = new Foo();
        System.out.println("Foo.dummy() = " + foo.dummy());

    }

    @Deprecated public int dummy() {
        return 42;
    }

}

class Foo extends JavaApplication10 {

    @Override public int dummy() {
        return 41;
    }

}

There is also an Annotation Arguments option (shown in the screen shot above), though since it has a default setting of Never you would probably never want to change it.


问:
Javascript variables not passing in php header script
I think i'm close but, adding the javascript variables to my PHP header script causes the page to halt.  I only have warnings in my php error log.  Thanks for any help.</p>

```<code><script>   /*-GET DATE SCRIPT START */
var currentdate = new Date();
var local_year = "" + currentdate.getFullYear();
var local_month = "" + ('0' + (currentdate.getMonth()+1)).slice(-2);
var local_day = "" + ('0' + (currentdate.getDate())).slice(-2);
var local_hours = "" + ('0' + (currentdate.getHours())).slice(-2);
var local_min = "" + ('0' + (currentdate.getMinutes())).slice(-2);
var local_sec = "" + ('0' + (currentdate.getSeconds())).slice(-2);

var local_year_var = document.getElementById("local_year").value;
var local_month_var = document.getElementById("local_month").value;
var local_day_var = document.getElementById("local_day").value;
var local_hours_var = document.getElementById("local_hours").value;
var local_min_var = document.getElementById("local_min").value;
var local_sec_var = document.getElementById("local_sec").value;

</script>

<?php

header("Location: https://my_php_page.php?p_shop_name=RCT+Estate+Sales
&cart_owner=" . $cart_owner . "&local_year="+local_year_var+"&local_month="+local_month_var+"&local_day="+local_day_var+"&local_hours="+local_hours_var+"&local_min="+local_min_var+"&local_sec="+local_sec_var+"&code_word=" . $code_word);

?>
</code>```

答:
Try This --

like this

```<code><script>   /*-GET DATE SCRIPT START */
var cart_owner = <?php echo $cart_owner; ?>;
var code_word = <?php echo $code_word; ?>;
var currentdate = new Date();
var local_year = "" + currentdate.getFullYear();
var local_month = "" + ('0' + (currentdate.getMonth()+1)).slice(-2);
var local_day = "" + ('0' + (currentdate.getDate())).slice(-2);
var local_hours = "" + ('0' + (currentdate.getHours())).slice(-2);
var local_min = "" + ('0' + (currentdate.getMinutes())).slice(-2);
var local_sec = "" + ('0' + (currentdate.getSeconds())).slice(-2);

var local_year_var = document.getElementById("local_year").value;
var local_month_var = document.getElementById("local_month").value;
var local_day_var = document.getElementById("local_day").value;
var local_hours_var = document.getElementById("local_hours").value;
var local_min_var = document.getElementById("local_min").value;
var local_sec_var = document.getElementById("local_sec").value;

    window.location.href = 'https://my_php_page.php?p_shop_name=RCT+Estate+Sales
&cart_owner='+cart_owner+'
&local_year='+local_year_var+'
&local_month='+local_month_var+'
&local_day='+local_day_var+'
&local_hours='+local_hours_var+'
&local_min='+local_min_var+'
&local_sec='+local_sec_var+'
&code_word='+code_word+';
</script>
</code>```

Body:
I think i'm close but, adding the javascript variables to my PHP header script causes the page to halt.  I only have warnings in my php error log.  Thanks for any help.

<?php

header("Location: https://my_php_page.php?p_shop_name=RCT+Estate+Sales
&cart_owner=" . $cart_owner . "&local_year="+local_year_var+"&local_month="+local_month_var+"&local_day="+local_day_var+"&local_hours="+local_hours_var+"&local_min="+local_min_var+"&local_sec="+local_sec_var+"&code_word=" . $code_word);

?>

Body:
Try This --

like this

<script>   /*-GET DATE SCRIPT START */
var cart_owner = <?php echo $cart_owner; ?>;
var code_word = <?php echo $code_word; ?>;
var currentdate = new Date();
var local_year = "" + currentdate.getFullYear();
var local_month = "" + ('0' + (currentdate.getMonth()+1)).slice(-2);
var local_day = "" + ('0' + (currentdate.getDate())).slice(-2);
var local_hours = "" + ('0' + (currentdate.getHours())).slice(-2);
var local_min = "" + ('0' + (currentdate.getMinutes())).slice(-2);
var local_sec = "" + ('0' + (currentdate.getSeconds())).slice(-2);

var local_year_var = document.getElementById("local_year").value;
var local_month_var = document.getElementById("local_month").value;
var local_day_var = document.getElementById("local_day").value;
var local_hours_var = document.getElementById("local_hours").value;
var local_min_var = document.getElementById("local_min").value;
var local_sec_var = document.getElementById("local_sec").value;

    window.location.href = 'https://my_php_page.php?p_shop_name=RCT+Estate+Sales
&cart_owner='+cart_owner+'
&local_year='+local_year_var+'
&local_month='+local_month_var+'
&local_day='+local_day_var+'
&local_hours='+local_hours_var+'
&local_min='+local_min_var+'
&local_sec='+local_sec_var+'
&code_word='+code_word+';
</script>


问:
Trying to setup a personal ANS server. Not able to bind domain name
Goal:

My goal is to setup a web server and an ANS server for my website at home where it is publicly available. I can access the webpage through my public IP address outside of my network, but can't figure out how to bind that address with the domain name I purchased on namecheap.com.

What I'm Running:

I'm using
VirtualBox 6.0.4
; 3 guest machines that are running Ubuntu 18.10 (for a primary and secondary dns server and a web server)
; my host machine is running Windows 10
; bind9 for ANS (DNS) and apache2 as a web server
; and my domain name was purchased at namecheap.com

What I've Done:

I've followed the instructions on this page to setup the DNS servers : https://www.digitalocean.com/community/tutorials/how-to-configure-bind-as-an-authoritative-only-dns-server-on-ubuntu-14-04

The network setting on VirtualBox(VB) is set to "bridged adapter."

On my router, I've opened (http) port 80 for the IP address of my apache web server and (tcp/udp) port 53 for the IP address of my primary DNS server.

My questions:

I'm unclear as to which IP addresses to put in at namecheap.com under "custom DNS"?? The IP addresses of my DNS servers in VB or the IP address of the DNS servers that is provided by my router? If it's the latter, then how do I add them to the named.conf files?

答: Considering that the public IP address of your router does not change, you should do port forwarding in the router for your VB to be accessed from the internet, then use your router's public IP to configure in namecheap.</p>


问:
I want to create image by passing list of tuple in python
```<code>import numpy as np

from PIL  import Image

img=Image.open("Car.jpg")

array= np.array(img)

a = array

rgb=250,0,0

for  i  in  range(768):
      for  j  in  range(500):
             a[ i ] [ j ]=rgb

new_image=Image.fromarray(array)

new_image.save( "new.jpg" )

new_image.show()
</code>```

I want to pass rgb values like list of tuple :

```<code>rgb = [(255,0,0),
(198, 252, 247), (255, 255, 250) ,(254, 253, 248) ,(251, 252, 246), (247, 248, 240) ...
(100, 144, 247), (255, 200, 250), (254, 253,0)]
</code>```

and rgb value change with i  and  j

```<code>a [ i ] [ j ] = rgb
</code>```

答:
You can get RGB by using getdata(). Then you can manipulate each pixel freely. For example, you want to flip an image.

```<code>from PIL import Image

# Resize for minimising pixels
width, height = 300, 200
src_image = ImageCall('cat.jpg').get_img()
src_image = src_image.resize((width, height), Image.ANTIALIAS)

# Get pixels in a list
pixels = list(src_image.getdata())
pixels = list(map(lambda i: i[::-1], pixels[:])) # Flipping
# pixels = [(r,g,b), (r,g,b), (r,g,b), (r,g,b), ..... n]

# Add new pixels to construct a new image
dst_image = Image.new('RGB', (width, height))
dst_image.putdata(pixels)  # Place pixels in the new image.
dst_image.save('result.png')  # Save the new image.
</code>```

Result:

Body:
import numpy as np

from PIL  import Image

img=Image.open("Car.jpg")

array= np.array(img)

a = array

rgb=250,0,0

for  i  in  range(768):
      for  j  in  range(500):
             a[ i ] [ j ]=rgb

new_image=Image.fromarray(array)

new_image.save( "new.jpg" )

new_image.show()

I want to pass rgb values like list of tuple :

rgb = [(255,0,0),
(198, 252, 247), (255, 255, 250) ,(254, 253, 248) ,(251, 252, 246), (247, 248, 240) ...
(100, 144, 247), (255, 200, 250), (254, 253,0)]

and rgb value change with i  and  j

a [ i ] [ j ] = rgb

Body:
You can get RGB by using getdata(). Then you can manipulate each pixel freely. For example, you want to flip an image.

from PIL import Image

# Resize for minimising pixels
width, height = 300, 200
src_image = ImageCall('cat.jpg').get_img()
src_image = src_image.resize((width, height), Image.ANTIALIAS)

# Get pixels in a list
pixels = list(src_image.getdata())
pixels = list(map(lambda i: i[::-1], pixels[:])) # Flipping
# pixels = [(r,g,b), (r,g,b), (r,g,b), (r,g,b), ..... n]

# Add new pixels to construct a new image
dst_image = Image.new('RGB', (width, height))
dst_image.putdata(pixels)  # Place pixels in the new image.
dst_image.save('result.png')  # Save the new image.

Result:


问:
Using numpy from the host OS for a spark container
I want to use the Docker image with Apache Spark on Ubuntu 18.04.

The more popular image from the hub has Spark 1.6.
The second image has a more recent version Spark 2.2

No image has numpy installed. The basic examples for Spark MLlib main guide require it.

I've tried running Dockerfile for installing numpy unsuccessfully, adding this to the original Dockerfile for Spark 2.2 image:

```<code>RUN apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose
</code>```

How do you set the container to use the OS's numpy installation? What is the procedure? Is this the correct direction at all?

Edit: OS is Ubuntu 18.04

答:
Dockerfile:

```<code>FROM p7hb/docker-spark

RUN apt-get update && apt install -y python-numpy
</code>```

Build command:

```<code>docker build -t my_image .
</code>```

Run container:

```<code>docker run -it --rm my_image /bin/bash
</code>```

Check numpy:

```<code>root@55ce4c59122c:~# python
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> print(numpy.__version__)
1.12.1
</code>```

Body:
I want to use the Docker image with Apache Spark on Ubuntu 18.04.

The more popular image from the hub has Spark 1.6.
The second image has a more recent version Spark 2.2

No image has numpy installed. The basic examples for Spark MLlib main guide require it.

I've tried running Dockerfile for installing numpy unsuccessfully, adding this to the original Dockerfile for Spark 2.2 image:

RUN apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose

How do you set the container to use the OS's numpy installation? What is the procedure? Is this the correct direction at all?

Edit: OS is Ubuntu 18.04

Body:
Dockerfile:

FROM p7hb/docker-spark

RUN apt-get update && apt install -y python-numpy

Build command:

docker build -t my_image .

Run container:

docker run -it --rm my_image /bin/bash

Check numpy:

root@55ce4c59122c:~# python
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> print(numpy.__version__)
1.12.1