问:
Creating my own filter function in python
I need to create my own filter function in python, i.e., it should return the value from an iterable only if running any given function on it returns True or, if the function is None, if the iterable itself returns True. My problem is that I cannot get to work with a function that returns only even numbers.

This is my code:

```<code>def my_own_filter(func, *iterable):
    l = []
    if func is None:
        for i in iterable:
            if i:
                l.append(i)
    else:
        for i in iterable:
            if func(i):
                l.append(i)
    return(l)

print(my_own_filter(None, 1, 0, -1, (), "hello", 1, 2, 3, 4))
print(my_own_filter(sum, (1, 2, 3), [], [3, 4, 5]))
</code>```

Any help will be highly appreciated!

答:
If I am understanding this correctly, you are trying to pass a function that will return all the arguments that were even?

If that is the case, you can easily do this if you only pass int arguments, not lists, tuples, or strings.

```<code>def isEven(x):
    if x % 2 == 0:
        return True
    else:
        return False
print(my_own_filter(isEven, 1, 0, -1, 1, 2, 3, 4))
</code>```

In order to make this work with all types, you will have to add some additional if statements to the my_own_filter function. Using the isinstance function, you can determine if you need to use a for loop to cycle through all the objects inside the list or tuple.

Here is what I came up with to make this work with lists and tuples:

```<code>def my_own_filter(func, *iterable):
    l = []
    if func is None:
        for i in iterable:
            if i:
                l.append(i)
    else:
        for i in iterable:
            if isinstance(i, int) and isEven(i):
                l.append(i)
            elif isinstance(i, list) or isinstance(i, tuple):
                for x in i:
                    if isEven(x):
                        l.append(x)
    return(l)

def isEven(x):
    if x % 2 == 0:
        return True
    else:
        return False
</code>```

Body:
I need to create my own filter function in python, i.e., it should return the value from an iterable only if running any given function on it returns True or, if the function is None, if the iterable itself returns True. My problem is that I cannot get to work with a function that returns only even numbers.

This is my code:

def my_own_filter(func, *iterable):
    l = []
    if func is None:
        for i in iterable:
            if i:
                l.append(i)
    else:
        for i in iterable:
            if func(i):
                l.append(i)
    return(l)

print(my_own_filter(None, 1, 0, -1, (), "hello", 1, 2, 3, 4))
print(my_own_filter(sum, (1, 2, 3), [], [3, 4, 5]))

Any help will be highly appreciated!

Body:
If I am understanding this correctly, you are trying to pass a function that will return all the arguments that were even?

If that is the case, you can easily do this if you only pass int arguments, not lists, tuples, or strings.

def isEven(x):
    if x % 2 == 0:
        return True
    else:
        return False
print(my_own_filter(isEven, 1, 0, -1, 1, 2, 3, 4))

In order to make this work with all types, you will have to add some additional if statements to the my_own_filter function. Using the isinstance function, you can determine if you need to use a for loop to cycle through all the objects inside the list or tuple.

Here is what I came up with to make this work with lists and tuples:

def my_own_filter(func, *iterable):
    l = []
    if func is None:
        for i in iterable:
            if i:
                l.append(i)
    else:
        for i in iterable:
            if isinstance(i, int) and isEven(i):
                l.append(i)
            elif isinstance(i, list) or isinstance(i, tuple):
                for x in i:
                    if isEven(x):
                        l.append(x)
    return(l)

def isEven(x):
    if x % 2 == 0:
        return True
    else:
        return False


来源: stackexchange

问:
iPhone Development: VNC Server Framework to mirror iPhone screen to Mac (Keynote)?
I developed an iPhone app which I now have to present an audience. For that purpose, I'm creating a presentation with Apple Keynote to show some facts — and after that, I also would like to hold a "live presentation" of the developed iPhone app.

To do that, I need to mirror the iPhone screen (that is, the iPhone running my app) up to my Mac. Best would be, if I could show this "live mirror view" right in Keynote — just as Apple does it in their keynotes.

My idea is to implement a VNC server into my app which mirrors the app to my MacBook which than acts like a VNC client. And at best I would need to show the VNC client's stream in Keynote.

iPhone as VNC Server --> MacBook as VNC Client --> Keynote showing VNC Client's "image stream"

Does anybody knows a good VNC Server framework, which I could implement into my app?

(And if someone has an idea related to the Keynote thing, I would love to hear about that, too.)

答:
If you're open to jailbreaking you could install Veency which is a VNC server for iOS. Or you could use ScreenSplitr and iDemo which is for jailbroken devices too.

But note, VNC (and possibly ScreenSplitr too) will be laggy. It won't be as smooth as when Apple does it at their keynotes.

ContentLicense: CC BY-SA 3.0


问:
How does one core get work in a multi-core system?
Is it the Operating System who delegates any job to core?

What is that specific algorithm or a way, on which it is decided that the next task will be assigned to which cpu core?

答:
Correct, it is the operating system's responsibility to designate tasks for the CPU to complete, regardless of how many cores it has. It does this via a scheduling algorithm, which decides in what order tasks/processes should be executed. In a symmetric multiprocessing environment, the OS views each core as an independent, identical CPU and therefore schedules them individually. When several cores are available, there are a couple important things to keep in mind:

1. Load balancing- For maximum performance, each core should be performing roughly the same amount of work.

2. Affinity- Because of caching, it is best (in terms of performance) for processes to complete the entirety of their execution on just one processor.

These things need to be kept in mind along with the traditional scheduling considerations of priority, fairness etc. Obviously, this topic is far too large for just one post to handle, so here are some resources that go in to further detail:

https://www.tutorialspoint.com/operating_system/os_process_scheduling_algorithms.htm
https://www.geeksforgeeks.org/multiple-processor-scheduling-in-operating-system/

ContentLicense: CC BY-SA 4.0


问:
Merging odd number of data frames with suffixes
I am trying to merge a list of data frames, and I came across many different answers in this community like this R - reduce with merge and more than 2 suffixes (or: how to merge multiple dataframes and keep track of columns) . But after working out on these answers it works on even number of data frames but not odd number of dataframes.

```<code>myDF <- cbind(typecar = rownames(mtcars), mtcars)
rownames(myDF) <- NULL
df1 <- myDF
df2 <-  myDF
df3<- myDF
df4 <- myDF

for(i in head(seq_along(list.df), -1)) {

  res <- merge(res, list.df[[i+1]], all = TRUE,
               suffixes = sfx[i:(i+1)], by = "typecar")
}
</code>```

Here the above code works as expected for even number of df, like following

```<code>list.df <- list(df1, df2, df3,df4)
sfx <- c(".df1", ".df2", ".df3", ".df4")
</code>```

But when trying on odd number the last .df3 is not added as suffix

```<code>list.df <- list(df1, df2, df3)
sfx <- c(".df1", ".df2", ".df3")
</code>```

here the colnames looks like this.

```<code> [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg"      "cyl"      "disp"
[27] "hp"       "drat"     "wt"       "qsec"     "vs"       "am"       "gear"     "carb"
</code>```

what I want is

```<code> [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg.df3"      "cyl.df3"      "disp.df3"
[27] "hp.df3"       "drat.df3"     "wt.df3"       "qsec.df3"     "vs.df3"       "am.df3"       "gear.df3"     "carb.df3"
</code>```

Tried with dplyr join but its the same case. Came across this https://github.com/tidyverse/dplyr/issues/1296 . Is there any approach to this that work on odd number of data frames ?

答:
An easier option is to name the list element column names with the corresponding list names or object names as suffix except the column name used as by variable in the merge.

```<code>list.df <- Map(function(x, nm) {i1 <- names(x) != 'typecar'
            names(x)[i1] <- paste0(names(x)[i1], ".", nm)
            x
    }, list.df, names(list.df))
</code>```

Then, we make use of Reduce/merge

```<code>out <- Reduce(function(...) merge(..., by = 'typecar', all = TRUE), list.df)
names(out)
#[1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1"
#[13] "mpg.df2"  "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg.df3"
#[25] "cyl.df3"  "disp.df3" "hp.df3"   "drat.df3" "wt.df3"   "qsec.df3" "vs.df3"   "am.df3"   "gear.df3" "carb.df3"
</code>```

data

```<code>list.df <- mget(paste0('df', 1:3))
</code>```

Body:
I am trying to merge a list of data frames, and I came across many different answers in this community like this R - reduce with merge and more than 2 suffixes (or: how to merge multiple dataframes and keep track of columns) . But after working out on these answers it works on even number of data frames but not odd number of dataframes.

myDF <- cbind(typecar = rownames(mtcars), mtcars)
rownames(myDF) <- NULL
df1 <- myDF
df2 <-  myDF
df3<- myDF
df4 <- myDF

for(i in head(seq_along(list.df), -1)) {

  res <- merge(res, list.df[[i+1]], all = TRUE,
               suffixes = sfx[i:(i+1)], by = "typecar")
}

Here the above code works as expected for even number of df, like following

list.df <- list(df1, df2, df3,df4)
sfx <- c(".df1", ".df2", ".df3", ".df4")

But when trying on odd number the last .df3 is not added as suffix

list.df <- list(df1, df2, df3)
sfx <- c(".df1", ".df2", ".df3")

