问:
Can you do a pointer to a class in c++?
Note: I do not mean a pointer to an OBJECT or INSTANCE I mean a pointer to a CLASS

I put this at the top because I know if I don't people will tell me that I can do

class MyClass;
MyClass* pointerToMyClass = new MyClass(); // Ta-da! pointer to class!
```

<p>This is not what I am looking for.  I would like to make a pointer to a class type itself, kind of like a function pointer, but for a class.</p>

<p>To make it more clear what I am asking, here is some code that roughly demonstrates what I am looking for.</p>

<pre class="lang-cpp prettyprint-override"><code>class MyClass; // real Class
class MyDerived : public MyClass; // derived class

class * ClassPointer = &MyClass; // pointer to my class
MyClass * instanceOfPointer = new ClassPointer(); // now makes an instance of MyClass

ClassPointer = &MyDerived; // pointer to derived class
MyClass * instance2 = new ClassPointer(); // now makes an instance of DerivedClass
</code>```

So kind of like a typedef, but more dynamic.

I would also want be able to make a vector of class pointers.  Currently, I am hacking in the behavior I need with a class function clone() that returns a new pointer to the base class, but I don't particularly like this approach.

Is there anything like this possible in C++?

Edit:
The current problem I am using this for is a polymorphic network protocol.
There is a base packet class:

class packet{
    int id=0;
    virtual packet* read(); // read packet type into id
    virtual packet* clone(){ return new packet(); }
};
```

<p>then multiple derived packets:</p>

<pre class="lang-cpp prettyprint-override"><code>class packet1 : public packet{
    int id=1
    packet* read(); // do packet specific reading
    packet * clone(){ return new packet1(); }
};

class packet2 : public packet{
    int id=2
    packet* read(); // do packet specific reading
    packet * clone(){ return new packet21(); }
};

class packet3 : public packet{
    int id=3
    packet* read(); // do packet specific reading
    packet * clone(){ return new packet3(); }
};
</code>```

then to read a packet all you have to do is

packet* array[] = { new packet(), new packet1(), new packet2(), new packet3() }; // array of packets, this should be class* if possible
packet type = packet();
type.read(); // read type from network
packet* data = array[type.id].clone(); // pick derived class based on type
data->read(); // read specific packet from network
```

The packet*[] would be replaced with a class*[] to avoid having to use clone().

This is a simplified but workable example.

答:
Best answer was never posed as an answer, credit to Raymond Chen

No you can not take a pointer to a class (and are actually forbidden to take the pointer of a constructor http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf 12.1.12), however you can make a pointer to an abject factory by

template<typename T> T* make<T>() { return new T(); }
```

and take a function pointer of make<classToPointTo>

Much better than my clone function and I didnt want this wonderful answer burred in the comments for the rest of time.

Title: Can you do a pointer to a class in c++?

Body:
Note: I do not mean a pointer to an OBJECT or INSTANCE I mean a pointer to a CLASS

I put this at the top because I know if I don't people will tell me that I can do

class MyClass;
MyClass* pointerToMyClass = new MyClass(); // Ta-da! pointer to class!

This is not what I am looking for.  I would like to make a pointer to a class type itself, kind of like a function pointer, but for a class.

To make it more clear what I am asking, here is some code that roughly demonstrates what I am looking for.

class MyClass; // real Class
class MyDerived : public MyClass; // derived class

class * ClassPointer = &MyClass; // pointer to my class
MyClass * instanceOfPointer = new ClassPointer(); // now makes an instance of MyClass

ClassPointer = &MyDerived; // pointer to derived class
MyClass * instance2 = new ClassPointer(); // now makes an instance of DerivedClass

So kind of like a typedef, but more dynamic.

I would also want be able to make a vector of class pointers.  Currently, I am hacking in the behavior I need with a class function clone() that returns a new pointer to the base class, but I don't particularly like this approach.

Is there anything like this possible in C++?

Edit:
The current problem I am using this for is a polymorphic network protocol.
There is a base packet class:

class packet{
    int id=0;
    virtual packet* read(); // read packet type into id
    virtual packet* clone(){ return new packet(); }
};

then multiple derived packets:

class packet1 : public packet{
    int id=1
    packet* read(); // do packet specific reading
    packet * clone(){ return new packet1(); }
};

class packet2 : public packet{
    int id=2
    packet* read(); // do packet specific reading
    packet * clone(){ return new packet21(); }
};

class packet3 : public packet{
    int id=3
    packet* read(); // do packet specific reading
    packet * clone(){ return new packet3(); }
};

then to read a packet all you have to do is

packet* array[] = { new packet(), new packet1(), new packet2(), new packet3() }; // array of packets, this should be class* if possible
packet type = packet();
type.read(); // read type from network
packet* data = array[type.id].clone(); // pick derived class based on type
data->read(); // read specific packet from network

The packet*[] would be replaced with a class*[] to avoid having to use clone().

This is a simplified but workable example.

Body:
Best answer was never posed as an answer, credit to Raymond Chen

No you can not take a pointer to a class (and are actually forbidden to take the pointer of a constructor http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf 12.1.12), however you can make a pointer to an abject factory by

template<typename T> T* make<T>() { return new T(); }

and take a function pointer of make<classToPointTo>

Much better than my clone function and I didnt want this wonderful answer burred in the comments for the rest of time.


来源: stackexchange

问:
Search arrays then echo with conditionals?
I'm trying to do somthing like this:

```<code>  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }
</code>```

SOLVED:

```<code>$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables ";
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits ";
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits";
        }
</code>```

Progression:

```<code>$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";
</code>```

答:
This could probably done more efficiently, but this is a simple way:</p>

```<code>$random = array("apple","celery","banana");

$define_fruits = array("apple","banana","pears","mango");
$define_vegetables = array("celery","lettuce","carrots","cucumber");

if( count(array_intersect($define_fruits,$random)) ){
  if( count(array_intersect($define_vegetables,$random)) )
    echo "both";
  else
    echo "fruit";
} elseif( count(array_intersect($define_vegetables,$random)) ){
  echo "vegetables";
} else {
  echo "neither";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do somthing like this:

  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }

SOLVED:

$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables ";
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits ";
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits";
        }

Progression:

$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";

Body:
This could probably done more efficiently, but this is a simple way:

$random = array("apple","celery","banana");

$define_fruits = array("apple","banana","pears","mango");
$define_vegetables = array("celery","lettuce","carrots","cucumber");

if( count(array_intersect($define_fruits,$random)) ){
  if( count(array_intersect($define_vegetables,$random)) )
    echo "both";
  else
    echo "fruit";
} elseif( count(array_intersect($define_vegetables,$random)) ){
  echo "vegetables";
} else {
  echo "neither";
}


问:
How To Delete All Records From Database All Tables
Can you guys help me solve my issue? How To Delete All Records From Database All Tables in a single click using Laravel ajax.
I have to delete all records from all tables, please help to solve my issue.

Thanks in advance

(https://i.stack.imgur.com/gu6Qg.png)

答:
You should try this

In ajax

```<code>$(document).on('.delete-all-record', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'GET',
        url: 'url',
        success: function (data) {
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Some problem occurred, please try again.");
        }
    });
});
</code>```

In Controller

```<code>$tableNames = DB::select('SHOW TABLES');
foreach ($tableNames as $name) {
    //if you don't want to truncate migrations
    if ($name->Tables_in_db_name == 'migrations') {
        continue;
    }
    if ($name->Tables_in_db_name == 'users') {
        continue;
    }
    DB::table($name->Tables_in_db_name)->truncate();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You should try this

In ajax

$(document).on('.delete-all-record', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'GET',
        url: 'url',
        success: function (data) {
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Some problem occurred, please try again.");
        }
    });
});

In Controller

$tableNames = DB::select('SHOW TABLES');
foreach ($tableNames as $name) {
    //if you don't want to truncate migrations
    if ($name->Tables_in_db_name == 'migrations') {
        continue;
    }
    if ($name->Tables_in_db_name == 'users') {
        continue;
    }
    DB::table($name->Tables_in_db_name)->truncate();
}


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

答:
The other solutions look okay but you don't really need to use sophisticated language features or library functions for this simple problem.

```<code>result, prev = [], None

for idx, cur in enumerate(x):
    if not prev or (prev > 0) != (cur > 0):
        n, summation = 1, cur
    else:
        n, summation = n + 1, summation + cur
    result.append((idx, cur, n, summation))
    prev = cur
</code>```

As you can see, you don't really need sign_indicator list, two for-loops or range function as in the snippet in the question section.

If you want index to start from 1, use enumerate(x, 1) instead of enumerate(x)

To see the result, you can run the following code

```<code>for idx, num, length, summation in result:
     print(f"{idx:>2d} {num:.3f} {length:>2d} {summation:.3f}")
</code>```

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
The other solutions look okay but you don't really need to use sophisticated language features or library functions for this simple problem.

result, prev = [], None

for idx, cur in enumerate(x):
    if not prev or (prev > 0) != (cur > 0):
        n, summation = 1, cur
    else:
        n, summation = n + 1, summation + cur
    result.append((idx, cur, n, summation))
    prev = cur

