问:
How does virtual dispatch interact with covariant return types?
With C++ support for covariant return types, you can write the following:

```<code>class Base {};
class Derived : public Base {};

...

class A {
 public:
  A(Base* b) : b_(b) {}
  virtual Base* Method() { return b_; }

 private:
  Base* b_;
}

class B : public A {
 public:
  B(Derived* b) : A(b) {}
  // Return `Derived*` type so callers can access functionality specific to
  // `Derived` (i.e., not in `Base`).
  Derived* Method() override {
    static_assert(std::is_base_of_v<Base, Derived>);
    // Need to call `A::Method()` since `b_` is private.
    // Alternatively, we can make `b_` protected and access it directly.
    return dynamic_cast<Derived*>(A::Method());
  }
}
</code>```

It seems like in most cases that use covariant return types, the derived class's method (B::Method() above) will just do a dynamic cast and return the narrower pointer type. It will not do anything else.

Given that assumption, is it generally better to not use virtual dispatch (i.e., remove the virtual and overridden keywords) for Method() to improve performance? After all, any generic code that operates on an A* type will have to use the Base* type to store the return value of A::Method() (even if the real type of the object that the pointer points to is Derived), but as long Base uses virtual dispatch properly, then the correct methods will be called on Base* whether they are Base's methods or Derived's methods.

答:
It seems like in most cases that use covariant return types, the derived class's method (B::Method() above) will just do a dynamic cast and return the narrower pointer type. It will not do anything else.

I would not be so sure about that.

These two features serve two different purposes:

virtual methods allow virtual dispatch - runtime choice of the code to execute based on the runtime type of the caller.

return type covariance leverages the type system to further constraint the return type as long as the "minimal API" given by Base is satisfied. This is compile-time check.

I would strongly argue that B::Method should not exist in it's current form at all, let's take this hierarchy:

```<code>struct Base{
    virtual ~Base()=default;
};
struct D1:Base{};
struct D2:Base{};

struct A {
  virtual Base* Method() { return new D1{}; }
};

struct B1 : A {
  D1* Method() override {
    return dynamic_cast<D1*>(A::Method());
  }
};
struct B2 : A {
  D2* Method() override {
    return dynamic_cast<D2*>(A::Method());
  }
};

</code>```

and this usage:

```<code>
#include <cassert>

int main()
{
    B1 b1;
    B2 b2;

    A* a = &b1;
    assert(a->Method()!=nullptr);
    a = &b2;
    assert(a->Method()==nullptr);
}
</code>```

That seems a little strange, how would you write the documentation of this A::Method? What could it be used for? A filter maybe?

I think the more common example, at least from what I've seen, is that the derived method produces a derived result on its own. Take for example hiearchy of Request, Response with virtual Response* Request::process method. Special requests likely return special responses.

To answer your question:
If you remove virtual, you lose virtual dispatch, if the user code can do with static polymorphism, sure. Just give it some though beforehand, in my experience, if you start replacing member variables of type Base* with T in some Foo, the templated code needed to handle storage of these now heterogenous Foo<T> tends to spread rather quickly. And for what, performance only? Surely you are considering this only because you measured the code and it is a clear bottleneck in your application.

Body:
With C++ support for covariant return types, you can write the following:

class Base {};
class Derived : public Base {};

...

class A {
 public:
  A(Base* b) : b_(b) {}
  virtual Base* Method() { return b_; }

 private:
  Base* b_;
}

class B : public A {
 public:
  B(Derived* b) : A(b) {}
  // Return `Derived*` type so callers can access functionality specific to
  // `Derived` (i.e., not in `Base`).
  Derived* Method() override {
    static_assert(std::is_base_of_v<Base, Derived>);
    // Need to call `A::Method()` since `b_` is private.
    // Alternatively, we can make `b_` protected and access it directly.
    return dynamic_cast<Derived*>(A::Method());
  }
}

It seems like in most cases that use covariant return types, the derived class's method (B::Method() above) will just do a dynamic cast and return the narrower pointer type. It will not do anything else.

Given that assumption, is it generally better to not use virtual dispatch (i.e., remove the virtual and overridden keywords) for Method() to improve performance? After all, any generic code that operates on an A* type will have to use the Base* type to store the return value of A::Method() (even if the real type of the object that the pointer points to is Derived), but as long Base uses virtual dispatch properly, then the correct methods will be called on Base* whether they are Base's methods or Derived's methods.

Body:
It seems like in most cases that use covariant return types, the derived class's method (B::Method() above) will just do a dynamic cast and return the narrower pointer type. It will not do anything else.

I would not be so sure about that.

These two features serve two different purposes:

virtual methods allow virtual dispatch - runtime choice of the code to execute based on the runtime type of the caller.

return type covariance leverages the type system to further constraint the return type as long as the "minimal API" given by Base is satisfied. This is compile-time check.

I would strongly argue that B::Method should not exist in it's current form at all, let's take this hierarchy:

struct Base{
    virtual ~Base()=default;
};
struct D1:Base{};
struct D2:Base{};

struct A {
  virtual Base* Method() { return new D1{}; }
};

struct B1 : A {
  D1* Method() override {
    return dynamic_cast<D1*>(A::Method());
  }
};
struct B2 : A {
  D2* Method() override {
    return dynamic_cast<D2*>(A::Method());
  }
};

and this usage:

#include <cassert>

int main()
{
    B1 b1;
    B2 b2;

    A* a = &b1;
    assert(a->Method()!=nullptr);
    a = &b2;
    assert(a->Method()==nullptr);
}

That seems a little strange, how would you write the documentation of this A::Method? What could it be used for? A filter maybe?

I think the more common example, at least from what I've seen, is that the derived method produces a derived result on its own. Take for example hiearchy of Request, Response with virtual Response* Request::process method. Special requests likely return special responses.

To answer your question:
If you remove virtual, you lose virtual dispatch, if the user code can do with static polymorphism, sure. Just give it some though beforehand, in my experience, if you start replacing member variables of type Base* with T in some Foo, the templated code needed to handle storage of these now heterogenous Foo<T> tends to spread rather quickly. And for what, performance only? Surely you are considering this only because you measured the code and it is a clear bottleneck in your application.


来源: stackexchange

问:
pm2 Single Page Application flag --spa throws 'unknown option' error
I am using pm2 (5.1.2) and serve (13.0.2) to deploy a Node.js app. When I run the following:

pm2 serve build 8080 --spa

I receive the following error:

error: unknown option '--spa'

Is the flag deprecated? What could be causing this?

答:
For pm2 there needs to be a space between -- and flags. The correct format is:

pm2 serve build 8080 -- spa

ContentLicense: CC BY-SA 4.0


问:
Child component value not updating after set state
I am attempting to update properties on a parent object via button clicks in the child components. After clicking the increment  button neither of the child components get updated.

NOTE: id is purely to differentiate between propA and B for saving state

Also is there a nice way to deal updating object properties without having to do a switch statement

Minimum reproduction

```<code>import { useState } from "react";
import "./styles.css";

export default function App() {
  let [object, setObject] = useState({
    propertyA: 0,
    propertyB: 0
  });

  function handleClick(id) {
    switch (id) {
      case 1:
        setObject((prevState) => ({
          ...prevState,
          propertyA: prevState.propertyA + 1
        }));
        break;
      case 2:
        setObject((prevState) => ({
          ...prevState,
          propertyB: prevState.propertyB + 1
        }));
        break;
      default:
        console.log(id);
        break;
    }
  }

  return (
    <div className="App">
      <Child
        id="1"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />
      <Child
        id="2"
        title="property B"
        value={object.propertyB}
        handleClick={handleClick}
      />
    </div>
  );
}

function Child(props) {
  return (
    <div>
      {props.title} : {props.value}
      <button onClick={props.handleClick(props.id)}>Increment</button>
    </div>
  );
}
</code>```

答:
onClick={props.handleClick(props.id)} should be onClick={()=>props.handleClick(props.id)},
and for the avoiding switch you can set the id as the property name

```<code> <Child
        id="propertyA"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />
</code>```

and then

```<code>function handleClick(id) {
  setObject((prevState) => ({
          ...prevState,
         [id]: prevState[id] + 1
        }))
}
</code>```

Body:
I am attempting to update properties on a parent object via button clicks in the child components. After clicking the increment  button neither of the child components get updated.

NOTE: id is purely to differentiate between propA and B for saving state

Also is there a nice way to deal updating object properties without having to do a switch statement

Minimum reproduction

import { useState } from "react";
import "./styles.css";

export default function App() {
  let [object, setObject] = useState({
    propertyA: 0,
    propertyB: 0
  });

  function handleClick(id) {
    switch (id) {
      case 1:
        setObject((prevState) => ({
          ...prevState,
          propertyA: prevState.propertyA + 1
        }));
        break;
      case 2:
        setObject((prevState) => ({
          ...prevState,
          propertyB: prevState.propertyB + 1
        }));
        break;
      default:
        console.log(id);
        break;
    }
  }

  return (

      <Child
        id="1"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />
      <Child
        id="2"
        title="property B"
        value={object.propertyB}
        handleClick={handleClick}
      />

  );
}

function Child(props) {
  return (

      {props.title} : {props.value}
      <button onClick={props.handleClick(props.id)}>Increment</button>

  );
}

Body:
onClick={props.handleClick(props.id)} should be onClick={()=>props.handleClick(props.id)},
and for the avoiding switch you can set the id as the property name

 <Child
        id="propertyA"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />

and then

function handleClick(id) {
  setObject((prevState) => ({
          ...prevState,
         [id]: prevState[id] + 1
        }))
}


问:
Android Room Persistent library update not working
I'm using room in my new Android app, and I'm trying to update an a model object's property at runtime, but it doesn't seem to get saved.

Entity

```<code>@Entity(tableName = "sessions")
data class Session(@ColumnInfo(name="id") @PrimaryKey(autoGenerate = true) var id: Int = 0,
                   @ColumnInfo(name="date") var date: Date,
                   @ColumnInfo(name="repetitions_completed") var repetitionsCompleted: Int,
                    @ColumnInfo(name="squeeze_time_per_rep") var squeezeTimePerRep: Int,
                    @ColumnInfo(name="finishing_repetitions_completed") var finishingRepetitionsCompleted: Int,
                    @ColumnInfo(name="finishing_squeeze_time_per_rep") var finishingSqueezeTimePerRep: Int)
</code>```

In my app I'm using it like this

```<code>session = Session(0,date,0,slowSeconds,0,quickSeconds)
sessionDao.insertAll(sessionDB)

...
session.repetitionsCompleted = totalSlowReps
session.finishingRepetitionsCompleted = totalQuickReps
sessionDao.updateSessions(session)
</code>```