here the colnames looks like this.

 [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg"      "cyl"      "disp"
[27] "hp"       "drat"     "wt"       "qsec"     "vs"       "am"       "gear"     "carb"

what I want is

 [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg.df3"      "cyl.df3"      "disp.df3"
[27] "hp.df3"       "drat.df3"     "wt.df3"       "qsec.df3"     "vs.df3"       "am.df3"       "gear.df3"     "carb.df3"

Tried with dplyr join but its the same case. Came across this https://github.com/tidyverse/dplyr/issues/1296 . Is there any approach to this that work on odd number of data frames ?

Body:
An easier option is to name the list element column names with the corresponding list names or object names as suffix except the column name used as by variable in the merge.

list.df <- Map(function(x, nm) {i1 <- names(x) != 'typecar'
            names(x)[i1] <- paste0(names(x)[i1], ".", nm)
            x
    }, list.df, names(list.df))

Then, we make use of Reduce/merge

out <- Reduce(function(...) merge(..., by = 'typecar', all = TRUE), list.df)
names(out)
#[1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1"
#[13] "mpg.df2"  "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg.df3"
#[25] "cyl.df3"  "disp.df3" "hp.df3"   "drat.df3" "wt.df3"   "qsec.df3" "vs.df3"   "am.df3"   "gear.df3" "carb.df3"

data

list.df <- mget(paste0('df', 1:3))


问:
Why does my value only remain in the array for one loop?
I am trying to fill an array with countries, however when I do, it only remains in the array for one loop. Anyone know how to help?

My code:

```<code>let country = ['3',"2"];

//This.setState in here.
data: data.map(country => {
          const { name } = country;
          country[count] = name;
          alert(country[0]);
          count++;
        })
</code>```

At first, the alert comes up as "Afghanistan", however every time after that it says "undefined".

答:
Since you havent provided a lot of info (where does the count variable come from for instance) i'll point you in a more debuggable way:

So you have several things not following the React way, you want to create an object with key (country name) and value number of occurrences in the state. For that you should:

this.setState(prevState => ({
  data: data.map((country) => ({ ...prevState.data, [country]: data[country] ? data[country]++ : 1 });
}));

// test if you have what you need:
console.alert(this.state.data[0]);
```

So to explain what I did:

Map returns an array;

You need to include the data that you previously build or you will overwrite the previous state data;

You'll have the key/value (dictionary) that you need.

This would work also for the reverse (key being the number and the value being the country).

Hope this helps!

Body:
I am trying to fill an array with countries, however when I do, it only remains in the array for one loop. Anyone know how to help?

My code:

let country = ['3',"2"];

//This.setState in here.
data: data.map(country => {
          const { name } = country;
          country[count] = name;
          alert(country[0]);
          count++;
        })

At first, the alert comes up as "Afghanistan", however every time after that it says "undefined".

Body:
Since you havent provided a lot of info (where does the count variable come from for instance) i'll point you in a more debuggable way:

So you have several things not following the React way, you want to create an object with key (country name) and value number of occurrences in the state. For that you should:

this.setState(prevState => ({
  data: data.map((country) => ({ ...prevState.data, [country]: data[country] ? data[country]++ : 1 });
}));

// test if you have what you need:
console.alert(this.state.data[0]);

So to explain what I did:

Map returns an array;

You need to include the data that you previously build or you will overwrite the previous state data;

You'll have the key/value (dictionary) that you need.

This would work also for the reverse (key being the number and the value being the country).

Hope this helps!


问:
Why does 'not in' return True with 2-dimensional lists that contain the cited value in their inner lists
I want this statement to return False. Clearly there are plenty of 0s in the list, however it returns True.

```<code>zeros = [[0] * 8] * 8
print(0 not in zeros)
# True
</code>```

Could someone explain this behaviour?
Also, is there a different expression I can use that will evaluate to False?

答:
The in operator only looks at the elements of zeros, and these are [0] and not 0. Therefore it returns false. You could convert it into a numpy.array, for which the in operator is defined as you would need it.

```<code>from numpy import array
zeros = array([[0] * 8] * 8)
print(0 not in zeros)
# False
</code>```

Just be aware, if the array is of floating point type, you need to test for 0.0 instead.

Body:
I want this statement to return False. Clearly there are plenty of 0s in the list, however it returns True.

zeros = [[0] * 8] * 8
print(0 not in zeros)
# True

Could someone explain this behaviour?
Also, is there a different expression I can use that will evaluate to False?

Body:
The in operator only looks at the elements of zeros, and these are [0] and not 0. Therefore it returns false. You could convert it into a numpy.array, for which the in operator is defined as you would need it.

from numpy import array
zeros = array([[0] * 8] * 8)
print(0 not in zeros)
# False

Just be aware, if the array is of floating point type, you need to test for 0.0 instead.


问:
Dynamically Enable and Disable Div using Mootools
Here is my HTML

```<code><div class="form-wrapper" id="1_1_18-wrapper">
    <input type="checkbox" class="field_container field_18 option_1 parent_1" style="" show="1" alias="confirm_student" value="1" id="1_1_18" name="1_1_18">
    <label class="optional" for="1_1_18">Are You a student</label>
</div>

<div class="form-wrapper" id="1_1_16-wrapper">
    <div class="form-label" id="1_1_16-label">
        <label class="optional" for="1_1_16">School Type</label>
    </div>
    <div class="form-element" id="1_1_16-element">
        <select onchange="changeFields(this)" class="field_container field_16 option_1 parent_1" style="" show="1" alias="" id="1_1_16" name="1_1_16">
                <option label="" value=""></option>
        </select>
    </div>
</div>

<div class="form-wrapper" id="1_1_17-wrapper">
    <div class="form-label" id="1_1_17-label">
        <label class="optional" for="1_1_17">School Name</label>
    </div>
    <div class="form-element" id="1_1_17-element">
        <input type="text" class="field_container field_17 option_1 parent_1" style="" show="1" alias="" value="" id="1_1_17" name="1_1_17">
    </div>
</div>

<div class="form-wrapper" id="1_1_8-wrapper">
    <div class="form-label" id="1_1_8-label">
        <label class="optional" for="1_1_8">Website</label>
    </div>
    <div class="form-element" id="1_1_8-element">
        <input type="text" class="field_container field_8 option_1 parent_1" show="1" alias="" value="" id="1_1_8" name="1_1_8">
    </div>
</div>
</code>```

How to enable next two div when checking the first check box (ie, Are You a student) and disable when uncheck the checkbox. All the id of every elements are getting from auto icremented mysql table fields. Only the check box alias attributes is user defined. Any idea will be appreciable

Thanks

答:
IF you want the DIVs to stop working once someone has clicked on them, I would recommend something like this:

The user clicks on the div (using an onclick event), and when the user has filled out the desired info, fire another event to validate the information. If the information checks out, then create a custom event for the div (while destroying the other events) that just stops the event. (addEvent('click), function (x) {x.stop()});) And to enable the other divs, you just set a variable to true.

Also, could you just add disabled="disabled" to the forms when the user clicks on it?

Body:
Here is my HTML

    <input type="checkbox" class="field_container field_18 option_1 parent_1" style="" show="1" alias="confirm_student" value="1" id="1_1_18" name="1_1_18">
    Are You a student

        School Type

        <select onchange="changeFields(this)" class="field_container field_16 option_1 parent_1" style="" show="1" alias="" id="1_1_16" name="1_1_16">
                <option label="" value=""></option>
        </select>

        School Name

        <input type="text" class="field_container field_17 option_1 parent_1" style="" show="1" alias="" value="" id="1_1_17" name="1_1_17">

        Website

        <input type="text" class="field_container field_8 option_1 parent_1" show="1" alias="" value="" id="1_1_8" name="1_1_8">

How to enable next two div when checking the first check box (ie, Are You a student) and disable when uncheck the checkbox. All the id of every elements are getting from auto icremented mysql table fields. Only the check box alias attributes is user defined. Any idea will be appreciable

Thanks


问:
how to use setInterval with redux-thunk?
I'm using redux-thunk to manage async functions, and I want to use setInterval within an action creator, this is my code:

```<code>export const startLobbyPolling = () => dispatch => {
  const pollTimer = setInterval(() => {
    dispatch(fetchLobby);
  }, POLL_TIME);
  dispatch({ type: START_LOBBY_POLLING, payload: pollTimer });
};
</code>```

fetchLobby is another action creator that simply fetch a request and store its data.
but surprisingly it's not working as it only shows START_LOBBY_POLLING action in redux debugger tool and nothing happens afterward. I would appreciate it to know how to use setInterval with redux.

答: There's nothing particular about using setInterval with redux-thunk. It should work just as it would anywhere else. You need to see the callback function which has been used in the setInterval.

Body:
I'm using redux-thunk to manage async functions, and I want to use setInterval within an action creator, this is my code:

export const startLobbyPolling = () => dispatch => {
  const pollTimer = setInterval(() => {
    dispatch(fetchLobby);
  }, POLL_TIME);
  dispatch({ type: START_LOBBY_POLLING, payload: pollTimer });
};

fetchLobby is another action creator that simply fetch a request and store its data.
but surprisingly it's not working as it only shows START_LOBBY_POLLING action in redux debugger tool and nothing happens afterward. I would appreciate it to know how to use setInterval with redux.


问:
Why is my web.config being overwritten when I publish?
I'm using an ASP.NET Core 3.1 MVC website project.

web.config set the property Copy to Output Directory set to Do not copy.

Yet when I publish the ASPNETCORE_ENVIRONMENT is changed from Production to Development - why?

Thanks in advance.

答:
ASPNETCORE_ENVIRONMENT is an environment variable, and it's set by your publish profile.

Environment variables in Core 3.1

See: For Windows IIS deployments: Include the  property in the publish profile (.pubxml) or project file. This approach sets the environment in web.config when the project is published


问:
Unable to evaluate ClojureScript using fireplace.vim when using the Clojure CLI
I was looking forward to experimenting with the new release of ClojureScript but I'm running into a problem when trying to evaluate code.

I have an nREPL server running and am (seemingly?) able to connect to it using :Fireplaceconnect localhost:$PORT. However, when I try to evaluate code (using either :Eval or :CljsEval) I see an error message which says, "Fireplace: no default ClojureScript REPL".

There's an issue in the fireplace.vim repository which mentions this problem, but it was closed with RTFM -- I have and I still can't figure out a solution.

~/.clojure/deps.edn

```<code>{
  :aliases {:nREPL
             {:extra-deps
               {nrepl/nrepl {:mvn/version "0.7.0"}
                cider/piggieback {:mvn/version "0.4.2"}}}}
}
</code>```

starting nrepl

```<code>> clj -R:nREPL -m nrepl.cmdline --middleware "[cider.piggieback/wrap-cljs-repl]"
</code>```

答:
I was able to find a workable solution and have documented the entire workflow here:

deps.edn:

```<code>{
 :aliases {:rebel {:main-opts ["-m" "rebel-readline.main"]}}
 :paths ["src" "resources" "target"]
 :deps {cider/cider-nrepl {:mvn/version "0.25.0-alpha1"}
        cider/piggieback {:mvn/version "0.5.0"}
        com.bhauman/figwheel-main {:mvn/version "0.2.6"}
        com.bhauman/rebel-readline {:mvn/version "0.1.4"}
        com.bhauman/rebel-readline-cljs {:mvn/version "0.1.4"}
        nrepl/nrepl {:mvn/version "0.7.0"}
        org.clojure/clojure {:mvn/version "1.10.1"}
        org.clojure/clojurescript {:mvn/version "1.10.773"}
        reagent {:mvn/version "0.10.0"
                 :exclusions [cljsjs/react cljsjs/react-dom]}}}
</code>```

Inside a Clojure REPL run the following commands to start the nREPL server, ClojureScript REPL and Figwheel build:

```<code>(require '[fullstack.helpers :refer :all])  ;; import nREPL helpers
(start-nrepl-server!)                       ;; start nREPL server on 7888

;; Some people run the following commands using Vim-Fireplace's `:CljEval`
;; command but I found that to be a little clunky.
;; If I do end up using this workflow regularly, I'll consider packaging these
;; steps up in a VimScript helper function.
;; Out of habit, I send them from this document inside vim to a parallel tmux
;; pane using vim-slime.

(require 'figwheel.main.api)    ;; require Figwheel's scripting API
(figwheel.main.api/start "dev") ;; start Figwheel build (using dev.cljs.edn) and REPL
</code>```

Within Vim, run the following command in the CLI prompt (hit : in command mode) in order to connect to the running ClojureScript REPL:

```<code>:Piggieback (figwheel.main.api/repl-env "dev") " connect to the CLJS REPL
</code>```

The major differences are moving the dependencies to the local deps.edn (this is not necessary, but I think it's a better, more flexible approach), upgrading Piggieback and leaning on the higher level Figwheel scripting API, instead of CLI flags.

Body:
I was looking forward to experimenting with the new release of ClojureScript but I'm running into a problem when trying to evaluate code.

I have an nREPL server running and am (seemingly?) able to connect to it using :Fireplaceconnect localhost:$PORT. However, when I try to evaluate code (using either :Eval or :CljsEval) I see an error message which says, "Fireplace: no default ClojureScript REPL".

There's an issue in the fireplace.vim repository which mentions this problem, but it was closed with RTFM -- I have and I still can't figure out a solution.

~/.clojure/deps.edn

{
  :aliases {:nREPL
             {:extra-deps
               {nrepl/nrepl {:mvn/version "0.7.0"}
                cider/piggieback {:mvn/version "0.4.2"}}}}
}

starting nrepl

> clj -R:nREPL -m nrepl.cmdline --middleware "[cider.piggieback/wrap-cljs-repl]"

Body:
I was able to find a workable solution and have documented the entire workflow here:

deps.edn:

{
 :aliases {:rebel {:main-opts ["-m" "rebel-readline.main"]}}
 :paths ["src" "resources" "target"]
 :deps {cider/cider-nrepl {:mvn/version "0.25.0-alpha1"}
        cider/piggieback {:mvn/version "0.5.0"}
        com.bhauman/figwheel-main {:mvn/version "0.2.6"}
        com.bhauman/rebel-readline {:mvn/version "0.1.4"}
        com.bhauman/rebel-readline-cljs {:mvn/version "0.1.4"}
        nrepl/nrepl {:mvn/version "0.7.0"}
        org.clojure/clojure {:mvn/version "1.10.1"}
        org.clojure/clojurescript {:mvn/version "1.10.773"}
        reagent {:mvn/version "0.10.0"
                 :exclusions [cljsjs/react cljsjs/react-dom]}}}

Inside a Clojure REPL run the following commands to start the nREPL server, ClojureScript REPL and Figwheel build:

(require '[fullstack.helpers :refer :all])  ;; import nREPL helpers
(start-nrepl-server!)                       ;; start nREPL server on 7888

;; Some people run the following commands using Vim-Fireplace's `:CljEval`
;; command but I found that to be a little clunky.
;; If I do end up using this workflow regularly, I'll consider packaging these
;; steps up in a VimScript helper function.
;; Out of habit, I send them from this document inside vim to a parallel tmux
;; pane using vim-slime.

(require 'figwheel.main.api)    ;; require Figwheel's scripting API
(figwheel.main.api/start "dev") ;; start Figwheel build (using dev.cljs.edn) and REPL

Within Vim, run the following command in the CLI prompt (hit : in command mode) in order to connect to the running ClojureScript REPL:

:Piggieback (figwheel.main.api/repl-env "dev") " connect to the CLJS REPL

The major differences are moving the dependencies to the local deps.edn (this is not necessary, but I think it's a better, more flexible approach), upgrading Piggieback and leaning on the higher level Figwheel scripting API, instead of CLI flags.


问:
Where to put a utility function in Angular
This is just an example working with Angular, let say I need to use a function in the component, in this case the getDay() function will be called by an event.

```<code>getDay()  {
  switch (new Date().getDay()) {
    case 0:
      day = "Sunday";
      break;
    case 1:
      day = "Monday";
      break;
    case 2:
       day = "Tuesday";
       break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
  }
}
</code>```

Since I'm using Typescript, should I just create a shared folder inside components directory and inside it:

Create a component e.g: formatDate.component.ts with export class FormateDateComponent and just add my function there and import where I want?

What would be the best practice.

答: When I have alike questions I look how guys from angular, material or rxjs or any other widely-used framework do. For your case it would be https://github.com/angular/angular/blob/master/packages/core/src/sanitization/url_sanitizer.ts -- just create file for a feature and export function with descriptive name. Organizing code by features is ok. But not create bulk of everything (e.g. utils.ts), try organizing by feature.

Body:
This is just an example working with Angular, let say I need to use a function in the component, in this case the getDay() function will be called by an event.

getDay()  {
  switch (new Date().getDay()) {
    case 0:
      day = "Sunday";
      break;
    case 1:
      day = "Monday";
      break;
    case 2:
       day = "Tuesday";
       break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
  }
}

Since I'm using Typescript, should I just create a shared folder inside components directory and inside it:

Create a component e.g: formatDate.component.ts with export class FormateDateComponent and just add my function there and import where I want?

What would be the best practice.


问:
Determine CSV size before inserting the next batch of data
I am working on a feature where I need to fetch the data from Oracle table and each row of table is mapped to a Java object. so I will be having the List of records and I need to create a CSV file with this data.

Different scenarios to consider here:

There is going to be millions of records and I will be fetching the data in 10k batches.

Each batch of 10k records will be appended to csv.

Restriction:

The CSV file should not exceed more than 100 MB.

If at any point, the size is more than 100 MB , I should create a new CSV file.

Question:

How can I make sure I dont insert records once CSV file size has reached 100 MB ?

Suppose I have list of records which contains 10k employee objects and I somehow calculate the size of this list as 1MB. So if I put these records in csv, will the size of csv will also be 1 MB?

答:
I propose the following solution.
 First of all,  we should not read millions of records from Oracle in a single query. The Oracle table should be partitioned by date, month, year, or any other criteria.  You can throttle the number of records and write into a file. </p>

<p>Secondly, the csv file size. Instead of looking at the csv file size before appending into a csv file, you can look at the size of the results object in java and determine how many records you want to append in that batch append. </p>

Body:
I propose the following solution.
 First of all,  we should not read millions of records from Oracle in a single query. The Oracle table should be partitioned by date, month, year, or any other criteria.  You can throttle the number of records and write into a file.

Secondly, the csv file size. Instead of looking at the csv file size before appending into a csv file, you can look at the size of the results object in java and determine how many records you want to append in that batch append.


问:
How can I access getSupportFragmentManager() in a fragment?
I have a FragmentActivity and I want to use a map fragment within it.  I'm having a problem getting the support fragment manager to access it.</p>

```<code> if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map1)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }

            // create marker
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title("Hello Maps ");

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(latitude, longitude)).zoom(15).build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            // adding marker
            googleMap.addMarker(marker);
</code>```

答:
The simple new way of doing it in kotlin

```<code>requireActivity().supportFragmentManager
</code>```

Body:
I have a FragmentActivity and I want to use a map fragment within it.  I'm having a problem getting the support fragment manager to access it.

 if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map1)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }

            // create marker
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title("Hello Maps ");

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(latitude, longitude)).zoom(15).build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            // adding marker
            googleMap.addMarker(marker);

Body:
The simple new way of doing it in kotlin

requireActivity().supportFragmentManager


问:
How to generate effect size [90%CI] in the summary table using R package “gtsummary”?
I am working on creating summary table using the R package "gtsummary". This is actually very good. The add_stat function gives you a lot of freedom to include add-ons. For example, in my area we want to inform the effect size with confidence interval (ES [90% CI]). So,  I would like help to include the CI range. The code I implemented is working, but without digit control and without the CI range.</p>

```<code># Packages ----------------------------------------------------------------
library(gtsummary)
library(gt)
library(dplyr)
library(purrr)

# Example 1 ---------------------------------------------------------------
# fn returns ES value
my_EStest <- function(data, variable, by, ...) {
  effsize::cohen.d(data[[variable]] ~ as.factor(data[[by]]),
                   conf.level=.90, pooled=TRUE, paired=FALSE,
                   hedges.correction=TRUE)$estimate
}

add_ES <-
  trial %>%
  select(trt, age) %>%
  tbl_summary(by = trt, missing = "no",
              statistic = list(all_continuous() ~ "{mean} ({sd})"),
              digits = list(all_continuous() ~ c(1,1))) %>%
  add_p(test = everything() ~ t.test) %>%
  add_stat(
    fns = everything() ~ my_EStest,
    fmt_fun = style_pvalue,
    header = "**ES**"
  )
add_ES

# counterproof
effsize::cohen.d(age ~ trt, data = trial, conf.level=.90, return.dm=TRUE, pooled=TRUE, paired=FALSE, hedges.correction=TRUE)
</code>```

答:
I think the easiest way to do this is to add the confidence interval along with the estimate already formatted.

You update my_EStest function to return an already formatted statistic including both the estimate and the confidence interval.  Does this output work for you?

library(tidyverse)
library(gtsummary)

my_EStest <- function(data, variable, by, ...) {
  # Cohen's D
  d <- effsize::cohen.d(data[[variable]] ~ as.factor(data[[by]]),
                   conf.level=.90, pooled=TRUE, paired=FALSE,
                   hedges.correction=TRUE)

  # Formatting statistic with CI
  est <- style_sigfig(d$estimate)
  ci <- style_sigfig(d$conf.int) %>% paste(collapse = ", ")

  # returning estimate with CI together
  str_glue("{est} ({ci})")
}

add_ES <-
  trial %>%
  select(trt, age) %>%
  tbl_summary(by = trt, missing = "no",
              statistic = list(all_continuous() ~ "{mean} ({sd})"),
              digits = list(all_continuous() ~ c(1,1))) %>%
  add_p(test = everything() ~ t.test) %>%
  add_stat(
    fns = everything() ~ my_EStest,
    fmt_fun = NULL,
    header = "**ES (90% CI)**"
  ) %>%
  modify_footnote(add_stat_1 ~ "Cohen's D (90% CI)")
```

Body:
I am working on creating summary table using the R package "gtsummary". This is actually very good. The add_stat function gives you a lot of freedom to include add-ons. For example, in my area we want to inform the effect size with confidence interval (ES [90% CI]). So,  I would like help to include the CI range. The code I implemented is working, but without digit control and without the CI range.

# Packages ----------------------------------------------------------------
library(gtsummary)
library(gt)
library(dplyr)
library(purrr)

# Example 1 ---------------------------------------------------------------
# fn returns ES value
my_EStest <- function(data, variable, by, ...) {
  effsize::cohen.d(data[[variable]] ~ as.factor(data[[by]]),
                   conf.level=.90, pooled=TRUE, paired=FALSE,
                   hedges.correction=TRUE)$estimate
}

add_ES <-
  trial %>%
  select(trt, age) %>%
  tbl_summary(by = trt, missing = "no",
              statistic = list(all_continuous() ~ "{mean} ({sd})"),
              digits = list(all_continuous() ~ c(1,1))) %>%
  add_p(test = everything() ~ t.test) %>%
  add_stat(
    fns = everything() ~ my_EStest,
    fmt_fun = style_pvalue,
    header = "**ES**"
  )
add_ES

# counterproof
effsize::cohen.d(age ~ trt, data = trial, conf.level=.90, return.dm=TRUE, pooled=TRUE, paired=FALSE, hedges.correction=TRUE)


问:
VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead
I ma using react-native-google-places-autocomplete package for google place autocomplete text input. But here I am getting the warning after tapping on address every time.

Warning::

VirtualizedLists should never be nested inside plain ScrollViews with
  the same orientation - use another VirtualizedList-backed container
  instead.

What is the other VirtualizedList-backed container that I should use, and why is it now advised not to use like that?

I have created a custom component for this, below I am adding code inside render of GooglePlacesInput component::

class GooglePlacesInput extends PureComponent {
  //..... other function

  // render function
  render() {
    const { placeholder, minSearchLen, address, name, enablePoweredByContainer, currentLocation, onChangeText } = this.props;
    return (
      <GooglePlacesAutocomplete
        placeholder={placeholder}
        name={name}
        minLength={minSearchLen}
        autoFocus={false}
        returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
        keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
        listViewDisplayed="false"   // true/false/undefined
        fetchDetails={true}
        getDefaultValue={() => address}
        renderDescription={row => row.description} // custom description render
        onPress={(data, details = null) => this.onPressAddress(data, details)}
        onNotFound={() => { }}
        query={{ key: GOOGLE_API_KEY }}
        currentLocation={currentLocation} // Will add a 'Current location' button at the top of the predefined places list
        currentLocationLabel="Current location"
        nearbyPlacesAPI="GooglePlacesSearch"
        textInputProps={{
          onChangeText: onChangeText,
        }}
        enablePoweredByContainer={enablePoweredByContainer}
        isRowScrollable={false}
        styles={{
          textInputContainer: {
            backgroundColor: 'rgba(0,0,0,0)',
            borderTopWidth: 0,
            borderBottomWidth: 0,
            width: '100%',
            marginBottom: 20,
          },
          textInput: {
            paddingHorizontal: 18,
            height: 40,
            color: Colors.grey,
            fontSize: 16,
          },
          predefinedPlacesDescription: {
            color: '#1faadb',
          },
        }}
      />
    );
  }
}

// default props values
GooglePlacesInput.defaultProps = {
  name: 'address',
  placeholder: 'Enter Address',
  minSearchLen: 2,
  address: '',
  enablePoweredByContainer: true,
  currentLocation: false,
  onChangeText: '',
};

export { GooglePlacesInput };
```

<p>And calling it inside another component like this::</p>

<pre class="lang-js prettyprint-override"><code><Content
contentContainerStyle={[flexGrow1, p10]}
>
  <View style={[alignItemsCenter, pt20, pb30]}>
    <ImageView source={Images.mapIcon} style={{ height: Base.getPixel('4.5rem'), width: Base.getPixel('4.5rem') }} />
  </View>
  <Formik
    initialValues={this.initialValues}
    onSubmit={(data) => this.onSubmitForm(data)}
    ref={el => (this.form = el)}
    validationSchema={validationSchema}
    isSubmitting={true}
    render={({ handleSubmit, values, setValues, setFieldValue, errors, touched, ...props }) => {
      return (
        <Form>
          <GooglePlacesInput
            onPress={(data, detail) => this.onPressOfAddress(data, detail)}
            address={values.address}
            name="address"
            onChangeText={(value) => setFieldValue('address', value)}
          />
          <Button onPress={() => popScreen(this.props.componentId)} block large variant="danger">CANCEL</Button>
        </Form>
      );
    }}
  />
</Content>
</code>```

It comes when I am clicking on autocomplete.

Please suggest me the solution to get rid of this problem either suggest me some other package it something is better than this.

This warning is coming from the main file of this package.

答:
I had the same problem using native ('from react-native') ScrollView and ListItem (from react-native-elements). Solved it wrapping both with a View Component:</p>
```<code><View>
    <ScrollView>
        <View> {
            data.map((l, i) => (
                <ListItem key={i}/>
            ))}
        </View>
    </ScrollView>
</View>
</code>```

Body:
I ma using react-native-google-places-autocomplete package for google place autocomplete text input. But here I am getting the warning after tapping on address every time.

Warning::

VirtualizedLists should never be nested inside plain ScrollViews with
  the same orientation - use another VirtualizedList-backed container
  instead.

What is the other VirtualizedList-backed container that I should use, and why is it now advised not to use like that?

I have created a custom component for this, below I am adding code inside render of GooglePlacesInput component::

class GooglePlacesInput extends PureComponent {
  //..... other function

  // render function
  render() {
    const { placeholder, minSearchLen, address, name, enablePoweredByContainer, currentLocation, onChangeText } = this.props;
    return (
      <GooglePlacesAutocomplete
        placeholder={placeholder}
        name={name}
        minLength={minSearchLen}
        autoFocus={false}
        returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
        keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
        listViewDisplayed="false"   // true/false/undefined
        fetchDetails={true}
        getDefaultValue={() => address}
        renderDescription={row => row.description} // custom description render
        onPress={(data, details = null) => this.onPressAddress(data, details)}
        onNotFound={() => { }}
        query={{ key: GOOGLE_API_KEY }}
        currentLocation={currentLocation} // Will add a 'Current location' button at the top of the predefined places list
        currentLocationLabel="Current location"
        nearbyPlacesAPI="GooglePlacesSearch"
        textInputProps={{
          onChangeText: onChangeText,
        }}
        enablePoweredByContainer={enablePoweredByContainer}
        isRowScrollable={false}
        styles={{
          textInputContainer: {
            backgroundColor: 'rgba(0,0,0,0)',
            borderTopWidth: 0,
            borderBottomWidth: 0,
            width: '100%',
            marginBottom: 20,
          },
          textInput: {
            paddingHorizontal: 18,
            height: 40,
            color: Colors.grey,
            fontSize: 16,
          },
          predefinedPlacesDescription: {
            color: '#1faadb',
          },
        }}
      />
    );
  }
}

// default props values
GooglePlacesInput.defaultProps = {
  name: 'address',
  placeholder: 'Enter Address',
  minSearchLen: 2,
  address: '',
  enablePoweredByContainer: true,
  currentLocation: false,
  onChangeText: '',
};

export { GooglePlacesInput };

And calling it inside another component like this::

<Content
contentContainerStyle={[flexGrow1, p10]}
>
  <View style={[alignItemsCenter, pt20, pb30]}>
    <ImageView source={Images.mapIcon} style={{ height: Base.getPixel('4.5rem'), width: Base.getPixel('4.5rem') }} />
  </View>
  <Formik
    initialValues={this.initialValues}
    onSubmit={(data) => this.onSubmitForm(data)}
    ref={el => (this.form = el)}
    validationSchema={validationSchema}
    isSubmitting={true}
    render={({ handleSubmit, values, setValues, setFieldValue, errors, touched, ...props }) => {
      return (
        <Form>
          <GooglePlacesInput
            onPress={(data, detail) => this.onPressOfAddress(data, detail)}
            address={values.address}
            name="address"
            onChangeText={(value) => setFieldValue('address', value)}
          />
          <Button onPress={() => popScreen(this.props.componentId)} block large variant="danger">CANCEL</Button>
        </Form>
      );
    }}
  />
</Content>

It comes when I am clicking on autocomplete.

Please suggest me the solution to get rid of this problem either suggest me some other package it something is better than this.

This warning is coming from the main file of this package.

Body:
I had the same problem using native ('from react-native') ScrollView and ListItem (from react-native-elements). Solved it wrapping both with a View Component:

<View>
    <ScrollView>
        <View> {
            data.map((l, i) => (
                <ListItem key={i}/>
            ))}
        </View>
    </ScrollView>
</View>


问:
How do I create mutually callable MethodInfos from MethodBuilders created from LambdaExpressions?
I'm currently working on an compiler in C#, where the behaviour is defined by LambdaExpressions, and then using CompileToMethod, transformed into MethodBuilders and saved to DLL. All functions are public and static.

However, I could not find a way to extract usable MethodInfo (or another method of reference) from the MethodBuilder until the behaviour is defined and declaring type is created/sealed. That means that at that until that point, it is impossible to use Expression.Call to call these functions. That makes self-recursion or mutual referencing between two functions impossible.

I ended up using Reflection to invoke the functions at runtime, but it's very suboptimal, and I'm still curious if there's a better way.

How do i ensure functions created with LambdaExpression.CompileToMethod(MethodBuilder) can self-call?

Alternatively, is there any other way to use LambdaExpressions which would allow this and support saving as a static method to a dll?

答:
I hope this helps.

This is complete code example which produces runtime defined type with single static recursive method.

For the simplicity of the example the recursive method is infinite - at the end of the Main method the recursive method is called

```<code>static void Main(string[] args)
{
    var moduleBuilder = CreateDynamicModuleBuilder();
    var typeBuilder = moduleBuilder.DefineType("Person", TypeAttributes.Public | TypeAttributes.Class);
    var methodBuilder = typeBuilder.DefineMethod("SayHello", MethodAttributes.Static | MethodAttributes.Public);
    var methodExpression = CreateRecursiveExpression();
    var lambda = Expression.Lambda(methodExpression);
    lambda.CompileToMethod(methodBuilder);

    var typeInfo = typeBuilder.CreateType();
    var methodInfo = typeInfo.GetMethod("SayHello", BindingFlags.Public | BindingFlags.Static);
    methodInfo.Invoke(null, null);
}

private static Expression CreateRecursiveExpression()
{
    var methodInfo = typeof(Console).GetMethod("WriteLine", new[] { typeof(String) });
    var arg = Expression.Constant("Hello");
    var consoleCall = Expression.Call(methodInfo, arg);
    var sayHelloActionVariable = Expression.Variable(typeof(Action), "sayHelloAction");
    var block = Expression.Block(
        new[] { sayHelloActionVariable },
        Expression.Assign(
            sayHelloActionVariable,
            Expression.Lambda(
                Expression.Block(
                    consoleCall,
                    Expression.Invoke(sayHelloActionVariable)
                )
            )
        ),
        Expression.Invoke(sayHelloActionVariable)
    );

    return block;
}

private static ModuleBuilder CreateDynamicModuleBuilder()
{
    var name = new AssemblyName("Example.DynamicRecursion");
    var am = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
    var mb = am.DefineDynamicModule(name.Name, $"{name.Name}.dll");
    return mb;
}
</code>```

This code will create type with the following signature

```<code>public class Person
{
   public static void SayHello()
   {
       Action sayHelloAction;
       sayHelloAction = () =>
       {
           Console.WriteLine("Hello");
           sayHelloAction();
       }
       sayHelloAction();
   }
}
</code>```

Body:
I hope this helps.

This is complete code example which produces runtime defined type with single static recursive method.

For the simplicity of the example the recursive method is infinite - at the end of the Main method the recursive method is called

static void Main(string[] args)
{
    var moduleBuilder = CreateDynamicModuleBuilder();
    var typeBuilder = moduleBuilder.DefineType("Person", TypeAttributes.Public | TypeAttributes.Class);
    var methodBuilder = typeBuilder.DefineMethod("SayHello", MethodAttributes.Static | MethodAttributes.Public);
    var methodExpression = CreateRecursiveExpression();
    var lambda = Expression.Lambda(methodExpression);
    lambda.CompileToMethod(methodBuilder);

    var typeInfo = typeBuilder.CreateType();
    var methodInfo = typeInfo.GetMethod("SayHello", BindingFlags.Public | BindingFlags.Static);
    methodInfo.Invoke(null, null);
}

private static Expression CreateRecursiveExpression()
{
    var methodInfo = typeof(Console).GetMethod("WriteLine", new[] { typeof(String) });
    var arg = Expression.Constant("Hello");
    var consoleCall = Expression.Call(methodInfo, arg);
    var sayHelloActionVariable = Expression.Variable(typeof(Action), "sayHelloAction");
    var block = Expression.Block(
        new[] { sayHelloActionVariable },
        Expression.Assign(
            sayHelloActionVariable,
            Expression.Lambda(
                Expression.Block(
                    consoleCall,
                    Expression.Invoke(sayHelloActionVariable)
                )
            )
        ),
        Expression.Invoke(sayHelloActionVariable)
    );

    return block;
}

private static ModuleBuilder CreateDynamicModuleBuilder()
{
    var name = new AssemblyName("Example.DynamicRecursion");
    var am = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
    var mb = am.DefineDynamicModule(name.Name, $"{name.Name}.dll");
    return mb;
}

This code will create type with the following signature

public class Person
{
   public static void SayHello()
   {
       Action sayHelloAction;
       sayHelloAction = () =>
       {
           Console.WriteLine("Hello");
           sayHelloAction();
       }
       sayHelloAction();
   }
}


问:
Git SSH issue: Terminal works fine, but all GUI clients fail
So, I'm having this issue with git & Github where things work as expected when I use the terminal however tying to do anything from Git GUI Clients like the GitHub desktop app, SourceTree, Fork gives me the  Permission denied (publickey) issue.

Even trying out commands like ssh -T git@github.com in the terminal, works as expected. Here's a screenshot of my Github Account settings from Fork: As you can see, it looks like even my SSH key has been configured correctly & seems to be recognized. I want to avoid the process of generating a new SSH key and setting it up in GitHub unless there's literally no other option.

答:
Even trying out commands like ssh -T git@github.com in the terminal, works as expected.

Double-check the SSH URL used for your remote repository in those GUI clients.

It should be git@github.com:<me>/<myrepo>.

As, as I mentioned here, try first, before launching GitHub Desktop:

```<code>git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"
</code>```

(assuming Windows 10 here)

For Mac, follow "How to Manage Multiple SSH Keys" and make sure your key is added to the ssh-agent:

```<code>ssh-add -K ~/.ssh/_id_rsa
</code>```

with a ~/.ssh/config

```<code>Host *
  AddKeysToAgent yes
  UseKeychain yes
</code>```

SSH will look for key in keychain and if it finds it you will not be prompted for password.

  Key will also be added to ssh-agent. On MacOS this will work on MacOS Sierra 10.12.2 or later.

Body:
Even trying out commands like ssh -T git@github.com in the terminal, works as expected.

Double-check the SSH URL used for your remote repository in those GUI clients.

It should be git@github.com:<me>/<myrepo>.

As, as I mentioned here, try first, before launching GitHub Desktop:

git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"

(assuming Windows 10 here)

For Mac, follow "How to Manage Multiple SSH Keys" and make sure your key is added to the ssh-agent:

ssh-add -K ~/.ssh/_id_rsa

with a ~/.ssh/config

Host *
  AddKeysToAgent yes
  UseKeychain yes

SSH will look for key in keychain and if it finds it you will not be prompted for password.

  Key will also be added to ssh-agent. On MacOS this will work on MacOS Sierra 10.12.2 or later.


Title: Logic to manipulate dataframe in spark scala [Spark]

Body:
Take for example the following dataFrame:
x.show(false)

+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|colId|hdfsPath                                                                                |timestamp    |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|11    |hdfs://novus-nameservice/a/b/c/done/compiled-20200218050518-1-0-0-1582020318751.snappy|1662157400000|
|12    |hdfs://novus-nameservice/a/b/c/done/compiled-20200219060507-1-0-0-1582023907108.snappy|1662158000000|
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+

Now I am trying to update the existing DF to create a new DF based based on the column hdfsPath

The new DF should look like the following:

+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|colId|hdfsPath                                                                                |timestamp    |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|11    |hdfs://novus-nameservice/a/b/c/target/20200218/11/compiled-20200218050518-1-0-0-1582020318751.snappy|1662157400000|
|12    |hdfs://novus-nameservice/a/b/c/target/20200219/12/compiled-20200219060507-1-0-0-1582023907108.snappy|1662158000000|
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+

So the path done changes to target and then from the compiled-20200218050518-1-0-0-1582020318751.snappy portion I get the date 20200218 and then colID 11 and then finally the snappy file. What would be the easiest and most efficient way to achieve this?

It's not a hard requirement to create a newDF, I can update the existing DF with a new column.

To summarize:
Current hdfsPath:

hdfs://novus-nameservice/a/b/c/done/compiled-20200218050518-1-0-0-1582020318751.snappy

Expected hdfsPath:

hdfs://novus-nameservice/a/b/c/target/20200218/11/compiled-20200218050518-1-0-0-1582020318751.snappy

Based on colID.

Body:
Here is what you can do with regex_replace and regex_extract, Extract the values you want and replace with it

df.withColumn("hdfsPath", regexp_replace(
  $"hdfsPath",
  lit("/done"),
  concat(
    lit("/target/"),
    regexp_extract($"hdfsPath", "compiled-([0-9]{1,8})", 1),
    lit("/"),
    $"colId")
))

Output:

+-----+----------------------------------------------------------------------------------------------------+-------------+
|colId|hdfsPath                                                                                |timestamp    |
+-----+----------------------------------------------------------------------------------------------------+-------------+
|11   |hdfs://novus-nameservice/a/b/c/target/20200218/11/compiled-20200218050518-1-0-0-1582020318751.snappy|1662157400000|
|12   |hdfs://novus-nameservice/a/b/c/target/20200219/12/compiled-20200219060507-1-0-0-1582023907108.snappy|1662158000000|
+-----+----------------------------------------------------------------------------------------------------+-------------+

Hope this helps!


问:
Use two different React/React-Dom versions in project
I'm in an extremely weird situation where the project structure looks like:

Project

MiniProject1

MiniProject2

node_modules

package.json

The mini projects themselves are react apps that get shown within a ruby container. So when a user goes to /route1 it loads the miniProject1 react page. when they go to /route2 it goes to the miniProject2 page.

I've been tasked to update the react version of MiniProject2 but not interfere with MiniProject1 or make any changes that could interfere with MiniProject1.

I went the route of installing react and react-dom as follows:

```<code> "react-latest": "npm:react@^16.13.1",
 "react-dom-latest": "npm:react-dom@^16.13.1",
</code>```

so I can then import the latest versions specifically in MiniProject2

The problem that I'm facing is the react-dom has the "React" a peer dependency and it's trying to pull the project react instead of my aliased "react-latest" which makes sense but now I'm stuck trying to figure out how I can force react-dom to require my react-latest alias instead of the default react peer dependency.

I'm also open to potential Webpack config solutions.

Any thoughts?

答:
After some digging I was able to force react-dom to use react-latest by doing the following:

package.json

```<code>"react": "^16.3.2",
"react-dom": "16.3.3",
"react-dom-latest": "npm:react-dom@^16.13.1",
"react-latest": "npm:react@^16.13.1",
</code>```

webpack.config.js

```<code>module: {
rules: [
  {
    test: /\/node_modules\/react-dom-latest\/.*.js/,
    resolve: {
      alias: {
        react: path.resolve('./node_modules/react-latest')
      }
    }
  }]},
</code>```

Then on the top of the files I need to use the latest react version for, I import react like so:

```<code>import React from 'react-latest'
//or
import ReactDOM from 'react-dom-latest' //for your index
</code>```

On the files I need to use the old react for, I import react like so:

```<code>import React from 'react'
//or
import ReactDOM from 'react-dom' //for your index
</code>```

That's all that needed to be done!

Disclaimer: Don't do this unless you have to and have no choice like I did. It'll increase the size of your bundle since you are bringing in two different versions of react and reactDom

Body:
I'm in an extremely weird situation where the project structure looks like:

Project

MiniProject1

MiniProject2

node_modules

package.json

The mini projects themselves are react apps that get shown within a ruby container. So when a user goes to /route1 it loads the miniProject1 react page. when they go to /route2 it goes to the miniProject2 page.

I've been tasked to update the react version of MiniProject2 but not interfere with MiniProject1 or make any changes that could interfere with MiniProject1.

I went the route of installing react and react-dom as follows:

 "react-latest": "npm:react@^16.13.1",
 "react-dom-latest": "npm:react-dom@^16.13.1",

so I can then import the latest versions specifically in MiniProject2

The problem that I'm facing is the react-dom has the "React" a peer dependency and it's trying to pull the project react instead of my aliased "react-latest" which makes sense but now I'm stuck trying to figure out how I can force react-dom to require my react-latest alias instead of the default react peer dependency.

I'm also open to potential Webpack config solutions.

Any thoughts?

Body:
After some digging I was able to force react-dom to use react-latest by doing the following:

package.json

"react": "^16.3.2",
"react-dom": "16.3.3",
"react-dom-latest": "npm:react-dom@^16.13.1",
"react-latest": "npm:react@^16.13.1",

webpack.config.js

module: {
rules: [
  {
    test: /\/node_modules\/react-dom-latest\/.*.js/,
    resolve: {
      alias: {
        react: path.resolve('./node_modules/react-latest')
      }
    }
  }]},

Then on the top of the files I need to use the latest react version for, I import react like so:

import React from 'react-latest'
//or
import ReactDOM from 'react-dom-latest' //for your index

On the files I need to use the old react for, I import react like so:

import React from 'react'
//or
import ReactDOM from 'react-dom' //for your index

That's all that needed to be done!

Disclaimer: Don't do this unless you have to and have no choice like I did. It'll increase the size of your bundle since you are bringing in two different versions of react and reactDom


问:
Prism Navigation error while performing remote build for iOS Xamarin forms
I have paired my visual studio to a virtual MAC machine, created the required keychain, and added to my project. I keep getting this error:

```<code>Prism.Navigation.NavigationException: An error occurred while resolving the page. This is most likely the result of invalid XAML or other type initialization exception --->
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---> Microsoft.Identity.Client.MsalClientException: The application cannot access the iOS keychain for the application publisher (the TeamId is null). This is needed to enable Single Sign-On between applications of the same publisher.
</code>```

I've also tried disabling the keychain in Entitlements.plist - doesn't work. Somehow it seems like a Prism navigation issue because when I eliminate that and simply navigate to a sample page, it works.

I also tried running my project on a Physical Mac, I get this:

```<code>2020-06-01 01:45:29.879475-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=6277
2020-06-01 01:45:29.880109-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskCopyDebugDescription: NatWest.KeepSafe[6277]/0#-1 LF=0
2020-06-01 01:45:29.897634-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=6277
2020-06-01 01:45:29.897992-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskCopyDebugDescription: NatWest.KeepSafe[6277]/0#-1 LF=0
</code>```

P.S: The code runs perfectly on a physical iPhone but gives problems while running on Simulator.

答:
This has nothing to do with Prism at all.. MSAL actually works just fine with Prism you can see the AP.AzureADAuth Module sample.

The error you've posted actually tells you exactly what the issue is. You have an issue with your Entitlements that's keeping it from running on the iOS Simulator.

For more information you'll want to check out the docs here:

https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-xamarin-ios-considerations

var builder = PublicClientApplicationBuilder
     .Create(ClientId)
     .WithIosKeychainSecurityGroup("com.microsoft.adalcache")
     .Build();
```

<p>and in your <code>Entitlements.plist</code> you'll want to update to something like:</p>

<pre class="lang-xml prettyprint-override"><code><dict>
  <key>keychain-access-groups</key>
  <array>
    <string>$(AppIdentifierPrefix)com.microsoft.adalcache</string>
  </array>
</dict>
</code>```

Body:
I have paired my visual studio to a virtual MAC machine, created the required keychain, and added to my project. I keep getting this error:

Prism.Navigation.NavigationException: An error occurred while resolving the page. This is most likely the result of invalid XAML or other type initialization exception --->
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---> Microsoft.Identity.Client.MsalClientException: The application cannot access the iOS keychain for the application publisher (the TeamId is null). This is needed to enable Single Sign-On between applications of the same publisher.

I've also tried disabling the keychain in Entitlements.plist - doesn't work. Somehow it seems like a Prism navigation issue because when I eliminate that and simply navigate to a sample page, it works.

I also tried running my project on a Physical Mac, I get this:

2020-06-01 01:45:29.879475-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=6277
2020-06-01 01:45:29.880109-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskCopyDebugDescription: NatWest.KeepSafe[6277]/0#-1 LF=0
2020-06-01 01:45:29.897634-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=6277
2020-06-01 01:45:29.897992-0700 NatWest.KeepSafe.MobileApp.iOS[6277:128192] SecTaskCopyDebugDescription: NatWest.KeepSafe[6277]/0#-1 LF=0

P.S: The code runs perfectly on a physical iPhone but gives problems while running on Simulator.

Body:
This has nothing to do with Prism at all.. MSAL actually works just fine with Prism you can see the AP.AzureADAuth Module sample.

The error you've posted actually tells you exactly what the issue is. You have an issue with your Entitlements that's keeping it from running on the iOS Simulator.

For more information you'll want to check out the docs here:

https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-xamarin-ios-considerations

var builder = PublicClientApplicationBuilder
     .Create(ClientId)
     .WithIosKeychainSecurityGroup("com.microsoft.adalcache")
     .Build();

and in your Entitlements.plist you'll want to update to something like:

<dict>
  <key>keychain-access-groups</key>
  <array>
    <string>$(AppIdentifierPrefix)com.microsoft.adalcache</string>
  </array>
</dict>


问:
Detecting common colors for groups of objects
I have an image with a collection of objects in K given perceived colors. Providing I extract those objects, how could I cluster them by their perceived color?

Let me give you an example. I am trying to cluster two football teams - so there will be two teams, referees and a keeper (or two, but that`s a rare situation) on the image - 3, 4 or 5 clusters.

For a human's eye, it`s an easy situation. On the picture above, we have white players, red players and a black ref. But it turns out not so easy for automatic processing.

What I have tried so far:

1) I've started working on the BGR colorspace, then tried HSV and now I am exploring CIE Luv, as I read it has unified distances describing the perceived differences between colors.

2) [BGR and HSV] taking the most common color from the contour (not the bounding box). this didn' work at all because of the noise (green field getting in the way), the quality of the image, the position of the player, etc. Colors were pretty much random.

3) [CIE Luv] Resizing all players' boxes to a common size and taking a small portion of the image from the middle (as marked by a black rectangle in the example below).