As you can see, you don't really need sign_indicator list, two for-loops or range function as in the snippet in the question section.

If you want index to start from 1, use enumerate(x, 1) instead of enumerate(x)

To see the result, you can run the following code

for idx, num, length, summation in result:
     print(f"{idx:>2d} {num:.3f} {length:>2d} {summation:.3f}")


问:
Flutter : Prevent Drawer Always Refresh at Swipe inside FutureBuilder

I have a problem make me annoying about the drawer. I have Drawer inside FutureBuilder for fetching user profiles from API. The problem is every I swipe/open the drawer, it will refresh before fetching the user profile. It makes a bad user experience.

I already searching how to make FutureBuilder run once only from this , But the drawer still refreshes.

 I missed something?

Drawer Custom

```<code>class _DrysDrawerCustomState extends State<DrysDrawerCustom> {
  Future<List<UserModel>> userList;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final username = Provider.of<GlobalProvider>(context).username;
    userList = userApi.getUserByUsername(username: username);
  }

  @override
  Widget build(BuildContext context) {
    final globalProvider = Provider.of<GlobalProvider>(context, listen: false);
    //TODO Change Structure Drawer
    return FutureBuilder(
      future: userList,
      builder: (BuildContext context, AsyncSnapshot<List<UserModel>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return ErrorFutureBuilder(errorText: snapshot.error);
          } else {
            final user = snapshot.data[0];
            return DrawerCustom(
              imageUrl: "${userApi.baseImageUrl}/${user.fotoUser}",
              detailUser: [
                Text(user.namaUser),
                Text(user.namaGroup),
              ],
              drawerMenu: [
                DrawerMenu(
                  menuName: "Profil Info",
                  icon: Icons.people_outline,
                  onTap: () => Navigator.of(context)
                      .pushNamed(ProfilInfoScreen.routeNamed),
                ),
                DrawerMenu(
                  menuName: "Ganti Password",
                  icon: Icons.lock,
                  onTap: () => Navigator.of(context)
                      .pushNamed(ChangePasswordScreen.routeNamed),
                ),
                Divider(),
                DrawerMenu(
                  menuName: "Logout",
                  icon: Icons.arrow_back,
                  onTap: () {
                    globalProvider.removeUsername();
                    Navigator.of(context)
                        .pushReplacementNamed(LoginScreen.routeNamed);
                  },
                ),
              ],
            );
          }
        } else {
          return LoadingFutureBuilder();
        }
      },
    );
  }
}

</code>```

Global Provider

```<code>GlobalProvider() {
    _initialSharedPreferences();
  }
String _username;
  String get username => _username;

  void _initialSharedPreferences() async {
    await getUsername();
  }

  Future updateUsername(String username) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.setString("username", username);
    //! It's Important !!! After update / remove sharedpreferences  , must called getUsername() to updated the value.
    await getUsername();
    notifyListeners();
  }

  Future removeUsername() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final result = await pref.remove("username");
    //! It's Important !!! After update / remove sharedpreferences  , must called getUsername() to updated the value.
    await getUsername();
    notifyListeners();
    return result;
  }

  Future getUsername() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final result = pref.getString("username");
    _username = result;
    notifyListeners();
  }
</code>```

答:
Make "user" a global variable and inside build check if user is null, then return FutureBuilder(...) as you've done; Otherwise, just return the DrawerCustom(...) immediately. Hope this answers your question.</p>

```<code>if(user == null)
  return FutureBuilder(...) // don't forget to set user as you've done already
else
  return DrawerCustom(...)
</code>```

Body:
I have a problem make me annoying about the drawer. I have Drawer inside FutureBuilder for fetching user profiles from API. The problem is every I swipe/open the drawer, it will refresh before fetching the user profile. It makes a bad user experience.

I already searching how to make FutureBuilder run once only from this , But the drawer still refreshes.

 I missed something?

Drawer Custom

class _DrysDrawerCustomState extends State<DrysDrawerCustom> {
  Future<List<UserModel>> userList;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final username = Provider.of<GlobalProvider>(context).username;
    userList = userApi.getUserByUsername(username: username);
  }

  @override
  Widget build(BuildContext context) {
    final globalProvider = Provider.of<GlobalProvider>(context, listen: false);
    //TODO Change Structure Drawer
    return FutureBuilder(
      future: userList,
      builder: (BuildContext context, AsyncSnapshot<List<UserModel>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return ErrorFutureBuilder(errorText: snapshot.error);
          } else {
            final user = snapshot.data[0];
            return DrawerCustom(
              imageUrl: "${userApi.baseImageUrl}/${user.fotoUser}",
              detailUser: [
                Text(user.namaUser),
                Text(user.namaGroup),
              ],
              drawerMenu: [
                DrawerMenu(
                  menuName: "Profil Info",
                  icon: Icons.people_outline,
                  onTap: () => Navigator.of(context)
                      .pushNamed(ProfilInfoScreen.routeNamed),
                ),
                DrawerMenu(
                  menuName: "Ganti Password",
                  icon: Icons.lock,
                  onTap: () => Navigator.of(context)
                      .pushNamed(ChangePasswordScreen.routeNamed),
                ),
                Divider(),
                DrawerMenu(
                  menuName: "Logout",
                  icon: Icons.arrow_back,
                  onTap: () {
                    globalProvider.removeUsername();
                    Navigator.of(context)
                        .pushReplacementNamed(LoginScreen.routeNamed);
                  },
                ),
              ],
            );
          }
        } else {
          return LoadingFutureBuilder();
        }
      },
    );
  }
}

Global Provider

GlobalProvider() {
    _initialSharedPreferences();
  }
String _username;
  String get username => _username;

  void _initialSharedPreferences() async {
    await getUsername();
  }

  Future updateUsername(String username) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.setString("username", username);
    //! It's Important !!! After update / remove sharedpreferences  , must called getUsername() to updated the value.
    await getUsername();
    notifyListeners();
  }

  Future removeUsername() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final result = await pref.remove("username");
    //! It's Important !!! After update / remove sharedpreferences  , must called getUsername() to updated the value.
    await getUsername();
    notifyListeners();
    return result;
  }

  Future getUsername() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final result = pref.getString("username");
    _username = result;
    notifyListeners();
  }

Body:
Make "user" a global variable and inside build check if user is null, then return FutureBuilder(...) as you've done; Otherwise, just return the DrawerCustom(...) immediately. Hope this answers your question.

if(user == null)
  return FutureBuilder(...) // don't forget to set user as you've done already
else
  return DrawerCustom(...)


问:
Submitting a form in an iframe with JavaScript
The iframe is on the same domain, I tried the following code, but none of it worked:

```<code> myframe.document.getElementById("myform").submit();
 parent.top.frames[0].document.forms[0].submit();
 myframe.document.getElementById("myform").submit();

 MyIFrame = document.getElementById("myframe");
 myIFrame.getElementById("myform").submit();
</code>```

Update:

This is the HTML:

```<code><html>
<body>
<iframe frameborder="0" scrolling="no" width="530" height="298"
  src="/iframe.php" name="myframe" id="myframe">
  <p>iframes are not supported by your browser.</p>
</iframe><br />

<form action="/styles.css" method="post" id="form1">
<input type="text" name="input1" value=""/>
<input type="text" name="input2" value=""/>
<input type="button" value="test" onclick="submitFrame()">
<input type="submit" value="submit">
</form>

<script>

function submitFrame(){

var MyIFrame = document.getElementById("myframe");
var MyIFrameDoc = (MyIFrame.contentWindow || MyIFrame.contentDocument);
if (MyIFrameDoc.document) MyIFrameDoc = MyIFrameDoc.document;
MyIFrameDoc.getElementById("myform").submit(); // ## error

}

</script>
</body>
</html>
</code>```

iframe.php:

```<code><form method="post" class="af-form-wrapper" id="myform" name="myform" action="/"  >

<input type="text" name="input1" value="2073809442" />
<input type="text" name="input2" value="1" />
<input type="submit" name="submit" value="submit" />
    </form>
</code>```

Firebug says:

```<code> MyIFrameDoc.getElementById("myform").submit is not a function
</code>```

答:
You do not need to post into iframe. You can use normal blank "visible" window. Define your form like this:

```<code>var request = document.createElement("FORM")
request.id = "request"
request.name = "request"
request.action = "callYour.php"
request.method = "POST"
request.target = "_blank"
</code>```

and in your php, when you are done just close the window by:

```<code>window.close();
</code>```

within the HTML part, or within embedded script tags. The new window temporarily opens up but closeses itself when it is completed.

Body:
The iframe is on the same domain, I tried the following code, but none of it worked:

 myframe.document.getElementById("myform").submit();
 parent.top.frames[0].document.forms[0].submit();
 myframe.document.getElementById("myform").submit();

 MyIFrame = document.getElementById("myframe");
 myIFrame.getElementById("myform").submit();

Update:

This is the HTML:

iframes are not supported by your browser.

<form action="/styles.css" method="post" id="form1">
<input type="text" name="input1" value=""/>
<input type="text" name="input2" value=""/>
<input type="button" value="test" onclick="submitFrame()">
<input type="submit" value="submit">
</form>