The problem is that session's property values like repetitionsCompleted and finishingRepetitionsCompleted doesn't seem to be saved, and it always remain 0 when I restart the app. updateSessions also returns 0

Here is the code for the Dao

```<code>@Dao
interface SessionDao {

    // https://developer.android.com/training/data-storage/room/accessing-data#query-params

    @Query("SELECT * FROM sessions")
    fun getAll(): List<Session>

    @Query("SELECT * FROM sessions WHERE date BETWEEN :from AND :to")
    fun getSessionsBetween(from: Date, to: Date): List<Session>

    @Query("SELECT * FROM sessions ORDER BY date LIMIT 1")
    fun getOldestSession(): List<Session>

    @Update
    fun updateSessions(vararg sessions: Session) : Int

    @Insert
    fun insertAll(vararg sessions: Session)

}
</code>```

What's weirder is that update seems to work in my unit test, but not in the actual app code.

I don't know if this affects things, but I'm running this in a service.

答:
Maybe you're not sending the class id.

the value @PrimaryKey of the @Entity Class

Body:
I'm using room in my new Android app, and I'm trying to update an a model object's property at runtime, but it doesn't seem to get saved.

Entity

@Entity(tableName = "sessions")
data class Session(@ColumnInfo(name="id") @PrimaryKey(autoGenerate = true) var id: Int = 0,
                   @ColumnInfo(name="date") var date: Date,
                   @ColumnInfo(name="repetitions_completed") var repetitionsCompleted: Int,
                    @ColumnInfo(name="squeeze_time_per_rep") var squeezeTimePerRep: Int,
                    @ColumnInfo(name="finishing_repetitions_completed") var finishingRepetitionsCompleted: Int,
                    @ColumnInfo(name="finishing_squeeze_time_per_rep") var finishingSqueezeTimePerRep: Int)

In my app I'm using it like this

session = Session(0,date,0,slowSeconds,0,quickSeconds)
sessionDao.insertAll(sessionDB)

...
session.repetitionsCompleted = totalSlowReps
session.finishingRepetitionsCompleted = totalQuickReps
sessionDao.updateSessions(session)

The problem is that session's property values like repetitionsCompleted and finishingRepetitionsCompleted doesn't seem to be saved, and it always remain 0 when I restart the app. updateSessions also returns 0

Here is the code for the Dao

@Dao
interface SessionDao {

    // https://developer.android.com/training/data-storage/room/accessing-data#query-params

    @Query("SELECT * FROM sessions")
    fun getAll(): List<Session>

    @Query("SELECT * FROM sessions WHERE date BETWEEN :from AND :to")
    fun getSessionsBetween(from: Date, to: Date): List<Session>

    @Query("SELECT * FROM sessions ORDER BY date LIMIT 1")
    fun getOldestSession(): List<Session>

    @Update
    fun updateSessions(vararg sessions: Session) : Int

    @Insert
    fun insertAll(vararg sessions: Session)

}

What's weirder is that update seems to work in my unit test, but not in the actual app code.

I don't know if this affects things, but I'm running this in a service.


问:
How to send data from S3 to redshift without duplicating and truncating table By LAMBDA?
I wish to copy data from S3 to Redshift.

However, the Copy command always duplicates the rows whenever the Lambda function triggers:

```<code>cur.execute('copy table from S3...... ' )
</code>```

Can someone suggest other ways to do it without truncating existing data?

for commenters: I tried to push directly from the dataframe to redshift.. append

There is one library pandas_redshift but it needs s3 connection first which might solve appending issue)

I also tried
#if cur.execute('truncate')  it can keep the table empty but I don't have delete rights

cur.execute('select distinct * from ABC.xyz')

cur.execute('copy......')

results keep appending...

Can someone please provide any code or right series of execution.

答:
Unfortunately there is no straight forward option to copy the files to perform upsert which can handle duplicates.

If you don't want to truncate the table, there are two workarounds:

You can create a staging table where you can copy the data first and then perform merge option. That will also act as upsert statement.

https://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-upsert.html

You can use manifest to control which files you want to copy and which needs to be avoided.
https://docs.aws.amazon.com/redshift/latest/dg/r_COPY_command_examples.html#copy-command-examples-manifest

Body:
I wish to copy data from S3 to Redshift.

However, the Copy command always duplicates the rows whenever the Lambda function triggers:

cur.execute('copy table from S3...... ' )

Can someone suggest other ways to do it without truncating existing data?

for commenters: I tried to push directly from the dataframe to redshift.. append

There is one library pandas_redshift but it needs s3 connection first which might solve appending issue)

I also tried
#if cur.execute('truncate')  it can keep the table empty but I don't have delete rights

cur.execute('select distinct * from ABC.xyz')

cur.execute('copy......')

results keep appending...

Can someone please provide any code or right series of execution.


问:
Contact details are not updated on Google Assistant page
I've updated Contact details on https://console.actions.google.com/ -> Deploy -> Directory information. I can see them there. But I can't see updated info on the Google Assistant page (https://assistant.google.com/ -> explore actions).

How this issue could be fixed?

Does Google Assistant page update all info mentioned on Directory information tab at the same time?

答:
Every action needs to be reviewed before being published to production so that might be the reason the Assistant page doesn’t show the updated information. You can reach out to the certification team by creating a support ticket and coordinate your contact detail change.

You can find more information about publishing your smart Home Action at https://developers.google.com/assistant/smarthome/develop/directory-information


问:
Using Variable Variable names (lists) in creating pandas datasets
I am creating datasets using data from JSON API. The program below works but the pandas datasets cannot be referenced using the object names in list (df1 or dff1) but only when they are referenced as list items: dct1(1). I would love to learn why this is happening or maybe there is an error in the code.</p>
```<code>dct1 = ['df1', 'df2', 'df3', 'df4']
dct2 = ['dff1', 'dff2', 'dff3', 'dff4']
dct3 = ['file1', 'file2', 'file3','file4']
for i in range(0,4):
    off=1000*i
    url = 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    dct2[i]=pd.read_json(url)
    dct3[i]= 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    dct1[i]=pd.read_json(dct3[i])
dct1[1].head(3)
Out[64]:
   Year State_Name  ... Avg_Risk_Score_AGND  Person_Years_AGND
0  2020   Kentucky  ...             1.08687            5509.67
1  2020   Kentucky  ...             1.05350             871.25
2  2020   Kentucky  ...             0.96509            1290.42
print(df1)
NameError: name 'df1' is not defined
print(dff1)
NameError: name 'dff1' is not defined**
</code>```

答:
It looks like what you're actually trying to do is set the name of variables within your workspace to the strings contained in dct1 and dct2. To do that, you can do something like this.

```<code>dct1 = ['df1', 'df2', 'df3', 'df4']
dct2 = ['dff1', 'dff2', 'dff3', 'dff4']
dct3 = ['file1', 'file2', 'file3','file4']
for i in range(0,4):
    off=1000*i
    url = 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    locals()[dct2[i]]=pd.read_json(url)
    locals()[dct3[i]]= 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    locals()[dct1[i]]=pd.read_json(dct3[i])
</code>```

However, a more conventional approach is to simply make a dictionary for which d['[name]'] has the desired value rather than assigning that value to a variable called [name].

Body:
I am creating datasets using data from JSON API. The program below works but the pandas datasets cannot be referenced using the object names in list (df1 or dff1) but only when they are referenced as list items: dct1(1). I would love to learn why this is happening or maybe there is an error in the code.

dct1 = ['df1', 'df2', 'df3', 'df4']
dct2 = ['dff1', 'dff2', 'dff3', 'dff4']
dct3 = ['file1', 'file2', 'file3','file4']
for i in range(0,4):
    off=1000*i
    url = 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    dct2[i]=pd.read_json(url)
    dct3[i]= 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    dct1[i]=pd.read_json(dct3[i])
dct1[1].head(3)
Out[64]:
   Year State_Name  ... Avg_Risk_Score_AGND  Person_Years_AGND
0  2020   Kentucky  ...             1.08687            5509.67
1  2020   Kentucky  ...             1.05350             871.25
2  2020   Kentucky  ...             0.96509            1290.42
print(df1)
NameError: name 'df1' is not defined
print(dff1)
NameError: name 'dff1' is not defined**

Body:
It looks like what you're actually trying to do is set the name of variables within your workspace to the strings contained in dct1 and dct2. To do that, you can do something like this.

dct1 = ['df1', 'df2', 'df3', 'df4']
dct2 = ['dff1', 'dff2', 'dff3', 'dff4']
dct3 = ['file1', 'file2', 'file3','file4']
for i in range(0,4):
    off=1000*i
    url = 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    locals()[dct2[i]]=pd.read_json(url)
    locals()[dct3[i]]= 'https://data.cms.gov/data-api/v1/dataset/7b181182-828c-4fa4-91bd-641759f6eddd/data?size=1000&offset={0}'.format(off)
    locals()[dct1[i]]=pd.read_json(dct3[i])

However, a more conventional approach is to simply make a dictionary for which d['[name]'] has the desired value rather than assigning that value to a variable called [name].


问:
4 buttons in 4 corners of the screen
I am working on a school project, and i need to place 4 buttons in the 4 quadrants of the screen. However, the first button has a little gap between it and the top of the screen as well as the side.

Code:

game.html

```<code><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>Game</title>
<link rel="stylesheet" href="css/game.css">
</head>
<body>
<div id="container">
<button class="button">A</button>
<button class="button">B</button>
<button class="button">C</button>
<button class="button">D</button>
</div>
</body>
</html>
</code>```

game.css

```<code>body {
  background-color: black;
  overflow: hidden;
  position: fixed;
}
h1, h2 {
  color: white;
  font-family: Ubuntu Mono;
}
#container {
  width: 100%;
  min-height: 100%;
  height: 100%;
}
.button {
  border: none;
  color: white;
  width: 50%;
  height: 50vh;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-family: Ubuntu Mono;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  position: fixed;
}
.button: nth-child(1) {
  background-color: #bf0000;
  top: 0;
  left: 0;
}
.button:nth-child(2) {
  background-color: #001fbf;
  top: 0;
  right: 0;
}
.button:nth-child(3) {
  background-color: #e6c52d;
  bottom: 0;
  left: 0;
}
.button:nth-child(4) {
  background-color: #1fbf1f;
  bottom: 0;
  right: 0;
}
</code>```

However, i get the output shown here:

How can I remove the gap at the first button?

(and if you want, help me with the color :D)

Any help is appreciated! :D

答:
It's a typo within CSS.

```<code>.button:nth-child(1) {
  background-color: #bf0000;
  top: 0;
  left: 0;
}
</code>```

Remove the space after .button:

Title: 4 buttons in 4 corners of the screen

Body:
I am working on a school project, and i need to place 4 buttons in the 4 quadrants of the screen. However, the first button has a little gap between it and the top of the screen as well as the side.

Code:

game.html

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>Game</title>
<link rel="stylesheet" href="css/game.css">

<button class="button">A</button>
<button class="button">B</button>
<button class="button">C</button>
<button class="button">D</button>

game.css

body {
  background-color: black;
  overflow: hidden;
  position: fixed;
}
h1, h2 {
  color: white;
  font-family: Ubuntu Mono;
}
#container {
  width: 100%;
  min-height: 100%;
  height: 100%;
}
.button {
  border: none;
  color: white;
  width: 50%;
  height: 50vh;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-family: Ubuntu Mono;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  position: fixed;
}
.button: nth-child(1) {
  background-color: #bf0000;
  top: 0;
  left: 0;
}
.button:nth-child(2) {
  background-color: #001fbf;
  top: 0;
  right: 0;
}
.button:nth-child(3) {
  background-color: #e6c52d;
  bottom: 0;
  left: 0;
}
.button:nth-child(4) {
  background-color: #1fbf1f;
  bottom: 0;
  right: 0;
}

