问:
Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences is giving weird output, list([2]) instead of [[2]]
Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences is giving weird output for Training Labels as shown below:

```<code>(training_label_list[0:10]) = [list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1])]
</code>```

but is printing Normal Array for the Validation Labels,

```<code>(validation_label_list[0:10]) = [[16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]]
</code>```

In other words, type(training_label_list[0]) =  <class 'list'> but

```<code>type(validation_label_list[0]) =  <class 'numpy.ndarray'>
</code>```

Consequently, while Training the Model using Keras Model.fit, it is resulting in the below Error,

```<code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
</code>```

This is the Link of the Google Colab, to reproduce the error easily.

Complete Code to reproduce the Error is given below:

```<code>!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = np.array(label_tokenizer.texts_to_sequences(T_L))

validation_label_list = np.array(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))
</code>```

I will be Grateful if someone can suggest me how can I get both Training Labels and Validation Labels in same Format, as I have spent so much time on it.

答:
Replacing np.array with np.hstack as mentioned in this Stack Overflow Answer has fixed that problem for me.

Now, the Correct Output is

```<code>(training_label_seq[0:10]) = [1 1 1 1 1 1 1 1 1 1]
(validation_label_seq[0:10]) = [16 16 16 16 16 16 16 16 16 16]
type(training_label_list[0]) =  <class 'numpy.int64'>
type(validation_label_seq[0]) =  <class 'numpy.int64'>
</code>```

Link of the working code is in this Google Colab.

Mentioned below is the working code (just in case if the above link doesn't work):

```<code>!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = np.hstack(label_tokenizer.texts_to_sequences(T_L))

validation_label_list = np.hstack(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))
</code>```

Body:
Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences is giving weird output for Training Labels as shown below:

(training_label_list[0:10]) = [list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1])]

but is printing Normal Array for the Validation Labels,

(validation_label_list[0:10]) = [[16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]]

In other words, type(training_label_list[0]) =  <class 'list'> but

type(validation_label_list[0]) =  <class 'numpy.ndarray'>

Consequently, while Training the Model using Keras Model.fit, it is resulting in the below Error,

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

This is the Link of the Google Colab, to reproduce the error easily.

Complete Code to reproduce the Error is given below:

!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = np.array(label_tokenizer.texts_to_sequences(T_L))

validation_label_list = np.array(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))

I will be Grateful if someone can suggest me how can I get both Training Labels and Validation Labels in same Format, as I have spent so much time on it.

Body:
Replacing np.array with np.hstack as mentioned in this Stack Overflow Answer has fixed that problem for me.

Now, the Correct Output is

(training_label_seq[0:10]) = [1 1 1 1 1 1 1 1 1 1]
(validation_label_seq[0:10]) = [16 16 16 16 16 16 16 16 16 16]
type(training_label_list[0]) =  <class 'numpy.int64'>
type(validation_label_seq[0]) =  <class 'numpy.int64'>

Link of the working code is in this Google Colab.

Mentioned below is the working code (just in case if the above link doesn't work):

!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = np.hstack(label_tokenizer.texts_to_sequences(T_L))

validation_label_list = np.hstack(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))


来源: stackexchange

问:
Jpa Repository save Inferred type 'S' for type parameter 'S' is not within its bound
I have entity user

```<code>@Entity
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String username;

    private String password;

}
</code>```

UserRepository

```<code>public interface UserRepository extends JpaRepository<UserRepository, Long> {
    User findByUsername(String username);
}
</code>```

Controller

```<code>@RestController
@RequestMapping("/user")
public class UserController {

    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/sign-up")
    public void signUp(@RequestBody User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }
}
</code>```

In class UserController in signUp method userRepository.save(user) throw error     Inferred type 'S' for type parameter 'S' is not within its bound; should implement 'Repository.UserRepository

答:
Reason: Teacher Liao's spring boot uses 1.4.1.RELEASE, and the new version is generally 2.0 or higher.
Solution: Replace the findOne method</p>

```<code>return repo.findById(id).orElse(null);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have entity user

@Entity
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String username;

    private String password;

}

UserRepository

public interface UserRepository extends JpaRepository<UserRepository, Long> {
    User findByUsername(String username);
}

Controller

@RestController
@RequestMapping("/user")
public class UserController {

    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/sign-up")
    public void signUp(@RequestBody User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }
}

In class UserController in signUp method userRepository.save(user) throw error     Inferred type 'S' for type parameter 'S' is not within its bound; should implement 'Repository.UserRepository

Body:
Reason: Teacher Liao's spring boot uses 1.4.1.RELEASE, and the new version is generally 2.0 or higher.
Solution: Replace the findOne method

return repo.findById(id).orElse(null);


问:
BizTalk hosts delay when used for the first time
Is a delay the first time the BizTalk hosts are used?

Is there a way to ensure that they are always "kept alive" and ready for any first requests that come in?

答:
Not the BizTalk host as such, but yes, there can be a delay the first time a web service or Orchestration is called to load a the DLLs needed.

If we want to keep it warm, for a web service you can set up a schedule adapter or scheduled task to call the web service to keep it alive.

To keep on Orchestration loaded it memory, the was a method of pinning it so it wasn't removed, by settings in the bts config file.  The other method would be to have some sort of keep alive message going to the Orchestration, which would then just discard that message.


问:
npm cannot install pm2 or nodemon in Windows 10
I try to install a nodemon for the auto-restart nodejs server when my file has been changed. But I got two warnings so, I try to install other npm packages like forever or pm2, but I still get the same warning.
Here is my warning capture:

答:
Windows 10 has execution policy built in that restrict any script execution by default. So, you have to set the policy first.

In Powershell (Admin rights), first look at the ExecutionPolicy with command

Get-ExecutionPolicy -List

'Undefined' policy means scripts like pm2 will be restricted. To enable it, run command

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser

Then, try run pm2.


问:
Change Javascript BLOB encoding to ANSI instead of UTF-8
I was wondering if it is possible to save a simple txt file with Javascript and BLOB with the ANSI encoding.

At this moment I have a script that creates a txt file with CRLF line endings, but with a UTF-8 encoding.

Is it possible to save it with the ANSI encoding? I need this to import the txt file on a 'old' windows program that needs ANSI instead of UTF-8.

This is the example I used:
https://jsfiddle.net/UselessCode/qm5AG/

```<code>let textFile = null;