iframe.php:

<form method="post" class="af-form-wrapper" id="myform" name="myform" action="/"  >

<input type="text" name="input1" value="2073809442" />
<input type="text" name="input2" value="1" />
<input type="submit" name="submit" value="submit" />
    </form>

Firebug says:

 MyIFrameDoc.getElementById("myform").submit is not a function

Body:
You do not need to post into iframe. You can use normal blank "visible" window. Define your form like this:

var request = document.createElement("FORM")
request.id = "request"
request.name = "request"
request.action = "callYour.php"
request.method = "POST"
request.target = "_blank"

and in your php, when you are done just close the window by:

window.close();

within the HTML part, or within embedded script tags. The new window temporarily opens up but closeses itself when it is completed.


问:
How does anaconda pick cudatoolkit
I have multiple enviroments of anaconda with different cuda toolkits installed on them.

env1 has  cudatoolkit               10.0.130

env2 has  cudatoolkit               10.1.168

env3 has   cudatoolkit               10.2.89

I found these by running conda list on each environment.

When i do nvidia-smi i get the following output no matter which environment i am in

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 435.21       Driver Version: 435.21       CUDA Version: 10.1     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce RTX 208...  Off  | 00000000:01:00.0  On |                  N/A |
|  0%   42C    P8     7W / 260W |    640MiB / 11016MiB |      2%      Default |
+-------------------------------+----------------------+----------------------+
</code>```

Is the cuda version shown above is same as cuda toolkit version?
If so why is it same in all the enviroments?

In env3 which has cudatoolkit version 10.2.89, i tried installing cupy library using the command pip install cupy-cuda102 .
I get the following error when i try to do it.

```<code>ERROR: Could not find a version that satisfies the requirement cupy-cuda102 (from versions: none)
ERROR: No matching distribution found for cupy-cuda102
</code>```

I was able to install using pip install cupy-cuda101 which is for cuda 10.1.
Why is it not able to find cudatoolkit 10.2?

The reason i am asking this question is because, i am getting an error cupy.cuda.cublas.CUBLASError: CUBLAS_STATUS_NOT_INITIALIZED when i am running a deep learning model. I am just wondering if cudatoolkit version has something to do with this error.Even if this error is not related to cudatoolkit version i want to know how anaconda uses cudatoolkit.

答:
Is the cuda version shown above is same as cuda toolkit version?

It has nothing to do with CUDA toolkit versions.

If so why is it same in all the enviroments [sic]?

Because it is a property of the driver. It is the maximum CUDA version that the active driver in your system supports. And when you try and use CUDA 10.2, it is why nothing works. Your driver needs to be updated to support CUDA 10.2.

Title: How does anaconda pick cudatoolkit

Body:
I have multiple enviroments of anaconda with different cuda toolkits installed on them.

env1 has  cudatoolkit               10.0.130

env2 has  cudatoolkit               10.1.168

env3 has   cudatoolkit               10.2.89

I found these by running conda list on each environment.

When i do nvidia-smi i get the following output no matter which environment i am in

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 435.21       Driver Version: 435.21       CUDA Version: 10.1     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce RTX 208...  Off  | 00000000:01:00.0  On |                  N/A |
|  0%   42C    P8     7W / 260W |    640MiB / 11016MiB |      2%      Default |
+-------------------------------+----------------------+----------------------+

Is the cuda version shown above is same as cuda toolkit version?
If so why is it same in all the enviroments?

In env3 which has cudatoolkit version 10.2.89, i tried installing cupy library using the command pip install cupy-cuda102 .
I get the following error when i try to do it.

ERROR: Could not find a version that satisfies the requirement cupy-cuda102 (from versions: none)
ERROR: No matching distribution found for cupy-cuda102

I was able to install using pip install cupy-cuda101 which is for cuda 10.1.
Why is it not able to find cudatoolkit 10.2?

The reason i am asking this question is because, i am getting an error cupy.cuda.cublas.CUBLASError: CUBLAS_STATUS_NOT_INITIALIZED when i am running a deep learning model. I am just wondering if cudatoolkit version has something to do with this error.Even if this error is not related to cudatoolkit version i want to know how anaconda uses cudatoolkit.


问:
Is there a way to query from method names with a list of parameters in Spring Boot
I am building an application in Spring Boot. I have a repository and I am creating queries from method names in the following way:

```<code>public interface Example extends Repository {

     User findUserByName(String name);

}
</code>```

Such a query works, and the result of the method call is a User with that name.
Is it possible in Spring Boot to create a query by name, where the input is a list of names and the output is a list of users where each user corresponds to at least a name in the list? For example something like:

```<code>      List<User> findAllUserByName(List<String> name)
</code>```

I have tried such a method, but it doesn't work.

答:
You can use below:

```<code>List<User> findByUserIn(List<String> nameList);
</code>```

Ref:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords

Body:
I am building an application in Spring Boot. I have a repository and I am creating queries from method names in the following way:

public interface Example extends Repository {

     User findUserByName(String name);

}

Such a query works, and the result of the method call is a User with that name.
Is it possible in Spring Boot to create a query by name, where the input is a list of names and the output is a list of users where each user corresponds to at least a name in the list? For example something like:

      List<User> findAllUserByName(List<String> name)

I have tried such a method, but it doesn't work.

Body:
You can use below:

List<User> findByUserIn(List<String> nameList);

Ref:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords


问:
Compare line by line within a linux file
I have a file (test1.txt) like this:

```<code>100 100
200 200
300 HR
400 IT
500 500
600 600
</code>```

And I want to desired output like this:

```<code>100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0
</code>```

I already try to run this command:

```<code>#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi
</code>```

but the result is not as I expected.

答:
Another approach:</p>

```<code>awk '{ printf "%s\t%s\t%d\n", $1, $2, $1 != $2 }' test1.txt
</code>```

Body:
I have a file (test1.txt) like this:

100 100
200 200
300 HR
400 IT
500 500
600 600

And I want to desired output like this:

100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0

I already try to run this command:

#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi

but the result is not as I expected.

Body:
Another approach:

awk '{ printf "%s\t%s\t%d\n", $1, $2, $1 != $2 }' test1.txt


答:
using Artisan::call()
create function in your controller

```<code>use Artisan;

public function refreshDatabase(){
   Artisan::call('migrate:refresh');
   return 'Success';
}

Route::get('refresh', 'YourController@refreshDatabase');

$.ajax('/refresh',
{
    success: function (data) {
           // you can write
    }
});
</code>```

EDITED

in your web.php file use like below without using controller function,

if you really want use controller function then change function name

```<code>    use Artisan;
    Route::get('refresh-tables',function(){
       Artisan::call('migrate:refresh');
           return 'Success';
    });

$.ajax('/refresh-tables',
    {
        success: function (data) {
               // you can write
        }
    });
</code>```

Body:
Can you guys help me solve my issue? How To Delete All Records From Database All Tables in a single click using Laravel ajax.
I have to delete all records from all tables, please help to solve my issue.

Thanks in advance

(https://i.stack.imgur.com/gu6Qg.png)

Body:
using Artisan::call()
create function in your controller

use Artisan;

public function refreshDatabase(){
   Artisan::call('migrate:refresh');
   return 'Success';
}

Route::get('refresh', 'YourController@refreshDatabase');

$.ajax('/refresh',
{
    success: function (data) {
           // you can write
    }
});

EDITED

in your web.php file use like below without using controller function,

if you really want use controller function then change function name

    use Artisan;
    Route::get('refresh-tables',function(){
       Artisan::call('migrate:refresh');
           return 'Success';
    });

$.ajax('/refresh-tables',
    {
        success: function (data) {
               // you can write
        }
    });


问:
MySQL 8 search JSON key by value in array
I've got MySQL table with JSON field, where I store data in such a format.

```<code>{
  "fields": {
    "1": {
      "s": "y"
    },
    "2": {
      "s": "n"
    }
  }
}
</code>```

I need to obtain the keys in fields, e.g. 1 or 2 given the value of s.

Example query:

```<code>create table mytable ( mycol json );

insert into mytable set mycol = '{"fields": {"1": {"s": "y"},"2": {"s": "n"}}}';

select j.* from mytable, JSON_TABLE(mycol,
'$.fields.*' COLUMNS (
    json_key VARCHAR(10) PATH '$',
    s VARCHAR(10) PATH '$.s'
  )
) AS j where j.s = 'y';
</code>```

gives:

```<code># json_key, s
null, y
</code>```

I would expect to get

```<code># json_key, s
1, y
</code>```

Is it possible to get that data somehow?

I don't need the results in row / table format. I would be happy to get the comma separated list of IDs (json_keys) meeting my criterium.

EDIT:
I was also thinking about getting the paths using JSON_SEARCH and passing that to JSON_EXTRACT, this was achieved here: Combining JSON_SEARCH and JSON_EXTRACT get me: "Invalid JSON path expression."
Unfortunately the difference is that I would need to use JSON_SEARCH in all mode, as I need all results. In such a mode JSON_SEARCH returns list of paths, where as JSON_EXTRACT accepts list of arguments.

答:
Try FOR ORDINALITY (see 12.17.6 JSON Table Functions), this type enumerates rows in the COLUMNS clause:

SELECT
  JSON_UNQUOTE(
    JSON_EXTRACT(
      JSON_KEYS(`mycol` ->> '$.fields'),
      CONCAT('$[', `j`.`row` - 1, ']')
    )
  ) `json_key`,
  `j`.`s`
FROM
  `mytable`,
  JSON_TABLE(
    `mycol`,
    '$.fields.*' COLUMNS (
      `row` FOR ORDINALITY,
      `s` VARCHAR(10) PATH '$.s'
  )
) `j`
WHERE
  `j`.`s` = 'y';
```

