问:
Multithreaded quicksort or mergesort
How can I implement a concurrent quicksort or mergesort algorithm for Java?

We've had issues on a 16-(virtual)-cores Mac where only one core (!) was working using the default Java sorting algo and it was, well, not good to see that very fine machine be completely underused.  So we wrote our own (I wrote it) and we did indeed gain good speedups (I wrote a multithreaded quicksort and due to its partitioning nature it parallelize very well but I could have written a mergesort too)...  But my implementation only scales up to 4 threads, it's proprietary code, and I'd rather use one coming from a reputable source instead of using my re-invented wheel.

The only one I found on the Web is an example of how not to write a multi-threaded quicksort in Java, it is busy-looping (which is really terrible) using a:

```<code>while (helpRequested) { }
</code>```

http://broadcast.oreilly.com/2009/06/may-column-multithreaded-algor.html

So in addition to losing one thread for no reason it's making sure to kill the perfs by busy-looping in that while loop (which is mindboggling).

Hence my question: do you know of any correctly multithreaded quicksort or mergesort implementation in Java that would be coming from a reputable source?

I put the emphasis on the fact that I know that the complexity stays O(n log n) but I'd still enjoy very much to see all these cores start working instead of idling.  Note that for other tasks, on that same 16 virtual cores Mac, I saw speedup of up to x7 by parallelizing the code (and I'm by no mean an expert in concurrency).

So even tough the complexity stays O(n log n), I'd really appreciate a x7 or x8 or even x16 speedup.

答:
Just coded up the above MergeSort and performance was very poor.

The code block refers to "coInvoke(left, right);" but there was no reference to this and replaced it with invokeAll(left, right);

Test code is:

```<code>MergeSort mysort = new MyMergeSort(array,0,array.length);
ForkJoinPool threadPool = new ForkJoinPool();
threadPool.invoke(mysort);
</code>```

but had to stop it due to poor performance.

I see that the article above is almost a year old and maybe things have changed now.

I have found the code in the alternative article to work: http://blog.quibb.org/2010/03/jsr-166-the-java-forkjoin-framework/

Title: Multithreaded quicksort or mergesort

Body:
How can I implement a concurrent quicksort or mergesort algorithm for Java?

We've had issues on a 16-(virtual)-cores Mac where only one core (!) was working using the default Java sorting algo and it was, well, not good to see that very fine machine be completely underused.  So we wrote our own (I wrote it) and we did indeed gain good speedups (I wrote a multithreaded quicksort and due to its partitioning nature it parallelize very well but I could have written a mergesort too)...  But my implementation only scales up to 4 threads, it's proprietary code, and I'd rather use one coming from a reputable source instead of using my re-invented wheel.

The only one I found on the Web is an example of how not to write a multi-threaded quicksort in Java, it is busy-looping (which is really terrible) using a:

while (helpRequested) { }

http://broadcast.oreilly.com/2009/06/may-column-multithreaded-algor.html

So in addition to losing one thread for no reason it's making sure to kill the perfs by busy-looping in that while loop (which is mindboggling).

Hence my question: do you know of any correctly multithreaded quicksort or mergesort implementation in Java that would be coming from a reputable source?

I put the emphasis on the fact that I know that the complexity stays O(n log n) but I'd still enjoy very much to see all these cores start working instead of idling.  Note that for other tasks, on that same 16 virtual cores Mac, I saw speedup of up to x7 by parallelizing the code (and I'm by no mean an expert in concurrency).

So even tough the complexity stays O(n log n), I'd really appreciate a x7 or x8 or even x16 speedup.

Body:
Just coded up the above MergeSort and performance was very poor.

The code block refers to "coInvoke(left, right);" but there was no reference to this and replaced it with invokeAll(left, right);

Test code is:

MergeSort mysort = new MyMergeSort(array,0,array.length);
ForkJoinPool threadPool = new ForkJoinPool();
threadPool.invoke(mysort);

but had to stop it due to poor performance.

I see that the article above is almost a year old and maybe things have changed now.

I have found the code in the alternative article to work: http://blog.quibb.org/2010/03/jsr-166-the-java-forkjoin-framework/


来源: stackexchange

问:
Datetime index filtering and changing of values

Date
COL_1
COL_2

2017-04-21
0.0
NaN

2017-04-24
1.0
0.0

2017-04-25
0.0
-1.0

Have the following table in datetime index.

What's the best way do I put in a conditional statement to filter where if COL_1 of the earliest index date is 0, COL_2 of the earliest index date, (Nan), is set to -1.

Need to keep it dynamic and filter without mentioning the specific dates.

Thanks!

ContentLicense: CC BY-SA 4.0

Body:
IIUC:

df.loc[(df.index == df.index.min()) & (df['COL_1'] == 0), 'COL_2'] = -1
print(df)

# Output
            COL_1  COL_2
2017-04-21    0.0   -1.0
2017-04-24    1.0    0.0
2017-04-25    0.0   -1.0


问:
How to iterate over a vue getter
I have this getter this.getHouseTypes it returns an array with objects from the vuex store.

But now i want to append 1 item to the array in the shortest way so i was thinking about ... like:

```<code>return [...this.getHouseTypes, newObject];
</code>```

But that gives me an error:

```<code>Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
</code>```

Does anyone know why this is ?

Any help is welcome !

EDIT: but in the vue inspector it shows the new array with this.getHouseTypes and newObject in it

答:
Sounds more like you should do something like this:

```<code>import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      houseTypes: [],
    }
  }
  // ...
  computed: {
    addHouseType(newType) {
      let houseTypes = this.getHouseTypes();

      this.houseTypes = this.houseTypes.concat(houseTypes).push(newType);

      return this.houseTypes;
    },
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'getHouseTypes',
      // ...
    ])
  }
}
</code>```

Have a data variable houseTypes, which is an empty array in the beginning.

Mix your getters, with your computed.

Have a computed that adds values to the local houseTypes and merges the store state.

Depending on what you are doing, you might want to split the adding and retrieving the new array.

Title: How to iterate over a vue getter

Body:
I have this getter this.getHouseTypes it returns an array with objects from the vuex store.

But now i want to append 1 item to the array in the shortest way so i was thinking about ... like:

return [...this.getHouseTypes, newObject];

But that gives me an error:

Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

Does anyone know why this is ?

Any help is welcome !

EDIT: but in the vue inspector it shows the new array with this.getHouseTypes and newObject in it

Body:
Sounds more like you should do something like this:

import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      houseTypes: [],
    }
  }
  // ...
  computed: {
    addHouseType(newType) {
      let houseTypes = this.getHouseTypes();

      this.houseTypes = this.houseTypes.concat(houseTypes).push(newType);

      return this.houseTypes;
    },
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'getHouseTypes',
      // ...
    ])
  }
}

Have a data variable houseTypes, which is an empty array in the beginning.

Mix your getters, with your computed.

Have a computed that adds values to the local houseTypes and merges the store state.

Depending on what you are doing, you might want to split the adding and retrieving the new array.


问:
Firebase V9 with React Native - Display Name updating too slow
I am new to react, firebase and stack overflow so please bear with me.
I'm trying to create a user registration form with firebase that includes a 'name' input. It does work to update the display name, but not fast enough to show the name when the user first logs in. I need to save the homescreen.js file and then the display name populates.

code from registerscreen.js

```<code> const [name, setName] = useState('')

const handleRegister = async () => {
if (confirmPass !== password){
  alert('Passwords Do Not Match')
  return false}
  else{
}
try{
const user = await createUserWithEmailAndPassword(auth, email, password)
updateProfile(auth.currentUser, {displayName: name})
console.log('logged in with', user.email)
} catch (error) {
    alert(error.message);
}
</code>```

and here is the text on the homescreen.js to display the users name:

```<code> <Text style={styles.text}>Logged in as {auth.currentUser?.displayName}</Text>
</code>```

答:
Just like createUserWithEmailAndPassword, the call to `updateProfile is an asynchronous call, so you'll want to await until it's done:

```<code>await updateProfile(auth.currentUser, {displayName: name})
</code>```

Body:
I am new to react, firebase and stack overflow so please bear with me.
I'm trying to create a user registration form with firebase that includes a 'name' input. It does work to update the display name, but not fast enough to show the name when the user first logs in. I need to save the homescreen.js file and then the display name populates.

code from registerscreen.js

 const [name, setName] = useState('')

const handleRegister = async () => {
if (confirmPass !== password){
  alert('Passwords Do Not Match')
  return false}
  else{
}
try{
const user = await createUserWithEmailAndPassword(auth, email, password)
updateProfile(auth.currentUser, {displayName: name})
console.log('logged in with', user.email)
} catch (error) {
    alert(error.message);
}

and here is the text on the homescreen.js to display the users name:

 <Text style={styles.text}>Logged in as {auth.currentUser?.displayName}</Text>

Body:
Just like createUserWithEmailAndPassword, the call to `updateProfile is an asynchronous call, so you'll want to await until it's done:

await updateProfile(auth.currentUser, {displayName: name})


问:
what's the difference between those two similar __init__ definitions in python?
what's the difference between

1)

```<code>def __init__(self): pass
</code>```

and

2)

```<code>def __init__(self) -> None: pass
</code>```

thank you for your help!

答:
In second one, you annotated the method and explicitly said that the return value of the __init__ method should be None.

Every function/method in Python will implicitly return None if you don't have any return statement in the body. It is necessary for __init__ to return None, otherwise you will get the error TypeError: __init__() should return None, in instantiation.

Annotation is optional and won't throw an error if you put different value from the specified one:

def fn() -> str:
    return 10

print(fn())  # 10
```
<p>But returning None is a must for <code>__init__</code>.</p>
<pre class="lang-py prettyprint-override"><code>class A:
    def __init__(self):
        return 10

obj = A()  # TypeError: __init__() should return None, not 'int'
</code>```

Body:
what's the difference between

1)

def __init__(self): pass

and

2)

def __init__(self) -> None: pass

thank you for your help!

Body:
In second one, you annotated the method and explicitly said that the return value of the __init__ method should be None.

Every function/method in Python will implicitly return None if you don't have any return statement in the body. It is necessary for __init__ to return None, otherwise you will get the error TypeError: __init__() should return None, in instantiation.

Annotation is optional and won't throw an error if you put different value from the specified one:

def fn() -> str:
    return 10

print(fn())  # 10

But returning None is a must for __init__.

class A:
    def __init__(self):
        return 10

obj = A()  # TypeError: __init__() should return None, not 'int'