function makeTextFile () {
    let text = `Some text with nice line endings\nand special characters like é and ü.`;

    const data = new Blob([text], {
        type: "text/plain",
        endings: "native"
    });

    if (textFile !== null) {
        window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
}
</code>```

答:
There used to be an option using the TextEncoder API to encode from USVStrings to arbitrary encodings, but this has been removed from specs and browsers.

You'd need to use a library in order to perform the conversion. Here, I'll use inexorabletash/text-encoding:

(async()=> {
const text = `Some text with nice line endings\nand special characters like é and ü.`;
const encoding = 'windows-1252'; // a.k.a ANSI

const encoder = new TextEncoder(encoding, {
  NONSTANDARD_allowLegacyEncoding: true
});
const data = encoder.encode(text); // `data` is an Uint8Array
const encoded_as_ANSI = new Blob([data]);

// for demo only
const encoded_as_UTF8 = new Blob([text]);

const ANSI_read = await readAsText(encoded_as_ANSI, encoding);
const UTF8_read = await readAsText(encoded_as_UTF8, encoding);

console.log("(ANSI)", ANSI_read);
console.log("(UTF8)", UTF8_read);
})();

function readAsText(blob, encoding) {
  return new Promise(res => {
    const reader = new FileReader();
    reader.onload = e => res(reader.result);
    reader.readAsText(blob, encoding);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>window.TextEncoder = null;// force installation of the polyfill</script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding-indexes.js"></script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding.js"></script></code>```

However going this route, we loose the endings option, since this applies only to string blobParts.

So one way would be to first create an utf-8 Blob, with the endings option, then convert this UTF-8 blob to ANSI:

(async () => {
  const text = `Some text with nice line endings\nand special characters like é and ü.`;
  const encoding = 'windows-1252'; // a.k.a ANSI

  const utf8_blob = new Blob( [text], { endings: "native" } );
  const utf_8_txt = await utf8_blob.text();

  const encoder = new TextEncoder(encoding, {
    NONSTANDARD_allowLegacyEncoding: true
  });
  const data = encoder.encode(utf_8_txt); // now `data` is an Uint8Array
  const encoded_as_ANSI = new Blob([data]);

  const read_as_ANSI = await readAsText(encoded_as_ANSI, encoding)
  console.log(read_as_ANSI);
})();

function readAsText(blob, encoding) {
  return new Promise(res => {
    const reader = new FileReader();
    reader.onload = e => res(reader.result);
    reader.readAsText(blob, encoding);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>window.TextEncoder = null;// force installation of the polyfill</script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding-indexes.js"></script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding.js"></script></code>```

Body:
I was wondering if it is possible to save a simple txt file with Javascript and BLOB with the ANSI encoding.

At this moment I have a script that creates a txt file with CRLF line endings, but with a UTF-8 encoding.

Is it possible to save it with the ANSI encoding? I need this to import the txt file on a 'old' windows program that needs ANSI instead of UTF-8.

This is the example I used:
https://jsfiddle.net/UselessCode/qm5AG/

let textFile = null;

function makeTextFile () {
    let text = `Some text with nice line endings\nand special characters like é and ü.`;

    const data = new Blob([text], {
        type: "text/plain",
        endings: "native"
    });

    if (textFile !== null) {
        window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
}

Body:
There used to be an option using the TextEncoder API to encode from USVStrings to arbitrary encodings, but this has been removed from specs and browsers.

You'd need to use a library in order to perform the conversion. Here, I'll use inexorabletash/text-encoding:

(async()=> {
const text = `Some text with nice line endings\nand special characters like é and ü.`;
const encoding = 'windows-1252'; // a.k.a ANSI

const encoder = new TextEncoder(encoding, {
  NONSTANDARD_allowLegacyEncoding: true
});
const data = encoder.encode(text); // `data` is an Uint8Array
const encoded_as_ANSI = new Blob([data]);

// for demo only
const encoded_as_UTF8 = new Blob([text]);

const ANSI_read = await readAsText(encoded_as_ANSI, encoding);
const UTF8_read = await readAsText(encoded_as_UTF8, encoding);

console.log("(ANSI)", ANSI_read);
console.log("(UTF8)", UTF8_read);
})();

function readAsText(blob, encoding) {
  return new Promise(res => {
    const reader = new FileReader();
    reader.onload = e => res(reader.result);
    reader.readAsText(blob, encoding);
  });
}

<script>window.TextEncoder = null;// force installation of the polyfill</script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding-indexes.js"></script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding.js"></script>

However going this route, we loose the endings option, since this applies only to string blobParts.

So one way would be to first create an utf-8 Blob, with the endings option, then convert this UTF-8 blob to ANSI:

(async () => {
  const text = `Some text with nice line endings\nand special characters like é and ü.`;
  const encoding = 'windows-1252'; // a.k.a ANSI

  const utf8_blob = new Blob( [text], { endings: "native" } );
  const utf_8_txt = await utf8_blob.text();

  const encoder = new TextEncoder(encoding, {
    NONSTANDARD_allowLegacyEncoding: true
  });
  const data = encoder.encode(utf_8_txt); // now `data` is an Uint8Array
  const encoded_as_ANSI = new Blob([data]);

  const read_as_ANSI = await readAsText(encoded_as_ANSI, encoding)
  console.log(read_as_ANSI);
})();

function readAsText(blob, encoding) {
  return new Promise(res => {
    const reader = new FileReader();
    reader.onload = e => res(reader.result);
    reader.readAsText(blob, encoding);
  });
}

<script>window.TextEncoder = null;// force installation of the polyfill</script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding-indexes.js"></script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding.js"></script>


问:
PHP removing a certain string in a string once
I recently have played around with the use of preg_replace in PHP to specifically remove a string once.

However I have a list of numbers (345, 346 and wanting to remove ", 346" for example) and I have kept on running into the same problem how it removes the whole string and leaves it empty.

Desired results are

```<code>345, 346
Removing ", 346"
Turns to
345
And also
345, 346, 347 removing ", 346"
Turns to
345, 347
</code>```

Code:

```<code>$oldpost = ", ".$_GET['id'];

$newposts = preg_replace($oldpost, "", $row['posts']);

</code>```

I tried this previously and haven't found anything that seems to do a better job.

答:
In your code, you have

```<code>$newposts = preg_replace($oldpost, "", $row['posts']);
</code>```

where you are actually giving the entire string itself to be replaced. Hence, it gives you an empty string because your 2nd parameter is an empty string.

You can match the exact 346(if it's present) with an optional matching of a , and replace them with empty string. So your regex would look like

```<code>/(,?\s*346(\s|,|\b))?/
</code>```

Snippet:

```<code><?php

$oldpost = "345,346,347";
$newposts = preg_replace("/(,?\s*346(\s|,|\b))?/", "$2", $oldpost);
echo $newposts,PHP_EOL;
</code>```

Demo: https://3v4l.org/MeSeK

Note that above approach works fine, but the best way to solve this problem is to explode the comma separated string and unset the location in the array where have the 346 and implode it back again.

Snippet:

```<code><?php

$oldpost = "345,346,347";
$posts = explode(",",$oldpost);

$index = array_search(346,$posts);

if($index !== false){
    unset($posts[$index]);
}

$new_post = implode(",",$posts);

echo $new_post;
</code>```

Demo: https://3v4l.org/qvSEN

Note that if there are multiple occurrences of 346, you can use a simple foreach to unset them.

Body:
I recently have played around with the use of preg_replace in PHP to specifically remove a string once.

However I have a list of numbers (345, 346 and wanting to remove ", 346" for example) and I have kept on running into the same problem how it removes the whole string and leaves it empty.

Desired results are

345, 346
Removing ", 346"
Turns to
345
And also
345, 346, 347 removing ", 346"
Turns to
345, 347

Code:

$oldpost = ", ".$_GET['id'];

$newposts = preg_replace($oldpost, "", $row['posts']);

I tried this previously and haven't found anything that seems to do a better job.

Body:
In your code, you have

$newposts = preg_replace($oldpost, "", $row['posts']);

where you are actually giving the entire string itself to be replaced. Hence, it gives you an empty string because your 2nd parameter is an empty string.

You can match the exact 346(if it's present) with an optional matching of a , and replace them with empty string. So your regex would look like

/(,?\s*346(\s|,|\b))?/

Snippet:

<?php

$oldpost = "345,346,347";
$newposts = preg_replace("/(,?\s*346(\s|,|\b))?/", "$2", $oldpost);
echo $newposts,PHP_EOL;

Demo: https://3v4l.org/MeSeK

Note that above approach works fine, but the best way to solve this problem is to explode the comma separated string and unset the location in the array where have the 346 and implode it back again.

Snippet:

<?php

$oldpost = "345,346,347";
$posts = explode(",",$oldpost);

$index = array_search(346,$posts);

if($index !== false){
    unset($posts[$index]);
}

$new_post = implode(",",$posts);

echo $new_post;

Demo: https://3v4l.org/qvSEN

Note that if there are multiple occurrences of 346, you can use a simple foreach to unset them.


问:
Avoid dummy text on an AJAX search (jQuery)
I'm using this code for an AJAX-based search in the event "the user stops writing". Now I want to detect when the user is writing  a fast succesion of characters with no sense, something like type 'edkpakdpakffnhnsc' dummy string.

```<code>$(document).ready(function() {

        var inputTimer;
        var lol = $('input#lol');
        var hola = $('#hola');

        hola.hide();

        $('#lol').keyup( function(){

            if(lol.val().length >= 3){

                clearTimeout(inputTimer);
                inputTimer = setTimeout(ajaxFunction, 500);

                function ajaxFunction(){
                    hola.show();
                }

            } else {
                hola.hide();
            }
            });

    });
</code>```

How I have to approach this problem???

Thanks

答:
Ok, assuming you already have a tree of legal words structured as:

```<code>var wordtree={
  'a': {
    'isWord': true,                   // 'a' is a word
    '_': {
      'r': {
        'isWord': false,              // 'ar' is not a word
        '_': {
          'e': {
            'isWord': true            // 'are' is a word
          },
          't': {
            'isWord': true            // 'art' is a word
          }
        }
      }
    }
  },
  'b': {
    'isWord': false,                  // 'b' is not a word
      ...
    }
  }
};
</code>```

you can check the validity of words as they are typed with:

```<code>function check(str) {
  var wordtree={ ... }, // as described above
      words=str.split(/\s+|[[:punct:]]+/);

  for(var i=0,len=words.length;i<len;i++) { // for each word in str
    var start=wordtree, word=words[i];

    for(var j=0,jlen=word.length,last=jlen-1;j<jlen;j++) { // for each char in word
      var ch=word.charAt(j),
          current=start[ch],
          type=current ? typeof current : undefined;

      if( !current ||
          (j < last && type !== 'object') ||
          (j===last && !current['isWord'])
      ) {
        console.log('word('+word+') fails');
        return false;
      }
      start=current['_'];
    }
    console.log('word('+word+') succeeds');
  }

  return true;
}
</code>```

This should perform well in realtime, though for any conceivable language, wordtree will be enormous.

ContentLicense: CC BY-SA 3.0

Body:
I'm using this code for an AJAX-based search in the event "the user stops writing". Now I want to detect when the user is writing  a fast succesion of characters with no sense, something like type 'edkpakdpakffnhnsc' dummy string.

$(document).ready(function() {

        var inputTimer;
        var lol = $('input#lol');
        var hola = $('#hola');

        hola.hide();

        $('#lol').keyup( function(){

            if(lol.val().length >= 3){

                clearTimeout(inputTimer);
                inputTimer = setTimeout(ajaxFunction, 500);

                function ajaxFunction(){
                    hola.show();
                }

            } else {
                hola.hide();
            }
            });

    });

How I have to approach this problem???

Thanks

Body:
Ok, assuming you already have a tree of legal words structured as:

var wordtree={
  'a': {
    'isWord': true,                   // 'a' is a word
    '_': {
      'r': {
        'isWord': false,              // 'ar' is not a word
        '_': {
          'e': {
            'isWord': true            // 'are' is a word
          },
          't': {
            'isWord': true            // 'art' is a word
          }
        }
      }
    }
  },
  'b': {
    'isWord': false,                  // 'b' is not a word
      ...
    }
  }
};

you can check the validity of words as they are typed with:

function check(str) {
  var wordtree={ ... }, // as described above
      words=str.split(/\s+|[[:punct:]]+/);

  for(var i=0,len=words.length;i<len;i++) { // for each word in str
    var start=wordtree, word=words[i];

    for(var j=0,jlen=word.length,last=jlen-1;j<jlen;j++) { // for each char in word
      var ch=word.charAt(j),
          current=start[ch],
          type=current ? typeof current : undefined;

      if( !current ||
          (j < last && type !== 'object') ||
          (j===last && !current['isWord'])
      ) {
        console.log('word('+word+') fails');
        return false;
      }
      start=current['_'];
    }
    console.log('word('+word+') succeeds');
  }

  return true;
}

This should perform well in realtime, though for any conceivable language, wordtree will be enormous.


问:
Get IP address of visitors using Flask for Python
I'm making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).

I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this? Surely there is a way to do it with Python?

答:
If You are using Gunicorn and Nginx environment then the following code template works for you.</p>

```<code>addr_ip4 = request.remote_addr
</code>```

Body:
If You are using Gunicorn and Nginx environment then the following code template works for you.

addr_ip4 = request.remote_addr


问:
How to share a WebSocket connection between different html pages?
I want to use the WebSockets for a basic Java Spring Web project. I'm new to this topic and have been researching it for a while now. Here's a demo I ran successfully: http://zetcode.com/spring/websocket/

What I want to achieve is, have events done on different HTML pages trigger changes to particular another one. Do I need to create a WebSocket instance on all pages and send data for given event and have the .onmessage functionality in the one page, where updates to HTML will happen (with help from JavaScript)? Or do I need to share the WebSocket with the JS sessionStorage?

Here's the dependencies I'm using so far:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

```

答:
To share one WebSocket connection between different html pages, you need to use SharedWorker.

I have researched a similar topic and made a simple example by chance so I'd like to make brief explanation about it and show simple example source code.

Solutions to what you want to achieve

From your question

What I want to achieve is, have events done on
    different HTML pages trigger changes to particular another one.

WebSocket instance on all pages

SharedWorker

It can be achieved by creating WebSocket connection on all pages(solution 1).

When you want to reduce the number of WebSocket connection per each client(to reduce the server load), SharedWorker would be a better choice(solution 2).

I think you have already understood solution 1 and are looking for a better solution so you ask:

How to share a WebSocket connection between different html pages?

So I'd like to write mainly about SharedWorker here.

[NOTE]
You can't share WebSocket connection by using sessionStorage and localStorage because they don't store javascript object itself but handle string key/value pairs(
Storing Objects in HTML5 localStorage).

About Shared Worker

From SharedWorker -
  MDN,

a specific kind of worker that can be accessed from several browsing
    contexts, such as several windows, iframes or even workers.

Worker(Web Worker) is javascript running in the background.
You can use WebSocket in worker.

When you create the connection in SharedWorker, you can use the same(shared) connection in multiple html pages via the worker.

Shared Worker Simple Example

We have 2 different html pages:

http://localhost:8080/pageA.html

http://localhost:8080/pageB.html

They have a button named message.
When the button is clicked:

They send a message to SharedWorker and the worker sends the message to the server using shared WebSocket connection.

The server responds to the client's message and send a message to the worker.

The 2 html pages recieve the server's message from the worker.

[server side - WebSocketHandler using Spring]

```<code>/**
 * End point '/hellows'
 */
public class MyWebsocketHnadler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("Message from client : " + message.getPayload());
        session.sendMessage(new TextMessage("Server responds to '" + message.getPayload() + "'"));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("Connection is opened.");
        session.sendMessage(new TextMessage("Open"));
    }
}
</code>```

[client side - pageA.html & pageB.html]

```<code><!-- For simplicity I omit DOCTYPE, html tag, head tag and body tag here -->
<button type="button" id="msg-btn"/>message</button>
<script src="main.js"></script>
</code>```

[client side - main.js]

```<code>const worker = new SharedWorker("worker.js");
worker.port.start();
// post message in order to make worker to push this page's port to port array.
worker.port.postMessage({ id: location.href });
worker.port.addEventListener("message", e => console.log(e.data.msg));

document.querySelector("#msg-btn").addEventListener("click", () => {
  worker.port.postMessage({ msg: "I am " + location.href });
});
</code>```

[client side - worker.js]

```<code>const ports = {};
const ws = new WebSocket("ws://localhost:8080/hellows");

ws.addEventListener("message", e => {
  Object.values(ports).forEach(port => {
    port.postMessage({ msg: "From sever: " + e.data });
  });
});

addEventListener("connect", e => {
  const port = e.ports[0];
  port.start();
  port.addEventListener("message", e => {
    // if you open same html page at multiple windows,
    // only newest window can send and recieve a message.
    if (e.data.id) ports[e.data.id] = port;
    if (e.data.msg) ws.send(e.data.msg);
  });
});
</code>```

When we access pageA and pageB and then click message buttons one after the other, we get the result like this:

[server side - console]

```<code>Connection is opened.
Message from client : I am http://localhost:8080/pageA.html
Message from client : I am http://localhost:8080/pageB.html
Message from client : I am http://localhost:8080/pageA.html
</code>```

[client side - pageA.html's console]

```<code>From sever: Open
From sever: Server responds to 'I am http://localhost:8080/pageA.html'
From sever: Server responds to 'I am http://localhost:8080/pageB.html'
From sever: Server responds to 'I am http://localhost:8080/pageA.html'
</code>```

[client side - pageB.html's console]

```<code>From sever: Server responds to 'I am http://localhost:8080/pageA.html'
From sever: Server responds to 'I am http://localhost:8080/pageB.html'
From sever: Server responds to 'I am http://localhost:8080/pageA.html'
</code>```

Consideration

What browsers do you have to support?

Some browsers don't support Shared Worker(Can I use ...).

See Also:

Web Workers API - MDN

SharedWorker - MDN

Scaling WebSocket Connections using Shared Workers - Ayush Gupta

Body:
To share one WebSocket connection between different html pages, you need to use SharedWorker.

I have researched a similar topic and made a simple example by chance so I'd like to make brief explanation about it and show simple example source code.

Solutions to what you want to achieve

From your question

What I want to achieve is, have events done on
    different HTML pages trigger changes to particular another one.

WebSocket instance on all pages

SharedWorker

It can be achieved by creating WebSocket connection on all pages(solution 1).

When you want to reduce the number of WebSocket connection per each client(to reduce the server load), SharedWorker would be a better choice(solution 2).

I think you have already understood solution 1 and are looking for a better solution so you ask:

How to share a WebSocket connection between different html pages?

So I'd like to write mainly about SharedWorker here.

[NOTE]
You can't share WebSocket connection by using sessionStorage and localStorage because they don't store javascript object itself but handle string key/value pairs(
Storing Objects in HTML5 localStorage).

About Shared Worker

From SharedWorker -
  MDN,

a specific kind of worker that can be accessed from several browsing
    contexts, such as several windows, iframes or even workers.

Worker(Web Worker) is javascript running in the background.
You can use WebSocket in worker.

When you create the connection in SharedWorker, you can use the same(shared) connection in multiple html pages via the worker.

Shared Worker Simple Example

We have 2 different html pages:

http://localhost:8080/pageA.html

http://localhost:8080/pageB.html

They have a button named message.
When the button is clicked:

They send a message to SharedWorker and the worker sends the message to the server using shared WebSocket connection.

The server responds to the client's message and send a message to the worker.

The 2 html pages recieve the server's message from the worker.

[server side - WebSocketHandler using Spring]

/**
 * End point '/hellows'
 */
public class MyWebsocketHnadler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("Message from client : " + message.getPayload());
        session.sendMessage(new TextMessage("Server responds to '" + message.getPayload() + "'"));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("Connection is opened.");
        session.sendMessage(new TextMessage("Open"));
    }
}

[client side - pageA.html & pageB.html]

<!-- For simplicity I omit DOCTYPE, html tag, head tag and body tag here -->
<button type="button" id="msg-btn"/>message</button>
<script src="main.js"></script>

[client side - main.js]

const worker = new SharedWorker("worker.js");
worker.port.start();
// post message in order to make worker to push this page's port to port array.
worker.port.postMessage({ id: location.href });
worker.port.addEventListener("message", e => console.log(e.data.msg));

document.querySelector("#msg-btn").addEventListener("click", () => {
  worker.port.postMessage({ msg: "I am " + location.href });
});

[client side - worker.js]

const ports = {};
const ws = new WebSocket("ws://localhost:8080/hellows");

ws.addEventListener("message", e => {
  Object.values(ports).forEach(port => {
    port.postMessage({ msg: "From sever: " + e.data });
  });
});

addEventListener("connect", e => {
  const port = e.ports[0];
  port.start();
  port.addEventListener("message", e => {
    // if you open same html page at multiple windows,
    // only newest window can send and recieve a message.
    if (e.data.id) ports[e.data.id] = port;
    if (e.data.msg) ws.send(e.data.msg);
  });
});

When we access pageA and pageB and then click message buttons one after the other, we get the result like this:

[server side - console]

Connection is opened.
Message from client : I am http://localhost:8080/pageA.html
Message from client : I am http://localhost:8080/pageB.html
Message from client : I am http://localhost:8080/pageA.html

[client side - pageA.html's console]

From sever: Open
From sever: Server responds to 'I am http://localhost:8080/pageA.html'
From sever: Server responds to 'I am http://localhost:8080/pageB.html'
From sever: Server responds to 'I am http://localhost:8080/pageA.html'

[client side - pageB.html's console]

From sever: Server responds to 'I am http://localhost:8080/pageA.html'
From sever: Server responds to 'I am http://localhost:8080/pageB.html'
From sever: Server responds to 'I am http://localhost:8080/pageA.html'

Consideration

What browsers do you have to support?

Some browsers don't support Shared Worker(Can I use ...).

See Also:

Web Workers API - MDN

SharedWorker - MDN

Scaling WebSocket Connections using Shared Workers - Ayush Gupta


问:
ValueError: Unable to coerce to Series, length must be 1: given n
I have been trying to use RF regression from scikit-learn, but I’m getting an error with my standard (from docs and tutorials) model. Here is the code:

```<code>import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor

db = pd.read_excel('/home/artyom/myprojects//valuevo/field2019/report/segs_inventar_dataframe/excel_var/invcents.xlsx')

age = df[['AGE_1', 'AGE_2', 'AGE_3', 'AGE_4', 'AGE_5']]

hight = df [['HIGHT_','HIGHT_1', 'HIGHT_2', 'HIGHT_3', 'HIGHT_4', 'HIGHT_5']]

diam = df[['DIAM_', 'DIAM_1', 'DIAM_2', 'DIAM_3', 'DIAM_4', 'DIAM_5']]

za = df[['ZAPSYR_', 'ZAPSYR_1', 'ZAPSYR_2', 'ZAPSYR_3', 'ZAPSYR_4', 'ZAPSYR_5']]

tova = df[['TOVARN_', 'TOVARN_1', 'TOVARN_2', 'TOVARN_3', 'TOVARN_4', 'TOVARN_5']]

#df['average'] = df.mean(numeric_only=True, axis=1)

df['meanage'] = age.mean(numeric_only=True, axis=1)
df['meanhight'] = hight.mean(numeric_only=True, axis=1)
df['mediandiam'] = diam.mean(numeric_only=True, axis=1)
df['medianza'] = za.mean(numeric_only=True, axis=1)
df['mediantova'] = tova.mean(numeric_only=True, axis=1)

unite = df[['gapA_segA','gapP_segP', 'A_median', 'p_median', 'circ_media','fdi_median', 'pfd_median', 'p_a_median', 'gsci_media','meanhight']].dropna()

from sklearn.model_selection import train_test_split as ttsplit

df_copy = unite.copy()
trainXset = df_copy[['gapA_segA','gapP_segP', 'A_median', 'p_median', 'circ_media','fdi_median', 'pfd_median', 'p_a_median', 'gsci_media']]

trainYset = df_copy [['meanhight']]

trainXset_train, trainXset_test, trainYset_train, trainYset_test = ttsplit(trainXset, trainYset, test_size=0.3) # 70% training and 30% test

rf = RandomForestRegressor(n_estimators = 100, random_state = 40)
rf.fit(trainXset_train, trainYset_train)
predictions = rf.predict(trainXset_test)
errors = abs(predictions - trainYset_test)
mape = 100 * (errors / trainYset_test)
accuracy = 100 - np.mean(mape)
print('Accuracy:', round(accuracy, 2), '%.')
</code>```

But output doesn’t look ok:

```<code>---> 24 errors = abs(predictions - trainYset_test)
     25 # Calculate mean absolute percentage error (MAPE)
     26 mape = 100 * (errors / trainYset_test)
..... somemore track
ValueError: Unable to coerce to Series, length must be 1: given 780
</code>```

How can I fix it? 780 is the shape of trainYset_test. I’m not asking for a solution (i.e. write code for me), but for advice on why this error happened. I followed everything as in tutorials.

答:
by seeing in error it is cleared that, the array has to have the shape of one ,

so use reshape to make it in correct shape,

```<code>predictions=predictions.reshape(780,1)
</code>```

Body:
I have been trying to use RF regression from scikit-learn, but I’m getting an error with my standard (from docs and tutorials) model. Here is the code:

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor

db = pd.read_excel('/home/artyom/myprojects//valuevo/field2019/report/segs_inventar_dataframe/excel_var/invcents.xlsx')

age = df[['AGE_1', 'AGE_2', 'AGE_3', 'AGE_4', 'AGE_5']]

hight = df [['HIGHT_','HIGHT_1', 'HIGHT_2', 'HIGHT_3', 'HIGHT_4', 'HIGHT_5']]

diam = df[['DIAM_', 'DIAM_1', 'DIAM_2', 'DIAM_3', 'DIAM_4', 'DIAM_5']]

za = df[['ZAPSYR_', 'ZAPSYR_1', 'ZAPSYR_2', 'ZAPSYR_3', 'ZAPSYR_4', 'ZAPSYR_5']]

tova = df[['TOVARN_', 'TOVARN_1', 'TOVARN_2', 'TOVARN_3', 'TOVARN_4', 'TOVARN_5']]

#df['average'] = df.mean(numeric_only=True, axis=1)

df['meanage'] = age.mean(numeric_only=True, axis=1)
df['meanhight'] = hight.mean(numeric_only=True, axis=1)
df['mediandiam'] = diam.mean(numeric_only=True, axis=1)
df['medianza'] = za.mean(numeric_only=True, axis=1)
df['mediantova'] = tova.mean(numeric_only=True, axis=1)

unite = df[['gapA_segA','gapP_segP', 'A_median', 'p_median', 'circ_media','fdi_median', 'pfd_median', 'p_a_median', 'gsci_media','meanhight']].dropna()

from sklearn.model_selection import train_test_split as ttsplit

df_copy = unite.copy()
trainXset = df_copy[['gapA_segA','gapP_segP', 'A_median', 'p_median', 'circ_media','fdi_median', 'pfd_median', 'p_a_median', 'gsci_media']]

trainYset = df_copy [['meanhight']]

trainXset_train, trainXset_test, trainYset_train, trainYset_test = ttsplit(trainXset, trainYset, test_size=0.3) # 70% training and 30% test

rf = RandomForestRegressor(n_estimators = 100, random_state = 40)
rf.fit(trainXset_train, trainYset_train)
predictions = rf.predict(trainXset_test)
errors = abs(predictions - trainYset_test)
mape = 100 * (errors / trainYset_test)
accuracy = 100 - np.mean(mape)
print('Accuracy:', round(accuracy, 2), '%.')

But output doesn’t look ok:

---> 24 errors = abs(predictions - trainYset_test)
     25 # Calculate mean absolute percentage error (MAPE)
     26 mape = 100 * (errors / trainYset_test)
..... somemore track
ValueError: Unable to coerce to Series, length must be 1: given 780

How can I fix it? 780 is the shape of trainYset_test. I’m not asking for a solution (i.e. write code for me), but for advice on why this error happened. I followed everything as in tutorials.

Body:
by seeing in error it is cleared that, the array has to have the shape of one ,

so use reshape to make it in correct shape,

predictions=predictions.reshape(780,1)


问:
Building a multi input and multi output model: giving AttributeError: 'dict' object has no attribute 'shape'
I am newbie to deep learning and trying to build the multi input and multi output model using keras functional API in R and getting this error.

My code

build_model <- function() {
    ### motif module

    # motif module input
    motif_module_input <- layer_input(shape = ncol(x_train_motif_module), name = 'motif_module_input')

    motif_module <- motif_module_input %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dropout(rate = 0.5) %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dropout(rate = 0.5) %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dropout(rate = 0.5) %>%
        layer_dense(units = 4, activation = 'relu')

    motif_module_output <- motif_module %>%
        layer_dense(units = 2, activation = 'softmax', name = 'motif_module_output')

    #SVM_input <- layer_input(shape = c(2), name = 'SVM_input')

    ### DNA module
    # DNA module input
    DNA_module_input <- layer_input(shape = c(user_img_rows, user_img_cols), name = 'DNA_module_input')

    DNA_module <- DNA_module_input %>%
        layer_conv_1d(filters = 128, kernel_size = 7, activation = 'relu', input_shape = c(user_img_rows, user_img_cols)) %>%
        layer_max_pooling_1d(pool_size = 4, strides = 2) %>%
        layer_dropout(rate = 0.3) %>%

        layer_conv_1d(filters = 128, kernel_size = 5, activation = 'relu', input_shape = c(user_img_rows, user_img_cols)) %>%
        layer_max_pooling_1d(pool_size = 8, strides = 4) %>%
        layer_dropout(rate = 0.3) %>%

        layer_flatten() %>%
        layer_dense(units  = 128, activation  = 'relu')

    DNA_module_output <- DNA_module %>%
        layer_dense(units = 2, activation = 'softmax', name = 'DNA_module_output')

    main_output <- layer_concatenate(c(motif_module, DNA_module)) %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dense(units = 4, activation = 'relu') %>%
        layer_dense(units = 2, activation = 'softmax', name = 'main_output')

    model <- keras_model(
        inputs = c(motif_module_input, DNA_module_input),
        outputs = c(motif_module_output, DNA_module_output, main_output)
    )

    model %>% compile(
        loss = list(motif_module_output = 'binary_crossentropy', DNA_module_output = 'binary_crossentropy', main_output = 'binary_crossentropy'),
        loss_weights = list(motif_module_output = 0.5, DNA_module_output = 0.5, main_output = 1),
        optimizer = optimizer_adam(lr = 0.001, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-08, decay = 1e-06),
        metrics   = c('accuracy')
    )

    model

}

model <- build_model()
# training the model
# Display training progress by printing a single dot for each completed epoch.
print_dot_callback <- callback_lambda(
    on_epoch_end = function(epoch, logs) {
        if (epoch %% 80 == 0) cat("\n")
        cat(".")
    }
)

# The patience parameter is the amount of epochs to check for improvement.
early_stop <- callback_early_stopping(monitor = "val_loss", patience = 5, restore_best_weights = FALSE)

# model <- build_model()
history <- model %>% fit(
    x = list(motif_module_input = x_train_motif_module, DNA_module_input = x_train_DNA_module),
    y = list(motif_module_output = y_train_DNA_module, DNA_module_output = y_train_DNA_module, main_output = y_train_DNA_module),
    epochs = user_epochs,
    validation_split = user_validation_split,
    batch_size = user_batch_size,
    use_multiprocessing = TRUE,
    verbose = 2,
    callbacks = list(early_stop, print_dot_callback)
)
```

This results in error py_call_impl(callable, dots$args, dots$keywords) :
    AttributeError: 'dict' object has no attribute 'shape'

Can some one help me understand the error. Thank you.

答:
This error is resulting due to the input data format. One of my input data is data frame and when converted to matrix type it worked fine.

Hope it helps others.

Body:
I am newbie to deep learning and trying to build the multi input and multi output model using keras functional API in R and getting this error.

My code

build_model <- function() {
    ### motif module

    # motif module input
    motif_module_input <- layer_input(shape = ncol(x_train_motif_module), name = 'motif_module_input')

    motif_module <- motif_module_input %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dropout(rate = 0.5) %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dropout(rate = 0.5) %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dropout(rate = 0.5) %>%
        layer_dense(units = 4, activation = 'relu')

    motif_module_output <- motif_module %>%
        layer_dense(units = 2, activation = 'softmax', name = 'motif_module_output')

    #SVM_input <- layer_input(shape = c(2), name = 'SVM_input')

    ### DNA module
    # DNA module input
    DNA_module_input <- layer_input(shape = c(user_img_rows, user_img_cols), name = 'DNA_module_input')

    DNA_module <- DNA_module_input %>%
        layer_conv_1d(filters = 128, kernel_size = 7, activation = 'relu', input_shape = c(user_img_rows, user_img_cols)) %>%
        layer_max_pooling_1d(pool_size = 4, strides = 2) %>%
        layer_dropout(rate = 0.3) %>%

        layer_conv_1d(filters = 128, kernel_size = 5, activation = 'relu', input_shape = c(user_img_rows, user_img_cols)) %>%
        layer_max_pooling_1d(pool_size = 8, strides = 4) %>%
        layer_dropout(rate = 0.3) %>%

        layer_flatten() %>%
        layer_dense(units  = 128, activation  = 'relu')

    DNA_module_output <- DNA_module %>%
        layer_dense(units = 2, activation = 'softmax', name = 'DNA_module_output')

    main_output <- layer_concatenate(c(motif_module, DNA_module)) %>%
        layer_dense(units = 16, activation = 'relu') %>%
        layer_dense(units = 4, activation = 'relu') %>%
        layer_dense(units = 2, activation = 'softmax', name = 'main_output')

    model <- keras_model(
        inputs = c(motif_module_input, DNA_module_input),
        outputs = c(motif_module_output, DNA_module_output, main_output)
    )

    model %>% compile(
        loss = list(motif_module_output = 'binary_crossentropy', DNA_module_output = 'binary_crossentropy', main_output = 'binary_crossentropy'),
        loss_weights = list(motif_module_output = 0.5, DNA_module_output = 0.5, main_output = 1),
        optimizer = optimizer_adam(lr = 0.001, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-08, decay = 1e-06),
        metrics   = c('accuracy')
    )

    model

}

model <- build_model()
# training the model
# Display training progress by printing a single dot for each completed epoch.
print_dot_callback <- callback_lambda(
    on_epoch_end = function(epoch, logs) {
        if (epoch %% 80 == 0) cat("\n")
        cat(".")
    }
)

# The patience parameter is the amount of epochs to check for improvement.
early_stop <- callback_early_stopping(monitor = "val_loss", patience = 5, restore_best_weights = FALSE)

# model <- build_model()
history <- model %>% fit(
    x = list(motif_module_input = x_train_motif_module, DNA_module_input = x_train_DNA_module),
    y = list(motif_module_output = y_train_DNA_module, DNA_module_output = y_train_DNA_module, main_output = y_train_DNA_module),
    epochs = user_epochs,
    validation_split = user_validation_split,
    batch_size = user_batch_size,
    use_multiprocessing = TRUE,
    verbose = 2,
    callbacks = list(early_stop, print_dot_callback)
)

This results in error py_call_impl(callable, dots$args, dots$keywords) :
    AttributeError: 'dict' object has no attribute 'shape'

Can some one help me understand the error. Thank you.


问:
PHP execute via curl_exec have Ajax request which is not working
I made a example of my problem.
I have 4 files

index.php

RunViaAjax.php

SendRequest.php

AjaxFile.php

index.php File

```<code><!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    </head>
    <body>

        <button id="OK">Test Ajax</button>

       <script>
    $("#OK").click(function(){
        $.ajax({
            type: "POST",
            url: 'RunViaAjax.php',
            data: {data: "someData"}, // serializes the form's elements.
            success: function(data){
                console.log(data);
            }
        });
    });
        </script>
    </body>
</html>
</code>```

RunViaAjax.php File

```<code><?php

    $curl = curl_init();
    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://localhost/tester/SendRequest.php',
        CURLOPT_USERAGENT => 'Codular Sample cURL Request'
    ]);
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    echo $resp;
    // Close request to clear up some resources
    curl_close($curl);

?>
</code>```

SendRequest.php File

```<code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>
    <p id="result"></p>
    <script>
    $.ajax({
      type: "POST",
      url: 'AjaxFile.php',
      data: {data: "someData"}, // serializes the form's elements.
      success: function(data){
        $('#result').html(data);
      }
    });

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

AjaxFile.php File

```<code><?php

    file_put_contents("OK-Report.php", "");
    echo "OK REPORT";

?>
</code>```

Now by running index.php, am getting source code of SendRequest.php.
What i need is to run SendRequest.php (SendRequest.php is dynamically created file).

答:
Hope this help you.</p>

```<code>File1.php

$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://localhost/test/MyFile.php',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
]);
// Send the request & save response to $resp
$resp = curl_exec($curl);
print_r($resp);
// Close request to clear up some resources
curl_close($curl);

MyFile.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>

    <p id="result"></p>
   <script>
    $.ajax({
           type: "POST",
           url: 'AjaxFile.php',
           data: {data: "someData"}, // serializes the form's elements.
           success: function(data)
           {
            $('#result').html(data);
           }
         });

    </script>
</body>
</html>

AjaxFile.php

<?php echo 'Ajax request recieved' ?>
</code>```

Body:
I made a example of my problem.
I have 4 files

index.php

RunViaAjax.php

SendRequest.php

AjaxFile.php

index.php File

<!DOCTYPE html>

        <button id="OK">Test Ajax</button>

RunViaAjax.php File

<?php

    $curl = curl_init();
    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://localhost/tester/SendRequest.php',
        CURLOPT_USERAGENT => 'Codular Sample cURL Request'
    ]);
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    echo $resp;
    // Close request to clear up some resources
    curl_close($curl);

?>

SendRequest.php File

<!DOCTYPE html>

AjaxFile.php File

<?php

    file_put_contents("OK-Report.php", "");
    echo "OK REPORT";

?>

Now by running index.php, am getting source code of SendRequest.php.
What i need is to run SendRequest.php (SendRequest.php is dynamically created file).

Body:
Hope this help you.

File1.php

$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://localhost/test/MyFile.php',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
]);
// Send the request & save response to $resp
$resp = curl_exec($curl);
print_r($resp);
// Close request to clear up some resources
curl_close($curl);

MyFile.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>

    <p id="result"></p>
   <script>
    $.ajax({
           type: "POST",
           url: 'AjaxFile.php',
           data: {data: "someData"}, // serializes the form's elements.
           success: function(data)
           {
            $('#result').html(data);
           }
         });

    </script>
</body>
</html>

AjaxFile.php

<?php echo 'Ajax request recieved' ?>


问:
Having trouble with this code. Discord purge command in js
I've been working on a Discord bot as a little experiment (since I'm new to coding). It turns out I'm having problem with this code:

```<code>  // delete from 2-100.

  const deleteCount = parseInt(args[0], 10);

  if(!deleteCount){
    return message.reply("Un numero del 2-100"); //"a number from 2-100"
  }

  const fetched = await message.channel.fetchMessages({limit: deleteCount});
  message.channel.bulkDelete(fetched)
    .catch(error => message.reply(`Error: ${error}`)) }
</code>```

This code does work: it purges the said amount of messages and sends the "Input a number from 2-100" message when only !purge or !clear is given. However, the message... it's also sent when I type the command !say, or after the bot kicks someone and sends the successfully kicked user message. It's even sent when !shop or !f are given (which aren't part of any of it's code).

How can I make the bot send the "Un numero del 2-100" only when the command is given without a value?

答:
You should use an if-statement to check if the message is the command so you can let this code execute only if it is the command.
E.g: if (msg.startsWith(prefix + 'purge') || msg.startsWith(prefix + 'clear') {}

From what I see, all this code gets executed regardless of the command specified, which is why that string is being output regardless of the command being called.

Body:
I've been working on a Discord bot as a little experiment (since I'm new to coding). It turns out I'm having problem with this code:

  // delete from 2-100.

  const deleteCount = parseInt(args[0], 10);

  if(!deleteCount){
    return message.reply("Un numero del 2-100"); //"a number from 2-100"
  }

  const fetched = await message.channel.fetchMessages({limit: deleteCount});
  message.channel.bulkDelete(fetched)
    .catch(error => message.reply(`Error: ${error}`)) }

This code does work: it purges the said amount of messages and sends the "Input a number from 2-100" message when only !purge or !clear is given. However, the message... it's also sent when I type the command !say, or after the bot kicks someone and sends the successfully kicked user message. It's even sent when !shop or !f are given (which aren't part of any of it's code).

How can I make the bot send the "Un numero del 2-100" only when the command is given without a value?


问:
Thunderbird Webextensions Plug-In get a messageList
I already tried different things to get a list of mails from my inbox folder in Thunderbird.

let page = await browser.messages.list(folder);

But how to declare folder?

MailFolder is explained in Thunderbird Docs, but how do i get

```<code>accountId (string) The account this folder belongs to.
path (string) Path to this folder in the account. Although paths look predictable, never guess a folder’s path, as there are a number of reasons why it may not be what you think it is.
[name] (string) The human-friendly name of this folder.
[type] (string) The type of folder, for several common types.
</code>```

?

Another way i found is to use query(queryInfo). Documentation explains:

Gets all messages that have the specified properties, or all messages if no properties are specified.

But when I pass no argument, i get an exception.

Can someone provide me a piece of code which just assigns my inbox folder to a messageList object?

答:
As promised, here the optimized code, which recursively "loops" asynchronusly one-after-the-other through all the MessageList "page" objects:

```<code>emailAccountName = "firstname.lastname@email.com";
wantedMailFolder = "inbox";
msgCnt = 0;

function accountsList_successCallback( arrayOfMailAccount ) {
    let accountId = false;
    for (let i = 0; i < arrayOfMailAccount.length; i++) {
    if ( arrayOfMailAccount[i].name == emailAccountName ) {
        accountId  = arrayOfMailAccount[i].id;
        break;
        }
    }
    console.log('Last line of accountsList_successCallback() before return of accountId: ' + accountId );
    return accountId;
}
function mailAccount_successCallback( mailAccount ) {
    let mailFolder = false;
    for (let i = 0; i < mailAccount.folders.length; i++) {
    if ( mailAccount.folders[i].type == wantedMailFolder ) {
        mailFolder = mailAccount.folders[i];
        break;
        }
    }
    console.log('Last line of mailAccount_successCallback(), returning mailAccount\'s MailFolder');
    return mailFolder;
}
function messagesList_successCallback( messageList ) {
    /***********************************************************
      (recursively) called to process the given "page" Promise
    ************************************************************/
    // console.log( "Number of Emails in this Page: " + messageList.messages.length );

    if ( messageList.messages.length ) {
    // iterating through messageList.messages
    for ( let i =0; i < messageList.messages.length; i++, msgCnt++) {
        /*
         * This is where you can place your message examining code.
         * For example a numbered list of all Subjects:
         *
         console.log( "Subject "
                      + ( "00000" + (msgCnt+1) ).slice(-5)
                      + ": "
                      + messageList.messages[ i ].subject );
         *
         *
         */
        }
    }
    if ( messageList.id ) {
        // continue with the NEXT "page" Promise
        browser.messages.continueList( messageList.id )
            .then( messagesList_successCallback, finalCatch );
    } else {
        // this was the LAST fulfilled "page" Promise,
        // we already acted upon
        console.log('Last return from messagesList_successCallback() with msgCnt == ' + msgCnt);
    }
}

browser.accounts.list()
    .then( accountsList_successCallback)  // after .accounts.list() Promise is fulfilled...
                                          // accountsList_successCallback is called, which
                                          // in this example returns the accountId string...
    .then( accountId => browser.accounts.get( accountId ))
    .then( mailAccount_successCallback)   // after .accounts.get() Promise is fulfilled...
                                          // mailAccount_successCallback is called, which
                                          // returns the wanted MailFolder...
    .then( mailFolder => browser.messages.list( mailFolder ))
    .then( messagesList_successCallback)  // after .messages.list() Promise is fulfilled...
                                          // messagesList_successCallback is called
                                          // with the FIRST "page" Promise, a MessageList
    .catch( finalCatch )
;

function finalCatch( error ) {
    console.error( "ERROR passed to finalCatch() : " + error);
}
</code>```

Hope this helps. richard

Body:
I already tried different things to get a list of mails from my inbox folder in Thunderbird.

let page = await browser.messages.list(folder);

But how to declare folder?

MailFolder is explained in Thunderbird Docs, but how do i get

accountId (string) The account this folder belongs to.
path (string) Path to this folder in the account. Although paths look predictable, never guess a folder’s path, as there are a number of reasons why it may not be what you think it is.
[name] (string) The human-friendly name of this folder.
[type] (string) The type of folder, for several common types.

?

Another way i found is to use query(queryInfo). Documentation explains:

Gets all messages that have the specified properties, or all messages if no properties are specified.

But when I pass no argument, i get an exception.

Can someone provide me a piece of code which just assigns my inbox folder to a messageList object?

Body:
As promised, here the optimized code, which recursively "loops" asynchronusly one-after-the-other through all the MessageList "page" objects:

emailAccountName = "firstname.lastname@email.com";
wantedMailFolder = "inbox";
msgCnt = 0;

function accountsList_successCallback( arrayOfMailAccount ) {
    let accountId = false;
    for (let i = 0; i < arrayOfMailAccount.length; i++) {
    if ( arrayOfMailAccount[i].name == emailAccountName ) {
        accountId  = arrayOfMailAccount[i].id;
        break;
        }
    }
    console.log('Last line of accountsList_successCallback() before return of accountId: ' + accountId );
    return accountId;
}
function mailAccount_successCallback( mailAccount ) {
    let mailFolder = false;
    for (let i = 0; i < mailAccount.folders.length; i++) {
    if ( mailAccount.folders[i].type == wantedMailFolder ) {
        mailFolder = mailAccount.folders[i];
        break;
        }
    }
    console.log('Last line of mailAccount_successCallback(), returning mailAccount\'s MailFolder');
    return mailFolder;
}
function messagesList_successCallback( messageList ) {
    /***********************************************************
      (recursively) called to process the given "page" Promise
    ************************************************************/
    // console.log( "Number of Emails in this Page: " + messageList.messages.length );

    if ( messageList.messages.length ) {
    // iterating through messageList.messages
    for ( let i =0; i < messageList.messages.length; i++, msgCnt++) {
        /*
         * This is where you can place your message examining code.
         * For example a numbered list of all Subjects:
         *
         console.log( "Subject "
                      + ( "00000" + (msgCnt+1) ).slice(-5)
                      + ": "
                      + messageList.messages[ i ].subject );
         *
         *
         */
        }
    }
    if ( messageList.id ) {
        // continue with the NEXT "page" Promise
        browser.messages.continueList( messageList.id )
            .then( messagesList_successCallback, finalCatch );
    } else {
        // this was the LAST fulfilled "page" Promise,
        // we already acted upon
        console.log('Last return from messagesList_successCallback() with msgCnt == ' + msgCnt);
    }
}

browser.accounts.list()
    .then( accountsList_successCallback)  // after .accounts.list() Promise is fulfilled...
                                          // accountsList_successCallback is called, which
                                          // in this example returns the accountId string...
    .then( accountId => browser.accounts.get( accountId ))
    .then( mailAccount_successCallback)   // after .accounts.get() Promise is fulfilled...
                                          // mailAccount_successCallback is called, which
                                          // returns the wanted MailFolder...
    .then( mailFolder => browser.messages.list( mailFolder ))
    .then( messagesList_successCallback)  // after .messages.list() Promise is fulfilled...
                                          // messagesList_successCallback is called
                                          // with the FIRST "page" Promise, a MessageList
    .catch( finalCatch )
;

function finalCatch( error ) {
    console.error( "ERROR passed to finalCatch() : " + error);
}

Hope this helps. richard


问:
List<T>.Remove does not remove Object
I am implementing the following code to remove an item from a list

```<code>// RemoveRole is a member function in a class for Person
// roles is defined as
// List<PersonOrganisationRoleModel> roles;
// And properly populated prior to this function call

public void RemoveRole(string RoleName)
{
    // I am creating an object that needs to be matched in the list
    PersonOrganisationRoleModel role = new PersonOrganisationRoleModel(OrganisationID, PersonID, RoleName)

    // "role" is now properly constructed, and is matching an exact copy of one of the objects in "roles"
    // the expectation now is the the object "role" must be matched with one of the objects in "roles",
    // and that one be removed
    roles.Remove(role);

}
</code>```

But the "Remove" function call on the "roles" list does not remove the item in the list that contains the exact same values.

My understanding is that this is supposed to work (it is just the inverse of List.Add

答:
You need to override Equals() in PersonOrganisationRoleModel class, otherwise the Remove() will compare the objects by reference, which will be false since role is a new object

```<code>public override bool Equals(object obj)
{
    if (obj == null)
    {
        return false;
    }

    PersonOrganisationRoleModel p = obj as PersonOrganisationRoleModel;
    if (p == null)
    {
        return false;
    }

    return this.OrganisationID == p.OrganisationID && this.PersonID == p.PersonID;
}
</code>```

If you are using dictionaries or sets to store this object you should also override GetHashCode()

```<code>public override GetHashCode()
{
    return OrganisationID.GetHashCode() ^ PersonID.GetHashCode();
}
</code>```

Title: List<T>.Remove does not remove Object

Body:
I am implementing the following code to remove an item from a list

// RemoveRole is a member function in a class for Person
// roles is defined as
// List<PersonOrganisationRoleModel> roles;
// And properly populated prior to this function call

public void RemoveRole(string RoleName)
{
    // I am creating an object that needs to be matched in the list
    PersonOrganisationRoleModel role = new PersonOrganisationRoleModel(OrganisationID, PersonID, RoleName)

    // "role" is now properly constructed, and is matching an exact copy of one of the objects in "roles"
    // the expectation now is the the object "role" must be matched with one of the objects in "roles",
    // and that one be removed
    roles.Remove(role);

}

But the "Remove" function call on the "roles" list does not remove the item in the list that contains the exact same values.

My understanding is that this is supposed to work (it is just the inverse of List.Add

Body:
You need to override Equals() in PersonOrganisationRoleModel class, otherwise the Remove() will compare the objects by reference, which will be false since role is a new object

public override bool Equals(object obj)
{
    if (obj == null)
    {
        return false;
    }

    PersonOrganisationRoleModel p = obj as PersonOrganisationRoleModel;
    if (p == null)
    {
        return false;
    }

    return this.OrganisationID == p.OrganisationID && this.PersonID == p.PersonID;
}

If you are using dictionaries or sets to store this object you should also override GetHashCode()

public override GetHashCode()
{
    return OrganisationID.GetHashCode() ^ PersonID.GetHashCode();
}


问:
awk print 1st row with condition
The command:

```<code>kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}'
</code>```

outputs

```<code>hello-uwsgi-deployment-5b7498f864-4bfrx
hello-uwsgi-deployment-5b7498f864-h9rxz
hello-uwsgi-deployment-5b7498f864-qlg8z
hello-uwsgi-deployment-5b7498f864-r5nfs
hello-uwsgi-deployment-5b7498f864-vxr6x
</code>```

How can I print only the first line with the above condition using awk?

I tried

```<code>kubectl get pods -n hello |
awk '($1 ~ "hello-uwsgi-deployment") && ('NR==1') {print $1}'
</code>```

but it outputs nothing.

EDIT:kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}' this works perfectly.

How to get the same working with multiple conditional statements using == and NR==?

答:
If I got your question correctly, you want to print only first line which has string hello-uwsgi-deployment then could you please try following. I am also using exit so that it will NOT read whole Input_file and will save time for us.

```<code>kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}'
</code>```

OR of you want to simply do search string in whole line then try following:

```<code>kubectl get pods -n hello | awk '/hello-uwsgi-deployment/{print;exit}'
</code>```

Title: awk print 1st row with condition

Body:
The command:

kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}'

outputs

hello-uwsgi-deployment-5b7498f864-4bfrx
hello-uwsgi-deployment-5b7498f864-h9rxz
hello-uwsgi-deployment-5b7498f864-qlg8z
hello-uwsgi-deployment-5b7498f864-r5nfs
hello-uwsgi-deployment-5b7498f864-vxr6x

How can I print only the first line with the above condition using awk?

I tried

kubectl get pods -n hello |
awk '($1 ~ "hello-uwsgi-deployment") && ('NR==1') {print $1}'

but it outputs nothing.

EDIT:kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}' this works perfectly.

How to get the same working with multiple conditional statements using == and NR==?

Body:
If I got your question correctly, you want to print only first line which has string hello-uwsgi-deployment then could you please try following. I am also using exit so that it will NOT read whole Input_file and will save time for us.

kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}'

OR of you want to simply do search string in whole line then try following:

kubectl get pods -n hello | awk '/hello-uwsgi-deployment/{print;exit}'