However, i get the output shown here:

How can I remove the gap at the first button?

(and if you want, help me with the color :D)

Any help is appreciated! :D

Body:
It's a typo within CSS.

.button:nth-child(1) {
  background-color: #bf0000;
  top: 0;
  left: 0;
}

Remove the space after .button:


问:
Recoding rare categories of a variable to category -"other" based on condition
Need to transform variable below, based on category quantity in the dataset

so that categories that appear less than two times are re-named to category "other"

Data example

Desirable output

I used to use below chunk of code for such transformation but since I moved to R 4.05 it throws me an error.

```<code>levels(data$Country_of_origin) <-ifelse(table(data&Country_of_origin)>2,"OTHER",levels(data&Country_of_origin))
</code>```

答:
Using dplyr, you can calculate frequency after group_by(country) and then mutate country when below a threshold:

library(dplyr)
library(tidyr)

data <- tibble( country = c('USA', 'USA', 'Germany', 'Japan', 'USA', 'USA'))

data |>
  group_by(country) |>
  mutate(country = ifelse(n() < 2, "OTHER", country))

# A tibble: 6 × 1
# Groups:   country [2]
  country
  <chr>
1 USA
2 USA
3 OTHER
4 OTHER
5 USA
6 USA
```

Body:
Need to transform variable below, based on category quantity in the dataset

so that categories that appear less than two times are re-named to category "other"

Data example

Desirable output

I used to use below chunk of code for such transformation but since I moved to R 4.05 it throws me an error.

levels(data$Country_of_origin) <-ifelse(table(data&Country_of_origin)>2,"OTHER",levels(data&Country_of_origin))


问:
Need help creating a Regex
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

答:
```<code>@"^20\d{2}[0-1]\d[1-3]$"
</code>```

Starts with 20, then 2 of any digits, then 0 or 1, then any digits, then 1, 2 or 3. If you need additional digits after the 7th, you can insert a \d* before the $:

```<code>@"^20\d{2}[0-1]\d[1-3]\d*$"
</code>```

Edit: As CodeMonkey points out, \d will be interpreted in C# as an escape sequence, so be sure to use a verbatim string (as now shown above.)

ContentLicense: CC BY-SA 3.0

Title: Need help creating a Regex

Body:
@"^20\d{2}[0-1]\d[1-3]$"

Starts with 20, then 2 of any digits, then 0 or 1, then any digits, then 1, 2 or 3. If you need additional digits after the 7th, you can insert a \d* before the $:

@"^20\d{2}[0-1]\d[1-3]\d*$"

Edit: As CodeMonkey points out, \d will be interpreted in C# as an escape sequence, so be sure to use a verbatim string (as now shown above.)


问:
Refresh query table when cell changes
I've build a number of tables using Power Query.  For table "TemplateDataQry", I have a parameter value in cell "G2".  The table resides on sheet "TemplateData"

What code is needed to automatically refresh the query when the the parameter cell changes?  i have not located anything yet that would work.

答: I found using the Worksheet Event pointing at the the parameter cell was the easiest way to handle it.</p>

Title: Refresh query table when cell changes


问:
SQLAlchemy + alembic: create schema migration
I'm not sure how to define a create schema foo migration? My Model looks like this (I'm using Flask-Migrate):

```<code>class MyTable(db.Model):
    __tablename__ = "my_table"
    __table_args__ = {"schema": "foo"}

    id = ColumnPrimKey()
    name = Column(Text, unique=True, nullable=False)
</code>```

When I execute mange db upgrade I get a failure because the schema "foo" does not exist. How can I add a migration for the schema with SQLAlchemy and Alembic?

答:
A potential issue with the accepted answer is that, for an initial migration, Alembic might have trouble finding a place to create the alembic_version. This is because because op.execute("create schema foo") is only executed after Alembic attempts to find its alembic_version table. The error pops up as:

```<code>sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidSchemaName) schema "foo" does not exist
</code>```

The easy way out would be to have the alembic_version table live in another schema passing version_table_schema to context.configure() (docs).

However, in many cases one might want to simultaneously (i) create a schema from scratch as part of an initial migration (e.g. to set up a testing environment) and (ii) have the alembic_version table in the target schema. In these cases, an alternative approach is to delegate the schema creation to env.py. Example:

# env.py
from sqlalchemy import create_engine

from bar import create_database_with_schema_if_not_exists

SQLALCHEMY_DATABASE_URI = ...
schema = "foo"
engine = create_engine(SQLALCHEMY_DATABASE_URI)
create_database_with_schema_if_not_exists(engine, schema)
...
```
<pre class="lang-py prettyprint-override"><code># bar.py
import sqlalchemy
from sqlalchemy_utils import create_database, database_exists

def create_database_with_schema_if_not_exists(engine, schema):
    if not database_exists(engine.url):
        create_database(engine.url)
    if not engine.dialect.has_schema(engine, schema):
        engine.execute(sqlalchemy.schema.CreateSchema(schema))
</code>```

Body:
I'm not sure how to define a create schema foo migration? My Model looks like this (I'm using Flask-Migrate):

class MyTable(db.Model):
    __tablename__ = "my_table"
    __table_args__ = {"schema": "foo"}

    id = ColumnPrimKey()
    name = Column(Text, unique=True, nullable=False)

When I execute mange db upgrade I get a failure because the schema "foo" does not exist. How can I add a migration for the schema with SQLAlchemy and Alembic?

Body:
A potential issue with the accepted answer is that, for an initial migration, Alembic might have trouble finding a place to create the alembic_version. This is because because op.execute("create schema foo") is only executed after Alembic attempts to find its alembic_version table. The error pops up as:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidSchemaName) schema "foo" does not exist

The easy way out would be to have the alembic_version table live in another schema passing version_table_schema to context.configure() (docs).

However, in many cases one might want to simultaneously (i) create a schema from scratch as part of an initial migration (e.g. to set up a testing environment) and (ii) have the alembic_version table in the target schema. In these cases, an alternative approach is to delegate the schema creation to env.py. Example:

# env.py
from sqlalchemy import create_engine

from bar import create_database_with_schema_if_not_exists

SQLALCHEMY_DATABASE_URI = ...
schema = "foo"
engine = create_engine(SQLALCHEMY_DATABASE_URI)
create_database_with_schema_if_not_exists(engine, schema)
...

# bar.py
import sqlalchemy
from sqlalchemy_utils import create_database, database_exists

def create_database_with_schema_if_not_exists(engine, schema):
    if not database_exists(engine.url):
        create_database(engine.url)
    if not engine.dialect.has_schema(engine, schema):
        engine.execute(sqlalchemy.schema.CreateSchema(schema))


问:
How to get real-time data on new data insert into MySQL db
I am using Laravel and pusher. Pusher is working good. But I want to know how can I get data when I will insert new data into database?

Process is if someone push/insert data on the table, then those data will automatically show without reloading the page.

Can anyone explain it? or give me any documentation or video link about it?

答:
What you need are Broadcast Events.

Let's assume that you are inserting a Post and you want all users to get notified about a new post, therefore refresh the posts table index.
All your users should be subscribed to a presence channel, but you could use private or public channel. IMO, presence channel works better for this scenario since you are dispatching just 1 event for all users instead of 1 event per user in case of private channel

In your store function in PostController.php you dispatch the event once Post has been created:

```<code>use App\Events\PostCreated;

public function store(Request $request)
{
    // Insert new post
    $post = Post::create($request->all());

    // Dispatch broadcast
    PostCreated::dispatch($post);

    return $result;
}
</code>```

Then in your PostCreated.php Event, you send the post itself as the event payload:

```<code><?php

namespace App\Events;

use App\Models\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PostCreated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $afterCommit = true;

    public Post $post;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'post.created';
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return $this->post;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('posts');
    }
}
</code>```

Now you need that all users subscribe to the right channel. Assuming, again, that you are using laravel echo, this is how I do it within a Vue Js app by joining a presence channel posts and listening for post.created event.

```<code>this.echoInstance.join('posts')
    .listen('.post.created', (post) => {
        // Do something like refresh table
        // or insert `post` object directly in posts array
    })
</code>```

Since you didn't provide any code, this is a generic sample. Next time, please share what you've done so far.

Body:
What you need are Broadcast Events.

Let's assume that you are inserting a Post and you want all users to get notified about a new post, therefore refresh the posts table index.
All your users should be subscribed to a presence channel, but you could use private or public channel. IMO, presence channel works better for this scenario since you are dispatching just 1 event for all users instead of 1 event per user in case of private channel

In your store function in PostController.php you dispatch the event once Post has been created:

use App\Events\PostCreated;

public function store(Request $request)
{
    // Insert new post
    $post = Post::create($request->all());

    // Dispatch broadcast
    PostCreated::dispatch($post);

    return $result;
}

Then in your PostCreated.php Event, you send the post itself as the event payload:

<?php

namespace App\Events;

use App\Models\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PostCreated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $afterCommit = true;

    public Post $post;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'post.created';
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return $this->post;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('posts');
    }
}

Now you need that all users subscribe to the right channel. Assuming, again, that you are using laravel echo, this is how I do it within a Vue Js app by joining a presence channel posts and listening for post.created event.

this.echoInstance.join('posts')
    .listen('.post.created', (post) => {
        // Do something like refresh table
        // or insert `post` object directly in posts array
    })

Since you didn't provide any code, this is a generic sample. Next time, please share what you've done so far.


问:
how to remove sails js default log messages
Please how to remove this default log messages that are displayed when "sails lift" that also written to my external log files :</p>

```<code>info: Starting app...