See dbfiddle.

Body:
I've got MySQL table with JSON field, where I store data in such a format.

{
  "fields": {
    "1": {
      "s": "y"
    },
    "2": {
      "s": "n"
    }
  }
}

I need to obtain the keys in fields, e.g. 1 or 2 given the value of s.

Example query:

create table mytable ( mycol json );

insert into mytable set mycol = '{"fields": {"1": {"s": "y"},"2": {"s": "n"}}}';

select j.* from mytable, JSON_TABLE(mycol,
'$.fields.*' COLUMNS (
    json_key VARCHAR(10) PATH '$',
    s VARCHAR(10) PATH '$.s'
  )
) AS j where j.s = 'y';

gives:

# json_key, s
null, y

I would expect to get

# json_key, s
1, y

Is it possible to get that data somehow?

I don't need the results in row / table format. I would be happy to get the comma separated list of IDs (json_keys) meeting my criterium.

EDIT:
I was also thinking about getting the paths using JSON_SEARCH and passing that to JSON_EXTRACT, this was achieved here: Combining JSON_SEARCH and JSON_EXTRACT get me: "Invalid JSON path expression."
Unfortunately the difference is that I would need to use JSON_SEARCH in all mode, as I need all results. In such a mode JSON_SEARCH returns list of paths, where as JSON_EXTRACT accepts list of arguments.

Body:
Try FOR ORDINALITY (see 12.17.6 JSON Table Functions), this type enumerates rows in the COLUMNS clause:

SELECT
  JSON_UNQUOTE(
    JSON_EXTRACT(
      JSON_KEYS(`mycol` ->> '$.fields'),
      CONCAT('$[', `j`.`row` - 1, ']')
    )
  ) `json_key`,
  `j`.`s`
FROM
  `mytable`,
  JSON_TABLE(
    `mycol`,
    '$.fields.*' COLUMNS (
      `row` FOR ORDINALITY,
      `s` VARCHAR(10) PATH '$.s'
  )
) `j`
WHERE
  `j`.`s` = 'y';

See dbfiddle.


问:
curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number
When I try to connect to any server (e.g. google.com) using curl (or libcurl) I get the error message:

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Verbose output:

```<code>$ curl www.google.com --verbose
* Rebuilt URL to: www.google.com/
* Uses proxy env variable no_proxy == 'localhost,127.0.0.1,localaddress,.localdomain.com'
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'
*   Trying 131.159.0.2...
* TCP_NODELAY set
* Connected to proxy.in.tum.de (131.159.0.2) port 8080 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* error:1408F10B:SSL routines:ssl3_get_record:wrong version number
* Closing connection 0
curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number'
</code>```