问:
Google Cloud Run - Using GitHub for continuous deployment : Your build failed to run: generic::invalid_argument: invalid build: invalid image name
After creating a successful build using gbuild I wanted to start the continues deployment function but on trigger it failed instantly with the name: Your build failed to run: generic::invalid_argument: invalid build: invalid image name

The answer is: don't use capital letters in your GitHub Repository Name as Google Cloud Run doesn't seem to like it and it causes that very vague error message

(Posting it here as a question/answer as it took my hours to figure out)

答: If you are using the the repo name parameter with $ and the repo name contains capital letters, the build fails. This issue is related to the gcr image creation as the build starts. When I replaced the parameterized repo name with a lower case letters for the container name, instead of the capitalized repo name, for the gcr image location, my build went through.


问:
Error "Error: A <Route> is only ever to be used as the child of <Routes> element"
I am trying to use routing for the first time and followed the exact instructions from Udemy:

File App.js:

```<code>import { Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div>
            <Route path = "/welcome">
                <Welcome />
            </Route>
            <Route path = "/game">
                <Game />
            </Route>
            <Route path = "/leaderboard">
                <Leaderboard />
            </Route>
        </div>
    );
}

export default App;
</code>```

File index.js

```<code>import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById('root')
);
</code>```

I get the following error:

Error: A Route is only ever to be used as the child of
element, never rendered directly. Please wrap your Route in a Routes.

Where have I gone wrong?

答:
I think there are many problems that can lead to that issue.

react-router-dom version 6 no longer supports the use of components directly. Use an element to specify the component you route.

Route has to be a child of Routes

Use the simple snippet.

import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
import Homescreen from './screens/Homescreen';

function App() {
  return (

      <Navbar/>
      <BrowserRouter>
        <Routes>
          <Route path='/home' element={<Homescreen/>} />
        </Routes>

      </BrowserRouter>

  );
}

export default App;```

Body:
I am trying to use routing for the first time and followed the exact instructions from Udemy:

File App.js:

import { Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (

            <Route path = "/welcome">
                <Welcome />
            </Route>
            <Route path = "/game">
                <Game />
            </Route>
            <Route path = "/leaderboard">
                <Leaderboard />
            </Route>

    );
}

export default App;

File index.js

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById('root')
);

I get the following error:

Error: A Route is only ever to be used as the child of
element, never rendered directly. Please wrap your Route in a Routes.

Where have I gone wrong?

Body:
I think there are many problems that can lead to that issue.

react-router-dom version 6 no longer supports the use of components directly. Use an element to specify the component you route.

Route has to be a child of Routes

Use the simple snippet.

import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
import Homescreen from './screens/Homescreen';

function App() {
  return (
    <div className="App">
      <Navbar/>
      <BrowserRouter>
        <Routes>
          <Route path='/home' element={<Homescreen/>} />
        </Routes>

      </BrowserRouter>

    </div>
  );
}

export default App;


问:
Extendscript in Indesign not creating or writing to file
I am writing a script for Indesign that collects the contents from TextStyleRange objects, adds them to a javascript object, and should then write out a JSON file with the stringified JSON.

I can create the JSON just fine, with the contents from all of the TextStyleRanges in the current document, however the final file never gets written.

Here is a simplified example of what I have:

#include "json2.js";
main();
function main(){
    myObj = { "key_1": "value_1", "key_2": "value_2" };
    myContents = JSON.stringify(myObj, null, 4);
    myFile = new File("~/Documents/myproject/en/translation.json");
    myFile.open("w");
    myFile.write( myContents );
    $.writeln( myContents );
    myFile.close();
}
```
<p>In the VSCode debugger I can correctly see the JSON being output by <code>$.writeln</code>, however the file is not being created on disk. Any ideas what might be going wrong?</p>
<p>I'm using Windows 10, and Adobe Indesign 2022.</p>
<p>I have also tried with file edit but no luck:</p>
<pre class="lang-js prettyprint-override"><code>myFile.open("e", "????", "????");
</code>```

答:
Actually it was simply that I needed to create the subfolder first:

var parentFolder = myFile.parent;
if (!parentFolder.exists && !parentFolder.create())
    throw new Error("Cannot create file in path " + myFile.fsName);
```

After adding this to my script the folder and the file were created successfully.

Body:
I am writing a script for Indesign that collects the contents from TextStyleRange objects, adds them to a javascript object, and should then write out a JSON file with the stringified JSON.

I can create the JSON just fine, with the contents from all of the TextStyleRanges in the current document, however the final file never gets written.

Here is a simplified example of what I have:

#include "json2.js";
main();
function main(){
    myObj = { "key_1": "value_1", "key_2": "value_2" };
    myContents = JSON.stringify(myObj, null, 4);
    myFile = new File("~/Documents/myproject/en/translation.json");
    myFile.open("w");
    myFile.write( myContents );
    $.writeln( myContents );
    myFile.close();
}

In the VSCode debugger I can correctly see the JSON being output by $.writeln, however the file is not being created on disk. Any ideas what might be going wrong?

I'm using Windows 10, and Adobe Indesign 2022.

I have also tried with file edit but no luck:

myFile.open("e", "????", "????");

Body:
Actually it was simply that I needed to create the subfolder first:

var parentFolder = myFile.parent;
if (!parentFolder.exists && !parentFolder.create())
    throw new Error("Cannot create file in path " + myFile.fsName);

After adding this to my script the folder and the file were created successfully.


问:
url path with image variable in image source uri React Native
I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

```<code><FlatList
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}
renderItem={({item}) => {
   return (

    <Image
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    />

   )
}}
/>
</code>```

Thanks for the help

答:
Thank you all for the respond, but I find the answer

First I define the url const URL = 'https://placewave.com/avatar';

Then Include it:

```<code><Image
     source={{ uri: URL + '/' + item.user_image}}
     resizeMode="cover"
     style={styles.userImage}
/>
</code>```

Body:
I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

<FlatList
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}
renderItem={({item}) => {
   return (

    <Image
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    />

   )
}}
/>

Thanks for the help

Body:
Thank you all for the respond, but I find the answer

First I define the url const URL = 'https://placewave.com/avatar';

Then Include it:

<Image
     source={{ uri: URL + '/' + item.user_image}}
     resizeMode="cover"
     style={styles.userImage}
/>


问:
How to use literal haskell functions in DSL?
I'd like to use literal haskell functions in a dsl as follows:

program :: forall m . DSL m => m ()
program = do
  stm $ Stm (Var "a")
  -- this way:
  f <- fun $ \(a :: Expr a) (b :: Expr b) -> do
    -- function body is of the same monad `m` as the one in top level
    stm $ Stm (Var "b")
  stm $ Stm $ Apply f (Var "c")
  pure ()
```
<p>.. and turn the above into code (<code>[Stm]</code>).</p>
<p>To make the functions work there is a helper class <code>Fun</code> (code below)
that saturates the function with fresh variables until it reaches
function body,
then returns both the list of arguments and body itself so that they
could be made into function syntax[1]. There is a recursive case to
generate arguments[2] and a base case to evaluate body to <code>[Stm]</code>.[3]</p>
<p>The worrisome instance is the base case[4], which currently requires
<code>{-# INCOHERENT #-}</code>, because ghc can't choose a Fun instance because
function's body in the <code>program</code> is ambiguous (while it should just be
whatever <code>m</code> is at top level code).</p>
<p>So the question is:</p>
<ul>
<li>is there a way to force the body to always use the
same <code>m</code> as in top level and not require incoherent instances?</li>
</ul>
<hr />
<p>A stub AST, the MTL-style DSL "effect" and a sample instance of the class:</p>
<pre class="lang-hs prettyprint-override"><code>-- | An AST
data Expr a
  = Var String
  | Apply String (Expr a)
  | Function String [String] [Stm]

data Stm = Stm (Expr ())

-- | The "effect"
class Monad m => DSL m where
  freshName :: m String -- generate fresh variable name
  stm :: Stm -> m () -- emit statement
  toAST :: m a -> m [Stm] -- turn code `m a` into [Stm] (without emitting it)
  fun :: Fun f m => f -> m String -- emit function f, return its name

-- | Helper class to convert literal haskell functions to the dsl
class Fun f m where
  mkFun :: DSL m => f -> [String] -> m ([String], [Stm])

instance Fun f m => Fun (Expr a -> f) m where
  mkFun f acc = do
    name <- freshName -- [2]
    mkFun (f $ Var name) (name : acc)

instance {-# INCOHERENT #-} (m0 ~ m) => Fun (m0 a) m where -- [4]
  mkFun m args = do
    fname <- freshName
    body <- toAST m -- [3]
    return (args, body)

-- | A sample implementation
instance DSL (StateT Int (Writer [Stm])) where
  freshName = do
    n <- get
    put $ n + 1
    return $ "var" <> show n
  stm stm' = tell [stm']
  toAST m = do
    state0 <- get
    let ((_, state1), w) = run m state0
    put state1
    return w
  fun f = do
    (args, body) <- mkFun f []
    name <- freshName
    stm $ Stm $ Function name args body -- [1]
    return name

run :: StateT Int (Writer [Stm]) a -> Int -> ((a, Int), [Stm])
run m s = runWriter $ runStateT m s
</code>```

答:
I guess one way is to mark the base case of the recursion yourself.

```<code>newtype Cook m a = Cook (m a)
deriving instance DSL m => DSL (Cook m)

instance Fun f m => Fun (Expr a -> f) m
instance m0 ~ m => Fun (Cook m0 a) (Cook m)

type SampleImplRaw = StateT Int (Writer [Stm])
type SampleImpl = Cook SampleImplRaw

instance DSL SampleImpl
</code>```

I haven't typed this into the compiler, so I'm not sure, but it may be that you get into a funny situation where you want a DSL m instance, and have a DSL (Cook m) instance in scope, but the compiler can't figure out how to get from A to B. In such a case it should be possible to coerce the offending term to use the Cook m instance.

Another way might be to try making the base case have a different kind. Something like this:

```<code>instance Fun f m => Fun (Expr a -> f) m
instance (m ~ m', p ~ p', p ~ '()) => Fun (m p a) (m' p')

data SampleImplRaw (x :: ()) a = {- whatever you would have written before for new data declarations -}
type SampleImpl = SampleImplRaw '()
newtype Const1 (x :: ()) m a = Const1 (m a) deriving (EVERYTHING) -- still need a cook for mere monad transformer stacks
</code>```

I guess probably if your plan is mostly to use transformer stacks, the first one will be less roundabout; if your plan is mostly to define new data types, the second will have a cleaner user experience.