debug: Deprecation warning: Support for `sails.config.sockets.onConnect` will be
 removed in an upcoming release. See the v0.11 migration guide for more informat
ion and alternate options.
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v0.12.4             |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `E:\Orange\sailsJS_workspace\server`
info: To see your app, visit http://localhost:1337
info: To shut down Sails, press <CTRL> + C at any time.
debug: -------------------------------------------------------
debug: :: Wed Nov 02 2016 12:03:45 GMT+0200 (Egypt Standard Time)
debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------
</code>```

答:
Set level: to silent in the log.js

Ex:

```<code>module.exports.log = {
    custom: blahblahBlah,
    inspect: false
    level: 'info'
};
</code>```

Body:
Please how to remove this default log messages that are displayed when "sails lift" that also written to my external log files :

info: Starting app...

debug: Deprecation warning: Support for `sails.config.sockets.onConnect` will be
 removed in an upcoming release. See the v0.11 migration guide for more informat
ion and alternate options.
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v0.12.4             |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `E:\Orange\sailsJS_workspace\server`
info: To see your app, visit http://localhost:1337
info: To shut down Sails, press <CTRL> + C at any time.
debug: -------------------------------------------------------
debug: :: Wed Nov 02 2016 12:03:45 GMT+0200 (Egypt Standard Time)
debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------

Body:
Set level: to silent in the log.js

Ex:

module.exports.log = {
    custom: blahblahBlah,
    inspect: false
    level: 'info'
};


问:
Possible to launch Apple's default weather app from my application?
One of my client wants to open Apple's native weather app from our application. After few I don't see a possible way, unless we need to go with any 3rd party apps which provides custom url scheme.

http://developer.apple.com/library/ios/#featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007899

It would be great if someone confirm or give me a lead if it is possible.

答:
The website handleOpenURL is an excellent resource for custom iOS URL schemes; use this link to search for the known Apple app schemes.

Unfortunately the weather app is not among them.

Another couple of sites with schemes (handleOpenURL seems to be the most complete, but it can't hurt to check the others):

app lookup

Akosma iPhone URL Scheme Wiki


问:
Batch process !ERRORLEVEL! is not working when running multiple commands in parallel
I am trying to create a batch script which runs 2 python scripts in parallel and return an errorcode if in either one (or both) of the scripts is an error. In case both script have run correctly the next python script should be ran.

When I use the script below the processes are ran in parallel but the !errorlevel! is always 0, even if there is an error in both of the scripts.

In case I run only one of the python scripts with the start /wait command or if I run the 2 scripts sequentially using && instead of |, the !errorlevel! is returned correctly.

How can these scripts be run in parallel while still output the correct errorlevel?

```<code>setlocal enableDelayedExpansion
start /wait python apirequest_0001.py | start /wait python apirequest_0002.py
echo !errorlevel!
if !errorlevel! neq 0 (goto end )
start /wait python join_data.py
</code>```

答:
A couple points here...

The start command is used to run a process in parallel, but start /wait switch cancel such a feature and waits for the process to end. In this way, using start /wait is the same as no use start command at all...

However, in your example both commands are connected via a pipeline, so they are effectively executed in parallel (because the pipe, not the start command).

The simplest way to get the ERRORLEVEL value of two (or more) parallel processes is via an auxiliary file:

```<code>del error.aux 2> NUL
(python apirequest_0001.py & if errorlevel 1 echo X > error.aux) | (python apirequest_0002.py & if errorlevel 1 echo X > error.aux)
if exist error.aux goto end
python join_data.py
</code>```

Although a "cleaner" way to do this is via this method

```<code>del error.aux 2> NUL
(
  start "" "python apirequest_0001.py & if errorlevel 1 echo X > error.aux"
  start "" "python apirequest_0002.py & if errorlevel 1 echo X > error.aux"
) | pause
if exist error.aux goto end
python join_data.py
</code>```

Note: In this solution there is a possibility that both commands ends at the same time and try to create the file at "same time". However, this is not a problem in the case, because anyway the file will be created...

Body:
I am trying to create a batch script which runs 2 python scripts in parallel and return an errorcode if in either one (or both) of the scripts is an error. In case both script have run correctly the next python script should be ran.

When I use the script below the processes are ran in parallel but the !errorlevel! is always 0, even if there is an error in both of the scripts.

In case I run only one of the python scripts with the start /wait command or if I run the 2 scripts sequentially using && instead of |, the !errorlevel! is returned correctly.

How can these scripts be run in parallel while still output the correct errorlevel?

setlocal enableDelayedExpansion
start /wait python apirequest_0001.py | start /wait python apirequest_0002.py
echo !errorlevel!
if !errorlevel! neq 0 (goto end )
start /wait python join_data.py

Body:
A couple points here...

The start command is used to run a process in parallel, but start /wait switch cancel such a feature and waits for the process to end. In this way, using start /wait is the same as no use start command at all...

However, in your example both commands are connected via a pipeline, so they are effectively executed in parallel (because the pipe, not the start command).

The simplest way to get the ERRORLEVEL value of two (or more) parallel processes is via an auxiliary file:

del error.aux 2> NUL
(python apirequest_0001.py & if errorlevel 1 echo X > error.aux) | (python apirequest_0002.py & if errorlevel 1 echo X > error.aux)
if exist error.aux goto end
python join_data.py

Although a "cleaner" way to do this is via this method

del error.aux 2> NUL
(
  start "" "python apirequest_0001.py & if errorlevel 1 echo X > error.aux"
  start "" "python apirequest_0002.py & if errorlevel 1 echo X > error.aux"
) | pause
if exist error.aux goto end
python join_data.py

Note: In this solution there is a possibility that both commands ends at the same time and try to create the file at "same time". However, this is not a problem in the case, because anyway the file will be created...


问:
Input and Ouput to ECS task in Step function
Have previously worked with lambda orchestration using AWS step function. This has been working very well. Setting the result_path of each lambda will pass along arguments to subsequent lambda.

However, I now need to run a fargate task and then pass along arguments from that fargate task to subsequent lambdas. I have created a python script that acts as the entrypoint in the container definition. Obviously in a lambda function the handler(event, context) acts as the entrypoint and by defining a return {"return_object": "hello_world"} its easy to pass a long a argument to the next state of the state machine.

In my case though, I have task definition with a container definition created from this Dockerfile:

```<code>FROM python:3.7-slim

COPY my_script.py /my_script.py
RUN ln -s /python/my_script.py /usr/bin/my_script && \
chmod +x /python/my_script.py

ENTRYPOINT ["my_script"]
</code>```

Hence, I am able to invoke the state machine and it will execute my_script as intended. But how do I get the output from this python script and pass it along to another state in the state machine?

I have found some documentation on how to pass along inputs, but no example of passing along outputs.

答:
To get output from an ECS/Fargate task, I think you have to use the Task Token Integration instead of Run Job (Sync) which is usually recommended for Fargate tasks. You can pass the token as a container override ("TASK_TOKEN": "$$.Task.Token"). Then inside your image you need some logic like this:

client = boto3.client('stepfunctions')
client.send_task_success(
    taskToken=os.environ["TASK_TOKEN"],
    output=output
)
```

to pass it back.

Body:
Have previously worked with lambda orchestration using AWS step function. This has been working very well. Setting the result_path of each lambda will pass along arguments to subsequent lambda.

However, I now need to run a fargate task and then pass along arguments from that fargate task to subsequent lambdas. I have created a python script that acts as the entrypoint in the container definition. Obviously in a lambda function the handler(event, context) acts as the entrypoint and by defining a return {"return_object": "hello_world"} its easy to pass a long a argument to the next state of the state machine.

In my case though, I have task definition with a container definition created from this Dockerfile:

FROM python:3.7-slim

COPY my_script.py /my_script.py
RUN ln -s /python/my_script.py /usr/bin/my_script && \
chmod +x /python/my_script.py

ENTRYPOINT ["my_script"]

Hence, I am able to invoke the state machine and it will execute my_script as intended. But how do I get the output from this python script and pass it along to another state in the state machine?

I have found some documentation on how to pass along inputs, but no example of passing along outputs.

Body:
To get output from an ECS/Fargate task, I think you have to use the Task Token Integration instead of Run Job (Sync) which is usually recommended for Fargate tasks. You can pass the token as a container override ("TASK_TOKEN": "$$.Task.Token"). Then inside your image you need some logic like this:

client = boto3.client('stepfunctions')
client.send_task_success(
    taskToken=os.environ["TASK_TOKEN"],
    output=output
)

to pass it back.


问:
Why is my VS Code text all the same color?
Alright so, I'm new to coding and I got VS Code and for some reason, all my text is mostly the same color. At first when I open VS Code it looks like this:

But, as soon as I type something it looks like this:

It's kind of hard to see different variables or methods when it's all the same color. Any idea why it looks like that? Also, I'm not sure if it helps but I'm using unity as well.

答:
It looks like that VS Code has problems communicating with Unity. Because all the Unity stuff is blue, the rest is colored as normal.

I would check if VS Code is set as editor. You can see it here:

Edit -> Preferences -> External Tools -> External Script Editor

Make sure VS Code is set there.


问:
Need to compare two arrays with a callback and return an object in Javascript
Construct a function objOfMatches that accepts two arrays and a callback. objOfMatches will build an object and return it. To build the object, objOfMatches will test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value. I got this so far:

```<code>const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }
</code>```

答:
```<code>const objOfMatches = (array1, array2, callback) => array1.reduce((prev, curr) => {
  if (callback(curr) === prev.compareAgainst[0]) {
    prev.obj[curr] = prev.compareAgainst[0];
  }
  prev.compareAgainst = prev.compareAgainst.slice(1);
  return prev;
}, {obj: {}, compareAgainst: array2}).obj;

console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], (str) => str.toUpperCase()));
// should log: { hi: 'HI', bye: 'BYE', later: 'LATER' }
</code>```

Body:
Construct a function objOfMatches that accepts two arrays and a callback. objOfMatches will build an object and return it. To build the object, objOfMatches will test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value. I got this so far:

const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }


问:
Laravel (Lumen) Eloquent querying with WHERE on a relation (Multi-level)
I have the following DB tables:

```<code>Purchase
-id
-workplace_id

Workplace
-id
-client_id
</code>```

(and obviously some more fields, but for the example these are all the needed ones).
I would like to make a query like this:

```<code>SELECT * FROM
  purchase
  INNER JOIN workplace ON (purchase.workplace_id = workplace.id)
WHERE
  (workplace.client_id = 1)
</code>```

I'm trying to make this work with the Eloquent models, but I can't figure out how to filter on a joined table.
I tried:

```<code>    $purchases = Purchase::query()
        -> workplace()
        -> where('client_id', '=', Auth::user() -> client_id)
        -> get();
</code>```

But apparently workplace() is undefined for some reason.

My Purchase.php model file looks like this:

```<code><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
    public function workplace(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Workplace::class);
    }
}
</code>```

Any pointers on how to make this simple select work?

Thanks!

====EDIT=====

I found a possible solution:

```<code>    $purchases = Purchase::with('workplace')
        -> whereHas('workplace', function($q) {
            return $q -> where('client_id', '=', Auth::user() -> client_id);
        })
        -> get();
</code>```

But this generates an SQL that seems more complicated and is probably also slower:

```<code>select * from `purchases` where exists (select * from `workplaces` where `purchases`.`workplace_id` =
`workplaces`.`id` and `client_id` = ? and `workplaces`.`deleted_at` is null)
</code>```

So I'm still looking for better alternatives

答:
If you want to do a join, you need to build it with the join method, you can't use a relationship. See here for the docs:

https://laravel.com/docs/9.x/queries#joins

So you should be able to do something like this:

```<code>$purchases = Purchase::query()
    ->join('workplace', 'purchase.workplace_id', '=', 'workplace.id')
    ->where('workplace.client_id', '=', Auth::user()->client_id)
    ->get();
</code>```

The generated SQL that you show in your edit is a sub-query, and you may still want to consider that. Sure, sub-queries are often slower than joins, but unless you're dealing with a massive dataset the performance difference might be negligible, and it allows you to use native Eloquent relationships.

See here for a discussion on this: https://stackoverflow.com/a/2577188/660694

Body:
I have the following DB tables:

Purchase
-id
-workplace_id

Workplace
-id
-client_id

(and obviously some more fields, but for the example these are all the needed ones).
I would like to make a query like this:

SELECT * FROM
  purchase
  INNER JOIN workplace ON (purchase.workplace_id = workplace.id)
WHERE
  (workplace.client_id = 1)

I'm trying to make this work with the Eloquent models, but I can't figure out how to filter on a joined table.
I tried:

    $purchases = Purchase::query()
        -> workplace()
        -> where('client_id', '=', Auth::user() -> client_id)
        -> get();

But apparently workplace() is undefined for some reason.

My Purchase.php model file looks like this:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
    public function workplace(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Workplace::class);
    }
}

Any pointers on how to make this simple select work?

Thanks!

====EDIT=====

I found a possible solution:

    $purchases = Purchase::with('workplace')
        -> whereHas('workplace', function($q) {
            return $q -> where('client_id', '=', Auth::user() -> client_id);
        })
        -> get();

But this generates an SQL that seems more complicated and is probably also slower:

select * from `purchases` where exists (select * from `workplaces` where `purchases`.`workplace_id` =
`workplaces`.`id` and `client_id` = ? and `workplaces`.`deleted_at` is null)

So I'm still looking for better alternatives

Body:
If you want to do a join, you need to build it with the join method, you can't use a relationship. See here for the docs:

https://laravel.com/docs/9.x/queries#joins

So you should be able to do something like this:

$purchases = Purchase::query()
    ->join('workplace', 'purchase.workplace_id', '=', 'workplace.id')
    ->where('workplace.client_id', '=', Auth::user()->client_id)
    ->get();

The generated SQL that you show in your edit is a sub-query, and you may still want to consider that. Sure, sub-queries are often slower than joins, but unless you're dealing with a massive dataset the performance difference might be negligible, and it allows you to use native Eloquent relationships.

See here for a discussion on this: https://stackoverflow.com/a/2577188/660694


问:
Visual Studio Asp.net Website Compilation error: Child nodes not allowed
"Child nodes not allowed" seems to be notorious compilation error on Asp.net website if you do some googling.

Environment: WinXp, VS2008 and VS2008 SP1, .NET 3.5 SP1

Behavior: create a brand new Asp.net website (not web application), then just build it, you got compilation error "Child nodes not allowed" on the Web.config on line where it says providerOption name="CompilerVersion" value="v3.5"/>

I got this problem after I re-installed vs2008.  Now, a lot of people are suggesting fixes but none worked for us.  Only one guy mentioned he successfully got rid of this problem by re-installing windows, but we don't want to go that far if we don't have to.  There is another person who opened a ticket to MS but hasn't gotten back a response yet.

If there is anyone out there who has similar environment like us and know how to get around this problem, we'd really appreciate it!!!

Edit  The weirdest part of all this is that I don't know how I got it.  It is a brand new box and brand new installation.

答: You probably need to reinstall Visual Studio 2008 SP1.</p>

LastEditorDisplayName: moocha

OwnerDisplayName: John Saunders

ContentLicense: CC BY-SA 2.5


问:
Django Deployment: ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py
Hi All and thank you for taking the time to look at my question.

I'm a newbie to Python, thought I have experience in php/mysql.

I was just handed a code repository of a django site and asked to get it up and running on a server.
I've been able to run syncdb and migrate.
Now I'm trying to navigate to my site in the browser and this is the error that I get:

```<code>ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py
</code>```

My apach2.conf python config looks like this:

```<code><Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonOption django.root /myproject
SetEnv DJANGO_SETTINGS_MODULE settings.py
PythonPath "['/home/ubuntu/envs/live/','/home/ubuntu/envs/live/myproject','/home/ubuntu/envs/live/myproject/apps', '/home/ubuntu/envs/stage/myproject', '/home/ubuntu/envs/', '/var/www'] + sys.path"
PythonDebug on
</code>```

The settings.py file is in the directory /home/ubuntu/venvs/live/myproject.

Can someone please help me here?

Thanks!

答:
It should be just:

```<code>SetEnv DJANGO_SETTINGS_MODULE settings
</code>```

No '.py'. Ie., it is a Python module path, not a file name.

Do note that mod_python is officially a dead project. The support in Django has been deprecated. You should look at alternatives instead of mod_python for hosting Django.

Body:
Hi All and thank you for taking the time to look at my question.

I'm a newbie to Python, thought I have experience in php/mysql.

I was just handed a code repository of a django site and asked to get it up and running on a server.
I've been able to run syncdb and migrate.
Now I'm trying to navigate to my site in the browser and this is the error that I get:

ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py

My apach2.conf python config looks like this:

<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonOption django.root /myproject
SetEnv DJANGO_SETTINGS_MODULE settings.py
PythonPath "['/home/ubuntu/envs/live/','/home/ubuntu/envs/live/myproject','/home/ubuntu/envs/live/myproject/apps', '/home/ubuntu/envs/stage/myproject', '/home/ubuntu/envs/', '/var/www'] + sys.path"
PythonDebug on

The settings.py file is in the directory /home/ubuntu/venvs/live/myproject.

Can someone please help me here?

Thanks!

Body:
It should be just:

SetEnv DJANGO_SETTINGS_MODULE settings

No '.py'. Ie., it is a Python module path, not a file name.

Do note that mod_python is officially a dead project. The support in Django has been deprecated. You should look at alternatives instead of mod_python for hosting Django.


问:
Getting 'java.lang.UnsatisfiedLinkError': no lwjgl in java.library.path
Note this is different from this question because it does not deal with linking because it's not asking how to link it via the CLI, but the GUI in Eclipse.

I have been trying to write a simple program using LWJGL. When I add the library to Eclipse (Kepler 4.3.1 on Windows 7 64bit) and write a program, it does not show red squigglies under the the things which use LWJGL. However, trying to run it gives me the following stacktrace:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at org.lwjgl.Sys$1.run(Sys.java:73)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
    at org.lwjgl.Sys.loadLibrary(Sys.java:95)
    at org.lwjgl.Sys.<clinit>(Sys.java:112)
    at org.lwjgl.opengl.Display.<clinit>(Display.java:135)
    at DisplayExample.start(DisplayExample.java:8)
    at DisplayExample.main(DisplayExample.java:23)
</code>```

(Yes, that is the example they give first, but I wanted to run it to make sure everything was installled properly)

My question is, how do I fix this error? Note that, even when running in Eclipse, it still fails. If I run something else which does not use LWJGL it works, too. I just downloaded it from the internet - it only had one version, so I assume it was the correct one. From what I can see, none of the other question askers have the same error as me - but if you could point me to informative questions that would be helpful too.

答: I solved the issue by adding the lwjgl.64.dll file to the jdk-14.0.1 bin folder</p>

Body:
Note this is different from this question because it does not deal with linking because it's not asking how to link it via the CLI, but the GUI in Eclipse.

I have been trying to write a simple program using LWJGL. When I add the library to Eclipse (Kepler 4.3.1 on Windows 7 64bit) and write a program, it does not show red squigglies under the the things which use LWJGL. However, trying to run it gives me the following stacktrace:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at org.lwjgl.Sys$1.run(Sys.java:73)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
    at org.lwjgl.Sys.loadLibrary(Sys.java:95)
    at org.lwjgl.Sys.<clinit>(Sys.java:112)
    at org.lwjgl.opengl.Display.<clinit>(Display.java:135)
    at DisplayExample.start(DisplayExample.java:8)
    at DisplayExample.main(DisplayExample.java:23)

(Yes, that is the example they give first, but I wanted to run it to make sure everything was installled properly)

My question is, how do I fix this error? Note that, even when running in Eclipse, it still fails. If I run something else which does not use LWJGL it works, too. I just downloaded it from the internet - it only had one version, so I assume it was the correct one. From what I can see, none of the other question askers have the same error as me - but if you could point me to informative questions that would be helpful too.


问:
Understanding x86-64 assembly for simple program in C with a function call
I have simple C program that produces this x86-64 assembly for function func

```<code>#include <stdio.h>
#include <string.h>

void func(char *name)
{
    char buf[90];
    strcpy(buf, name);
    printf("Welcome %s\n", buf);
}