Taking the mean value of all pixels in each player's window  and adding to the list (so, it`s one pixel with the mean value per player). Using K-means (with a defined number of clusters) to find out clusters on that list. This has proven somewhat successful, for the image above I have redish, white and blackish centres in the clusters.

Unfortunately, the assignment of players back to these clusters is pretty much random. I am doing that by calculating the mean color for each player like I described above and then measuring the distance to each cluster. A player might be assigned to the white cluster on one frame and to the red one on the next. Part of the problem might be that the window in the middle of the player's box will sometimes catch a number, grass or shorts, instead of the jersey.

I have already spent a considerable amount of time on trying to figure that out, grateful for any help.

答:
I may be overcomplicating the problem since you just have 3 classes, but try training an SVM classifier based on HOG descriptors. maybe try LDA to improve speed

Some references -

1] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.627.6465&rep=rep1&type=pdf - skip to recognition part

2] https://rodrigob.github.io/documents/2013_ijcnn_traffic_signs.pdf - skip to recognition part.

3] https://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial/ - if you want to jump into the code right away

This will always work as long as your detection is good. and can also help to identify different players  based on their shirt number
(maybe more???) if you train it right

EDIT: Okkay I have another idea, based on colour segmentation since that was your original approach and require less work (maybe not? color segmentation is a pain! also LIGHTING! LIGHTING! LIGHTING!).
Create a green mask and create a threshold so you detect as little grass as possible when doing your kmeans. Then instead of finding mean, try median instead, that will get you closer to red, coz white is detected as 0 and mean just drops drastically, median doesnt. So it'll be way more robust and you should be able to sort players better (hair color and skin color shouldnt affect it too much)