Body:
I'd like to use literal haskell functions in a dsl as follows:

program :: forall m . DSL m => m ()
program = do
  stm $ Stm (Var "a")
  -- this way:
  f <- fun $ \(a :: Expr a) (b :: Expr b) -> do
    -- function body is of the same monad `m` as the one in top level
    stm $ Stm (Var "b")
  stm $ Stm $ Apply f (Var "c")
  pure ()

.. and turn the above into code ([Stm]).

To make the functions work there is a helper class Fun (code below)
that saturates the function with fresh variables until it reaches
function body,
then returns both the list of arguments and body itself so that they
could be made into function syntax[1]. There is a recursive case to
generate arguments[2] and a base case to evaluate body to [Stm].[3]

The worrisome instance is the base case[4], which currently requires
{-# INCOHERENT #-}, because ghc can't choose a Fun instance because
function's body in the program is ambiguous (while it should just be
whatever m is at top level code).

So the question is:

is there a way to force the body to always use the
same m as in top level and not require incoherent instances?

A stub AST, the MTL-style DSL "effect" and a sample instance of the class:

-- | An AST
data Expr a
  = Var String
  | Apply String (Expr a)
  | Function String [String] [Stm]

data Stm = Stm (Expr ())

-- | The "effect"
class Monad m => DSL m where
  freshName :: m String -- generate fresh variable name
  stm :: Stm -> m () -- emit statement
  toAST :: m a -> m [Stm] -- turn code `m a` into [Stm] (without emitting it)
  fun :: Fun f m => f -> m String -- emit function f, return its name

-- | Helper class to convert literal haskell functions to the dsl
class Fun f m where
  mkFun :: DSL m => f -> [String] -> m ([String], [Stm])

instance Fun f m => Fun (Expr a -> f) m where
  mkFun f acc = do
    name <- freshName -- [2]
    mkFun (f $ Var name) (name : acc)

instance {-# INCOHERENT #-} (m0 ~ m) => Fun (m0 a) m where -- [4]
  mkFun m args = do
    fname <- freshName
    body <- toAST m -- [3]
    return (args, body)

-- | A sample implementation
instance DSL (StateT Int (Writer [Stm])) where
  freshName = do
    n <- get
    put $ n + 1
    return $ "var" <> show n
  stm stm' = tell [stm']
  toAST m = do
    state0 <- get
    let ((_, state1), w) = run m state0
    put state1
    return w
  fun f = do
    (args, body) <- mkFun f []
    name <- freshName
    stm $ Stm $ Function name args body -- [1]
    return name

run :: StateT Int (Writer [Stm]) a -> Int -> ((a, Int), [Stm])
run m s = runWriter $ runStateT m s

Body:
I guess one way is to mark the base case of the recursion yourself.

newtype Cook m a = Cook (m a)
deriving instance DSL m => DSL (Cook m)

instance Fun f m => Fun (Expr a -> f) m
instance m0 ~ m => Fun (Cook m0 a) (Cook m)

type SampleImplRaw = StateT Int (Writer [Stm])
type SampleImpl = Cook SampleImplRaw

instance DSL SampleImpl

I haven't typed this into the compiler, so I'm not sure, but it may be that you get into a funny situation where you want a DSL m instance, and have a DSL (Cook m) instance in scope, but the compiler can't figure out how to get from A to B. In such a case it should be possible to coerce the offending term to use the Cook m instance.

Another way might be to try making the base case have a different kind. Something like this:

instance Fun f m => Fun (Expr a -> f) m
instance (m ~ m', p ~ p', p ~ '()) => Fun (m p a) (m' p')

data SampleImplRaw (x :: ()) a = {- whatever you would have written before for new data declarations -}
type SampleImpl = SampleImplRaw '()
newtype Const1 (x :: ()) m a = Const1 (m a) deriving (EVERYTHING) -- still need a cook for mere monad transformer stacks

I guess probably if your plan is mostly to use transformer stacks, the first one will be less roundabout; if your plan is mostly to define new data types, the second will have a cleaner user experience.


问:
onChange event not triggered in react when using select jsx attribute
I am trying to trigger the onChange event of with select jsx/html attribute. The event doesn't fire, here is the code:

```<code>    const [dataType, setDataType] = useState(false);
    const [data, setData] = useState('Art');
    const handleOnChange = (event) => {
        console.log("is 3D? ", dataType);
        console.log("event.target.value ", event.target.value);
        event.target.value === "3D" ? setDataType(true) : setDataType(false);
    }
</code>```

jsx section:

```<code>    <div className="form-group col-md-6 pb-10">
        <select value={data} onChange={handleOnChange} id="category">
            <option value="3D">3D</option>
            <option value="Art">Art</option>
            <option value="Collectibles">Collectibles</option>
            <option value="Photography">Photography</option>
        </select>
    </div>
</code>```

I am using the latest react version and I followed the doc in this: https://reactjs.org/docs/forms.html#the-select-tag

答:
You need to actively invoke the handleChange function and pass the event to your handleChange function:

```<code>onChange={e => handleOnChange(e)}
</code>```

The complete example then looks like:

  <select value={data} onChange={e => handleOnChange(e)} id="category">
    <option value="3D">3D</option>
    <option value="Art">Art</option>
    <option value="Collectibles">Collectibles</option>
    <option value="Photography">Photography</option>
  </select>

```

Here's a working CodeSandbox example

Body:
I am trying to trigger the onChange event of with select jsx/html attribute. The event doesn't fire, here is the code:

    const [dataType, setDataType] = useState(false);
    const [data, setData] = useState('Art');
    const handleOnChange = (event) => {
        console.log("is 3D? ", dataType);
        console.log("event.target.value ", event.target.value);
        event.target.value === "3D" ? setDataType(true) : setDataType(false);
    }

jsx section:

        <select value={data} onChange={handleOnChange} id="category">
            <option value="3D">3D</option>
            <option value="Art">Art</option>
            <option value="Collectibles">Collectibles</option>
            <option value="Photography">Photography</option>
        </select>

I am using the latest react version and I followed the doc in this: https://reactjs.org/docs/forms.html#the-select-tag

Body:
You need to actively invoke the handleChange function and pass the event to your handleChange function:

onChange={e => handleOnChange(e)}

The complete example then looks like:

<div className="form-group col-md-6 pb-10">
  <select value={data} onChange={e => handleOnChange(e)} id="category">
    <option value="3D">3D</option>
    <option value="Art">Art</option>
    <option value="Collectibles">Collectibles</option>
    <option value="Photography">Photography</option>
  </select>
</div>

Here's a working CodeSandbox example


问:
How to add +9 hours on my jQuery script?
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

```<code>$end = mktime(16, 54, 0, 8, 18, 2011);
</code>```

and the copy it below

Countdown Script

```<code><script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);