int main(int argc, char *argv[])
{
   func(argv[1]);
   return 0;
}
</code>```

So I think this

```<code>   0x000000000000118d <+4>: push   %rbp
</code>```

pushes the base pointer like placed argument which is char *name

then 0x000000000000118e <+5>:  mov    %rsp,%rbp set stack pointer to what at base pointer I belive that above and this makes stack point points to char *name at this point

then

```<code>   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp
</code>```

I am little unsure about this. Why is 0xffffffffffffff80 added to rsp? What is the point of this instruction. Can any one please tell.

then in next instruction 0x0000000000001195 <+12>: mov    %rdi,-0x78(%rbp)
its just setting -128 decimal to rdi. But still no buffer char buf[90] can be seen, where is my buffer? in following assmebly, can anyone please tell?

also what this line 0x00000000000011a2 <+25>:  mov    %rax,-0x8(%rbp)

```<code>Dump of assembler code for function func:
   0x0000000000001189 <+0>: endbr64
   0x000000000000118d <+4>: push   %rbp
   0x000000000000118e <+5>: mov    %rsp,%rbp
   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp
   0x0000000000001195 <+12>:    mov    %rdi,-0x78(%rbp)
   0x0000000000001199 <+16>:    mov    %fs:0x28,%rax
   0x00000000000011a2 <+25>:    mov    %rax,-0x8(%rbp)
   0x00000000000011a6 <+29>:    xor    %eax,%eax
   0x00000000000011a8 <+31>:    mov    -0x78(%rbp),%rdx
   0x00000000000011ac <+35>:    lea    -0x70(%rbp),%rax
   0x00000000000011b0 <+39>:    mov    %rdx,%rsi
   0x00000000000011b3 <+42>:    mov    %rax,%rdi
   0x00000000000011b6 <+45>:    call   0x1070 <strcpy@plt>
   0x00000000000011bb <+50>:    lea    -0x70(%rbp),%rax
   0x00000000000011bf <+54>:    mov    %rax,%rsi
   0x00000000000011c2 <+57>:    lea    0xe3b(%rip),%rax        # 0x2004
   0x00000000000011c9 <+64>:    mov    %rax,%rdi
   0x00000000000011cc <+67>:    mov    $0x0,%eax
   0x00000000000011d1 <+72>:    call   0x1090 <printf@plt>
   0x00000000000011d6 <+77>:    nop
   0x00000000000011d7 <+78>:    mov    -0x8(%rbp),%rax
   0x00000000000011db <+82>:    sub    %fs:0x28,%rax
   0x00000000000011e4 <+91>:    je     0x11eb <func+98>
   0x00000000000011e6 <+93>:    call   0x1080 <__stack_chk_fail@plt>
   0x00000000000011eb <+98>:    leave
   0x00000000000011ec <+99>:    ret
End of assembler dump.
</code>```

also what in above assembly the use of fs register what this instruction actually doing 0x0000000000001199 <+16>:  mov    %fs:0x28,%rax

答:
As to "why use an add %rsp rather than a sub %rsp instruction":

On x86_64 there are actually two versions of these add/sub immediate with rsp instructions

a 4 byte version with a 1 byte immediate

a 7 byte version with a 4 byte immediate

For both versions, the immediate will be sign-extended to 64 bits and then added to (or subtracted from) %rsp.  Now because of that sign extension, a 1-byte immediate can be any value from -128 (-0x80) up to 127 (0x7f). So the instruction

```<code>add $-0x80, %rsp
</code>```

can use the 4-byte encoding, while the instruction

```<code>sub $0x80, %rsp
</code>```

would require the 7 byte encoding.  All else being equal (as it never is), the shorter encoding is better as it occupies less memory/cache.

Body:
I have simple C program that produces this x86-64 assembly for function func

#include <stdio.h>
#include <string.h>

void func(char *name)
{
    char buf[90];
    strcpy(buf, name);
    printf("Welcome %s\n", buf);
}

int main(int argc, char *argv[])
{
   func(argv[1]);
   return 0;
}

So I think this

   0x000000000000118d <+4>: push   %rbp

pushes the base pointer like placed argument which is char *name

then 0x000000000000118e <+5>:  mov    %rsp,%rbp set stack pointer to what at base pointer I belive that above and this makes stack point points to char *name at this point

then

   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp

I am little unsure about this. Why is 0xffffffffffffff80 added to rsp? What is the point of this instruction. Can any one please tell.

then in next instruction 0x0000000000001195 <+12>: mov    %rdi,-0x78(%rbp)
its just setting -128 decimal to rdi. But still no buffer char buf[90] can be seen, where is my buffer? in following assmebly, can anyone please tell?

also what this line 0x00000000000011a2 <+25>:  mov    %rax,-0x8(%rbp)

Dump of assembler code for function func:
   0x0000000000001189 <+0>: endbr64
   0x000000000000118d <+4>: push   %rbp
   0x000000000000118e <+5>: mov    %rsp,%rbp
   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp
   0x0000000000001195 <+12>:    mov    %rdi,-0x78(%rbp)
   0x0000000000001199 <+16>:    mov    %fs:0x28,%rax
   0x00000000000011a2 <+25>:    mov    %rax,-0x8(%rbp)
   0x00000000000011a6 <+29>:    xor    %eax,%eax
   0x00000000000011a8 <+31>:    mov    -0x78(%rbp),%rdx
   0x00000000000011ac <+35>:    lea    -0x70(%rbp),%rax
   0x00000000000011b0 <+39>:    mov    %rdx,%rsi
   0x00000000000011b3 <+42>:    mov    %rax,%rdi
   0x00000000000011b6 <+45>:    call   0x1070 <strcpy@plt>
   0x00000000000011bb <+50>:    lea    -0x70(%rbp),%rax
   0x00000000000011bf <+54>:    mov    %rax,%rsi
   0x00000000000011c2 <+57>:    lea    0xe3b(%rip),%rax        # 0x2004
   0x00000000000011c9 <+64>:    mov    %rax,%rdi
   0x00000000000011cc <+67>:    mov    $0x0,%eax
   0x00000000000011d1 <+72>:    call   0x1090 <printf@plt>
   0x00000000000011d6 <+77>:    nop
   0x00000000000011d7 <+78>:    mov    -0x8(%rbp),%rax
   0x00000000000011db <+82>:    sub    %fs:0x28,%rax
   0x00000000000011e4 <+91>:    je     0x11eb <func+98>
   0x00000000000011e6 <+93>:    call   0x1080 <__stack_chk_fail@plt>
   0x00000000000011eb <+98>:    leave
   0x00000000000011ec <+99>:    ret
End of assembler dump.

also what in above assembly the use of fs register what this instruction actually doing 0x0000000000001199 <+16>:  mov    %fs:0x28,%rax

Body:
As to "why use an add %rsp rather than a sub %rsp instruction":

On x86_64 there are actually two versions of these add/sub immediate with rsp instructions

a 4 byte version with a 1 byte immediate

a 7 byte version with a 4 byte immediate

For both versions, the immediate will be sign-extended to 64 bits and then added to (or subtracted from) %rsp.  Now because of that sign extension, a 1-byte immediate can be any value from -128 (-0x80) up to 127 (0x7f). So the instruction

add $-0x80, %rsp

can use the 4-byte encoding, while the instruction

sub $0x80, %rsp

would require the 7 byte encoding.  All else being equal (as it never is), the shorter encoding is better as it occupies less memory/cache.


问:
Pixi.js in SvelteKit gives a 'self is not defined' error only while building
As the title states, when using Pixi.js in SvelteKit, ONLY and ONLY while building the application, it will spit out a "self is not defined" error, and it traces back to the @pixi/settings module. I have tried every possible way that I know to fix this. First I used a shim to give it some dummy information, but that didn't work:

if (typeof window === 'undefined') {
    globalThis.window = {} as any;
}
if (typeof self === 'undefined') {
    globalThis.self = globalThis.window;
}
if (typeof document === 'undefined') {
    if (window.document) {
        globalThis.document = window.document;
    } else {
        globalThis.document = window.document = {
            createElement: (elementName: string) => {
                switch (elementName) {
                    case 'canvas':
                        return {
                            getContext: (contextName: string) => {
                                switch (contextName) {
                                    case 'webgl':
                                        return {
                                            getExtension: () => {}
                                        };
                                    case '2d':
                                        return {
                                            fillRect: () => {},
                                            drawImage: () => {},
                                            getImageData: () => {}
                                        };
                                }
                            }
                        };
                }
            }
        } as any;
    }
    if (typeof CanvasRenderingContext2D === 'undefined') {
        globalThis.CanvasRenderingContext2D = { prototype: {} };
    }
}
export {};

```
<p>The shim gives all the necessary dummy informations and variables needed to run, but I guess it doesn't matter on build. Then I tried to import pixi.js dynamically onMount inside the code like so:</p>
<pre class="lang-html prettyprint-override"><code><script lang="ts">
    import '$utils/pixi-ssr-shim';
    import { onMount } from 'svelte';
    import App from './utils/App';
    import { run } from './seating-chart';

    let el: HTMLDivElement;

    onMount(async () => {
        //@ts-ignore
        const PIXI = await import('pixi.js');

        run(el, PIXI);

        window.addEventListener('resize', () => {
            App.app.destroy(true);
            App.app = null;
            App.viewport = null;

            run(el, PIXI);
        });
    });
</script>

<div class="flex items-center justify-around">
    <div bind:this={el} />
</div>

</code>```

I also tried creating my own bundle of pixi.js like how pixijs.io/customize do, and that only creates another issue that I couldn't be bothered with.

So, I have no idea what to do to fix this, because I cannot just go around the error and run the program.

答:
This was actually caused by the pixijs code having used self in their code and when the sveltekit compiler analyzes it, it errors out because nodejs doesn't have self as a variable, I have fixed this issue and created a pull request into the main branch of pixijs that will be released at 6.3.0.

Here's the PR:
https://github.com/pixijs/pixijs/pull/8050

Body:
As the title states, when using Pixi.js in SvelteKit, ONLY and ONLY while building the application, it will spit out a "self is not defined" error, and it traces back to the @pixi/settings module. I have tried every possible way that I know to fix this. First I used a shim to give it some dummy information, but that didn't work:

if (typeof window === 'undefined') {
    globalThis.window = {} as any;
}
if (typeof self === 'undefined') {
    globalThis.self = globalThis.window;
}
if (typeof document === 'undefined') {
    if (window.document) {
        globalThis.document = window.document;
    } else {
        globalThis.document = window.document = {
            createElement: (elementName: string) => {
                switch (elementName) {
                    case 'canvas':
                        return {
                            getContext: (contextName: string) => {
                                switch (contextName) {
                                    case 'webgl':
                                        return {
                                            getExtension: () => {}
                                        };
                                    case '2d':
                                        return {
                                            fillRect: () => {},
                                            drawImage: () => {},
                                            getImageData: () => {}
                                        };
                                }
                            }
                        };
                }
            }
        } as any;
    }
    if (typeof CanvasRenderingContext2D === 'undefined') {
        globalThis.CanvasRenderingContext2D = { prototype: {} };
    }
}
export {};

The shim gives all the necessary dummy informations and variables needed to run, but I guess it doesn't matter on build. Then I tried to import pixi.js dynamically onMount inside the code like so:

I also tried creating my own bundle of pixi.js like how pixijs.io/customize do, and that only creates another issue that I couldn't be bothered with.

So, I have no idea what to do to fix this, because I cannot just go around the error and run the program.


问:
Binary to Decimal conversion not working properly: C++
can anyone please help me with this code I wrote. I am multiplying the digit from the string that is either 0 or 1 by 2 to the power of "power" which is an integer incrementing every time we loop and I am adding the result to the return value...but for some reason it's not working.

So for example: "10" is returning 48 instead of 2

```<code>#include <iostream>
#include <string>
#include <cmath>
#include <sstream>