EDIT 2: Just noticed, if you use the black rectangle you'll get shirt number more (which is white), gonna mess up your classifier, use original box with green masked out

EDIT 3: Also. You can just create 3 thresholds for your required colors and split them up! don't really need Kmeans in this actually. Basically you just need your detected boxes to give out a value inside that threshold. Try the median method I mentioned above. Should improve. Also, might need some more minor tweaks here and there (blur, morphology etc to improve detection)


问:
How to share dynamic text content of DIV or SPAN on whatsapp using jquery?
I have been trying to share text content of DIV on whatsapp. But, no success yet. I do not want to share the whole document. I just want to share a part of it (I want to share contents of showques only).

Here is my code:

SHARE IN WHATSAPP
```

<p>Value of <code>showques</code> gets updated from the following code:</p>

<pre class="lang-js prettyprint-override"><code><script>
function nxtRiddle() {
        var chooserdl = [];
        for (i = 0; i < 164; i++) {
            chooserdl.push(i);
        }
        console.log(chooserdl);
        var riddleno = chooserdl[Math.floor(Math.random() * chooserdl.length)];
        console.log(riddleno);
        $('#showques').append(riddleques[riddleno]);
        $('#showans').append(riddleans[riddleno]);
        return;
    }
    nxtRiddle(0);
</script>
</code>```