For some reason curl seems to use TLSv1.3 even if I force it to use TLSv1.2 with the command --tlsv1.2  (it will still print TLSv1.3 (OUT), ..."
I am using the newest version of both Curl and OpenSSL :

```<code>$ curl -V
curl 7.61.0-DEV (x86_64-pc-linux-gnu) libcurl/7.61.0-DEV OpenSSL/1.1.1 zlib/1.2.8
Release-Date: [unreleased]
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP UnixSockets HTTPS-proxy
</code>```

I think this is a problem related to my installation of the programms.
Can somebody explain to me what this error message means?

答:
Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number.
Set proxy by opening subl ~/.curlrc or use any other text  editor. Then add the following line to file:

```<code>proxy= proxyserver:proxyport
</code>```

For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.

Body:
When I try to connect to any server (e.g. google.com) using curl (or libcurl) I get the error message:

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Verbose output:

$ curl www.google.com --verbose
* Rebuilt URL to: www.google.com/
* Uses proxy env variable no_proxy == 'localhost,127.0.0.1,localaddress,.localdomain.com'
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'
*   Trying 131.159.0.2...
* TCP_NODELAY set
* Connected to proxy.in.tum.de (131.159.0.2) port 8080 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* error:1408F10B:SSL routines:ssl3_get_record:wrong version number
* Closing connection 0
curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number'

For some reason curl seems to use TLSv1.3 even if I force it to use TLSv1.2 with the command --tlsv1.2  (it will still print TLSv1.3 (OUT), ..."
I am using the newest version of both Curl and OpenSSL :

$ curl -V
curl 7.61.0-DEV (x86_64-pc-linux-gnu) libcurl/7.61.0-DEV OpenSSL/1.1.1 zlib/1.2.8
Release-Date: [unreleased]
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP UnixSockets HTTPS-proxy

I think this is a problem related to my installation of the programms.
Can somebody explain to me what this error message means?

Body:
Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number.
Set proxy by opening subl ~/.curlrc or use any other text  editor. Then add the following line to file:

proxy= proxyserver:proxyport

For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.


问:
How to implement decimal to binary conversion
I implemented a binary to decimal function in Haskell and am currently working on a function that would convert a decimal into a binary value. (I'm aware that these functionalities are available somewhere although they're not part of Prelude.hs)

I came up with the following code for a C-type procedural language, but I have trouble adapting it into the functional paradigm.

while (n > 0)
{
    if (n % 2 == 1)
        str = str + "1";
    else
        str = str + "0";
    n = n / 2;
}
```

<p>I ventured into functional programming in Haskell only recently so I'm quite new to the functional way of thinking. I attempted the above using both recursion and list comprehension, but I'm not sure on how to place the guards and the logic properly since this involves multiple conditions. I use an <code>Int</code> list to hold the separate binary bits.</p>

```--Decimal to binary
toBin:: Int -> [Int]
toBin 0 = [0]
toBin n | (n % 2 == 1) =
        |(n % 2 == 0) =
```

<p>I've understood that the above pattern would let the program choose either guard and end evaluating the function. Am I on the wrong track here?</p>

<p>Below is what I came up with primitive recursion to convert any base (less than 10, in place of the 2) to decimal.</p>

```toDecimal :: [Int] -> Int
toDecimal [] = 0
toDecimal (x:xs) = (x * 2 ^(length xs)) + bin xs
```

答:
You can use bit shifts from Data.Bits</p>

```<code>fromBits :: Bits a => a -> [Bool]
fromBits b
    | b == zeroBits = []
    | otherwise     = testBit b 0 : fromBits (shiftR b 1)

fromBits_ :: Bits a => a -> [Bool]
fromBits_ = reverse . fromBits
</code>```

Body:
I implemented a binary to decimal function in Haskell and am currently working on a function that would convert a decimal into a binary value. (I'm aware that these functionalities are available somewhere although they're not part of Prelude.hs)

I came up with the following code for a C-type procedural language, but I have trouble adapting it into the functional paradigm.

while (n > 0)
{
    if (n % 2 == 1)
        str = str + "1";
    else
        str = str + "0";
    n = n / 2;
}

I ventured into functional programming in Haskell only recently so I'm quite new to the functional way of thinking. I attempted the above using both recursion and list comprehension, but I'm not sure on how to place the guards and the logic properly since this involves multiple conditions. I use an Int list to hold the separate binary bits.

--Decimal to binary
toBin:: Int -> [Int]
toBin 0 = [0]
toBin n | (n % 2 == 1) =
        |(n % 2 == 0) =

I've understood that the above pattern would let the program choose either guard and end evaluating the function. Am I on the wrong track here?

Below is what I came up with primitive recursion to convert any base (less than 10, in place of the 2) to decimal.

toDecimal :: [Int] -> Int
toDecimal [] = 0
toDecimal (x:xs) = (x * 2 ^(length xs)) + bin xs

Body:
You can use bit shifts from Data.Bits

fromBits :: Bits a => a -> [Bool]
fromBits b
    | b == zeroBits = []
    | otherwise     = testBit b 0 : fromBits (shiftR b 1)

fromBits_ :: Bits a => a -> [Bool]
fromBits_ = reverse . fromBits


问:
Toggling a non-attr_accessible variable
I am creating a Rails application that is a blogging platform, with many contributing writers.  My User model has a :writer boolean attribute to indicate whether or not a particular user has permission to publish an article.  In order to prevent mass assignment, the :writer attribute is NOT listed under attr_accessible for the User model.  Instead, I thought of creating a function similar to the following, to allow for toggling of the writer-permissions:

```<code>def toggle_writer
  if User.find(:id).writer?
    User.find(:id).update_attribute(:writer, false)
  else
    User.find(:id).update_attribute(:writer, true)
  end
  flash[:success] = "User permissions toggled."
  redirect_to admintools_users_path
end
</code>```

I have several questions regarding this approach, though:

How would I invoke this from a view?  Is there a way to invoke a function via a link_to or button_for?

Where would I put such a function?  In a controller, or helper?

Would I need to edit any routes in the config/routes.rb file?

Thanks in advance for your help!

答:
Yes you can.

Better if you put it in the users_controller.

Yes, you would. As this action is going to update a single user, so, you should do the following in routes.rb:

```<code> resources :users do
   member do #this means you are doing with a certain object
     get :toggle_writer, :as => :toggle_writer_for # this line will generate toggle_writer_for_user_path route
   end
 end
</code>```

Now you can use this route with link_to, like link_to("Toggle writer", toggle_writer_for_user_path(@user)), where @user is you can get from params[:id].

Title: Toggling a non-attr_accessible variable

Body:
I am creating a Rails application that is a blogging platform, with many contributing writers.  My User model has a :writer boolean attribute to indicate whether or not a particular user has permission to publish an article.  In order to prevent mass assignment, the :writer attribute is NOT listed under attr_accessible for the User model.  Instead, I thought of creating a function similar to the following, to allow for toggling of the writer-permissions:

def toggle_writer
  if User.find(:id).writer?
    User.find(:id).update_attribute(:writer, false)
  else
    User.find(:id).update_attribute(:writer, true)
  end
  flash[:success] = "User permissions toggled."
  redirect_to admintools_users_path
end

I have several questions regarding this approach, though:

How would I invoke this from a view?  Is there a way to invoke a function via a link_to or button_for?

Where would I put such a function?  In a controller, or helper?

Would I need to edit any routes in the config/routes.rb file?

Thanks in advance for your help!

Body:
Yes you can.

Better if you put it in the users_controller.

Yes, you would. As this action is going to update a single user, so, you should do the following in routes.rb:

 resources :users do
   member do #this means you are doing with a certain object
     get :toggle_writer, :as => :toggle_writer_for # this line will generate toggle_writer_for_user_path route
   end
 end

Now you can use this route with link_to, like link_to("Toggle writer", toggle_writer_for_user_path(@user)), where @user is you can get from params[:id].


问:
How to open VSCode Remote-WSL by right click
I would like to open the current folder on VSCode Remote-WSL by right click from Windows File Explorer.
How can I make it?
Thank you in advance.</p>

答:
To add Windows context menu for a directory to open it in Visual Studio Code within Remote WSL, add these windows registry keys as admin:

```<code>reg add "HKEY_CLASSES_ROOT\Directory\shell\WSLVSCode\command" /t REG_EXPAND_SZ /d "wsl.exe code `wslpath '%1'`"
reg add "HKEY_CLASSES_ROOT\Directory\shell\WSLVSCode" /t REG_EXPAND_SZ /d "Open in WSL VSCode"
reg add "HKEY_CLASSES_ROOT\Directory\shell\WSLVSCode" /v Icon /t REG_EXPAND_SZ /d "C:\Users\User\AppData\Local\Programs\Microsoft VS Code\Code.exe"
</code>```

Update the correct path for icon file.

Body:
To add Windows context menu for a directory to open it in Visual Studio Code within Remote WSL, add these windows registry keys as admin:

reg add "HKEY_CLASSES_ROOT\Directory\shell\WSLVSCode\command" /t REG_EXPAND_SZ /d "wsl.exe code `wslpath '%1'`"
reg add "HKEY_CLASSES_ROOT\Directory\shell\WSLVSCode" /t REG_EXPAND_SZ /d "Open in WSL VSCode"
reg add "HKEY_CLASSES_ROOT\Directory\shell\WSLVSCode" /v Icon /t REG_EXPAND_SZ /d "C:\Users\User\AppData\Local\Programs\Microsoft VS Code\Code.exe"

Update the correct path for icon file.


问:
How to hide keyboard in iOS mobile automation using Appium
I am using iOS version of 10.2 and xcode version is 8.3.

Can anyone let me know how to hide the keyboard in iOS mobile automation using Appium?

programming language used: Java.

答:
You can use below code snippet to hide keyboard:</p>

```<code>driver.getKeyboard().pressKey(Keys.RETURN);
</code>```

Body:
You can use below code snippet to hide keyboard:

driver.getKeyboard().pressKey(Keys.RETURN);


问:
I want to apply an INNER JOIN and use WHERE condition using 3 tables
```<code>SELECT
  *
FROM
  retailer
WHERE
  states = 1
  AND newsletter.status = 1
  AND (
    company_id IN (
      SELECT
        id
      FROM
        retailer
      WHERE
        muli_ret_id = 0
    )
  )
ORDER BY
  email
</code>```

答:
I'm not sure that your exact current query can be expressee using an inner join instead of the where clause.  You might try:

```<code>SELECT DISTINCT r1.*
FROM retailer r1
INNER JOIN retailer r2
    ON r1.company_id = r2.id
WHERE
    r1.states = 1 AND
    r1.newsletter.status = 1 AND
    r2.muli_ret_id = 0
ORDER BY
    r1.email;
</code>```

I use select distinct to remove possible duplicates which could arise from the self join.  But honestly, you current approach is fine, though I might use exists here:

```<code>SELECT r1.*
FROM retailer r1
WHERE
    r1.states = 1 AND
    r1.newsletter.status = 1 AND
    EXISTS (SELECT 1 FROM retailer r2
            WHERE r2.id = r1.company_id AND r2.muli_ret_id = 0)
ORDER BY
    r1.email;
</code>```

Body:
I'm not sure that your exact current query can be expressee using an inner join instead of the where clause.  You might try:

SELECT DISTINCT r1.*
FROM retailer r1
INNER JOIN retailer r2
    ON r1.company_id = r2.id
WHERE
    r1.states = 1 AND
    r1.newsletter.status = 1 AND
    r2.muli_ret_id = 0
ORDER BY
    r1.email;

I use select distinct to remove possible duplicates which could arise from the self join.  But honestly, you current approach is fine, though I might use exists here:

SELECT r1.*
FROM retailer r1
WHERE
    r1.states = 1 AND
    r1.newsletter.status = 1 AND
    EXISTS (SELECT 1 FROM retailer r2
            WHERE r2.id = r1.company_id AND r2.muli_ret_id = 0)
ORDER BY
    r1.email;


问:
Can you mutate the properties of a factory function without using this?
I've been reading about the benefits of using factory functions over classes, however, I'm having trouble getting them to work in a similar manner.

For instance, with classes:

```<code>class NumberManager {
    constructor(numbers){
        this.numbers = numbers;
    }

    removeNumber(input){
        this.numbers = this.numbers.filter( number => number != input )
    }
}

n = new NumberManager([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1]
</code>```

However, with a factory function:

```<code>const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    numbers = numbers.filter( number => number != input )
  }

  return {
    numbers,
    removeNumber
  }
}

n = NumberFactory([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1, 2]
</code>```

Is it possible to have a similar level of freedom that classes have (e.g. easily mutating properties), without having to use things like this (which can break across execution contexts) and new (which can break if having to convert a class to a factory)?

答:
Put the object you want to return from the factory into a variable before returning it, then you can reference that variable and mutate the object:

const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    instance.numbers = instance.numbers.filter( number => number != input );
  };
  const instance = { numbers, removeNumber };

  return instance;
}

const n = NumberFactory([1, 2]);
console.log(n.numbers); // --> [1, 2]
n.removeNumber(2);
console.log(n.numbers); // --> [1]```

Body:
I've been reading about the benefits of using factory functions over classes, however, I'm having trouble getting them to work in a similar manner.

For instance, with classes:

class NumberManager {
    constructor(numbers){
        this.numbers = numbers;
    }

    removeNumber(input){
        this.numbers = this.numbers.filter( number => number != input )
    }
}

n = new NumberManager([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1]

However, with a factory function:

const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    numbers = numbers.filter( number => number != input )
  }

  return {
    numbers,
    removeNumber
  }
}

n = NumberFactory([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1, 2]

Is it possible to have a similar level of freedom that classes have (e.g. easily mutating properties), without having to use things like this (which can break across execution contexts) and new (which can break if having to convert a class to a factory)?


问:
Html.AntiForgeryToken() causeing errors after upgrading to .NET 3.5 SP1
I've just updated to .NET 3.5 SP1 and my once working ASP.NET MVC page has now stopped working.

When trying to load a page I get the following YSOD

```<code>[CryptographicException: Padding is invalid and cannot be removed.]
   System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) +7596702
   System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) +208
   System.Security.Cryptography.CryptoStream.FlushFinalBlock() +33
   System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) +225
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +195

[ViewStateException: Invalid viewstate.
    Client IP: 127.0.0.1
    Port:
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)
    ViewState: hC6BC8KsuD/yoy2iG74bUZ8TYhGfuDDeIjh9fg/L18yr/E+1Nk/pjS5gyn9O+2jY
    Referer: http://localhost:1092/admin/product
    Path: /admin.aspx/product/edit/4193]

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
   System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +14
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +242
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.Mvc.AntiForgeryTokenSerializer.Deserialize(String serializedToken) +73
</code>```

If I remove the line

```<code><%= Html.AntiForgeryToken() %>
</code>```

Everything works again, any ideas what might be causing this? I would have expected more luck in finding a solution if this was an MVC or .NET issue so I'm guess it is something to do with my configuration.

I've tried reinstalling the MVC framework to see if it was because I installed before SP1 but I still get the same issue. Google and SO search hasn't resulted in any firm conclusions.

答: Looks like this problem has been solved now. Take a look at http://forums.asp.net/p/1388671/2960554.aspx </p>

OwnerDisplayName: Remmus

ContentLicense: CC BY-SA 2.5

Body:
I've just updated to .NET 3.5 SP1 and my once working ASP.NET MVC page has now stopped working.

When trying to load a page I get the following YSOD

[CryptographicException: Padding is invalid and cannot be removed.]
   System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) +7596702
   System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) +208
   System.Security.Cryptography.CryptoStream.FlushFinalBlock() +33
   System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) +225
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +195