$(document).ready(function() {
    $("#time").countdown({
        date: end_date,
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>
</code>```

答:
Call this before your countdown:

```<code>end_date = end_date.setTime((end_date + (9 * 3600)) * 1000).toGMTString();
</code>```

EDIT: I removed the get_time() and the "* 1000" as end_date is already a UNIX timestamp.

EDIT2: Apparently, timestamps in js are in milliseconds so we also have to multiply the PHP timestamp (which is in seconds).

ContentLicense: CC BY-SA 3.0

Body:
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

$end = mktime(16, 54, 0, 8, 18, 2011);

and the copy it below

Countdown Script

Body:
Call this before your countdown:

end_date = end_date.setTime((end_date + (9 * 3600)) * 1000).toGMTString();

EDIT: I removed the get_time() and the "* 1000" as end_date is already a UNIX timestamp.

EDIT2: Apparently, timestamps in js are in milliseconds so we also have to multiply the PHP timestamp (which is in seconds).


问:
Mkdocs "can not display mermaid in the right way"
I try to use this theme plugin to display the graph

Link:
https://squidfunk.github.io/mkdocs-material/reference/diagrams/?h=mermaid

the settings file:

```<code>- pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid-experimental
          format: !!python/name:pymdownx.superfences.fence_code_format
extra_javascript:
  - https://unpkg.com/mermaid@8.6.4/dist/mermaid.min.js
</code>```

all i got is this..
enter image description here

i dont think it is version problem

Has anyone got any suggestions?thanks

答:
This was part of the insiders offer at your time. If you upgrade your mkdocs-material version it should work.

https://squidfunk.github.io/mkdocs-material/insiders/

Body:
I try to use this theme plugin to display the graph

Link:
https://squidfunk.github.io/mkdocs-material/reference/diagrams/?h=mermaid

the settings file:

- pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid-experimental
          format: !!python/name:pymdownx.superfences.fence_code_format
extra_javascript:
  - https://unpkg.com/mermaid@8.6.4/dist/mermaid.min.js

all i got is this..
enter image description here

i dont think it is version problem

Has anyone got any suggestions?thanks


问:
Trouble parsing out shapefile by market using geopandas package
im trying to follow documentation from https://geopandas.org/en/stable/docs/user_guide/io.html to try to read subsets of a massive shapefile.

this is the code they give as an example to read in a subset of just data in Africa:

```<code>gdf_mask = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_lowres")
)
gdf = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_cities"),
    mask=gdf_mask[gdf_mask.continent=="Africa"],
)
</code>```

Now here is the code i used for my case:

```<code>newdf_mask = geopandas.read_file('C:\\Users\\path\\to\\file.zip')
newdf = geopandas.read_file('C:\\Users\\path\\to\\file.zip', mask=newdf_mask[newdf_mask.RMName = "Tampa/St. Petersburg"],)
</code>```

I received an invalid syntax error. I also tried it without that trailing comma which seems out of place but they have it in their example.

as you can see from my code, I want to read a subset of the shapefile where the RMName = "Tampa/St. Petersburg".

Is this the best way to do it or is there a better or easier way?

答:
you are trying to read zip file, where as you should be reading shape files

code below better shows this - downloads zip files, unzips them then reads shape files

```<code>import requests
from pathlib import Path
import urllib
from zipfile import ZipFile
import geopandas as gpd

# fmt: off
url = ["https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip",
       "https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_populated_places.zip"]

# fmt: on

for url in url:
    f = Path.cwd().joinpath(urllib.parse.urlparse(url).path.split("/")[-1])
    if not f.exists():
        r = requests.get(url, stream=True, headers={"User-Agent": "XY"})
        with open(f, "wb") as fd:
            for chunk in r.iter_content(chunk_size=128):
                fd.write(chunk)
    zfile = ZipFile(f)
    zfile.extractall(f.stem)

# NB reading shape file, not zip file
gdf_mask = gpd.read_file(list(Path.cwd().glob("ne_110m*/*countries*.shp"))[0])

gdf = gpd.read_file(
    list(Path.cwd().glob("ne_110m*/*populated*.shp"))[0],
    mask=gdf_mask.loc[gdf_mask["CONTINENT"].eq("Africa")],
)

# visualize....
m = gdf_mask.loc[
    gdf_mask["CONTINENT"].eq("Africa"), ["CONTINENT", "geometry"]
].explore()
gdf.loc[:, ["NAME", "geometry"]].explore(m=m, color="red")
</code>```

Body:
im trying to follow documentation from https://geopandas.org/en/stable/docs/user_guide/io.html to try to read subsets of a massive shapefile.

this is the code they give as an example to read in a subset of just data in Africa:

gdf_mask = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_lowres")
)
gdf = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_cities"),
    mask=gdf_mask[gdf_mask.continent=="Africa"],
)

Now here is the code i used for my case:

newdf_mask = geopandas.read_file('C:\\Users\\path\\to\\file.zip')
newdf = geopandas.read_file('C:\\Users\\path\\to\\file.zip', mask=newdf_mask[newdf_mask.RMName = "Tampa/St. Petersburg"],)

I received an invalid syntax error. I also tried it without that trailing comma which seems out of place but they have it in their example.

as you can see from my code, I want to read a subset of the shapefile where the RMName = "Tampa/St. Petersburg".

Is this the best way to do it or is there a better or easier way?

Body:
you are trying to read zip file, where as you should be reading shape files

code below better shows this - downloads zip files, unzips them then reads shape files

import requests
from pathlib import Path
import urllib
from zipfile import ZipFile
import geopandas as gpd

# fmt: off
url = ["https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip",
       "https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_populated_places.zip"]

# fmt: on

for url in url:
    f = Path.cwd().joinpath(urllib.parse.urlparse(url).path.split("/")[-1])
    if not f.exists():
        r = requests.get(url, stream=True, headers={"User-Agent": "XY"})
        with open(f, "wb") as fd:
            for chunk in r.iter_content(chunk_size=128):
                fd.write(chunk)
    zfile = ZipFile(f)
    zfile.extractall(f.stem)

# NB reading shape file, not zip file
gdf_mask = gpd.read_file(list(Path.cwd().glob("ne_110m*/*countries*.shp"))[0])

gdf = gpd.read_file(
    list(Path.cwd().glob("ne_110m*/*populated*.shp"))[0],
    mask=gdf_mask.loc[gdf_mask["CONTINENT"].eq("Africa")],
)

# visualize....
m = gdf_mask.loc[
    gdf_mask["CONTINENT"].eq("Africa"), ["CONTINENT", "geometry"]
].explore()
gdf.loc[:, ["NAME", "geometry"]].explore(m=m, color="red")


问:
rules with temporary objects and args by reference
say I have a class:

```<code>class A
{
 public:
 A() {}
};
</code>```

and a function:

```<code>void x(const A & s) {}
</code>```

and I do:

```<code>x(A());
</code>```

could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?

Thanks!

答: x() must either take a const reference to a temporary A, or x() must take an A by-value.</p>

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Body:
say I have a class:

class A
{
 public:
 A() {}
};

and a function:

void x(const A & s) {}

and I do:

x(A());

could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?

Thanks!

OwnerDisplayName: John Dibling


答:
mktime returns seconds, so you simply add the desired amount of seconds

using the end_date created with php, add this line:

```<code>end_date+=9*60*60
</code>```

Title: How to add +9 hours on my jQuery script?

Body:
mktime returns seconds, so you simply add the desired amount of seconds

using the end_date created with php, add this line:

end_date+=9*60*60


问:
How to show custom content beside dropdown items while being multiselect in vuetify?
In vuetify I want to show a dropdown but for each item, I want to have a slot to show something beside it like an icon but on the right side of the text. But also to have it multiple select.

This example does not work, it removed the checkboxes when I add the slot

https://codepen.io/Sneaky6666/pen/KKyqNaB?editors=101

```<code><div id="app">
  <v-app id="inspire">
      <v-autocomplete
        v-model="selectedFruits"
        :items="fruits"
        label="Favorite Fruits"
        multiple
      >
        <template v-slot:item="{item}">
          {{item}}
        </template>
      </v-autocomplete>
    </v-container>
  </v-app>
</div>
</code>```

js

```<code>new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    fruits: [
      'Apples',
      'Apricots',
      'Avocado',
      'Bananas',
      'Blueberries',
      'Blackberries',
      'Boysenberries',
      'Bread fruit',
      'Cantaloupes (cantalope)',
      'Cherries',
      'Cranberries',
      'Cucumbers',
      'Currants',
      'Dates',
      'Eggplant',
      'Figs',
      'Grapes',
      'Grapefruit',
      'Guava',
      'Honeydew melons',
      'Huckleberries',
      'Kiwis',
      'Kumquat',
      'Lemons',
      'Limes',
      'Mangos',
      'Mulberries',
      'Muskmelon',
      'Nectarines',
      'Olives',
      'Oranges',
      'Papaya',
      'Peaches',
      'Pears',
      'Persimmon',
      'Pineapple',
      'Plums',
      'Pomegranate',
      'Raspberries',
      'Rose Apple',
      'Starfruit',
      'Strawberries',
      'Tangerines',
      'Tomatoes',
      'Watermelons',
      'Zucchini',
    ],
    selectedFruits: [],
  }),

  computed: {
    likesAllFruit () {
      return this.selectedFruits.length === this.fruits.length
    },
    likesSomeFruit () {
      return this.selectedFruits.length > 0 && !this.likesAllFruit
    },
    icon () {
      if (this.likesAllFruit) return 'mdi-close-box'
      if (this.likesSomeFruit) return 'mdi-minus-box'
      return 'mdi-checkbox-blank-outline'
    },
  },

  methods: {
    toggle () {
      this.$nextTick(() => {
        if (this.likesAllFruit) {
          this.selectedFruits = []
        } else {
          this.selectedFruits = this.fruits.slice()
        }
      })
    },
  },
})
</code>```

答:
A workaround is to make the item a v-checkbox, and use its label and append-icon properties:

<v-autocomplete
  v-model="selectedFruits"
  :items="fruits"
  label="Favorite Fruits"
  multiple
>
  <template v-slot:item="{ on, attrs, item }">
    <v-checkbox v-on="on" v-bind="attrs" append-icon="people" :label="item"></v-checkbox>
  </template>
</v-autocomplete>
```
<p>The <code>attrs</code> binding causes the underlying native checkbox to appear for some reason, but you can hide that with CSS:</p>
<pre class="lang-css prettyprint-override"><code>.v-input--selection-controls__input > input {
  display: none;
}
</code>```

Another quirk to this solution is that clicking the label does not toggle the checkbox, but explicitly (re)-forwarding the click event seems to work in my tests:

<v-checkbox v-on="on" @click="on.click($event)">
```

demo

Body:
In vuetify I want to show a dropdown but for each item, I want to have a slot to show something beside it like an icon but on the right side of the text. But also to have it multiple select.

This example does not work, it removed the checkboxes when I add the slot

https://codepen.io/Sneaky6666/pen/KKyqNaB?editors=101

  <v-app id="inspire">
      <v-autocomplete
        v-model="selectedFruits"
        :items="fruits"
        label="Favorite Fruits"
        multiple
      >
        <template v-slot:item="{item}">
          {{item}}
        </template>
      </v-autocomplete>
    </v-container>
  </v-app>

js

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    fruits: [
      'Apples',
      'Apricots',
      'Avocado',
      'Bananas',
      'Blueberries',
      'Blackberries',
      'Boysenberries',
      'Bread fruit',
      'Cantaloupes (cantalope)',
      'Cherries',
      'Cranberries',
      'Cucumbers',
      'Currants',
      'Dates',
      'Eggplant',
      'Figs',
      'Grapes',
      'Grapefruit',
      'Guava',
      'Honeydew melons',
      'Huckleberries',
      'Kiwis',
      'Kumquat',
      'Lemons',
      'Limes',
      'Mangos',
      'Mulberries',
      'Muskmelon',
      'Nectarines',
      'Olives',
      'Oranges',
      'Papaya',
      'Peaches',
      'Pears',
      'Persimmon',
      'Pineapple',
      'Plums',
      'Pomegranate',
      'Raspberries',
      'Rose Apple',
      'Starfruit',
      'Strawberries',
      'Tangerines',
      'Tomatoes',
      'Watermelons',
      'Zucchini',
    ],
    selectedFruits: [],
  }),

  computed: {
    likesAllFruit () {
      return this.selectedFruits.length === this.fruits.length
    },
    likesSomeFruit () {
      return this.selectedFruits.length > 0 && !this.likesAllFruit
    },
    icon () {
      if (this.likesAllFruit) return 'mdi-close-box'
      if (this.likesSomeFruit) return 'mdi-minus-box'
      return 'mdi-checkbox-blank-outline'
    },
  },

  methods: {
    toggle () {
      this.$nextTick(() => {
        if (this.likesAllFruit) {
          this.selectedFruits = []
        } else {
          this.selectedFruits = this.fruits.slice()
        }
      })
    },
  },
})

Body:
A workaround is to make the item a v-checkbox, and use its label and append-icon properties:

<v-autocomplete
  v-model="selectedFruits"
  :items="fruits"
  label="Favorite Fruits"
  multiple
>
  <template v-slot:item="{ on, attrs, item }">
    <v-checkbox v-on="on" v-bind="attrs" append-icon="people" :label="item"></v-checkbox>
  </template>
</v-autocomplete>

The attrs binding causes the underlying native checkbox to appear for some reason, but you can hide that with CSS:

.v-input--selection-controls__input > input {
  display: none;
}

Another quirk to this solution is that clicking the label does not toggle the checkbox, but explicitly (re)-forwarding the click event seems to work in my tests:

<v-checkbox v-on="on" @click="on.click($event)">

demo


问:
git merge in vscode wipes out code on master without merge conflict
My problem is that when try to do a simple git merge the branch that I am merging into loses entries but there is no merge conflict - just lost files.

This is taking place in an internal class (robot practice)

master:

```<code>public final class Constants {

   public static final class DriveInfo {
      public static final int LEFT_FRONT_DRIVE_MOTOR_ID = 1;
      public static final int LEFT_REAR_DRIVE_MOTOR_ID = 2;
      public static final int RIGHT_FRONT_DRIVE_MOTOR_ID = 4;
      public static final int RIGHT_REAR_DRIVE_MOTOR_ID = 3;

      public static final MotorType DRIVE_MOTOR_BRUSHED_TYPE = MotorType.kBrushed;

      public static final boolean LEFT_DRIVE_MOTORS_ARE_INVERTED = true;
      public static final boolean RIGHT_DRIVE_MOTORS_ARE_INVERTED = false;

      public static final double DIFFERENTIAL_DRIVE_DEADBAND = 0.08;

      public static final int LEFT_DRIVE_ENCODER_CHANNEL_A = 0;
      public static final int LEFT_DRIVE_ENCODER_CHANNEL_B = 1;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_A = 2;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_B = 3;

      public static final EncodingType DRIVE_MOTOR_ENCODER_ENCODINGTYPE = EncodingType.k2X;
   }

   public static final class RobotInfo{
      public static int MECHANISM_CONTROLLER_ID = 0;
      public static int DRIVE_CONTROLLER_ID = 1;
   }
}
</code>```

robot-info

```<code>public final class Constants {

   public static final class DriveInfo {
      public static final int LEFT_FRONT_DRIVE_MOTOR_ID = 1;
      public static final int LEFT_REAR_DRIVE_MOTOR_ID = 2;
      public static final int RIGHT_FRONT_DRIVE_MOTOR_ID = 4;
      public static final int RIGHT_REAR_DRIVE_MOTOR_ID = 3;

      public static final MotorType DRIVE_MOTOR_BRUSHED_TYPE = MotorType.kBrushed;

      public static final boolean LEFT_DRIVE_MOTORS_ARE_INVERTED = true;
      public static final boolean RIGHT_DRIVE_MOTORS_ARE_INVERTED = false;

      public static final double DIFFERENTIAL_DRIVE_DEADBAND = 0.08;

      public static final int LEFT_DRIVE_ENCODER_CHANNEL_A = 0;
      public static final int LEFT_DRIVE_ENCODER_CHANNEL_B = 1;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_A = 2;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_B = 3;

      public static final EncodingType DRIVE_MOTOR_ENCODER_ENCODINGTYPE = EncodingType.k2X;
   }

   public static final class RobotInfo{
      private static final double DRIVE_WHEEL_DIAMETER = 6.0;
      private static final double WHEEL_CIRCUMFERENCE_IN_INCHES = DRIVE_WHEEL_DIAMETER * Math.PI;
      private static final double DRIVE_ENCODER_CLICKS_PER_ROTATION = 2048.0;
      public static final double CLICKS_PER_INCH =
          WHEEL_CIRCUMFERENCE_IN_INCHES / DRIVE_ENCODER_CLICKS_PER_ROTATION;

      private static final double INCHES_WIDTH_OF_AXLE = 22.0;
      private static final double INCHES_LENGTH_OF_AXLE = 24.0;
      private static final double DIAGONAL_INCHES_BETWEEN_AXES =
          Math.sqrt((INCHES_WIDTH_OF_AXLE * INCHES_WIDTH_OF_AXLE) + (INCHES_LENGTH_OF_AXLE * INCHES_LENGTH_OF_AXLE));
      private static final double ROBOT_ROTATION_CIRCUMFERENCE = DIAGONAL_INCHES_BETWEEN_AXES * Math.PI;
      public static final double DRIVE_ENCODER_CLICKS_PER_DEGREE =
          ROBOT_ROTATION_CIRCUMFERENCE / CLICKS_PER_INCH / 360;
  }
}
</code>```

when I do 'git merge robotInfo' the RobotInfo class in master is completely overwritten by the RobotInfo class in robotInfo. It is not combined and there are no merge conflicts.

I have scoured to find any solutions but no dice. Does this have to do with it being an internal class? Usually I have run across merge conflicts, but never one where it simply discarded any issues.

What am I doing wrong?

答:
I do not know about VSCode, but git does not care about your internal class. So this can not happen because of that. I think it is more likely that something was deleted in the other branch and so git is doing what it should.
To make it more clear: If I have branch A and B and I delete a file in branch B and then merge B into A, the file will of course also be deleted in branch A.

I would recommend:

Check the git log with git log --stat  for both branches and see where the file was deleted

Check the diff between the branches with a command like git diff BranchA..BranchB

Body:
My problem is that when try to do a simple git merge the branch that I am merging into loses entries but there is no merge conflict - just lost files.

This is taking place in an internal class (robot practice)

master:

public final class Constants {

   public static final class DriveInfo {
      public static final int LEFT_FRONT_DRIVE_MOTOR_ID = 1;
      public static final int LEFT_REAR_DRIVE_MOTOR_ID = 2;
      public static final int RIGHT_FRONT_DRIVE_MOTOR_ID = 4;
      public static final int RIGHT_REAR_DRIVE_MOTOR_ID = 3;

      public static final MotorType DRIVE_MOTOR_BRUSHED_TYPE = MotorType.kBrushed;

      public static final boolean LEFT_DRIVE_MOTORS_ARE_INVERTED = true;
      public static final boolean RIGHT_DRIVE_MOTORS_ARE_INVERTED = false;

      public static final double DIFFERENTIAL_DRIVE_DEADBAND = 0.08;

      public static final int LEFT_DRIVE_ENCODER_CHANNEL_A = 0;
      public static final int LEFT_DRIVE_ENCODER_CHANNEL_B = 1;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_A = 2;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_B = 3;

      public static final EncodingType DRIVE_MOTOR_ENCODER_ENCODINGTYPE = EncodingType.k2X;
   }

   public static final class RobotInfo{
      public static int MECHANISM_CONTROLLER_ID = 0;
      public static int DRIVE_CONTROLLER_ID = 1;
   }
}

robot-info

public final class Constants {

   public static final class DriveInfo {
      public static final int LEFT_FRONT_DRIVE_MOTOR_ID = 1;
      public static final int LEFT_REAR_DRIVE_MOTOR_ID = 2;
      public static final int RIGHT_FRONT_DRIVE_MOTOR_ID = 4;
      public static final int RIGHT_REAR_DRIVE_MOTOR_ID = 3;

      public static final MotorType DRIVE_MOTOR_BRUSHED_TYPE = MotorType.kBrushed;

      public static final boolean LEFT_DRIVE_MOTORS_ARE_INVERTED = true;
      public static final boolean RIGHT_DRIVE_MOTORS_ARE_INVERTED = false;

      public static final double DIFFERENTIAL_DRIVE_DEADBAND = 0.08;

      public static final int LEFT_DRIVE_ENCODER_CHANNEL_A = 0;
      public static final int LEFT_DRIVE_ENCODER_CHANNEL_B = 1;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_A = 2;
      public static final int RIGHT_DRIVE_ENCODER_CHANNEL_B = 3;

      public static final EncodingType DRIVE_MOTOR_ENCODER_ENCODINGTYPE = EncodingType.k2X;
   }

   public static final class RobotInfo{
      private static final double DRIVE_WHEEL_DIAMETER = 6.0;
      private static final double WHEEL_CIRCUMFERENCE_IN_INCHES = DRIVE_WHEEL_DIAMETER * Math.PI;
      private static final double DRIVE_ENCODER_CLICKS_PER_ROTATION = 2048.0;
      public static final double CLICKS_PER_INCH =
          WHEEL_CIRCUMFERENCE_IN_INCHES / DRIVE_ENCODER_CLICKS_PER_ROTATION;

      private static final double INCHES_WIDTH_OF_AXLE = 22.0;
      private static final double INCHES_LENGTH_OF_AXLE = 24.0;
      private static final double DIAGONAL_INCHES_BETWEEN_AXES =
          Math.sqrt((INCHES_WIDTH_OF_AXLE * INCHES_WIDTH_OF_AXLE) + (INCHES_LENGTH_OF_AXLE * INCHES_LENGTH_OF_AXLE));
      private static final double ROBOT_ROTATION_CIRCUMFERENCE = DIAGONAL_INCHES_BETWEEN_AXES * Math.PI;
      public static final double DRIVE_ENCODER_CLICKS_PER_DEGREE =
          ROBOT_ROTATION_CIRCUMFERENCE / CLICKS_PER_INCH / 360;
  }
}

when I do 'git merge robotInfo' the RobotInfo class in master is completely overwritten by the RobotInfo class in robotInfo. It is not combined and there are no merge conflicts.

I have scoured to find any solutions but no dice. Does this have to do with it being an internal class? Usually I have run across merge conflicts, but never one where it simply discarded any issues.

What am I doing wrong?


问:
Removing special character in data in databricks
My company is in a migration project from MapR to databricks, and we have the following piece of code that used to work fine in this platform, but once in databricks it stopped working. I noticed that this is failing with this specific regular expression because this is not getting any error with others.

The Error is "Error while obtaining a new communication channel", and after that, we can not continue writing code and testing, something breaks.