using BINARY = unsigned long;
typedef int BI;

class Binary_
{
private:
std::string binary_string;
BINARY return_binary()
{
    BINARY result = 0;
    BI power = 0, binary_value = 0;
    for(int i = this->binary_string.length() - 1; i > 0; i--)
    {
        std::string binary_char_hold = std::to_string(this->binary_string[i]);
        std::stringstream Binary_stream(binary_char_hold);
        Binary_stream >> binary_value;
        result = result + (binary_value * pow(2, power));
        power++;
    }
    return result;
 }
 public :
    BINARY get_binary(std::string binary_string)
    {
        BINARY binary_val = 0;
        for (int i = 0; i < binary_string.length(); i++)
        {
            if (binary_string[i] == '0' || binary_string[i] == '1') { this->binary_string =
            binary_string; binary_val = return_binary(); }
            else this->binary_string = "Binary value you entered is invalid and not of base 2 system!";
        }
        return binary_val;
    }
   };
</code>```

答:
There is another simpler implementation by strtoull() function  for your problem.

More details can be found at  C++: binary std::string to decimal

Body:
can anyone please help me with this code I wrote. I am multiplying the digit from the string that is either 0 or 1 by 2 to the power of "power" which is an integer incrementing every time we loop and I am adding the result to the return value...but for some reason it's not working.

So for example: "10" is returning 48 instead of 2

#include <iostream>
#include <string>
#include <cmath>
#include <sstream>

using BINARY = unsigned long;
typedef int BI;

class Binary_
{
private:
std::string binary_string;
BINARY return_binary()
{
    BINARY result = 0;
    BI power = 0, binary_value = 0;
    for(int i = this->binary_string.length() - 1; i > 0; i--)
    {
        std::string binary_char_hold = std::to_string(this->binary_string[i]);
        std::stringstream Binary_stream(binary_char_hold);
        Binary_stream >> binary_value;
        result = result + (binary_value * pow(2, power));
        power++;
    }
    return result;
 }
 public :
    BINARY get_binary(std::string binary_string)
    {
        BINARY binary_val = 0;
        for (int i = 0; i < binary_string.length(); i++)
        {
            if (binary_string[i] == '0' || binary_string[i] == '1') { this->binary_string =
            binary_string; binary_val = return_binary(); }
            else this->binary_string = "Binary value you entered is invalid and not of base 2 system!";
        }
        return binary_val;
    }
   };


问:
Clojure presentation for beginners?
I need to make a presentation for beginners about the Clojure language.  What are your suggestions on selecting topics on it? What are the points I need to include?

Note: By beginners, I mean that they are experienced in other programming paradigms, but not in the functional programming model.

答:
You've got to think about your target audience. I'm going to make an assumption that they probably know Java.

The best authority on Clojure is the source himself, Rich Hickey. He's written an introduction to Clojure for Java Programmers.

Slides are here.

Him giving the presentation with audio is here and part2 is here.

Title: Clojure presentation for beginners?


问:
Why Go cqlsh can't get a token while keeps running requests good?
My service runs in AWS cluster and uses Keyspaces. The service has a role and gets, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_SESSION_TOKEN, AWS_SECURITY_TOKEN env vars.

To connect Keyspaces I do the following:

import (
    "context"
    "time"

    credentialsV1 "github.com/aws/aws-sdk-go/aws/credentials"
    ec2rolecredsV1 "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
    ec2metadataV1 "github.com/aws/aws-sdk-go/aws/ec2metadata"
    aws_sess "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin/sigv4"
    "github.com/gocql/gocql"
)

type Repository struct {
    session *gocql.Session
    ...
}

func (r *Repository) ConnectCassandra(ctx context.Context) {
    awsSession, err := aws_sess.NewSession()

    creds := credentialsV1.NewChainCredentials(
        []credentialsV1.Provider{
            &credentialsV1.EnvProvider{},
            &ec2rolecredsV1.EC2RoleProvider{
                Client: ec2metadataV1.New(awsSession),
            },
        },
    )

    value, err := creds.Get()

    auth := sigv4.NewAwsAuthenticator()
    auth.SessionToken = value.SessionToken
    auth.AccessKeyId = value.AccessKeyID
    auth.SecretAccessKey = value.SecretAccessKey

    cluster := gocql.NewCluster(Host)

    cluster.Timeout = 10 * time.Second
    cluster.ConnectTimeout = 10 * time.Second
    cluster.Consistency = gocql.LocalQuorum
    cluster.Keyspace = Keyspace
    cluster.Port = Port

    cluster.Authenticator = auth

    r.session, err = cluster.CreateSession()

}

func (r *Repository) GetData() (*Data, error) {
    iter := r.session.Query(...)

    scanner := iter.Scanner()

    for scanner.Next() {
        ...
    }
}
```
<p>The service periodically requests some data. After some time (~24h) I start getting errors:</p>
```2022/02/10 20:29:50 error: failed to connect to XX.XX.XX.XX:9142 due to error: Authentication failure: Session token expired at Wed Feb 09 10:11:42 UTC 2022
```

Meanwhile requests are running with no errors. Obviously that means that finally gocql driver retrieves a token. But why I get these errors and what's done wrong? What should I change to stop getting and to be sure that everything works as it should?

答:
A SessionToken is a temporary credential that is retrieved using your AccessKeyId and SecretAccessKey. Session Tokens have an expiration, and are only valid for a period of time.

When it expires, any AWS API call made using that token will return that expiration error you are getting. There are a couple of ways to handle this, but effectively you want to 'refresh' the creds you are using by retrieving a new token, and retrying failed calls.

Looking at your code, you may want to define a cred refresh method on your Repository struct that can be called to get new creds again when that specific error is hit, and retry the failed call.

Can read more here: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html

Body:
My service runs in AWS cluster and uses Keyspaces. The service has a role and gets, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_SESSION_TOKEN, AWS_SECURITY_TOKEN env vars.

To connect Keyspaces I do the following:

import (
    "context"
    "time"

    credentialsV1 "github.com/aws/aws-sdk-go/aws/credentials"
    ec2rolecredsV1 "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
    ec2metadataV1 "github.com/aws/aws-sdk-go/aws/ec2metadata"
    aws_sess "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin/sigv4"
    "github.com/gocql/gocql"
)

type Repository struct {
    session *gocql.Session
    ...
}

func (r *Repository) ConnectCassandra(ctx context.Context) {
    awsSession, err := aws_sess.NewSession()

    creds := credentialsV1.NewChainCredentials(
        []credentialsV1.Provider{
            &credentialsV1.EnvProvider{},
            &ec2rolecredsV1.EC2RoleProvider{
                Client: ec2metadataV1.New(awsSession),
            },
        },
    )

    value, err := creds.Get()

    auth := sigv4.NewAwsAuthenticator()
    auth.SessionToken = value.SessionToken
    auth.AccessKeyId = value.AccessKeyID
    auth.SecretAccessKey = value.SecretAccessKey

    cluster := gocql.NewCluster(Host)

    cluster.Timeout = 10 * time.Second
    cluster.ConnectTimeout = 10 * time.Second
    cluster.Consistency = gocql.LocalQuorum
    cluster.Keyspace = Keyspace
    cluster.Port = Port

    cluster.Authenticator = auth

    r.session, err = cluster.CreateSession()

}

func (r *Repository) GetData() (*Data, error) {
    iter := r.session.Query(...)

    scanner := iter.Scanner()

    for scanner.Next() {
        ...
    }
}

The service periodically requests some data. After some time (~24h) I start getting errors:

2022/02/10 20:29:50 error: failed to connect to XX.XX.XX.XX:9142 due to error: Authentication failure: Session token expired at Wed Feb 09 10:11:42 UTC 2022

Meanwhile requests are running with no errors. Obviously that means that finally gocql driver retrieves a token. But why I get these errors and what's done wrong? What should I change to stop getting and to be sure that everything works as it should?


问:
my result only get 1 data, can you help me for get more data and save another file?

import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = 'http://h1.nobbd.de/index.php?start='
for page in range(1,10):
    req = requests.get(URL + str(page) + '=')
    soup = BeautifulSoup(req.text, 'html.parser')
    h1 = soup.find_all('div',attrs={'class','report-wrapper'})
    for hack in h1:
      h2 = hack.find_all("div",attrs={"class","report"})
      for i in h2:
        layanan = i.find_all('b')[0].text.strip()
        report = i.find_all('a')[2].text.strip()
        bug_hunter = i.find_all('a')[1].text.strip()
        mirror = i.find("a", {"class": "title"})['href']
        date = i.find_all("div", {"class": "date"})
        for d in date:
          waktu = d.text
        data = {"Company": [layanan], "Title:": [report], "Submit:": [bug_hunter], "Link:": [mirror], "Date:": [waktu]}
        df = pd.DataFrame(data)
```
<p>my result only get 1 data, can you help me for get more data and save another file?</p>
```df.head()
```

index
Company
Title:
Submit:
Link:
Date:

0
Reddit
Application level DOS at Login Page ( Accepts Long Password )
e100_speaks
https://hackerone.com/reports/1168804
03 Feb 2022

答:
What happens?

Based on your questions code, you will overwrite your dataframe with every iteration, thats why you only get one result.

How to fix?

Create an empty list before your loops

Append all the extracted dicts to this list

Create your dataframe based on that list of dicts

Example

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd

data = []
url = 'http://h1.nobbd.de/index.php?start='
for page in range(1,3):
    req = requests.get(url + str(page))
    soup = BeautifulSoup(req.text, 'html.parser')
    h1 = soup.find_all('div',attrs={'class','report-wrapper'})
    for hack in h1:
        h2 = hack.find_all("div",attrs={"class","report"})
        for i in h2:
            layanan = i.find_all('b')[0].text.strip()
            report = i.find_all('a')[2].text.strip()
            bug_hunter = i.find_all('a')[1].text.strip()
            mirror = i.find("a", {"class": "title"})['href']
            date = i.find_all("div", {"class": "date"})
            for d in date:
                waktu = d.text
            data.append({'Company':[layanan], 'Title':[report], 'Submit':[hunter], 'link':[mirror], 'Date':[waktu]})

df = pd.DataFrame(data)
</code>```