[ViewStateException: Invalid viewstate.
    Client IP: 127.0.0.1
    Port:
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)
    ViewState: hC6BC8KsuD/yoy2iG74bUZ8TYhGfuDDeIjh9fg/L18yr/E+1Nk/pjS5gyn9O+2jY
    Referer: http://localhost:1092/admin/product
    Path: /admin.aspx/product/edit/4193]

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
   System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +14
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +242
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.Mvc.AntiForgeryTokenSerializer.Deserialize(String serializedToken) +73

If I remove the line

<%= Html.AntiForgeryToken() %>

Everything works again, any ideas what might be causing this? I would have expected more luck in finding a solution if this was an MVC or .NET issue so I'm guess it is something to do with my configuration.

I've tried reinstalling the MVC framework to see if it was because I installed before SP1 but I still get the same issue. Google and SO search hasn't resulted in any firm conclusions.

OwnerDisplayName: furybyname


问:
inserting the records in the c# form
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}
</code>```

I am not getting the answer..

答:
You need to surround the values in single quotes:</p>

```<code>    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES ('" + textBox1.Text + "', '" + textBox4.Text + "')", con);
</code>```

Title: inserting the records in the c# form

Body:
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}

I am not getting the answer..

Body:
You need to surround the values in single quotes:

    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES ('" + textBox1.Text + "', '" + textBox4.Text + "')", con);


问:
How to count a same data in JSON?
JSON to count:

```<code>[{"thn":"2017","jumlah":"30"},{"thn":"2018","jumlah":"80"},{"thn":"2018","jumlah":"64"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"4"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"198"},{"thn":"2018","jumlah":"2"},{"thn":"2018","jumlah":"202"},{"thn":"2019","jumlah":"31"},{"thn":"2019","jumlah":"1"}]
</code>```

this is my code

```<code>var data_nama=[];
var data_jumlah=[];