I am attaching a screenshot for reference.
[

```<code>import pyspark.sql.functions as pyfunc

df=spark.read.parquet("/mnt/gpdipedlstgamrasp50565/stg_db/intermediate/ODX/ODW/STUDY_REPORT/Current/Data/")

df.count()

df = df.withColumn('CSR_RESULTS_SUMMARY', pyfunc.regexp_replace(pyfunc.col('CSR_RESULTS_SUMMARY'),u'([\ud800-\udfff\ufdd0-\ufdef\ufffe-\uffff+])',''))

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

Thank you very much in advance.

答:
I suspect the error is caused by the u'' in the regex pattern you pass to regexp_replace function. You should use r'' for python raw string:

```<code>df = df.withColumn(
    'column',
    pyfunc.regexp_replace(pyfunc.col('column'), r'[\ud800-\udfff\ufdd0-\ufdef\ufffe-\uffff]+', '')
)
</code>```

Or use two backslashes \\ to escape:

```<code>df = df.withColumn(
    'column',
    pyfunc.regexp_replace(pyfunc.col('column'), '[\\ud800-\\udfff\\ufdd0-\\ufdef\\ufffe-\\uffff]+', '')
)
</code>```

Body:
My company is in a migration project from MapR to databricks, and we have the following piece of code that used to work fine in this platform, but once in databricks it stopped working. I noticed that this is failing with this specific regular expression because this is not getting any error with others.

The Error is "Error while obtaining a new communication channel", and after that, we can not continue writing code and testing, something breaks.

I am attaching a screenshot for reference.
[

import pyspark.sql.functions as pyfunc

df=spark.read.parquet("/mnt/gpdipedlstgamrasp50565/stg_db/intermediate/ODX/ODW/STUDY_REPORT/Current/Data/")

df.count()

df = df.withColumn('CSR_RESULTS_SUMMARY', pyfunc.regexp_replace(pyfunc.col('CSR_RESULTS_SUMMARY'),u'([\ud800-\udfff\ufdd0-\ufdef\ufffe-\uffff+])',''))

df.show()

Thank you very much in advance.

Body:
I suspect the error is caused by the u'' in the regex pattern you pass to regexp_replace function. You should use r'' for python raw string:

df = df.withColumn(
    'column',
    pyfunc.regexp_replace(pyfunc.col('column'), r'[\ud800-\udfff\ufdd0-\ufdef\ufffe-\uffff]+', '')
)

Or use two backslashes \\ to escape:

df = df.withColumn(
    'column',
    pyfunc.regexp_replace(pyfunc.col('column'), '[\\ud800-\\udfff\\ufdd0-\\ufdef\\ufffe-\\uffff]+', '')
)


问:
How can I change part of a PyTorch tensor based on the values of another tensor?
This question may not be clear, so please ask for clarification in the comments and I will expand.

I have the following tensors of the following shape:

```<code>mask.size() == torch.Size([1, 400])
clean_input_spectrogram.size() == torch.Size([1, 400, 161])
output.size() == torch.Size([1, 400, 161])
</code>```

mask is comprised only of 0 and 1. Since it's a mask, I want to set the elements of output equal to clean_input_spectrogram where that relevant mask value is 1.

How would I do that?

答:
Basic usage of a mask:

a = torch.zeros([2,])     # tensor([0., 0.])
b = torch.ones([2,]) * 7  # tensor([7., 7.])

m = torch.tensor([True, False])

a[m] = b[m]               # tensor([7., 0.])
```
<p>In this case, you have an extra dimension in <code>a</code> and <code>b</code>, but not in mask. This is no problem and will be handled automatically due to broadcasting. Example:</p>
<pre class="lang-py prettyprint-override"><code>a = torch.zeros([2, 161])
b = torch.ones([2, 161]) * 7

m = torch.tensor([True, False])

a[m] = b[m]
print(a)
</code>```

Body:
This question may not be clear, so please ask for clarification in the comments and I will expand.

I have the following tensors of the following shape:

mask.size() == torch.Size([1, 400])
clean_input_spectrogram.size() == torch.Size([1, 400, 161])
output.size() == torch.Size([1, 400, 161])

mask is comprised only of 0 and 1. Since it's a mask, I want to set the elements of output equal to clean_input_spectrogram where that relevant mask value is 1.

How would I do that?

Body:
Basic usage of a mask:

a = torch.zeros([2,])     # tensor([0., 0.])
b = torch.ones([2,]) * 7  # tensor([7., 7.])

m = torch.tensor([True, False])

a[m] = b[m]               # tensor([7., 0.])

In this case, you have an extra dimension in a and b, but not in mask. This is no problem and will be handled automatically due to broadcasting. Example:

a = torch.zeros([2, 161])
b = torch.ones([2, 161]) * 7

m = torch.tensor([True, False])

a[m] = b[m]
print(a)


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
okay, getCtr is a function that returns an other function.
It also contains a var called "i" which is set to 0.
"i" is also available in the scope of the returned function.
the preincrement of "i" before logging it to the console causes that it increases by 1 every time the returned function, which is stored in "ctr", is called.</p>

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.


问:
How to get current DATE/TIME with microseconds in CI4?
Awkward problem -> I'm trying to get current date&time in ISO 8601 format (like this: 2022-02-11 12:30:02.846108).

When I run $time = new Time('now', 'Europe/Amsterdam') in CI4, $time returns this:

```<code>object(CodeIgniter\I18n\Time)#79 (6)
  { ["timezone":protected]=> object(DateTimeZone)#80 (2)
    { ["timezone_type"]=> int(3)
      ["timezone"]=> string(16) "Europe/Amsterdam"
    }
    ["locale":protected]=> string(2) "en"
    ["toStringFormat":protected]=> string(19) "yyyy-MM-dd HH:mm:ss"
    ["date"]=> string(26) "2022-02-11 12:30:02.846108"
    ["timezone_type"]=> int(3)
    ["timezone"]=> string(16) "Europe/Amsterdam"
}

</code>```

but when i try to get $time->date returns NULL.

Any ideea how to access date string in order to get the current time with microseconds?

答:
Found out there is no ->date attribute in the DateTime object, which is why  $time->date returns NULL.

The proper way to get the date with microseconds is:

```<code>$time->format('Y-m-d\TH:i:s.u')
</code>```

Body:
Awkward problem -> I'm trying to get current date&time in ISO 8601 format (like this: 2022-02-11 12:30:02.846108).

When I run $time = new Time('now', 'Europe/Amsterdam') in CI4, $time returns this:

object(CodeIgniter\I18n\Time)#79 (6)
  { ["timezone":protected]=> object(DateTimeZone)#80 (2)
    { ["timezone_type"]=> int(3)
      ["timezone"]=> string(16) "Europe/Amsterdam"
    }
    ["locale":protected]=> string(2) "en"
    ["toStringFormat":protected]=> string(19) "yyyy-MM-dd HH:mm:ss"
    ["date"]=> string(26) "2022-02-11 12:30:02.846108"
    ["timezone_type"]=> int(3)
    ["timezone"]=> string(16) "Europe/Amsterdam"
}

but when i try to get $time->date returns NULL.

Any ideea how to access date string in order to get the current time with microseconds?

Body:
Found out there is no ->date attribute in the DateTime object, which is why  $time->date returns NULL.

The proper way to get the date with microseconds is:

$time->format('Y-m-d\TH:i:s.u')


问:
How to calculate the average of all vertical, horizontal and diagonal neighbours of a cell in a matrix (2D-list)?
Given a 2D-list of integers, how can I calculate the average of the vertical, horizontal and diagonal neighbors of each element? The results need to be printed as floating point numbers and in a matrix with every row on one line.

So an example 2D-list is:

```<code>matrix = [[3, 9, 0],
          [4, 1, 4],
          [3, 8, 5]]
</code>```

and the output for this one would then be:

```<code>[4.666666666666667, 2.4, 4.666666666666667]
[4.8, 4.5, 4.6]
[4.333333333333333, 3.4, 4.333333333333333]
</code>```

As further clarification. For the element in row and column 1 it would be:

(9+4+1)/3 = 4.667

答:
Find the row and column of the value in question. Then just surround the next part in try excepts to see if there is an index error. To find surrounding neighbors, you just increment and decrement both the row and column until all permutations are covered to collect the value, and then find the average. Surround all of this in a for loop that iterates over the entire matrix and stores the value in a blank matrix outside the loop.

```<code>create empty matrix
for i in rows:
    for j in rows[i]:
        list = []
        value1 = rows[i-1][j-1]
        value2 = rows[i][j-1]
        ... to value9
        add all values to the list
        calculate the mean
        store the mean in the i,j spot in the matrix above
</code>```

Be sure to include try excepts around each value statement since you can run into index errors.

Body:
Given a 2D-list of integers, how can I calculate the average of the vertical, horizontal and diagonal neighbors of each element? The results need to be printed as floating point numbers and in a matrix with every row on one line.

So an example 2D-list is:

matrix = [[3, 9, 0],
          [4, 1, 4],
          [3, 8, 5]]

and the output for this one would then be:

[4.666666666666667, 2.4, 4.666666666666667]
[4.8, 4.5, 4.6]
[4.333333333333333, 3.4, 4.333333333333333]

As further clarification. For the element in row and column 1 it would be:

(9+4+1)/3 = 4.667

Body:
Find the row and column of the value in question. Then just surround the next part in try excepts to see if there is an index error. To find surrounding neighbors, you just increment and decrement both the row and column until all permutations are covered to collect the value, and then find the average. Surround all of this in a for loop that iterates over the entire matrix and stores the value in a blank matrix outside the loop.

create empty matrix
for i in rows:
    for j in rows[i]:
        list = []
        value1 = rows[i-1][j-1]
        value2 = rows[i][j-1]
        ... to value9
        add all values to the list
        calculate the mean
        store the mean in the i,j spot in the matrix above

Be sure to include try excepts around each value statement since you can run into index errors.


问:
Evaluate if only on startup
consider the following example:

use std::fs;
use std::path::Path;

fn get_battery() -> String {
    let power = if Path::new("/sys/class/power_supply/BAT0/power_now").exists() {
        fs::read_to_string("/sys/class/power_supply/BAT0/power_now")
            .expect("Error BAT0/power_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6)
    } else {
        let current = fs::read_to_string("/sys/class/power_supply/BAT0/current_now")
            .expect("Error BAT0/current_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6);
        let voltage = fs::read_to_string("/sys/class/power_supply/BAT0/voltage_now")
            .expect("Error BAT0/voltage_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6);
        current * voltage
    };

    return power.to_string()
}

fn main() {

    loop {
        std::thread::sleep(std::time::Duration::from_secs(1))
        println!("{}", get_battery());
    }
}
```

I would like to evaluate the if statement, inside the get_battery function, once on startup and follow that branch (read power or read current/voltage) in the successive function call.

Is there a way to instuct the compiler to compile two versions of the same function and run the right one based on the existence of a file on startup?

Thanks

答:
You can do it with the once_cell crate and two functions. Something like this (untested):

```<code>use once_cell::sync::Lazy;
use std::fs;
use std::path::Path;

fn get_power() -> f32 {
    fs::read_to_string("/sys/class/power_supply/BAT0/power_now")
        .expect("Error BAT0/power_now")
        .trim()
        .parse::<f32>()
        .unwrap()
        / f32::powi(10.0, 6)
}

fn get_current_voltage() -> f32 {
    let current = fs::read_to_string("/sys/class/power_supply/BAT0/current_now")
        .expect("Error BAT0/current_now")
        .trim()
        .parse::<f32>()
        .unwrap()
        / f32::powi(10.0, 6);
    let voltage = fs::read_to_string("/sys/class/power_supply/BAT0/voltage_now")
        .expect("Error BAT0/voltage_now")
        .trim()
        .parse::<f32>()
        .unwrap()
        / f32::powi(10.0, 6);
    current * voltage
}

static GET_POWER: Lazy<fn()->f32> = Lazy::new(|| {
    if Path::new("/sys/class/power_supply/BAT0/power_now").exists() {
        get_power
    } else {
        get_current_voltage
    }
});

</code>```

Title: Evaluate if only on startup

Body:
consider the following example:

use std::fs;
use std::path::Path;

fn get_battery() -> String {
    let power = if Path::new("/sys/class/power_supply/BAT0/power_now").exists() {
        fs::read_to_string("/sys/class/power_supply/BAT0/power_now")
            .expect("Error BAT0/power_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6)
    } else {
        let current = fs::read_to_string("/sys/class/power_supply/BAT0/current_now")
            .expect("Error BAT0/current_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6);
        let voltage = fs::read_to_string("/sys/class/power_supply/BAT0/voltage_now")
            .expect("Error BAT0/voltage_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6);
        current * voltage
    };

    return power.to_string()
}

fn main() {

    loop {
        std::thread::sleep(std::time::Duration::from_secs(1))
        println!("{}", get_battery());
    }
}

I would like to evaluate the if statement, inside the get_battery function, once on startup and follow that branch (read power or read current/voltage) in the successive function call.

Is there a way to instuct the compiler to compile two versions of the same function and run the right one based on the existence of a file on startup?

Thanks

Body:
You can do it with the once_cell crate and two functions. Something like this (untested):

use once_cell::sync::Lazy;
use std::fs;
use std::path::Path;

fn get_power() -> f32 {
    fs::read_to_string("/sys/class/power_supply/BAT0/power_now")
        .expect("Error BAT0/power_now")
        .trim()
        .parse::<f32>()
        .unwrap()
        / f32::powi(10.0, 6)
}

fn get_current_voltage() -> f32 {
    let current = fs::read_to_string("/sys/class/power_supply/BAT0/current_now")
        .expect("Error BAT0/current_now")
        .trim()
        .parse::<f32>()
        .unwrap()
        / f32::powi(10.0, 6);
    let voltage = fs::read_to_string("/sys/class/power_supply/BAT0/voltage_now")
        .expect("Error BAT0/voltage_now")
        .trim()
        .parse::<f32>()
        .unwrap()
        / f32::powi(10.0, 6);
    current * voltage
}

static GET_POWER: Lazy<fn()->f32> = Lazy::new(|| {
    if Path::new("/sys/class/power_supply/BAT0/power_now").exists() {
        get_power
    } else {
        get_current_voltage
    }
});


问:
multiple conditional renderings inside a map function
Hi there I'm looking if there's a better way to render my todos

I have this

```<code>         {
            todos.map((todo) => (

                todo.status === 1 && (
                    <p>{todo.title}</p>
                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 2 && (
                    <p>{todo.title}</p>
                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 3 && (
                    <p>{todo.title}</p>
                )
            ))
        }
</code>```

Is there a way to do this?

Thanks a lot

答:
Making no assumptions about the status, you could do something like this:

const getTodos = (status) => todos
  .filter((todo) => todo.status === status)
  .map((todo) =>
{todo.title}
);
...
{getTodos(1)}
{getTodos(2)}
{getTodos(3)}
```

Body:
Hi there I'm looking if there's a better way to render my todos

I have this

         {
            todos.map((todo) => (

                todo.status === 1 && (

{todo.title}

                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 2 && (

{todo.title}

                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 3 && (

{todo.title}

                )
            ))
        }

Is there a way to do this?

Thanks a lot

Body:
Making no assumptions about the status, you could do something like this:

const getTodos = (status) => todos
  .filter((todo) => todo.status === status)
  .map((todo) => <p>{todo.title}</p>);
...
{getTodos(1)}
{getTodos(2)}
{getTodos(3)}


问:
EditorJS not showing up? How to fix this?
I am creating a blog. Here I am using EditorJS as my blog-post editor. I am using nodejs, express and ejs. I can't see the EditorJS interface on my screen.
Here is my code.

code for app.js:

```<code>const express = require('express')
const app = express()

app.use(express.json())
app.set('view engine', 'ejs')

app.get('/', function(req, res) {
    res.render('index.ejs')
})

app.listen(3000, function(){
    console.log('Server is running on port 3000.')
})
</code>```

code for index.ejs file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home | Editor JS</title>
</head>

<body>
    <form action="/create-post" method="POST">
        <label for="title">Title</label>
        <input type="text" class="form-control" name="title" placeholder="Title" required>
        <label for="content">Content</label>
        <input type="text" id="editorjs" name="content" placeholder="Content" required>
        <button type="submit">Create</button>
    </form>

    <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script>
    <script>
        const editor = new EditorJS('editorjs')
    </script>
    </body>
</html>
</code>```

How to make the EditorJS interface to be appeared in the ejs file?

答:
An error message would be helpful.

Did you start your express server? Your app.js seems to be missing app.listen(8080);

Also your app.get() call is missing the closing bracket.

The following code is working for me:

const express = require('express')
const app = express()

app.use(express.json())
app.set('view engine', 'ejs')

app.get('/', function(req, res) {
    res.render('index.ejs')
})

app.listen(8080);
```

Did you install express and ejs correctly?
npm i -s ejs express

Also the view engine seems to expect your ejs-files to be in the "views" folder. When you open the page in your browser, you should see an error message if it is still not working.

Body:
I am creating a blog. Here I am using EditorJS as my blog-post editor. I am using nodejs, express and ejs. I can't see the EditorJS interface on my screen.
Here is my code.

code for app.js:

const express = require('express')
const app = express()

app.use(express.json())
app.set('view engine', 'ejs')

app.get('/', function(req, res) {
    res.render('index.ejs')
})

app.listen(3000, function(){
    console.log('Server is running on port 3000.')
})

code for index.ejs file:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home | Editor JS</title>

    <form action="/create-post" method="POST">
        Title
        <input type="text" class="form-control" name="title" placeholder="Title" required>
        Content
        <input type="text" id="editorjs" name="content" placeholder="Content" required>
        <button type="submit">Create</button>
    </form>

How to make the EditorJS interface to be appeared in the ejs file?

Body:
An error message would be helpful.

Did you start your express server? Your app.js seems to be missing app.listen(8080);

Also your app.get() call is missing the closing bracket.

The following code is working for me:

const express = require('express')
const app = express()

app.use(express.json())
app.set('view engine', 'ejs')

app.get('/', function(req, res) {
    res.render('index.ejs')
})

app.listen(8080);

Did you install express and ejs correctly?
npm i -s ejs express

Also the view engine seems to expect your ejs-files to be in the "views" folder. When you open the page in your browser, you should see an error message if it is still not working.


问:
How to render Page attributes in a model when displayed in StreamField?
I have the following StructBlock and Page model:

```<code>class PostGrid(blocks.StructBlock):
    title = blocks.CharBlock()
    post_1 = blocks.PageChooserBlock()
    post_2 = blocks.PageChooserBlock()

    class Meta:
        template = 'post-grid.html'

class BlogIndex(Page):
    body = StreamField([('POSTS', PostGrid()),])

    class Meta:
        template = 'base.html'

class PostPage(Page):
    hero_title =  models.CharField(max_length=255)
</code>```

I want to render the attributes of post_1 and post_2 in the body StreamField:

base.html:

```<code>{% for block in page.body %}
    {% include_block block %}
{% endfor %}
</code>```

post-grid.html:

```<code>{{ value.post_1.url }}
{{ value.post_1.hero_title }}
</code>```

value.post_1.url renders the URL fine. However, value.post_1.hero_title is blank.

How do I render the Page attributes?

答:
When you use PageChooserBlock() with no further options specified, Wagtail does not know in advance what the page type will be when retrieving it, and so it returns a basic Page instance which only consists of the basic fields common to all page types, such as title.

In this case, presumably only pages of PostPage should be allowed for these choosers, so you can specify that in the PageChooserBlock definition:

```<code>class PostGrid(blocks.StructBlock):
    title = blocks.CharBlock()
    post_1 = blocks.PageChooserBlock(page_type='myapp.PostPage')
    post_2 = blocks.PageChooserBlock(page_type='myapp.PostPage')
    # replace 'myapp' with your app name
</code>```

With this change, the chooser will only allow selecting pages of type PostPage, and on the template, value.post_1 and value.post_2 will be returned as full PostPage instances, allowing you to use hero_title.

Alternatively, if you aren't able to make this change because there are multiple allowed page types, you can force it to fetch the full page object with .specific:

```<code>{% with value.post_1.specific as post_1 %}
    {{ post_1.url }}
    {{ post_1.hero_title }}
{% endwith %}
</code>```

However, each call to specific will make an additional database query.

Body:
I have the following StructBlock and Page model:

class PostGrid(blocks.StructBlock):
    title = blocks.CharBlock()
    post_1 = blocks.PageChooserBlock()
    post_2 = blocks.PageChooserBlock()

    class Meta:
        template = 'post-grid.html'

class BlogIndex(Page):
    body = StreamField([('POSTS', PostGrid()),])

    class Meta:
        template = 'base.html'

class PostPage(Page):
    hero_title =  models.CharField(max_length=255)

I want to render the attributes of post_1 and post_2 in the body StreamField:

base.html:

{% for block in page.body %}
    {% include_block block %}
{% endfor %}

post-grid.html:

{{ value.post_1.url }}
{{ value.post_1.hero_title }}

value.post_1.url renders the URL fine. However, value.post_1.hero_title is blank.

How do I render the Page attributes?

Body:
When you use PageChooserBlock() with no further options specified, Wagtail does not know in advance what the page type will be when retrieving it, and so it returns a basic Page instance which only consists of the basic fields common to all page types, such as title.

In this case, presumably only pages of PostPage should be allowed for these choosers, so you can specify that in the PageChooserBlock definition:

class PostGrid(blocks.StructBlock):
    title = blocks.CharBlock()
    post_1 = blocks.PageChooserBlock(page_type='myapp.PostPage')
    post_2 = blocks.PageChooserBlock(page_type='myapp.PostPage')
    # replace 'myapp' with your app name

With this change, the chooser will only allow selecting pages of type PostPage, and on the template, value.post_1 and value.post_2 will be returned as full PostPage instances, allowing you to use hero_title.

Alternatively, if you aren't able to make this change because there are multiple allowed page types, you can force it to fetch the full page object with .specific:

{% with value.post_1.specific as post_1 %}
    {{ post_1.url }}
    {{ post_1.hero_title }}
{% endwith %}

However, each call to specific will make an additional database query.


问:
PandasNotImplementedError: The method `pd.Series.__iter__()` is not implemented. If you want to collect your data as an NumPy array
I try to create a new column in Koalas dataframe df. The dataframe has 2 columns: col1 and col2. I need to create a new column newcol as a median of col1 and col2 values.

```<code>import numpy as np
import databricks.koalas as ks

# df is Koalas dataframe
df = df.assign(newcol=lambda x: np.median(x.col1, x.col2).astype(float))
</code>```

But I get the following error:

PandasNotImplementedError: The method pd.Series.__iter__() is not
implemented. If you want to collect your data as an NumPy array, use
'to_numpy()' instead.

Also I tried:

```<code>df.newcol = df.apply(lambda x: np.median(x.col1, x.col2), axis=1)
</code>```

But it didn't work.

答:
I had the same problem. One caveat, I'm using pyspark.pandas instead of koalas, but my understanding is that pyspark.pandas came from koalas, so my solution might still help. I tried to test it with koalas but was unable to run a cluster with a reasonable version.

import pyspark.pandas as ps

data = {"col_1": [1,2,3], "col_2": [4,5,6]}
df = ps.DataFrame(data)

median_series = df[["col_1","col_2"]].apply(lambda x: x.median(), axis=1)
median_series.name = "median"

df = ps.merge(df, median_series, left_index=True, right_index=True, how='left')
```

On apply, the lambda parameter x is a pandas.Series of each row, so I used its median method. Annoyingly, I couldn't get any assigning to work, the only way I found was to make this ugly merge. Oh, and used left to have the peace of mind that df would keep the same number of rows, but inner could be fine depending on context

Body:
I try to create a new column in Koalas dataframe df. The dataframe has 2 columns: col1 and col2. I need to create a new column newcol as a median of col1 and col2 values.

import numpy as np
import databricks.koalas as ks

# df is Koalas dataframe
df = df.assign(newcol=lambda x: np.median(x.col1, x.col2).astype(float))

But I get the following error:

PandasNotImplementedError: The method pd.Series.__iter__() is not
implemented. If you want to collect your data as an NumPy array, use
'to_numpy()' instead.

Also I tried:

df.newcol = df.apply(lambda x: np.median(x.col1, x.col2), axis=1)

But it didn't work.

Body:
I had the same problem. One caveat, I'm using pyspark.pandas instead of koalas, but my understanding is that pyspark.pandas came from koalas, so my solution might still help. I tried to test it with koalas but was unable to run a cluster with a reasonable version.

import pyspark.pandas as ps

data = {"col_1": [1,2,3], "col_2": [4,5,6]}
df = ps.DataFrame(data)

median_series = df[["col_1","col_2"]].apply(lambda x: x.median(), axis=1)
median_series.name = "median"

df = ps.merge(df, median_series, left_index=True, right_index=True, how='left')

On apply, the lambda parameter x is a pandas.Series of each row, so I used its median method. Annoyingly, I couldn't get any assigning to work, the only way I found was to make this ugly merge. Oh, and used left to have the peace of mind that df would keep the same number of rows, but inner could be fine depending on context


问:
How can I get a full list of class members without instantiating a class?
Good day!

I'm writing a little tool that builds a GUI for my data-aware app.

The basic idea is to get a module containing a model description (sqla/elixir entities) as an input, and to present the user with a list of available classes (inherited from Entity()) and their fields (inherited from Field()) from this module.

The pyclbr module is fine for getting classes and their methods, but it can't read other class-members. I know about __dict__ and inspect module, but the problem is they require instantiation of a class in question, and that is kind of wrong in this context. So, is there another way ?

I really don't want to parse modules as text.  :)

答:
I'm not sure I know what you mean:

```<code>class a(object):
    b = 'a'
    c = 'd'

print dir(a)
</code>```

prints

```<code>['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'b', 'c']
</code>```

You can use

```<code>print [i for i in dir(a) if not i.endswith('__')]
</code>```

if you don't want to see the special methods.

You don't need to instantiate the class to see it's members. You won't see attributes added inside methods, but everything defined in the class definition or a metaclass' __new__ method will be there.

See my answer to inspect.getmembers() vs __dict__.items() vs dir() for more info on what exactly these different functions return.

Body:
I'm not sure I know what you mean:

class a(object):
    b = 'a'
    c = 'd'

print dir(a)

prints

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'b', 'c']

You can use

print [i for i in dir(a) if not i.endswith('__')]

if you don't want to see the special methods.

You don't need to instantiate the class to see it's members. You won't see attributes added inside methods, but everything defined in the class definition or a metaclass' __new__ method will be there.

See my answer to inspect.getmembers() vs __dict__.items() vs dir() for more info on what exactly these different functions return.


问:
How can i debug my code when i'm targeting multiple versions of .net?
I'm trying to target multiple .net framework versions with the built in preprocessor directives but i can't debug the targeted version of my code because that part of my code is cannot be hit during debug.

Here's my code:

```<code>   private static void WriterTask(string processName, byte[] byteArray)
   {
#if NET_46
        Task.Run(() =>
        {
            FileWriter(_path, processName, byteArray);
        });
#elif NET_35
        FileWriter(_path, processName, byteArray);
#endif
   }
</code>```

答:
If you are debugging an application via Visual Studio, you need to check the framework version you are using to launch it. The corresponding setting can be found in the launch button dropdown.

Here is how this setting looks like in VS2019 for my application, which is targeting both .NET Framework 4.5 and .NET Core 3.0:

On the screenshot, the .NET Framework 4.5 is selected, but I can switch to .NET Core 3.0 by selecting the corresponding item in the menu.

My application contains a few #if NET45 sections, and they can be debugged properly in this case.

Body:
I'm trying to target multiple .net framework versions with the built in preprocessor directives but i can't debug the targeted version of my code because that part of my code is cannot be hit during debug.

Here's my code:

   private static void WriterTask(string processName, byte[] byteArray)
   {
#if NET_46
        Task.Run(() =>
        {
            FileWriter(_path, processName, byteArray);
        });
#elif NET_35
        FileWriter(_path, processName, byteArray);
#endif
   }


问:
'set' object has no attribute 'get' CSV (in praw)
This code is supposed to get some information about a post like title, upvotes etc. And then write it in a CSV file. But when is run it I get this error:

```<code>Traceback (most recent call last):
  File "main.py", line 71, in <module>
    writer.writerow(data)
  File "/usr/lib/python3.8/csv.py", line 154, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/usr/lib/python3.8/csv.py", line 151, in <genexpr>
    return (rowdict.get(key, self.restval) for key in self.fieldnames)
AttributeError: 'set' object has no attribute 'get'
</code>```

And this is the code:

```<code>    import praw
    import random
    import time
    import csv
    #from keep_Aliv import keep_alive

    username = "XXXXXX"

    #keep_alive()

    print('AAAAAAA')

    reddit = praw.Reddit(client_id="XXXXXX",
                         client_secret="XXXXXX",
                         user_agent="bot",
                         username=username,
                         password='XXXXXX')

    subreddit = reddit.subreddit('all')

   with open('pdata.csv', 'a') as f:
    headers = [
        'ID', 'Date_utc', 'Upvotes', 'Number of Comments', 'Subthread name'
    ]
    writer = csv.DictWriter(f,
                            fieldnames=headers,
                            extrasaction='ignore',
                            dialect='excel')
    writer.writeheader()
    for post in subreddit.stream.submissions():
        #print(post.title)

        data = {
                "ID": post.id,
                "Date_utc": post.created_utc,
                "Upvotes": post.ups,
                "Number of comments": post.num_comments,
                "Subthread name": post.title,
                }
        writer.writerow(data)
        print(data)
</code>```

ok, so how am I supposed to fix this? pls tell if some other information is required.

Thanks :)

(The main problem is now fixed and the compiler is not throwing an error now, but on the other hand the program isn't writing anything in the csv file. There isn't any error detected by the compiler but it's still not doing what it's supposed to. How do I fix that? btw the code in the post the working code)

答:
You are using a dict writer, which accepts dicts. You are passing a string to it.

You should construct a dict, and write that:

```<code>data = {
    "ID": post,
    "Date_utc": post.created_utc,
    "Upvotes": post.ups,
    "Number of comments": post.num_comments,
    "Subthread name": post.title,
}
writer.writerow(data)
</code>```

For more information how to use the dictwriter you can go here: https://www.programiz.com/python-programming/writing-csv-files

Body:
This code is supposed to get some information about a post like title, upvotes etc. And then write it in a CSV file. But when is run it I get this error:

Traceback (most recent call last):
  File "main.py", line 71, in <module>
    writer.writerow(data)
  File "/usr/lib/python3.8/csv.py", line 154, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/usr/lib/python3.8/csv.py", line 151, in <genexpr>
    return (rowdict.get(key, self.restval) for key in self.fieldnames)
AttributeError: 'set' object has no attribute 'get'

And this is the code:

    import praw
    import random
    import time
    import csv
    #from keep_Aliv import keep_alive

    username = "XXXXXX"

    #keep_alive()

    print('AAAAAAA')

    reddit = praw.Reddit(client_id="XXXXXX",
                         client_secret="XXXXXX",
                         user_agent="bot",
                         username=username,
                         password='XXXXXX')

    subreddit = reddit.subreddit('all')

   with open('pdata.csv', 'a') as f:
    headers = [
        'ID', 'Date_utc', 'Upvotes', 'Number of Comments', 'Subthread name'
    ]
    writer = csv.DictWriter(f,
                            fieldnames=headers,
                            extrasaction='ignore',
                            dialect='excel')
    writer.writeheader()
    for post in subreddit.stream.submissions():
        #print(post.title)

        data = {
                "ID": post.id,
                "Date_utc": post.created_utc,
                "Upvotes": post.ups,
                "Number of comments": post.num_comments,
                "Subthread name": post.title,
                }
        writer.writerow(data)
        print(data)

ok, so how am I supposed to fix this? pls tell if some other information is required.

Thanks :)

(The main problem is now fixed and the compiler is not throwing an error now, but on the other hand the program isn't writing anything in the csv file. There isn't any error detected by the compiler but it's still not doing what it's supposed to. How do I fix that? btw the code in the post the working code)

Body:
You are using a dict writer, which accepts dicts. You are passing a string to it.

You should construct a dict, and write that:

data = {
    "ID": post,
    "Date_utc": post.created_utc,
    "Upvotes": post.ups,
    "Number of comments": post.num_comments,
    "Subthread name": post.title,
}
writer.writerow(data)

For more information how to use the dictwriter you can go here: https://www.programiz.com/python-programming/writing-csv-files