Body:
import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = 'http://h1.nobbd.de/index.php?start='
for page in range(1,10):
    req = requests.get(URL + str(page) + '=')
    soup = BeautifulSoup(req.text, 'html.parser')
    h1 = soup.find_all('div',attrs={'class','report-wrapper'})
    for hack in h1:
      h2 = hack.find_all("div",attrs={"class","report"})
      for i in h2:
        layanan = i.find_all('b')[0].text.strip()
        report = i.find_all('a')[2].text.strip()
        bug_hunter = i.find_all('a')[1].text.strip()
        mirror = i.find("a", {"class": "title"})['href']
        date = i.find_all("div", {"class": "date"})
        for d in date:
          waktu = d.text
        data = {"Company": [layanan], "Title:": [report], "Submit:": [bug_hunter], "Link:": [mirror], "Date:": [waktu]}
        df = pd.DataFrame(data)

my result only get 1 data, can you help me for get more data and save another file?

df.head()

index
Company
Title:
Submit:
Link:
Date:

0
Reddit
Application level DOS at Login Page ( Accepts Long Password )
e100_speaks
https://hackerone.com/reports/1168804
03 Feb 2022

Body:
What happens?

Based on your questions code, you will overwrite your dataframe with every iteration, thats why you only get one result.

How to fix?

Create an empty list before your loops

Append all the extracted dicts to this list

Create your dataframe based on that list of dicts

Example

import requests
from bs4 import BeautifulSoup
import pandas as pd

data = []
url = 'http://h1.nobbd.de/index.php?start='
for page in range(1,3):
    req = requests.get(url + str(page))
    soup = BeautifulSoup(req.text, 'html.parser')
    h1 = soup.find_all('div',attrs={'class','report-wrapper'})
    for hack in h1:
        h2 = hack.find_all("div",attrs={"class","report"})
        for i in h2:
            layanan = i.find_all('b')[0].text.strip()
            report = i.find_all('a')[2].text.strip()
            bug_hunter = i.find_all('a')[1].text.strip()
            mirror = i.find("a", {"class": "title"})['href']
            date = i.find_all("div", {"class": "date"})
            for d in date:
                waktu = d.text
            data.append({'Company':[layanan], 'Title':[report], 'Submit':[hunter], 'link':[mirror], 'Date':[waktu]})

df = pd.DataFrame(data)


问:
How can I add shadow on piechart in recharts?
I want to add shadow on piechart. I am using recharts library.

Please let me know if you have any solutions.
Thanks.

答:
You can add a drop shadow filter on the Cell component(s) to add this effect.  I just passed the values in via the style prop, but you can do whatever works best for you.

```<code>    <PieChart width={800} height={400}>
      <Pie
        data={data}
        cx={120}
        cy={200}
        innerRadius={70}
        outerRadius={80}
        fill="#8884d8"
        dataKey="value"
      >
        {data.map((entry, index) => (
          <Cell
            key={`cell-${index}`}
            fill={COLORS[index % COLORS.length]}
            style={{
              filter: `drop-shadow(0px 0px 5px ${COLORS[index % COLORS.length]}`
            }}
            stroke="0"
          />
        ))}
      </Pie>
    </PieChart>
</code>```

Working Example CodeSandbox: https://codesandbox.io/s/pie-chart-with-drop-shadow-fxe8x?file=/src/App.tsx

Body:
You can add a drop shadow filter on the Cell component(s) to add this effect.  I just passed the values in via the style prop, but you can do whatever works best for you.

    <PieChart width={800} height={400}>
      <Pie
        data={data}
        cx={120}
        cy={200}
        innerRadius={70}
        outerRadius={80}
        fill="#8884d8"
        dataKey="value"
      >
        {data.map((entry, index) => (
          <Cell
            key={`cell-${index}`}
            fill={COLORS[index % COLORS.length]}
            style={{
              filter: `drop-shadow(0px 0px 5px ${COLORS[index % COLORS.length]}`
            }}
            stroke="0"
          />
        ))}
      </Pie>
    </PieChart>

Working Example CodeSandbox: https://codesandbox.io/s/pie-chart-with-drop-shadow-fxe8x?file=/src/App.tsx


问:
List all harddrives in a linux system
I'm having problems to detect which one of my block devices is the hard drive. My system has a cd-rom drive, USB drives, and a single hard drive of unknown vendor/type.

How can I identify the hard drive with a linux command, script, or C application?

答:
```<code>sudo lshw -class disk
</code>```

will show you the available disks in the system

Title: List all harddrives in a linux system

Body:
sudo lshw -class disk

will show you the available disks in the system


问:
Counting values in SQL with conditional logic / multiple criteria
I have a table that contains several thousand products with the following columns:

scores: includes the quality of a score from 1-100

y_2018: the product was in service during 2018

y_2020: the product was in service during 2020

y_2021: the product was in service during 2021

My objective is to categorize products by the different years that they have been in service. This would mean there would be a "1/3" column for products in service only in 2018, only in 2020, and only in 2021. There would also be a "2/3" column for products in service in 2018 and 2020 but not 2021, 2018 and 2021 but not 2020, and 2020 and 2021 but not 2018. Lastly there would be a "3/3" column for the products that have been in service for 2018, 2020, and 2021. This is the code I have thusfar:

```<code>SELECT
case
when (case scores)>=0 and scores<30 then '0-30'
when (case scores)>=30 and scores<70 then '30-70'
when (case scores)>=70 and scores<100 then '70-100'
ELSE NULL end as "Score Range"
,COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020 IS NULL AND y_2021 IS
NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NULL AND y_2020
IS NOT NULL AND y_2021 IS NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NULL AND y_2020
IS NULL AND y_2021 IS NOT NULL) THEN 1 ELSE 0 END) AS "1/3"
,COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020 IS NOT NULL AND y_2021 IS
NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NULL AND y_2020
IS NOT NULL AND y_2021 IS NOT NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020
IS NULL AND y_2021 IS NOT NULL) THEN 1 ELSE 0 END) AS "2/3"
,COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020 IS NOT NULL AND y_2021 IS
NOT NULL) THEN 1 ELSE 0 END) AS "3/3"
FROM table
GROUP BY 1
ORDER BY 1
</code>```

I think I'm close and my current output looks like this:

```<code>Score Range  |  1/3    2/3   3/3
70-100       |  2000   2000   500
30-70        |  1000   1000   300
0-30         |  1500   1500   400
</code>```

The main question I have is why the "1/3" and "2/3" are the same and how can I adjust my query to get what I'm looking for?

答:
You need to make three different columns with three different conditions like below:</p>
```<code>SELECT
case
when (case scores)>=0 and scores<30 then '0-30'
when (case scores)>=30 and scores<70 then '30-70'
when (case scores)>=70 and scores<100 then '70-100'
ELSE NULL end as "Score Range"
,SUM(CASE WHEN y_2021 IS NOT NULL AND y_2020 IS NULL AND y_2018 IS NULL THEN 1 ELSE 0 END) AS "y_2021_COUNT"
,SUM(CASE WHEN y_2021 IS NOT NULL AND y_2020 IS NOT NULL AND y_2018 IS NULL THEN 1 ELSE 0 END) AS "y_2021_2020_COUNT"
,SUM(CASE WHEN y_2021 IS NOT NULL AND y_2020 IS NOT NULL AND y_2018 IS NOT NULL THEN 1 ELSE 0 END) AS "y_2021_2020_2018_COUNT"
FROM table
GROUP BY 1
</code>```

Body:
I have a table that contains several thousand products with the following columns:

scores: includes the quality of a score from 1-100

y_2018: the product was in service during 2018

y_2020: the product was in service during 2020

y_2021: the product was in service during 2021

My objective is to categorize products by the different years that they have been in service. This would mean there would be a "1/3" column for products in service only in 2018, only in 2020, and only in 2021. There would also be a "2/3" column for products in service in 2018 and 2020 but not 2021, 2018 and 2021 but not 2020, and 2020 and 2021 but not 2018. Lastly there would be a "3/3" column for the products that have been in service for 2018, 2020, and 2021. This is the code I have thusfar:

SELECT
case
when (case scores)>=0 and scores<30 then '0-30'
when (case scores)>=30 and scores<70 then '30-70'
when (case scores)>=70 and scores<100 then '70-100'
ELSE NULL end as "Score Range"
,COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020 IS NULL AND y_2021 IS
NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NULL AND y_2020
IS NOT NULL AND y_2021 IS NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NULL AND y_2020
IS NULL AND y_2021 IS NOT NULL) THEN 1 ELSE 0 END) AS "1/3"
,COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020 IS NOT NULL AND y_2021 IS
NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NULL AND y_2020
IS NOT NULL AND y_2021 IS NOT NULL) THEN 1 ELSE 0 END)
+
COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020
IS NULL AND y_2021 IS NOT NULL) THEN 1 ELSE 0 END) AS "2/3"
,COUNT(CASE WHEN y_2018 IS NOT NULL AND y_2020 IS NOT NULL AND y_2021 IS
NOT NULL) THEN 1 ELSE 0 END) AS "3/3"
FROM table
GROUP BY 1
ORDER BY 1

I think I'm close and my current output looks like this:

Score Range  |  1/3    2/3   3/3
70-100       |  2000   2000   500
30-70        |  1000   1000   300
0-30         |  1500   1500   400

The main question I have is why the "1/3" and "2/3" are the same and how can I adjust my query to get what I'm looking for?

Body:
You need to make three different columns with three different conditions like below:

SELECT
case
when (case scores)>=0 and scores<30 then '0-30'
when (case scores)>=30 and scores<70 then '30-70'
when (case scores)>=70 and scores<100 then '70-100'
ELSE NULL end as "Score Range"
,SUM(CASE WHEN y_2021 IS NOT NULL AND y_2020 IS NULL AND y_2018 IS NULL THEN 1 ELSE 0 END) AS "y_2021_COUNT"
,SUM(CASE WHEN y_2021 IS NOT NULL AND y_2020 IS NOT NULL AND y_2018 IS NULL THEN 1 ELSE 0 END) AS "y_2021_2020_COUNT"
,SUM(CASE WHEN y_2021 IS NOT NULL AND y_2020 IS NOT NULL AND y_2018 IS NOT NULL THEN 1 ELSE 0 END) AS "y_2021_2020_2018_COUNT"
FROM table
GROUP BY 1