$.post("<?=base_url('Welcome/checkData')?>",
    function(data){
        var obj = JSON.parse(data);
        $.each(obj,function(test,item){
            data_nama.push(item.thn);
            data_jumlah.push(item.jumlah);
        });
</code>```

How to add the same year for example

2018 is must 562 , not 80 , 64

sorry for my bad english ><

Title: How to count a same data in JSON?

Body:
JSON to count:

[{"thn":"2017","jumlah":"30"},{"thn":"2018","jumlah":"80"},{"thn":"2018","jumlah":"64"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"4"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"198"},{"thn":"2018","jumlah":"2"},{"thn":"2018","jumlah":"202"},{"thn":"2019","jumlah":"31"},{"thn":"2019","jumlah":"1"}]

this is my code

var data_nama=[];
var data_jumlah=[];

$.post("<?=base_url('Welcome/checkData')?>",
    function(data){
        var obj = JSON.parse(data);
        $.each(obj,function(test,item){
            data_nama.push(item.thn);
            data_jumlah.push(item.jumlah);
        });

How to add the same year for example

2018 is must 562 , not 80 , 64

sorry for my bad english ><

Body:
You can use reduce() to easily accomplish this:

// Your JSON data
let data = [{'thn': '2017', 'jumlah': '30'}, {'thn': '2018', 'jumlah': '80'}, {'thn': '2018', 'jumlah': '64'}, {'thn': '2018', 'jumlah': '5'}, {'thn': '2018', 'jumlah': '1'}, {'thn': '2018', 'jumlah': '1'}, {'thn': '2018', 'jumlah': '4'}, {'thn': '2018', 'jumlah': '5'}, {'thn': '2018', 'jumlah': '198'}, {'thn': '2018', 'jumlah': '2'}, {'thn': '2018', 'jumlah': '202'}, {'thn': '2019', 'jumlah': '31'}, {'thn': '2019', 'jumlah': '1'}];

let counts = data.reduce((acc, {thn, jumlah}) => {
    if (!acc[thn]) {
        acc[thn] = 0;
    }
    acc[thn] += parseInt(jumlah);

    return acc;
}, {});

This will set counts to:

{2017: 30, 2018: 562, 2019: 32}


问:
Having trouble using a file as a command-line argument in the same directory as the python script
I'm trying to write a .py script that takes in another file as a command argument, with the cmd-argument file in the same directory as said script.

What I have so far is:

```<code>import sys
java_file = open(sys.argv[1],"r")
<rest of file>
</code>```

Which works fine if I have a command-line argument like this:

```<code>python.exe "D:\<user>\<more file directories>\balanced.py" "D:\<user>\<same file directories>\Driver.java"
</code>```

What I'd like to do is have the command-line argument be something like:

```<code>python.exe "D:\<user>\<more file directories>\balanced.py" Driver.java
</code>```

Running on Windows 10 command prompt using Python 3.7.3.

答:
on Windows, sys.argv[0] should be the full path to your script, so you can use os.path.split(sys.argv[0])[0] to get the path, then os.path.join() to join it

```<code>import sys, os
java_file = open(os.path.join(os.path.split(sys.argv[0])[0], sys.argv[1]))

</code>```

Body:
I'm trying to write a .py script that takes in another file as a command argument, with the cmd-argument file in the same directory as said script.

What I have so far is:

import sys
java_file = open(sys.argv[1],"r")
<rest of file>

Which works fine if I have a command-line argument like this:

python.exe "D:\<user>\<more file directories>\balanced.py" "D:\<user>\<same file directories>\Driver.java"

What I'd like to do is have the command-line argument be something like:

python.exe "D:\<user>\<more file directories>\balanced.py" Driver.java

Running on Windows 10 command prompt using Python 3.7.3.

Body:
on Windows, sys.argv[0] should be the full path to your script, so you can use os.path.split(sys.argv[0])[0] to get the path, then os.path.join() to join it

import sys, os
java_file = open(os.path.join(os.path.split(sys.argv[0])[0], sys.argv[1]))


问:
Embedded Bokeh DataTable not showing in Django
I have developed a Django web application showing interactive maps generated by Bokeh, and sent to the templates as script/div using 'components' (from bokeh.embed). All items (figure, slider, title) are shown correctly except DataTable, which I can show in a standalone document or in Jupyter, but not with 'components'.

I have read Bokeh DataTable not show in Flask, Embedding bokeh plot and datatable in flask and other threads, which helped me to fix the JS/CSS links, but it did not help with my problem.

I tried to wrap the DataTable inside different modules, like Panel, WidgetBox, etc., after reading https://github.com/bokeh/bokeh/issues/4507, without success. For simplicity, I used example data with no link to my data to generate the table in a separate Django view, and created a separate template.

I have run out of ideas for now. I know that widgets in Bokeh have had rendering issues, so I am guessing my issue could be related to those issues, but more likely to my lack of knowledge. The code is below.

DJANGO VIEW:

```<code>def datatable_test(request):

data = dict(
    dates=[date(2014, 3, i + 1) for i in range(10)],
    downloads=[randint(0, 100) for i in range(10)],
)
source = ColumnDataSource(data)

columns = [
    TableColumn(field="dates", title="Date", formatter=DateFormatter()),
    TableColumn(field="downloads", title="Downloads"),
]

data_table_mth = DataTable(source=source, columns=columns, width=400, height=280)

layout = column(
    Spacer(width=100),
    WidgetBox(data_table_mth),
    )

script_table, div_table = components(layout)
output_file("DATATABLE TEST.html")
show(layout)

return render(request, 'integrated/datatable_test.html', {'script_table': script_table,'div_table': div_table})
</code>```

DJANGO TEMPLATE:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>{% block title %}{% endblock %}</title>

  <link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.4.0.min.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-1.4.0.min.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.bokeh.org/bokeh/release/bokeh-tables-1.4.0.min.css" rel="stylesheet" type="text/css">

  {{ script_table | safe }}

                {{ div_table | safe }}

```

Output as embedded table is blank:
output as embedded table

Output as standalone html works:
output as standalone

答:
As bigreddot suggested, I opened the browser console, showing the following error messages when the DataTable is embedded in its original view/template:

browser console

Body:
I have developed a Django web application showing interactive maps generated by Bokeh, and sent to the templates as script/div using 'components' (from bokeh.embed). All items (figure, slider, title) are shown correctly except DataTable, which I can show in a standalone document or in Jupyter, but not with 'components'.

I have read Bokeh DataTable not show in Flask, Embedding bokeh plot and datatable in flask and other threads, which helped me to fix the JS/CSS links, but it did not help with my problem.

I tried to wrap the DataTable inside different modules, like Panel, WidgetBox, etc., after reading https://github.com/bokeh/bokeh/issues/4507, without success. For simplicity, I used example data with no link to my data to generate the table in a separate Django view, and created a separate template.

I have run out of ideas for now. I know that widgets in Bokeh have had rendering issues, so I am guessing my issue could be related to those issues, but more likely to my lack of knowledge. The code is below.

DJANGO VIEW:

def datatable_test(request):

data = dict(
    dates=[date(2014, 3, i + 1) for i in range(10)],
    downloads=[randint(0, 100) for i in range(10)],
)
source = ColumnDataSource(data)

columns = [
    TableColumn(field="dates", title="Date", formatter=DateFormatter()),
    TableColumn(field="downloads", title="Downloads"),
]

data_table_mth = DataTable(source=source, columns=columns, width=400, height=280)

layout = column(
    Spacer(width=100),
    WidgetBox(data_table_mth),
    )

script_table, div_table = components(layout)
output_file("DATATABLE TEST.html")
show(layout)

return render(request, 'integrated/datatable_test.html', {'script_table': script_table,'div_table': div_table})

DJANGO TEMPLATE:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>{% block title %}{% endblock %}</title>

  <link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.4.0.min.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-1.4.0.min.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.bokeh.org/bokeh/release/bokeh-tables-1.4.0.min.css" rel="stylesheet" type="text/css">

  {{ script_table | safe }}

                {{ div_table | safe }}

Output as embedded table is blank:
output as embedded table

Output as standalone html works:
output as standalone


问:
Bash - replace in file strings from first array with strings from second array
I have two arrays. The first one is filled with values greped from the file that I want to replace with the new ones downloaded.

Please note that I don't know exactly how the first array will look like, meaning some values will have _, other - and some won't have any of that and immediately after the name will be placed : (colon).

Example arrays:

array1:

[account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123]

array2:

[account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124]

Those arrays are the only example, there are more than 50 values to replace.

I am doing a comparison of every item in the second array with every item in the first array as shown below:

```<code>file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                 fi
        done
done
</code>```

Here I substring only the first part for every item in the second array so I can compare it with the item in the first array.

e.g. account_custom_2:124 -> account or notification-dispatcher_custom_2:124 -> notification-dispatcher.

This works nice but I encounter problem when notification is in notification-core_1:123 and notification-dispatcher_core_1:123 and notification-dispatcher-smschannel_core_1:123.

Can you please give advice on how to fix this or if you can suggest another approach to this?

答:
The point is the base of array2 element may include other element
as a substring and will cause an improper replacement depending on the order
of matching.
To avoid this, you can sort the array in descending order so the
longer pattern comes first.

Assuming the strings in the arrays do not contain tab characters, would
you please try:

```<code>file_name="<path_to_file>/file.txt"
array1=(account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123)
array2=(account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124)

# insert the following block to sort array2 in descending order
array2=( $(for j in "${array2[@]}"; do
    array_2_base=${j%%_*}
    printf "%s\t%s\n" "$array_2_base" "$j"
done | sort -r | cut -f2-) )

# the following code will work "as is"
for i in "${!array1[@]}"
do
    for j in "${!array2[@]}"
    do
        array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
        if [[ "${array1[$i]}" == *"$array_2_base"* ]]
        then
            sed -i "s=${array1[$i]}=${array2[$j]}=g" "$file_name"
            delete="${array1[$i]}"
            array1=( "${array1[@]/$delete}" )
        fi
    done
done
</code>```

The script above will be inefficent in execution time due to the repetitive
invocation of sed -i command.

The script below will run faster
by pre-generating the sed script and executing it just once.

```<code>file_name="<path_to_file>/file.txt"
array1=(
    account:123
    shoppingcart-1:123
    notification-core_1:123
    notification-dispatcher_core_1:123
    notification-dispatcher-smschannel_core_1:123
)
array2=(
    account_custom_2:124
    shoppingcart_custom_2:124
    notification_custom_2:124
    notification-dispatcher_custom_2:124
    notification-dispatcher-smschannel_custom_2:124
)

while IFS=$'\t' read -r base a2; do     # read the sorted list line by line
    for a1 in "${array1[@]}"; do
        if [[ $a1 == *$base* ]]; then
            scr+="s=$a1=$a2=g;"         # generate sed script by appending the "s" command
            continue 2
        fi
    done
done < <(for j in "${array2[@]}"; do
    array_2_base=${j%%_*}               # substring before the 1st "_"
    printf "%s\t%s\n" "$array_2_base" "$j"
                                        # print base and original element side by side
done | sort -r)

sed -i "$scr" "$file_name"              # execute the replacement at once
</code>```

Body:
I have two arrays. The first one is filled with values greped from the file that I want to replace with the new ones downloaded.

Please note that I don't know exactly how the first array will look like, meaning some values will have _, other - and some won't have any of that and immediately after the name will be placed : (colon).

Example arrays:

array1:

[account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123]

array2:

[account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124]

Those arrays are the only example, there are more than 50 values to replace.

I am doing a comparison of every item in the second array with every item in the first array as shown below:

file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                 fi
        done
done

Here I substring only the first part for every item in the second array so I can compare it with the item in the first array.

e.g. account_custom_2:124 -> account or notification-dispatcher_custom_2:124 -> notification-dispatcher.

This works nice but I encounter problem when notification is in notification-core_1:123 and notification-dispatcher_core_1:123 and notification-dispatcher-smschannel_core_1:123.

Can you please give advice on how to fix this or if you can suggest another approach to this?

Body:
The point is the base of array2 element may include other element
as a substring and will cause an improper replacement depending on the order
of matching.
To avoid this, you can sort the array in descending order so the
longer pattern comes first.

Assuming the strings in the arrays do not contain tab characters, would
you please try:

file_name="<path_to_file>/file.txt"
array1=(account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123)
array2=(account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124)

# insert the following block to sort array2 in descending order
array2=( $(for j in "${array2[@]}"; do
    array_2_base=${j%%_*}
    printf "%s\t%s\n" "$array_2_base" "$j"
done | sort -r | cut -f2-) )

# the following code will work "as is"
for i in "${!array1[@]}"
do
    for j in "${!array2[@]}"
    do
        array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
        if [[ "${array1[$i]}" == *"$array_2_base"* ]]
        then
            sed -i "s=${array1[$i]}=${array2[$j]}=g" "$file_name"
            delete="${array1[$i]}"
            array1=( "${array1[@]/$delete}" )
        fi
    done
done

The script above will be inefficent in execution time due to the repetitive
invocation of sed -i command.

The script below will run faster
by pre-generating the sed script and executing it just once.

file_name="<path_to_file>/file.txt"
array1=(
    account:123
    shoppingcart-1:123
    notification-core_1:123
    notification-dispatcher_core_1:123
    notification-dispatcher-smschannel_core_1:123
)
array2=(
    account_custom_2:124
    shoppingcart_custom_2:124
    notification_custom_2:124
    notification-dispatcher_custom_2:124
    notification-dispatcher-smschannel_custom_2:124
)

while IFS=$'\t' read -r base a2; do     # read the sorted list line by line
    for a1 in "${array1[@]}"; do
        if [[ $a1 == *$base* ]]; then
            scr+="s=$a1=$a2=g;"         # generate sed script by appending the "s" command
            continue 2
        fi
    done
done < <(for j in "${array2[@]}"; do
    array_2_base=${j%%_*}               # substring before the 1st "_"
    printf "%s\t%s\n" "$array_2_base" "$j"
                                        # print base and original element side by side
done | sort -r)

sed -i "$scr" "$file_name"              # execute the replacement at once


问:
Python: How do I compare two sets containing strings and replace one value with the other if they are not equal?
I am writing a python script to create/update/delete values in AWS SSM parameter store.

My current logic is:

```<code>def lambda_handler(event, context):
    logger.info(event)#removing tab
    files = get_local_files() #set of all application.properties files
    count = 0
    for file in files: #iterate in each application.properties file
        remote_key_vals = get_ssm_paramstore_values(file) #remote_key_vals is a set of keys from ssm
        local_key_vals = read_ssm_local_file(file) #local_key_vals is a set of keys from local file
        if(len(remote_key_vals)==0):
            create_ssm_paramstore(file)
            count=count+1
        elif(local_key_vals>remote_key_vals):
            diff = local_key_vals-remote_key_vals
            if(len(diff)>0):
                update_ssm_paramstore(file, diff)
                count=count+1
        elif(remote_key_vals>local_key_vals):
            diff=remote_key_vals - local_key_vals
            if(len(diff)>0):
                delete_ssm_paramstore(file, diff)
                count = count+1
        else:
            logger.info(file+' already exist')
        logger.info(local_key_vals)
    try:
        req = requests.put(event['ResponseURL'],
                          data=getResponse(event, context,
                                            responseStatus))
        if req.status_code != 200:
            logger.info(req.text)
            raise Exception('Received non 200 response while sending response to CFN.'
                            )
    except requests.exceptions.RequestException, e:
        logger.info(e)
        raise
    return
</code>```

This code works for 3 conditions only:

When the SSM parameter store is empty, the local application.properties file will get created/loaded if the length of the remote_key_vals set is 0 (as in no ssm parameter exists).

When there is an extra value in local_key_vals than remote_key_vals. I've calculated the difference of the two sets and updated the difference in parameter store (application.properties file)

Delete a value from SSM parameter store if local application.properties file doesn't have that key/value anymore.

I need to handle a condition wherein the size of both sets is the same, a key in local application.properties file has an updated name and remote ssm needs to be updated with this name.

E.g.: Key set for local student/application.properties: set(['APPLICATION_NAME_TEST', 'VERSION', 'S3_BUCKET'])

Key set for SSM parameter store (student/application.properties): set(['APPLICATION_NAME', 'VERSION', 'S3_BUCKET'])

How can I update APPLICATION_NAME key in SSM parameter store to APPLICATION_NAME_TEST key(present in local file)?

答:
This solution worked for me.</p>

```<code>local_key_set = set(['APPLICATION_NAME_TEST', 'VERSION']);
remote_key_set= set(['APPLICATION_NAME', 'VERSION']);

local_key_list = list(local_key_set);
remote_key_list= list(local_key_set);

for i in range(0,len(local_key_list)):
    if local_key_list[i] != remote_key_list[i]:
        remote_key_list[i] = local_key_list[i]

remote_key_set = set(remote_key_list);
</code>```

Body:
I am writing a python script to create/update/delete values in AWS SSM parameter store.

My current logic is:

def lambda_handler(event, context):
    logger.info(event)#removing tab
    files = get_local_files() #set of all application.properties files
    count = 0
    for file in files: #iterate in each application.properties file
        remote_key_vals = get_ssm_paramstore_values(file) #remote_key_vals is a set of keys from ssm
        local_key_vals = read_ssm_local_file(file) #local_key_vals is a set of keys from local file
        if(len(remote_key_vals)==0):
            create_ssm_paramstore(file)
            count=count+1
        elif(local_key_vals>remote_key_vals):
            diff = local_key_vals-remote_key_vals
            if(len(diff)>0):
                update_ssm_paramstore(file, diff)
                count=count+1
        elif(remote_key_vals>local_key_vals):
            diff=remote_key_vals - local_key_vals
            if(len(diff)>0):
                delete_ssm_paramstore(file, diff)
                count = count+1
        else:
            logger.info(file+' already exist')
        logger.info(local_key_vals)
    try:
        req = requests.put(event['ResponseURL'],
                          data=getResponse(event, context,
                                            responseStatus))
        if req.status_code != 200:
            logger.info(req.text)
            raise Exception('Received non 200 response while sending response to CFN.'
                            )
    except requests.exceptions.RequestException, e:
        logger.info(e)
        raise
    return

This code works for 3 conditions only:

When the SSM parameter store is empty, the local application.properties file will get created/loaded if the length of the remote_key_vals set is 0 (as in no ssm parameter exists).

When there is an extra value in local_key_vals than remote_key_vals. I've calculated the difference of the two sets and updated the difference in parameter store (application.properties file)

Delete a value from SSM parameter store if local application.properties file doesn't have that key/value anymore.

I need to handle a condition wherein the size of both sets is the same, a key in local application.properties file has an updated name and remote ssm needs to be updated with this name.

E.g.: Key set for local student/application.properties: set(['APPLICATION_NAME_TEST', 'VERSION', 'S3_BUCKET'])

Key set for SSM parameter store (student/application.properties): set(['APPLICATION_NAME', 'VERSION', 'S3_BUCKET'])

How can I update APPLICATION_NAME key in SSM parameter store to APPLICATION_NAME_TEST key(present in local file)?

Body:
This solution worked for me.

local_key_set = set(['APPLICATION_NAME_TEST', 'VERSION']);
remote_key_set= set(['APPLICATION_NAME', 'VERSION']);

local_key_list = list(local_key_set);
remote_key_list= list(local_key_set);

for i in range(0,len(local_key_list)):
    if local_key_list[i] != remote_key_list[i]:
        remote_key_list[i] = local_key_list[i]

remote_key_set = set(remote_key_list);


问:
SqlTableDependency Permission Issues
I am trying to use the SqlTableDependency class  in my C# .Net application and I am unable to grant myself the required database permissions needed. Specifically, I need permissions:

ALTER

CONTROL

CREATE CONTRACT

CREATE MESSAGE TYPE

CREATE PROCEDURE

CREATE QUEUE

CREATE SERVICE

EXECUTE

SELECT

SUBSCRIBE QUERY NOTIFICATIONS

VIEW DATABASE STATE

VIEW DEFINITION

CONNECT

The error message states:

"An unhandled exception of type
  'TableDependency.SqlClient.Exceptions.UserWithNoPermissionException'
  occurred in TableDependency.SqlClient.dll. Additional information:
  User with no CREATE MESSAGE TYPE permission"

I have tried granting myself the permission using this query:

```<code>GRANT CREATE MESSAGE TYPE TO dbo
</code>```

but I get this error:

"Cannot grant, deny, or revoke permissions to sa, dbo, entity owner,
  information_schema, sys, or yourself."

I have confirmed that dbo is the owner of my database.

I am running Sql Server 2008 R2.

How can I grant myself permissions to my server?

答:
Make sure to do this:

Enable broker

```<code>ALTER DATABASE Your_db_name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
Go
</code>```

Add to db_owner

```<code>ALTER ROLE db_owner ADD MEMBER Your_user_db_name
GO
</code>```

Set authorization

```<code>ALTER AUTHORIZATION ON DATABASE::Your_db_name TO Your_user_db_name;
</code>```

I hope this help.

Title: SqlTableDependency Permission Issues

Body:
I am trying to use the SqlTableDependency class  in my C# .Net application and I am unable to grant myself the required database permissions needed. Specifically, I need permissions:

ALTER

CONTROL

CREATE CONTRACT

CREATE MESSAGE TYPE

CREATE PROCEDURE

CREATE QUEUE

CREATE SERVICE

EXECUTE

SELECT

SUBSCRIBE QUERY NOTIFICATIONS

VIEW DATABASE STATE

VIEW DEFINITION

CONNECT

The error message states:

"An unhandled exception of type
  'TableDependency.SqlClient.Exceptions.UserWithNoPermissionException'
  occurred in TableDependency.SqlClient.dll. Additional information:
  User with no CREATE MESSAGE TYPE permission"

I have tried granting myself the permission using this query:

GRANT CREATE MESSAGE TYPE TO dbo

but I get this error:

"Cannot grant, deny, or revoke permissions to sa, dbo, entity owner,
  information_schema, sys, or yourself."

I have confirmed that dbo is the owner of my database.

I am running Sql Server 2008 R2.

How can I grant myself permissions to my server?

Body:
Make sure to do this:

Enable broker

ALTER DATABASE Your_db_name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
Go

Add to db_owner

ALTER ROLE db_owner ADD MEMBER Your_user_db_name
GO

Set authorization

ALTER AUTHORIZATION ON DATABASE::Your_db_name TO Your_user_db_name;

I hope this help.


问:
Replacing elements in numpy array
```<code>import numpy as np

a = np.array([0.75, 0.5, 0.21])
one_list = [1] * 3
L_vec = np.diag(one_list)
L_vec[1,0] = a[0]
print(L_vec)
</code>```

Expected Result:

```<code>[[1,0,0],[0.75,1,0],[0,0,1]]
</code>```

Actual Result:

```<code>[[1 0 0]
 [0 1 0]
 [0 0 1]]
</code>```

this is the result I got. I have no idea why.

答:
By default dtype for np.diag is int

convert it into float so your float values from array a can replace older value

L_vec = L_vec.astype(float)

Use below code

```<code>a = np.array([0.75, 0.5, 0.21])
one_list = [1]*3
L_vec = np.diag(one_list)
L_vec = L_vec.astype(float)

L_vec[1,0] = a[0]
print(L_vec)
</code>```

Output:

```<code>[[1.   0.   0.  ]
 [0.75 1.   0.  ]
 [0.   0.   1.  ]]
</code>```

You can check datatype using print(L_vec.dtype)

Title: Replacing elements in numpy array

Body:
import numpy as np

a = np.array([0.75, 0.5, 0.21])
one_list = [1] * 3
L_vec = np.diag(one_list)
L_vec[1,0] = a[0]
print(L_vec)

Expected Result:

[[1,0,0],[0.75,1,0],[0,0,1]]

Actual Result:

[[1 0 0]
 [0 1 0]
 [0 0 1]]

this is the result I got. I have no idea why.

Body:
By default dtype for np.diag is int

convert it into float so your float values from array a can replace older value

L_vec = L_vec.astype(float)

Use below code

a = np.array([0.75, 0.5, 0.21])
one_list = [1]*3
L_vec = np.diag(one_list)
L_vec = L_vec.astype(float)

L_vec[1,0] = a[0]
print(L_vec)

Output:

[[1.   0.   0.  ]
 [0.75 1.   0.  ]
 [0.   0.   1.  ]]

You can check datatype using print(L_vec.dtype)