答:
First you need to get the content of the question from DOM.
Then you'll have to trigger the link click event from JS and open a new tab with correct WhatsApp url. Hope this will help.

document.getElementById("whatsAppShareButton").addEventListener('click', function(e) {
  e.preventDefault();
  var question = encodeURIComponent(document.getElementById("showques").textContent);
  window.open('whatsapp://send?text=' + question, '_blank');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="showques" style="font-size: 48px;">
  This is a sample question...
</div>
<div id="showans" style="font-size: 48px;">
</div>
SHARE IN WHATSAPP</code>```

Body:
I have been trying to share text content of DIV on whatsapp. But, no success yet. I do not want to share the whole document. I just want to share a part of it (I want to share contents of showques only).

Here is my code:

SHARE IN WHATSAPP

Value of showques gets updated from the following code:

Body:
First you need to get the content of the question from DOM.
Then you'll have to trigger the link click event from JS and open a new tab with correct WhatsApp url. Hope this will help.

document.getElementById("whatsAppShareButton").addEventListener('click', function(e) {
  e.preventDefault();
  var question = encodeURIComponent(document.getElementById("showques").textContent);
  window.open('whatsapp://send?text=' + question, '_blank');
});

<div id="showques" style="font-size: 48px;">
  This is a sample question...
</div>
<div id="showans" style="font-size: 48px;">
</div>
<a href="#" id="whatsAppShareButton" data-action="share/whatsapp/share" style="background-color: green; color: ivory;font-size: 48px;height:48px;width:500px">SHARE IN WHATSAPP</a>


问:
DASK SSH Cluster in Jupyter Notebook
UPDATE
I have copied over the SSH keys to all my machines and they are able to communicate without a password, however I still need to specify the username@hostname instead of just the hostname.
I tried many different methods with no luck:
Method 1: I input the following on my jupyter notebook:

```<code>from dask.distributed import Client, SSHCluster
cluster = SSHCluster(
["localhost", username@hostname],
connect_options={"known_hosts": None},
worker_options={"nthreads": 2},
 )
client = Client(cluster)
</code>```

I understand the connect_options is what the asyncio library does to connect ssh so I thought known_hosts is ok since it looks like the authorized keys in my .ssh directory.
However, I keep getting the following error:

```<code> ~/anaconda3/lib/python3.7/concurrent/futures/thread.py in run(self)
 55
 56         try:
 57             result = self.fn(*self.args, **self.kwargs)
 58         except BaseException as exc:
 59             self.future.set_exception(exc)

~/anaconda3/lib/python3.7/socket.py in getaddrinfo(host, port, family, type,
proto, flags)
750     # and socket type values to enum constants.
751     addrlist = []
--> 752     for res in _socket.getaddrinfo(host, port, family, type, proto,
flags):
753         af, socktype, proto, canonname, sa = res
754         addrlist.append((_intenum_converter(af, AddressFamily),

gaierror: [Errno -2] Name or service not known
</code>```

The second method I tried was dask-ssh which I typed the following in the command line:

```<code>dask-ssh localhost username@hostname username@hostnameb --nprocs 10
</code>```

However, when I open the dashboard I don't see anything from the worker nodes from the remote machines in the dashboard, only the 10 workers from the localhost.

Please help, I read tutorials, looked at Stack Overflow, I even tried Kubernetes (microk8s, k3s, minikube, kubeadm) and Apache Hadoop/Yarn with many many hours failed results and dask ssh seems to be my only hope.
I also like Dask because the dashboard looks better than Hadoop (that yellow elephant kinda bugs me).

PREVIOUS
I'm trying to create a DASK cluster between my machines at home using Jupyter Notebook.
I understand the concept behind schedulers, workers and clients.
On the Dask Docs, they provided the following example which I'm having a hard time figuring out how to make it work:

```<code>from dask.distributed import Client,SSHCluster
cluster = SSHCluster(
          [["localhost", "localhost", "localhost", "localhost"],
           connect_options={"known_hosts": None},
           worker_options={"nthreads": 2},
           scheduler_options={"port": 0, "dashboard_address": ":8797"}
           client = Client(cluster)
</code>```

My question is how do I configure SSHCluster so I can create a cluster between different machines. How do I set the IP address, username, and password?
I understand there are better options out there like Hadoop/Yarn, Kubernetes etc, but I wanted to understand the SSH cluster concept through Jupyter Notebook.

Thanks,

答:
The documentation tells you what to do.

How do I set the IP address, username, and password?

replace the list of "localhost"s with the names or IP addresses of the machines you want to connect to. You must be able to log into each with SSH without username/password, and they must all have identical python environments set up

do not try to use username/password, set up key-based auth; there are many ways to do this, so pick a simple one

SSH cluster concept through Jupyter Notebook

Use of a notebook is immaterial here, you are executing python just the same.

there are better options out there like Hadoop/Yarn, Kubernetes

Many many people use SSH, because it is very simple, but it does leave you to manage any orchestration (e.g., making sure machines are on the same network and can communicate, and managing environments).

-EDIT-

(to updated question)

Reading the asyncSSH documentation, you want to pass an option called username= on connect_option (see here). asyncssh does not currently support using a ~/.ssh config file to define targets, unfortunately, so if you have different options for each server, you are out of luck.

Note that if you are doing something very custom, you do not need to use dask-ssh at all, you can login and run dask explicitly on each server.

Title: DASK SSH Cluster in Jupyter Notebook

Body:
UPDATE
I have copied over the SSH keys to all my machines and they are able to communicate without a password, however I still need to specify the username@hostname instead of just the hostname.
I tried many different methods with no luck:
Method 1: I input the following on my jupyter notebook:

from dask.distributed import Client, SSHCluster
cluster = SSHCluster(
["localhost", username@hostname],
connect_options={"known_hosts": None},
worker_options={"nthreads": 2},
 )
client = Client(cluster)

I understand the connect_options is what the asyncio library does to connect ssh so I thought known_hosts is ok since it looks like the authorized keys in my .ssh directory.
However, I keep getting the following error:

 ~/anaconda3/lib/python3.7/concurrent/futures/thread.py in run(self)
 55
 56         try:
 57             result = self.fn(*self.args, **self.kwargs)
 58         except BaseException as exc:
 59             self.future.set_exception(exc)

~/anaconda3/lib/python3.7/socket.py in getaddrinfo(host, port, family, type,
proto, flags)
750     # and socket type values to enum constants.
751     addrlist = []
--> 752     for res in _socket.getaddrinfo(host, port, family, type, proto,
flags):
753         af, socktype, proto, canonname, sa = res
754         addrlist.append((_intenum_converter(af, AddressFamily),

gaierror: [Errno -2] Name or service not known

The second method I tried was dask-ssh which I typed the following in the command line:

dask-ssh localhost username@hostname username@hostnameb --nprocs 10

However, when I open the dashboard I don't see anything from the worker nodes from the remote machines in the dashboard, only the 10 workers from the localhost.

Please help, I read tutorials, looked at Stack Overflow, I even tried Kubernetes (microk8s, k3s, minikube, kubeadm) and Apache Hadoop/Yarn with many many hours failed results and dask ssh seems to be my only hope.
I also like Dask because the dashboard looks better than Hadoop (that yellow elephant kinda bugs me).

PREVIOUS
I'm trying to create a DASK cluster between my machines at home using Jupyter Notebook.
I understand the concept behind schedulers, workers and clients.
On the Dask Docs, they provided the following example which I'm having a hard time figuring out how to make it work:

from dask.distributed import Client,SSHCluster
cluster = SSHCluster(
          [["localhost", "localhost", "localhost", "localhost"],
           connect_options={"known_hosts": None},
           worker_options={"nthreads": 2},
           scheduler_options={"port": 0, "dashboard_address": ":8797"}
           client = Client(cluster)

My question is how do I configure SSHCluster so I can create a cluster between different machines. How do I set the IP address, username, and password?
I understand there are better options out there like Hadoop/Yarn, Kubernetes etc, but I wanted to understand the SSH cluster concept through Jupyter Notebook.

Thanks,


问:
check if database exits in union sql server
i want to union query from multiple database. but before union i want to check if database exits then union, if second database exits then union and so on...

```<code>IF EXISTS(SELECT * FROM sys.sysdatabases where name='FirstDB')
select * from FirstDB.dbo.tablename
union
IF EXISTS(SELECT * FROM sys.sysdatabases where name='SecondDB')
select * from SecondDB.dbo.tablename.
</code>```

How to do that.
Thanks in advance.

答: Selecting databases or tables on runtime is code smell. It might be valid in your case, but it's certainly suspect. If you have any control over the databases being used, consider re-evaluating your database design. Are databases created and destroyed on runtime? That is almost certainly a bad idea.</p>

Body:
i want to union query from multiple database. but before union i want to check if database exits then union, if second database exits then union and so on...

IF EXISTS(SELECT * FROM sys.sysdatabases where name='FirstDB')
select * from FirstDB.dbo.tablename
union
IF EXISTS(SELECT * FROM sys.sysdatabases where name='SecondDB')
select * from SecondDB.dbo.tablename.

How to do that.
Thanks in advance.


问:
How to draw a rectangle in a html file dynamically using javascript ? Google chrome extension Page Ruler have similar feature
I want to draw rectangles over texts or paragraphs in a HTML file. I want to achieve this using javascript without the use of canvas. Multiple rectangles can also exist for selecting multiple paragraphs. Is there any library for achieving this kind of functionality.

Click here to see the intended result

page Ruler link here https://chrome.google.com/webstore/detail/page-ruler-redux/giejhjebcalaheckengmchjekofhhmal?hl=en-US

答:
You can use the absolute positioned div element to draw a rectangle over the web page. You need to listen for events when the user presses the mouse button (mousedown), when the user moves the mouse (mousemove), and when the user releases the button (mouseup). Here is a simple example:

```<code>const rectangle = document.createElement("div");
rectangle.style.position = "absolute";
rectangle.style.backgroundColor = "rgba(204,230,255, 0.7)";
rectangle.style.border = "1px dashed black";
document.body.appendChild(rectangle);

    let isDragged = false;
    let rectangleCoords = [];

    const clearRectangleCoords = () => {
        rectangleCoords = [];
    };

    const addFirstRectangleCoords = coords => {
        rectangleCoords[0] = coords;
    };

    const addSecondRectangleCoords = coords => {
        rectangleCoords[1] = coords;
    };

    const redrawRectangle = () => {
        const top = Math.min(rectangleCoords[0].y, rectangleCoords[1].y);
        const height = Math.max(rectangleCoords[0].y, rectangleCoords[1].y) - top;
        const left = Math.min(rectangleCoords[0].x, rectangleCoords[1].x);
        const width = Math.max(rectangleCoords[0].x, rectangleCoords[1].x) - left;
      rectangle.style.top = top + "px";
      rectangle.style.height = height + "px";
      rectangle.style.left = left + "px";
      rectangle.style.width = width + "px";
    };

    window.addEventListener("mousedown", e => {
        isDragged = true;
      clearRectangleCoords();
      addFirstRectangleCoords({x: e.pageX, y: e.pageY});
      addSecondRectangleCoords({x: e.pageX, y: e.pageY});
      redrawRectangle();
    });

    window.addEventListener("mousemove", e => {
        if (isDragged) {
        addSecondRectangleCoords({x: e.pageX, y: e.pageY});
        redrawRectangle();
      }
    });

    window.addEventListener("mouseup", e => {
        if (isDragged) {
        addSecondRectangleCoords({x: e.pageX, y: e.pageY});
        redrawRectangle();
            isDragged = false;
      }
    });
</code>```

You can play with the code on JSFiddle

Body:
You can use the absolute positioned div element to draw a rectangle over the web page. You need to listen for events when the user presses the mouse button (mousedown), when the user moves the mouse (mousemove), and when the user releases the button (mouseup). Here is a simple example:

const rectangle = document.createElement("div");
rectangle.style.position = "absolute";
rectangle.style.backgroundColor = "rgba(204,230,255, 0.7)";
rectangle.style.border = "1px dashed black";
document.body.appendChild(rectangle);

    let isDragged = false;
    let rectangleCoords = [];

    const clearRectangleCoords = () => {
        rectangleCoords = [];
    };

    const addFirstRectangleCoords = coords => {
        rectangleCoords[0] = coords;
    };

    const addSecondRectangleCoords = coords => {
        rectangleCoords[1] = coords;
    };

    const redrawRectangle = () => {
        const top = Math.min(rectangleCoords[0].y, rectangleCoords[1].y);
        const height = Math.max(rectangleCoords[0].y, rectangleCoords[1].y) - top;
        const left = Math.min(rectangleCoords[0].x, rectangleCoords[1].x);
        const width = Math.max(rectangleCoords[0].x, rectangleCoords[1].x) - left;
      rectangle.style.top = top + "px";
      rectangle.style.height = height + "px";
      rectangle.style.left = left + "px";
      rectangle.style.width = width + "px";
    };

    window.addEventListener("mousedown", e => {
        isDragged = true;
      clearRectangleCoords();
      addFirstRectangleCoords({x: e.pageX, y: e.pageY});
      addSecondRectangleCoords({x: e.pageX, y: e.pageY});
      redrawRectangle();
    });

    window.addEventListener("mousemove", e => {
        if (isDragged) {
        addSecondRectangleCoords({x: e.pageX, y: e.pageY});
        redrawRectangle();
      }
    });

    window.addEventListener("mouseup", e => {
        if (isDragged) {
        addSecondRectangleCoords({x: e.pageX, y: e.pageY});
        redrawRectangle();
            isDragged = false;
      }
    });

You can play with the code on JSFiddle