问:
IF Else with Jquery and input box
I am very very green with jquery.  I know the logic but am missing how to get this to work properly.

Basically this checks if the input box has the @ sign in it and if it does returns a message.  This is probably very simple but im lost at the moment.

```<code><script>
               $("input[name='email']").keyup(function () {
                 if($("#emailaddress").val().indexOf("@")){
                    $(".dynamic").html('Do Not include @domain.net');
                 }else{
                 $(".dynamic").html(this.value + '@domain.net');
                      }
             });
             </script>
</code>```

I also tried to make it so it just changes the background using this

```<code><script>
               $("input[name='email']").keyup(function () {
                 $(".dynamic").html(this.value + '@domain.net');

                 $("input[name='email']:contains(@)").css("background-color", "yellow");
             });
             </script>
</code>```

Neither work

Here is the part of my form i am looking at

```<code>    <div class="form-row">

          <div class="form-group col-md-auto ">
              <small id="emailHelp" class="form-text text-muted">Your Email Username Only <b>Do not include your FULL Email</b></small>
            <input type="text" class="form-control email" id="emailaddress" name="email" placeholder="Your E-mail username ONLY IE: johns" required >
          </div>
          <div class="form-group col-md-auto ">
            <small id="emailHelp" class="form-text text-muted"><br /></small>
            <div> <span class="dynamic" style="font-size: 26px"></span>
             <span class="static" style="font-size: 26px"></span>
             <script>
               $("input[name='email']").keyup(function () {
                 if($("#emailaddress").val().indexOf("@")){
                    $(".dynamic").html('Do NOt include @domain.net')
                 }
                 $(".dynamic").html(this.value + '@domain.net') <-----This works

             });
             </script>

            </div>
          </div>

    </div>
</code>```

答:
The function indexOf() can return a zero, indicating that the string has been found at the very beginning of the string. If the string is not found at all, it returns -1.  So you can not simply check it like

```<code>if( something.indexOf('foobar') ) {
   // found
}
</code>```

Instead, if you have to check if the value is -1 like so

```<code>if( something.indexOf('foobar') > -1 ) {
   // found
}
</code>```

Title: IF Else with Jquery and input box

Body:
I am very very green with jquery.  I know the logic but am missing how to get this to work properly.

Basically this checks if the input box has the @ sign in it and if it does returns a message.  This is probably very simple but im lost at the moment.

I also tried to make it so it just changes the background using this

Neither work

Here is the part of my form i am looking at

              Your Email Username Only Do not include your FULL Email
            <input type="text" class="form-control email" id="emailaddress" name="email" placeholder="Your E-mail username ONLY IE: johns" required >

Body:
The function indexOf() can return a zero, indicating that the string has been found at the very beginning of the string. If the string is not found at all, it returns -1.  So you can not simply check it like

if( something.indexOf('foobar') ) {
   // found
}

Instead, if you have to check if the value is -1 like so

if( something.indexOf('foobar') > -1 ) {
   // found
}


来源: stackexchange

问:
Invalid key Error when selecting Values from an pandas array using a boolean array as mask
Im trying to run code to generate a plot from this tutorial:
In Section 3 "3 - Projection Onto the New Feature Space" a Matplot is generated that shows all three flowers using following code:

```<code>with plt.style.context('seaborn-whitegrid'):
plt.figure(figsize=(6, 4))
for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'),
                    ('blue', 'red', 'green')):
    plt.scatter(Y[y==lab, 0],
                Y[y==lab, 1],
                label=lab,
                c=col)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend(loc='lower center')
plt.tight_layout()
plt.show()
</code>```

When I run this code, I get an following error, and I can't figure out how to solve it:

```<code>    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-5a7e436e90e3> in <module>
    17         plt.subplot(2, 2, cnt+1)
    18         for lab in ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'):
---> 19             plt.hist(X[y==lab, cnt],
    20                      label=lab,
    21                      bins=10,

~/anaconda3/envs/ml/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798             if self.columns.nlevels > 1:
2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
2801             if is_integer(indexer):
2802                 indexer = [indexer]

~/anaconda3/envs/ml/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2644                 )
2645             try:
-> 2646                 return self._engine.get_loc(key)
2647             except KeyError:
2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

TypeError: '(     class
0     True
1     True
2     True
3     True
4     True
..     ...
145  False
146  False
147  False
148  False
149  False

[150 rows x 1 columns], 0)' is an invalid key
</code>```

答:
You want to change this:

```<code>plt.scatter(Y[y==lab, 0],
            Y[y==lab, 1],
            label=lab,
            c=col)
</code>```

to:

```<code>plt.scatter(Y.loc[y==lab, 0],
            Y.loc[y==lab, 1],
            label=lab,
            c=col)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im trying to run code to generate a plot from this tutorial:
In Section 3 "3 - Projection Onto the New Feature Space" a Matplot is generated that shows all three flowers using following code:

with plt.style.context('seaborn-whitegrid'):
plt.figure(figsize=(6, 4))
for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'),
                    ('blue', 'red', 'green')):
    plt.scatter(Y[y==lab, 0],
                Y[y==lab, 1],
                label=lab,
                c=col)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend(loc='lower center')
plt.tight_layout()
plt.show()

When I run this code, I get an following error, and I can't figure out how to solve it:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-5a7e436e90e3> in <module>
    17         plt.subplot(2, 2, cnt+1)
    18         for lab in ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'):
---> 19             plt.hist(X[y==lab, cnt],
    20                      label=lab,
    21                      bins=10,

~/anaconda3/envs/ml/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798             if self.columns.nlevels > 1:
2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
2801             if is_integer(indexer):
2802                 indexer = [indexer]

~/anaconda3/envs/ml/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2644                 )
2645             try:
-> 2646                 return self._engine.get_loc(key)
2647             except KeyError:
2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

TypeError: '(     class
0     True
1     True
2     True
3     True
4     True
..     ...
145  False
146  False
147  False
148  False
149  False

[150 rows x 1 columns], 0)' is an invalid key

Body:
You want to change this:

plt.scatter(Y[y==lab, 0],
            Y[y==lab, 1],
            label=lab,
            c=col)

to:

plt.scatter(Y.loc[y==lab, 0],
            Y.loc[y==lab, 1],
            label=lab,
            c=col)


问:
mysqlworkbench giving version error on exporting database
When I try to export my database through MySQL Workbench remotely from localserver,

I am getting some below version error:

mysqldump Version Mismatch  [Content] mysqldump.exe is version 5.5.16, but the MySQL Server to be dumped has version 5.6.10-log. Because the version of mysqldump is older than the server, some features may not be backed up properly. It is recommended you upgrade your local MySQL client programs, including mysqldump to a version equal to or newer than that of the target server. The path to the dump tool must then be set in Preferences -> Administrator -> Path to mysqldump Tool

I am trying to find a solution - I searched for solution on google but couldn't find a good answer to solve the issue.

Does anyone know, how to fix this issue in MySQL Workbench?

答:
None of the other answers here has worked for me, so I'll post another way that has fixed mine(I'm using Windows WSL Ubuntu 18.04).

TL;DR: check if you have the line local_infile=1 in the configuration file of your MySQL and change it to loose-local-infile=1 or comment it out altogether if you don't need it now and then restart your MySQL Workbench.

Further Explanation: I closed MySQL Workbench and opened up my terminal and ran mysqldump --version and it gave me this error: mysqldump: [ERROR] unknown variable 'local_infile=1'., I realized that I'd added something to the /etc/my.cnf file previously in order to import some data into a database using a local file, but as it turns out, some other MySQL tools (such as mysqldump, probably) do not understand this line well, so I commented it out and then mysqldump --version works fine and gives the correct version number without any other issues. Now I open the MySQL Workbench once again and this time it's working fine.

HTH.


问:
Function to mangle/demangle functions
I have previously, here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading them one way or another because Callgrind, part of Valgrind, show them demangled while in assembly they are shown mangled.

So I would like to either mangle the Valgrind function output or demangle the assembly names of functions. Anyone ever tried something like that? I was looking at a website and found out the following:

```<code>Code to implement demangling is part of the GNU Binutils package;
see libiberty/cplus-dem.c and include/demangle.h.
</code>```

Has anyone ever tried something like that? I want to demangle/mangle in C.

My compiler is gcc 4.x.

答:
This is a slight variation on Dave's version above. This is a unique_ptr version with a little bit of checking on the return type, though it looks like you could just ignore that, but somehow that just seems unclean.</p>
```<code>auto cppDemangle (const char *abiName)
{
    //
    // This function allocates and returns storage in ret
    //
    int status;
    char *ret = abi::__cxa_demangle(abiName, 0 /* output buffer */, 0 /* length */, &status);

    auto deallocator = ( [](char *mem) { if (mem) free((void*)mem); } );

    if (status) {
        // 0: The demangling operation succeeded.
        // -1: A memory allocation failure occurred.
        // -2: mangled_name is not a valid name under the C++ ABI mangling rules.
        // -3: One of the arguments is invalid.
        std::unique_ptr<char, decltype(deallocator) > retval(nullptr, deallocator);
        return retval;
    }

    //
    // Create a unique pointer to take ownership of the returned string so it
    // is freed when that pointers goes out of scope
    //
    std::unique_ptr<char, decltype(deallocator) > retval(ret, deallocator);
    return retval;
}
</code>```

Title: Function to mangle/demangle functions

Body:
I have previously, here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading them one way or another because Callgrind, part of Valgrind, show them demangled while in assembly they are shown mangled.

So I would like to either mangle the Valgrind function output or demangle the assembly names of functions. Anyone ever tried something like that? I was looking at a website and found out the following:

Code to implement demangling is part of the GNU Binutils package;
see libiberty/cplus-dem.c and include/demangle.h.

Has anyone ever tried something like that? I want to demangle/mangle in C.

My compiler is gcc 4.x.

Body:
This is a slight variation on Dave's version above. This is a unique_ptr version with a little bit of checking on the return type, though it looks like you could just ignore that, but somehow that just seems unclean.

auto cppDemangle (const char *abiName)
{
    //
    // This function allocates and returns storage in ret
    //
    int status;
    char *ret = abi::__cxa_demangle(abiName, 0 /* output buffer */, 0 /* length */, &status);

    auto deallocator = ( [](char *mem) { if (mem) free((void*)mem); } );

    if (status) {
        // 0: The demangling operation succeeded.
        // -1: A memory allocation failure occurred.
        // -2: mangled_name is not a valid name under the C++ ABI mangling rules.
        // -3: One of the arguments is invalid.
        std::unique_ptr<char, decltype(deallocator) > retval(nullptr, deallocator);
        return retval;
    }

    //
    // Create a unique pointer to take ownership of the returned string so it
    // is freed when that pointers goes out of scope
    //
    std::unique_ptr<char, decltype(deallocator) > retval(ret, deallocator);
    return retval;
}


问:
Is there a fast Way to return Sin and Cos of the same value in Python?
I need to return the sin and cos values of every element in a large array.  At the moment I am doing:

```<code>a,b=np.sin(x),np.cos(x)
</code>```

where x is some large array.  I need to keep the sign information for each result, so:

```<code>a=np.sin(x)
b=(1-a**2)**0.5
</code>```

is not an option.  Is there any faster way to return both sin and cos at once?

答:
I compared the suggested solution with perfplot and found that nothing beats calling sin and cos explicitly.

Code to reproduce the plot:

import perfplot
import numpy as np

def sin_cos(x):
    return np.sin(x), np.cos(x)

def exp_ix(x):
    eix = np.exp(1j * x)
    return eix.imag, eix.real

def cos_from_sin(x):
    sin = np.sin(x)
    abs_cos = np.sqrt(1 - sin**2)
    sgn_cos = np.sign(((x - np.pi / 2) % (2 * np.pi)) - np.pi)
    cos = abs_cos * sgn_cos
    return sin, cos

b = perfplot.bench(
    setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
    kernels=[sin_cos, exp_ix, cos_from_sin],
    n_range=[2**k for k in range(20)],
    xlabel="n",
)
b.save("out.png")
b.show()
```

ContentLicense: CC BY-SA 3.0

Body:
I need to return the sin and cos values of every element in a large array.  At the moment I am doing:

a,b=np.sin(x),np.cos(x)

where x is some large array.  I need to keep the sign information for each result, so:

a=np.sin(x)
b=(1-a**2)**0.5

is not an option.  Is there any faster way to return both sin and cos at once?


问:
TLS 1.2 support for camel-ftp version 2.17.0.redhat-630262 - Java 8
I was wondering if TLS 1.2 is supported by "camel-ftp" library for Java. The version used is 2.17.0.redhat-630262. Or should we upgrade the version to the latest for getting TLS 1.2 support? The Java version is 8.</p>

答:
The SSL support is provided by the underlying JDK. Java 8 has TLS V1.2, so this is available to camel -ftp (sftp endpoint).  If you set securityProtocol to TLS, you will get the TLS protocols.

You may want to ensure that only the TLS V1.2 protocols are enabled in your jre/lib/security/java.security file, as the older, weaker, TLS versions are enabled by default.


问:
How do I enter/ find the correct token or error?
I want to create a Discord bot that can remotely start my Minecraft SpigotMC Server, but when I try to run my bot using node bot.js, it outputs an error message,

```<code>(node:19880) UnhandledPromiseRejectionWarning: Error [TOKEN_INVALID]: An invalid token was provided.
    at WebSocketManager.connect (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\websocket\WebSocketManager.js:135:26)
    at Client.login (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\Client.js:221:21)
(node:19880) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19880) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Here is my package.json code:

{
  "name": "Serverstart",
  "version": "1.0.0",
  "description": "Bot doing Bot things",
  "main": "bot.js",
  "author": "PalanixYT",
  "dependencies": {
    "discord.io": "https://github.com/woor/discord.io/tarball/gateway_v6",
    "discord.js": "^12.2.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "winston": "^3.2.1"
  }
}
```

<p>And my auth.json:(Don't worry, I already renewed my token)</p>

<pre class="lang-js prettyprint-override"><code>{
  "token":"NzE3MTI2NDcyMjM3NTgwMjg4.XtWKZw.go81ay5fCu52yyn-xYiK1eIwTzI"
}
</code>```

If I need to give more information, I am more then willing to do so.

答:
You can use config.json like others have said, but if you push to git, or if you want to use it in actual production you should use process.env

file: .env (main/root folder)

```<code>TOKEN=YOUR_TOKEN_HERE
</code>```

file: .gitignore

```<code>.env
</code>```

file: main.js

require("dotenv").config();
bot.login(process.env.TOKEN);
```

You will have to download the dotenv module though.
npm i dotenv

Depending on which platform you host it on, they might have env variables you can define on the project page like heroku.

Body:
I want to create a Discord bot that can remotely start my Minecraft SpigotMC Server, but when I try to run my bot using node bot.js, it outputs an error message,

(node:19880) UnhandledPromiseRejectionWarning: Error [TOKEN_INVALID]: An invalid token was provided.
    at WebSocketManager.connect (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\websocket\WebSocketManager.js:135:26)
    at Client.login (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\Client.js:221:21)
(node:19880) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19880) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here is my package.json code:

{
  "name": "Serverstart",
  "version": "1.0.0",
  "description": "Bot doing Bot things",
  "main": "bot.js",
  "author": "PalanixYT",
  "dependencies": {
    "discord.io": "https://github.com/woor/discord.io/tarball/gateway_v6",
    "discord.js": "^12.2.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "winston": "^3.2.1"
  }
}

And my auth.json:(Don't worry, I already renewed my token)

{
  "token":"NzE3MTI2NDcyMjM3NTgwMjg4.XtWKZw.go81ay5fCu52yyn-xYiK1eIwTzI"
}

If I need to give more information, I am more then willing to do so.

Body:
You can use config.json like others have said, but if you push to git, or if you want to use it in actual production you should use process.env

file: .env (main/root folder)

TOKEN=YOUR_TOKEN_HERE

file: .gitignore

.env

file: main.js

require("dotenv").config();
bot.login(process.env.TOKEN);

You will have to download the dotenv module though.
npm i dotenv

Depending on which platform you host it on, they might have env variables you can define on the project page like heroku.


问:
Unexpected output in converting from long in C to long in C++ in VS?
I'm writing a program in C (with a school-specific IDE), then converting it to C++ in Visual Studio. The program in C takes a long variable as user input of 371449635398431 (using the school IDE and a unique compiler function called get_long)   When I copy this to Visual Studio, using cin >> instead of get_long, it interprets the long as 2147483647 unless I make it a long long in VS. Are longs in C different than longs in C++ (with longs in C being equivalent to long long in C++?), or  could a compiler mismatch be causing the issue? </p>

答:
The size of long depends of compiler, settings, data model and phase of moon (the last reason is a joke). But the long size is at least 32 bit.

If you want to use exact size you can use int64_t. for example.


问:
i'm trying to format String in java
iam trying to form string in java to be like this

```<code>        String ss = String.format("%-20s %s", "itime1", " IQD\n");
        String bb = String.format("%-20s %s", "itw", " IQD\n");

                String NN = ss + bb;

                System.out.println(NN);

       JOptionPane.showMessageDialog(rootPane, NN);
</code>```

The OutPut in the log is :-

```<code>itime1                IQD
itw                   IQD
</code>```

But in JOptionPane Is :-

```<code>itime1           IQD
itw           IQD
</code>```

i need the output to be the same !

any help ?

答: Fixed Font for Arabic. .setFont(new Font("Simplified Arabic Fixed", Font.PLAIN, 15));

Title: i'm trying to format String in java

Body:
iam trying to form string in java to be like this

        String ss = String.format("%-20s %s", "itime1", " IQD\n");
        String bb = String.format("%-20s %s", "itw", " IQD\n");

                String NN = ss + bb;

                System.out.println(NN);

       JOptionPane.showMessageDialog(rootPane, NN);

The OutPut in the log is :-

itime1                IQD
itw                   IQD

But in JOptionPane Is :-

itime1           IQD
itw           IQD

i need the output to be the same !

any help ?


问:
How do I train a pseudo-projective parser on spaCy?
I am trying to train a parser for custom semantics following the sample code from https://raw.githubusercontent.com/explosion/spaCy/master/examples/training/train_intent_parser.py
The idea is to get a non-projective parse so when I pass a text like: ROOT AAAA BBBB 12 21 12 becomes a child of AAAA and 21 becomes a child of BBBB. To test this I am training only this case and testing this same case but it doesn't seem to work, what I get as a response is:

```<code>[('ROOT', 'ROOT', 'ROOT'), ('AAAA', 'LETTERS', 'ROOT'), ('BBBB', 'LETTERS', 'ROOT'), ('12', 'NUMBERS', 'BBBB'), ('21', 'NUMBERS', 'BBBB')]
</code>```

As you can see both numbers are dependent on BBBB when 12 should be dependent on AAAA.

The code I am using to train and test is:

```<code>import plac
import random
import spacy
from spacy.util import minibatch, compounding

TRAIN_DATA = list()

samples = 1000
for _ in range(samples):
    sample = (
        'ROOT AAAA BBBB 12 21',
        {
            'heads': [0, 0, 0, 1, 2],
            'deps': ['ROOT', 'LETTERS', 'LETTERS', 'NUMBERS', 'NUMBERS']
        }
    )
    TRAIN_DATA.append(sample)

def test_model(nlp):
    texts = ['ROOT AAAA BBBB 12 21']
    docs = nlp.pipe(texts)
    for doc in docs:
        print(doc.text)
        print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != "-"])

@plac.annotations(
    model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
    n_iter=("Number of training iterations", "option", "n", int),
)

#  Just in case I am using the german model since it supports pseudo-projective parsing (https://explosion.ai/blog/german-model#word-order)
def main(model='de_core_news_sm', n_iter=15):
    """Load the model, set up the pipeline and train the parser."""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank("en")  # create blank Language class
        print("Created blank 'en' model")

    # We'll use the built-in dependency parser class, but we want to create a
    # fresh instance – just in case.
    if "parser" in nlp.pipe_names:
        nlp.remove_pipe("parser")
    parser = nlp.create_pipe("parser")
    nlp.add_pipe(parser, first=True)

    for text, annotations in TRAIN_DATA:
        for dep in annotations.get("deps", []):
            parser.add_label(dep)

    pipe_exceptions = ["parser", "trf_wordpiecer", "trf_tok2vec"]
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
    with nlp.disable_pipes(*other_pipes):  # only train parser
        optimizer = nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(texts, annotations, sgd=optimizer, losses=losses)
            print("Losses", losses)

    # test the trained model
    test_model(nlp)

if __name__ == "__main__":
    plac.call(main)
</code>```

So, what am I doing wrong?

Thank you in advance for any help on this!

答:
The problem is that the simple training example script isn't projectivitizing the training instances when initializing and training the model. The parsing algorithm itself can only handle projective parses, but if the parser component finds projectivized labels in its output, they're deprojectivitzed in a postprocessing step. You don't need to modify any parser settings (so starting with a German model makes no difference), just provide projectivized input in the right format.

The initial projectivization is handled automatically by the train CLI, which uses GoldCorpus.train_docs() to prepare the training examples for nlp.update() and sets make_projective=True when creating the GoldParses.  In general, I'd recommend switching to the train CLI (which also requires switching to the internal JSON training format, which is admittedly a minor hassle), because the train CLI sets a lot of better defaults.

However, a toy example also works fine as long as you create projectivized training examples (with GoldParse(make_projective=True), add all the projectivized dependency labels to the parser, and train with Doc and the projectivized GoldParse input instead of the text/annotation input:

```<code># tested with spaCy v2.2.4
import spacy
from spacy.util import minibatch, compounding
from spacy.gold import GoldParse

TRAIN_DATA = [
    (
        'ROOT AAAA BBBB 12 21',
        {
            'heads': [0, 0, 0, 1, 2],
            'deps': ['ROOT', 'LETTERS', 'LETTERS', 'NUMBERS', 'NUMBERS']
        }
    )
]

samples = 200

def test_model(nlp):
    texts = ["ROOT AAAA BBBB 12 21"]
    for doc in nlp.pipe(texts):
        print(doc.text)
        print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != "-"])
        spacy.displacy.serve(doc)

@plac.annotations(
    n_iter=("Number of training iterations", "option", "n", int),
)

def main(n_iter=10):
    """Load the model, set up the pipeline and train the parser."""
    nlp = spacy.blank("xx")
    parser = nlp.create_pipe("parser")
    nlp.add_pipe(parser)

    docs_golds = []
    for text, annotation in TRAIN_DATA:
        doc = nlp.make_doc(text)
        gold = GoldParse(doc, **annotation, make_projective=True)
        # add the projectivized labels
        for dep in gold.labels:
            parser.add_label(dep)
        docs_golds.append((doc, gold))
    # duplicate the training instances
    docs_golds = docs_golds * samples

    pipe_exceptions = ["parser", "trf_wordpiecer", "trf_tok2vec"]
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
    with nlp.disable_pipes(*other_pipes):  # only train parser
        optimizer = nlp.begin_training(min_action_freq=1)
        for itn in range(n_iter):
            random.shuffle(docs_golds)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(docs_golds, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                docs, golds = zip(*batch)
                nlp.update(docs, golds, sgd=optimizer, losses=losses)
            print("Losses", losses)

    # test the trained model
    test_model(nlp)

if __name__ == "__main__":
    plac.call(main)
</code>```

Body:
I am trying to train a parser for custom semantics following the sample code from https://raw.githubusercontent.com/explosion/spaCy/master/examples/training/train_intent_parser.py
The idea is to get a non-projective parse so when I pass a text like: ROOT AAAA BBBB 12 21 12 becomes a child of AAAA and 21 becomes a child of BBBB. To test this I am training only this case and testing this same case but it doesn't seem to work, what I get as a response is:

[('ROOT', 'ROOT', 'ROOT'), ('AAAA', 'LETTERS', 'ROOT'), ('BBBB', 'LETTERS', 'ROOT'), ('12', 'NUMBERS', 'BBBB'), ('21', 'NUMBERS', 'BBBB')]

As you can see both numbers are dependent on BBBB when 12 should be dependent on AAAA.

The code I am using to train and test is:

import plac
import random
import spacy
from spacy.util import minibatch, compounding

TRAIN_DATA = list()

samples = 1000
for _ in range(samples):
    sample = (
        'ROOT AAAA BBBB 12 21',
        {
            'heads': [0, 0, 0, 1, 2],
            'deps': ['ROOT', 'LETTERS', 'LETTERS', 'NUMBERS', 'NUMBERS']
        }
    )
    TRAIN_DATA.append(sample)

def test_model(nlp):
    texts = ['ROOT AAAA BBBB 12 21']
    docs = nlp.pipe(texts)
    for doc in docs:
        print(doc.text)
        print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != "-"])

@plac.annotations(
    model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
    n_iter=("Number of training iterations", "option", "n", int),
)

#  Just in case I am using the german model since it supports pseudo-projective parsing (https://explosion.ai/blog/german-model#word-order)
def main(model='de_core_news_sm', n_iter=15):
    """Load the model, set up the pipeline and train the parser."""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank("en")  # create blank Language class
        print("Created blank 'en' model")

    # We'll use the built-in dependency parser class, but we want to create a
    # fresh instance – just in case.
    if "parser" in nlp.pipe_names:
        nlp.remove_pipe("parser")
    parser = nlp.create_pipe("parser")
    nlp.add_pipe(parser, first=True)

    for text, annotations in TRAIN_DATA:
        for dep in annotations.get("deps", []):
            parser.add_label(dep)

    pipe_exceptions = ["parser", "trf_wordpiecer", "trf_tok2vec"]
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
    with nlp.disable_pipes(*other_pipes):  # only train parser
        optimizer = nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(texts, annotations, sgd=optimizer, losses=losses)
            print("Losses", losses)

    # test the trained model
    test_model(nlp)

if __name__ == "__main__":
    plac.call(main)

So, what am I doing wrong?

Thank you in advance for any help on this!

Body:
The problem is that the simple training example script isn't projectivitizing the training instances when initializing and training the model. The parsing algorithm itself can only handle projective parses, but if the parser component finds projectivized labels in its output, they're deprojectivitzed in a postprocessing step. You don't need to modify any parser settings (so starting with a German model makes no difference), just provide projectivized input in the right format.

The initial projectivization is handled automatically by the train CLI, which uses GoldCorpus.train_docs() to prepare the training examples for nlp.update() and sets make_projective=True when creating the GoldParses.  In general, I'd recommend switching to the train CLI (which also requires switching to the internal JSON training format, which is admittedly a minor hassle), because the train CLI sets a lot of better defaults.

However, a toy example also works fine as long as you create projectivized training examples (with GoldParse(make_projective=True), add all the projectivized dependency labels to the parser, and train with Doc and the projectivized GoldParse input instead of the text/annotation input:

# tested with spaCy v2.2.4
import spacy
from spacy.util import minibatch, compounding
from spacy.gold import GoldParse

TRAIN_DATA = [
    (
        'ROOT AAAA BBBB 12 21',
        {
            'heads': [0, 0, 0, 1, 2],
            'deps': ['ROOT', 'LETTERS', 'LETTERS', 'NUMBERS', 'NUMBERS']
        }
    )
]

samples = 200

def test_model(nlp):
    texts = ["ROOT AAAA BBBB 12 21"]
    for doc in nlp.pipe(texts):
        print(doc.text)
        print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != "-"])
        spacy.displacy.serve(doc)

@plac.annotations(
    n_iter=("Number of training iterations", "option", "n", int),
)

def main(n_iter=10):
    """Load the model, set up the pipeline and train the parser."""
    nlp = spacy.blank("xx")
    parser = nlp.create_pipe("parser")
    nlp.add_pipe(parser)

    docs_golds = []
    for text, annotation in TRAIN_DATA:
        doc = nlp.make_doc(text)
        gold = GoldParse(doc, **annotation, make_projective=True)
        # add the projectivized labels
        for dep in gold.labels:
            parser.add_label(dep)
        docs_golds.append((doc, gold))
    # duplicate the training instances
    docs_golds = docs_golds * samples

    pipe_exceptions = ["parser", "trf_wordpiecer", "trf_tok2vec"]
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
    with nlp.disable_pipes(*other_pipes):  # only train parser
        optimizer = nlp.begin_training(min_action_freq=1)
        for itn in range(n_iter):
            random.shuffle(docs_golds)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(docs_golds, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                docs, golds = zip(*batch)
                nlp.update(docs, golds, sgd=optimizer, losses=losses)
            print("Losses", losses)

    # test the trained model
    test_model(nlp)

if __name__ == "__main__":
    plac.call(main)


问:
How to ensure the output of _best_programs of SymbolicTransformer of gplearn is different?
I am using the SymbolicTransformer of gplearn to generate some automated features. The issue is, when I inspect the expression of the features via looking at _best_programs after fitting, I find that most of the features have the same expression. I am wondering whether there is a way to ensure that we output different features using SymbolicTransformer after fitting?</p>

答:
I don't know if there is a way to explicitly enforce this but you can probably try to enforce more diverse populations each generation in the hopes that this leads to a a collection of more diverse _best_programs. In my opinion a few parameters you could look into are:

p_crossover

p_subtree_mutation

p_hoise_mutation

p_point_mutation

p_point_replace

If you increase the chance of crossover or mutation you will increase your expected diversity but you must not overdue it. There is a balance between a diverse population and an accurate one. The higher the crossover or mutation the more likely that you will take a strong individual candidate and change it into something meaningless.


问:
game.state is undefined in Phaser 3 (TypeError)
I began coding a game in phaser and while getting the game states ready. It popped up a 'game.state is undefined' type error in the console. Not sure what to do as I've tried whatever I can to try to fix this problem. The code is given below.

The index.html file:

<!DOCTYPE html>

 <title>Phaser Game</title>
 <meta charset="utf-8">

```
</div>
</div>
</p>

<p>The Main.js file:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const game = new Phaser.Game(600, 400, Phaser.AUTO);
game.State.add('state1', demo.state1);
game.State.start('state1');</code>```

The state1.js file:

var demo = {};
demo.state1 = function(){};
demo.state1.prototype = {
 preload: function(){},
 create: function(){},
 update: function(){}
};```

答:
There isn't state in game object. you should replace it with scene.

It's also better to use the standard way to create game object.

```<code>var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 600,
    height: 400,
    scene:  {
      preload: function(){},
      create: function(){},
      update: function(){}
    }
};

var game = new Phaser.Game(config);
</code>```

More details can be found on the phaser docs

You can Find many useful examples here

Body:
I began coding a game in phaser and while getting the game states ready. It popped up a 'game.state is undefined' type error in the console. Not sure what to do as I've tried whatever I can to try to fix this problem. The code is given below.

The index.html file:

<!DOCTYPE html>

 <title>Phaser Game</title>
 <meta charset="utf-8">

The Main.js file:

const game = new Phaser.Game(600, 400, Phaser.AUTO);
game.State.add('state1', demo.state1);
game.State.start('state1');

The state1.js file:

var demo = {};
demo.state1 = function(){};
demo.state1.prototype = {
 preload: function(){},
 create: function(){},
 update: function(){}
};

Body:
There isn't state in game object. you should replace it with scene.

It's also better to use the standard way to create game object.

var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 600,
    height: 400,
    scene:  {
      preload: function(){},
      create: function(){},
      update: function(){}
    }
};

var game = new Phaser.Game(config);

More details can be found on the phaser docs

You can Find many useful examples here


问:
How do I convert an ATL/MFC CString to a QString?
Given the encoding of the project is probably Unicode (but not for sure) what is the best way of converting ATL::CString to QString?

What I have thought of is this:

```<code>CString c(_T("SOME_TEXT"));
//...
std::basic_string<TCHAR> intermediate((LPCTSTR)c);
QString q;

#ifdef _UNICODE
q = QString::fromStdWString(intermediate);
#else
q = QString::fromStdString(intermediate);
#endif
</code>```

Do you think that it works? Any other ideas?

答:
You don't need the intermediate conversion to a std::string. The CString class can be treated as a simple C-style string; that is, an array of characters. All you have to do is cast it to an LPCTSTR.

And once you have that, you just need to create the QString object depending on whether the characters in your CString are of type char or wchar_t. For the former, you can use one of the standard constructors for QString, and for the latter, you can use the fromWCharArray function.

Something like the following code (untested, I don't have Qt installed anymore):

```<code>CString c(_T("SOME_TEXT"));
QString q;

#ifdef _UNICODE
q = QString::fromWCharArray((LPCTSTR)c, c.GetLength());
#else
q = QString((LPCTSTR)c);
#endif
</code>```

Edit: As suggested in the comments, you have to disable "Treat wchar_t as a built-in type` in your project's Properties to get the above code to link correctly in Visual Studio (source).

For _UNICODE, I believe you could also use the fromUtf16 function:

```<code>CString c(_T("SOME TEXT"));
QString q = QString::fromUtf16(c.GetBuffer(), c.GetLength());
</code>```

Body:
Given the encoding of the project is probably Unicode (but not for sure) what is the best way of converting ATL::CString to QString?

What I have thought of is this:

CString c(_T("SOME_TEXT"));
//...
std::basic_string<TCHAR> intermediate((LPCTSTR)c);
QString q;

#ifdef _UNICODE
q = QString::fromStdWString(intermediate);
#else
q = QString::fromStdString(intermediate);
#endif

Do you think that it works? Any other ideas?

Body:
You don't need the intermediate conversion to a std::string. The CString class can be treated as a simple C-style string; that is, an array of characters. All you have to do is cast it to an LPCTSTR.

And once you have that, you just need to create the QString object depending on whether the characters in your CString are of type char or wchar_t. For the former, you can use one of the standard constructors for QString, and for the latter, you can use the fromWCharArray function.

Something like the following code (untested, I don't have Qt installed anymore):

CString c(_T("SOME_TEXT"));
QString q;

#ifdef _UNICODE
q = QString::fromWCharArray((LPCTSTR)c, c.GetLength());
#else
q = QString((LPCTSTR)c);
#endif

Edit: As suggested in the comments, you have to disable "Treat wchar_t as a built-in type` in your project's Properties to get the above code to link correctly in Visual Studio (source).

For _UNICODE, I believe you could also use the fromUtf16 function:

CString c(_T("SOME TEXT"));
QString q = QString::fromUtf16(c.GetBuffer(), c.GetLength());


问:
Schedule Firebase Cloud Messaging
I'm looking for a way to schedule notifications set by the user, which will notify all the devices they are using my app on.

Currently I'm using firestore to store the users data, including when the notification is due, and AlarmManager to set the alarms. The problem with this is that the user can set the notification on one device, but it's not synced to their other devices.

My plan is to use scheduled cloud functions, and then cloud messaging to notify the user on all devices. However I can't seem to find a way to update or cancel the cloud functions. Users could have multiple notifications set at one time.

How could I go about doing this, or is there a better way?

答:
While you can run Cloud Functions on a schedule, that schedule is configured in your code/when you deploy the Function. There is no dynamic scheduling built into Cloud Functions.

It is possible to build dynamic scheduling in a few ways, most popularly by using Cloud Scheduler. Instead of repeating the same information here, I'll list some great tutorials and previous questions:

⏱ Scheduling Firebase Cloud Functions with Cloud Scheduler

Dynamic Scheduled Background Jobs in Firebase

How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL)

How can scheduled Firebase Cloud Messaging notifications be made outside of the Firebase Console?

Firebase scheduled notification in android

How to schedule push notifcations for react native expo?

How to create cron jobs in firebase programmatically

Title: Schedule Firebase Cloud Messaging


问:
REACT-Native conditional props throwing error
I'm fairly new REACT/REACT-Native developer. I'm building a React-Native app and I have a form that is used to create a new budget or edit a budget. I started out simple and had two separate components for each create and edit functions. I got all my functionality working so I started refactoring my code to make a resuable component out of the budget form. I created a new component for the budget form.
In the budget form, I setup my state as shown below. When the "create" form is used the budget props are null, as nothing is passed into the component. When the "Edit" form is used the budget props are passed in.

```<code>state = {
formMode: this.props.formMode,
budget: {
  id: this.props.budget.BudgetId ? this.props.budget.BudgetId : "",
  name: this.props.budget.Name ? this.props.budget.Name : "",
  color: this.props.budget.Color
    ? this.props.budget.Color
    : this.backgroundColors[0],
  type: this.props.budget.Type ? this.props.budget.Type : "",
  startDate: this.props.budget.StartDate ? this.props.budget.StartDate : "",
  endDate: this.props.budget.EndDate ? this.props.budget.EndDate : "",
},
deviceLocale: "",
datepickerMode: "date",
showStartDatePicker: false,
showEndDatePicker: false,
};
</code>```

I call the "Create" form from my parent component as shown below

```<code><BudgetForm formMode={Constants.FORM_Mode_Add} />
</code>```

I call the "edit" form from my parent component as shown below

```<code><BudgetForm formMode={Constants.FORM_Mode_Edit} budget={this.props.list}/>
</code>```

When I open the form for "create" I get this error:

```<code>TypeError: undefined is not an object (evaluating '_this.props.budget.BudgetId')
</code>```

I'm using this conditional ternary operator on my props in another form in my app and its working fine there. I cannot seem to figure out what is the issue here?

答:
I solved my issue by changing the state object in my BudgetFrom component as shown below.

```<code>constructor(props) {
super(props);
this.state = {
  formMode: this.props.formMode,
  id: this.props.id ? this.props.id : "",
  name: this.props.name ? this.props.name : "",
  color: this.props.color ? this.props.color : backgroundColors[0],
  type: this.props.type ? this.props.type : "",
  startDate: this.props.startDate ? this.props.startDate : "",
  endDate: this.props.endDate ? this.props.endDate : "",
  deviceLocale: "",
  datepickerMode: "date",
  showStartDatePicker: false,
  showEndDatePicker: false,
};
</code>```

}

By not having the "budget" object within state as "child" object it seemed to fix the issue.

Body:
I'm fairly new REACT/REACT-Native developer. I'm building a React-Native app and I have a form that is used to create a new budget or edit a budget. I started out simple and had two separate components for each create and edit functions. I got all my functionality working so I started refactoring my code to make a resuable component out of the budget form. I created a new component for the budget form.
In the budget form, I setup my state as shown below. When the "create" form is used the budget props are null, as nothing is passed into the component. When the "Edit" form is used the budget props are passed in.

state = {
formMode: this.props.formMode,
budget: {
  id: this.props.budget.BudgetId ? this.props.budget.BudgetId : "",
  name: this.props.budget.Name ? this.props.budget.Name : "",
  color: this.props.budget.Color
    ? this.props.budget.Color
    : this.backgroundColors[0],
  type: this.props.budget.Type ? this.props.budget.Type : "",
  startDate: this.props.budget.StartDate ? this.props.budget.StartDate : "",
  endDate: this.props.budget.EndDate ? this.props.budget.EndDate : "",
},
deviceLocale: "",
datepickerMode: "date",
showStartDatePicker: false,
showEndDatePicker: false,
};

I call the "Create" form from my parent component as shown below

<BudgetForm formMode={Constants.FORM_Mode_Add} />

I call the "edit" form from my parent component as shown below

<BudgetForm formMode={Constants.FORM_Mode_Edit} budget={this.props.list}/>

When I open the form for "create" I get this error:

TypeError: undefined is not an object (evaluating '_this.props.budget.BudgetId')

I'm using this conditional ternary operator on my props in another form in my app and its working fine there. I cannot seem to figure out what is the issue here?

Body:
I solved my issue by changing the state object in my BudgetFrom component as shown below.

constructor(props) {
super(props);
this.state = {
  formMode: this.props.formMode,
  id: this.props.id ? this.props.id : "",
  name: this.props.name ? this.props.name : "",
  color: this.props.color ? this.props.color : backgroundColors[0],
  type: this.props.type ? this.props.type : "",
  startDate: this.props.startDate ? this.props.startDate : "",
  endDate: this.props.endDate ? this.props.endDate : "",
  deviceLocale: "",
  datepickerMode: "date",
  showStartDatePicker: false,
  showEndDatePicker: false,
};

}

By not having the "budget" object within state as "child" object it seemed to fix the issue.


问:
How to delete an ManyToMany related object when one part is empty?
Here is the BlogPost model :

```<code>@Entity
@Table(name = "blog_posts")
public class BlogPost extends Model {
    @Required
    @MaxSize(50)
    @MinSize(3)
    @Column(length=50)
    public String title;

    @Lob
    @Required
    @MaxSize(10000)
    public String description;

    @Temporal(TemporalType.TIMESTAMP)
    public Date created;

    @ManyToMany(targetEntity=PostTag.class, cascade=CascadeType.DETACH)
    @OrderBy("name ASC")
    public List<PostTag> tags;

        // + other fields
}
</code>```

And the PostTag :

```<code>@Entity
@Table(name = "post_tags")
public class PostTag extends Model {
    @Match("^([a-zA-Z0-9\\-]{3,25})$")
    @MinSize(3)
    @MaxSize(25)
    @Required
    @Column(length=25, unique=true)
    public String name;

    @ManyToMany(targetEntity=BlogPost.class, mappedBy="tags", cascade=CascadeType.REMOVE)
    public List<BlogPost> posts;
}
</code>```

The relation works fine, but what I'd like, is when I remove a tag from my post, if no other post use this tag, then I can remove it definitely from my database.

Here's the code I tried, but generate an Hibernate exception :

```<code>public boolean removeTag(PostTag tag) {
    if (!tags.contains(tag)) {
        return false;
    }

    tags.remove(tag);
    save();

    if (tag.posts == null || tag.posts.isEmpty()) {
        tag.delete();
    }

    return true;
}
</code>```

The exact exception is:

```<code>org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails
</code>```

I tried to change CascadeType to DELETE_ORPHANS, but it's deprecated, and the new version only seems to works for OneToOne and OneToMany relationships only :/

How can I do ?

Thanks for your help!

答:
Ok I've found where the problem was, so I'll explain it here in case someone have the same issue.

The exception was because I was trying to delete a Tag that still had relationship (it was not left alone).

Here is a working solution on how to delete Tags when there is no Posts using it anymore:

```<code>public boolean removeTag(PostTag tag) {
    if (!tags.contains(tag)) {
        return false;
    }

    tags.remove(tag);
    save();

    if (PostTag.find("name = ? AND size(posts) = 0", tag.name).first() != null) {
        tag.delete();
    }

    return true;
}
</code>```

Body:
Here is the BlogPost model :

@Entity
@Table(name = "blog_posts")
public class BlogPost extends Model {
    @Required
    @MaxSize(50)
    @MinSize(3)
    @Column(length=50)
    public String title;

    @Lob
    @Required
    @MaxSize(10000)
    public String description;

    @Temporal(TemporalType.TIMESTAMP)
    public Date created;

    @ManyToMany(targetEntity=PostTag.class, cascade=CascadeType.DETACH)
    @OrderBy("name ASC")
    public List<PostTag> tags;

        // + other fields
}

And the PostTag :

@Entity
@Table(name = "post_tags")
public class PostTag extends Model {
    @Match("^([a-zA-Z0-9\\-]{3,25})$")
    @MinSize(3)
    @MaxSize(25)
    @Required
    @Column(length=25, unique=true)
    public String name;

    @ManyToMany(targetEntity=BlogPost.class, mappedBy="tags", cascade=CascadeType.REMOVE)
    public List<BlogPost> posts;
}

The relation works fine, but what I'd like, is when I remove a tag from my post, if no other post use this tag, then I can remove it definitely from my database.

Here's the code I tried, but generate an Hibernate exception :

public boolean removeTag(PostTag tag) {
    if (!tags.contains(tag)) {
        return false;
    }

    tags.remove(tag);
    save();

    if (tag.posts == null || tag.posts.isEmpty()) {
        tag.delete();
    }

    return true;
}

The exact exception is:

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails

I tried to change CascadeType to DELETE_ORPHANS, but it's deprecated, and the new version only seems to works for OneToOne and OneToMany relationships only :/

How can I do ?

Thanks for your help!

Body:
Ok I've found where the problem was, so I'll explain it here in case someone have the same issue.

The exception was because I was trying to delete a Tag that still had relationship (it was not left alone).

Here is a working solution on how to delete Tags when there is no Posts using it anymore:

public boolean removeTag(PostTag tag) {
    if (!tags.contains(tag)) {
        return false;
    }

    tags.remove(tag);
    save();

    if (PostTag.find("name = ? AND size(posts) = 0", tag.name).first() != null) {
        tag.delete();
    }

    return true;
}


问:
How do I put a p tag under two divs?
So I've two divs positioned next to each other via float left for the left div and float right for the right div. I want my p to appear underneath these two divs. However it just refuses to do that. It always appears at the top of the page or between the two divs. I've already tried setting the two divs to display inline block but then they don't stay next to each other and do a line-break instead. I'm relatively new to HTML and CSS so maybe its just a simple beginners fault but I would be gratefull if someone could help me out.

.p {
  background: red;
  width: 100%;
}

.tippsboxright {
  color: rgb(238, 238, 238);
  max-width: 45%;
  margin: 0 0 0 5%;
  float: right;
  font-size: 1.7vw;
  padding: 0;
}

.boxleft {
  max-width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <header>
    <h1>My header</h1>
  </header>
  <div class="content">
    <div class="boxleft">
      <img src="../images/questionguy.png" alt="Typ mit fragen" class="imgkauftipps">
    </div>
    <div class="tippsboxright">
      <p>
        This is the right box with text inside of it.
      </p>
    </div>
    <p class="p">This is the p tag that I want to be at the bottom of the page.</p>
  </div>
</main></code>```

答:
There are several ways to get this type of layout, and while floating is the oldest and most common, it's not really designed for this type of thing. float is designed for text to flow around the block, like you see in magazines. So that's what you see happening: your text is flowing around the floats. There is a way to stop this though: clear. Clear tells text to not flow around left, right, or both floated objects. So you can use that to get the layout you desire:

.p {
  background: red;
  width: 100%;
  clear: both;
}

.tippsboxright {
  background: lightyellow;
  color: rgb(238, 238, 238);
  max-width: 45%;
  margin: 0 0 0 5%;
  float: right;
  font-size: 1.7vw;
  padding: 0;
}

.boxleft {
  background: lightblue;
  max-width: 50%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <header>
    <h1>My header</h1>
  </header>
  <div class="content">
    <div class="boxleft">
      <img src="../images/questionguy.png" alt="Typ mit fragen" class="imgkauftipps">
    </div>
    <div class="tippsboxright">
      <p>
        This is the right box with text inside of it.
      </p>
    </div>
    <p class="p">This is the p tag that I want to be at the bottom of the page.</p>
  </div>
</main></code>```

It is however better and easier to use either flex box or grid layouts in this case. They are designed for block style layouts, which seems to be what you want, not flowing text around blocks.

Title: How do I put a p tag under two divs?

Body:
So I've two divs positioned next to each other via float left for the left div and float right for the right div. I want my p to appear underneath these two divs. However it just refuses to do that. It always appears at the top of the page or between the two divs. I've already tried setting the two divs to display inline block but then they don't stay next to each other and do a line-break instead. I'm relatively new to HTML and CSS so maybe its just a simple beginners fault but I would be gratefull if someone could help me out.

.p {
  background: red;
  width: 100%;
}

.tippsboxright {
  color: rgb(238, 238, 238);
  max-width: 45%;
  margin: 0 0 0 5%;
  float: right;
  font-size: 1.7vw;
  padding: 0;
}

.boxleft {
  max-width: 50%;
}

My header

        This is the right box with text inside of it.

This is the p tag that I want to be at the bottom of the page.

Body:
There are several ways to get this type of layout, and while floating is the oldest and most common, it's not really designed for this type of thing. float is designed for text to flow around the block, like you see in magazines. So that's what you see happening: your text is flowing around the floats. There is a way to stop this though: clear. Clear tells text to not flow around left, right, or both floated objects. So you can use that to get the layout you desire:

.p {
  background: red;
  width: 100%;
  clear: both;
}

.tippsboxright {
  background: lightyellow;
  color: rgb(238, 238, 238);
  max-width: 45%;
  margin: 0 0 0 5%;
  float: right;
  font-size: 1.7vw;
  padding: 0;
}

.boxleft {
  background: lightblue;
  max-width: 50%;
  float: left;
}

<main>
  <header>
    <h1>My header</h1>
  </header>
  <div class="content">
    <div class="boxleft">
      <img src="../images/questionguy.png" alt="Typ mit fragen" class="imgkauftipps">
    </div>
    <div class="tippsboxright">
      <p>
        This is the right box with text inside of it.
      </p>
    </div>
    <p class="p">This is the p tag that I want to be at the bottom of the page.</p>
  </div>
</main>

It is however better and easier to use either flex box or grid layouts in this case. They are designed for block style layouts, which seems to be what you want, not flowing text around blocks.


问:
How can I set up SSO with Azure AD and our back end strapi?
I am wondering if anyone has done this before,

I have an azure Active Directory, and I host the front end of our app in IIS. The back is controlled by pm2. How can I set up SSO with Azure AD and our back end strapi?

Thank you for any help

答:
Strapi supports natively Microsoft SSO.

You must act on three fronts: Azure Portal, Strapi Admin, Frontend App

1 - AZURE Portal: (create application, configure, get params)

1.1 Create application, go to the App registrations site and register an app

1.2 Click New Registration

1.3 Fill the form as show in below ScreenShot

1.3.1 In "Supported account types" set Multitenant option (in strapi, single tenant is not supported by default, if you need to set single tenant you must create a custom provider, but multitenant is ok)

1.3.2 In the Redirect URI field, put "Web" and

/connect/microsoft/callback

```<code>(i.e. http://localhost:1337/connect/microsoft/callback or your strapi
production url https://mystrapiexample.com/connect/microsoft/callback)
</code>```

1.3.3 Register and go to next page

1.4 Go to the "Authentication" page of your registered App (left menu) to enable the implicit grant flow (Access tokens)

1.5 Go to the "Certificate and secrets" page of your registered App (left menu) to create a "New client secret" and annotate the value, You will use it when you configure the provider on strapi.

1.6 Also note the "Application (client) ID" in the Overview page, You will use it when you configure the provider on strapi

2 - STRAPI ADMIN: (create application, configure, get params)

2.1 Go to "Roles and Permission" > Providers > Microsoft

2.2 Set Enable "ON" and your clientId and secret that you get in previous steps (1.5 and 1.6)

2.3 The redirect URI to your front-end app which gets and redirects the microsoft access_code (this step will be clearer later)

3 - FRONTEND APP:

Ready? At this point the flow begins, starts to jump to complete the authentication and obtain a strapi jwt to make the requests as an authenticated user.

3.1 Create a link in your frontend application to strapi microsoft sign-in

/connect/microsoft

```<code>(i.e. http://localhost:1337/connect/microsoft or your strapi
production url https://mystrapiexample.com/connect/microsoft)
</code>```

3.2 Strapi redirects the user to microsoft authentication page, on success the user will be redirected on strapi with a microsoft access_code (this step is transparent for you)

3.3 Strapi redirects the access_code to the frontend url set in 2.3, which must redirect (with access_code) to strapi page auth

/auth/microsoft/callback

```<code>(i.e http://localhost:1337/auth/microsoft/callback or your strapi
production url https://mystrapiexample.com/auth/microsoft/callback ).....
</code>```

3.4 At this point strapi creates its own JWT token which returns to the frontend application, which can store it (in localstorage, session storage...) to make requests to the strapi endpoints.

References

https://github.com/strapi/strapi-examples/blob/master/login-react/doc/microsoft_setup.md

https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow

Body:
Strapi supports natively Microsoft SSO.

You must act on three fronts: Azure Portal, Strapi Admin, Frontend App

1 - AZURE Portal: (create application, configure, get params)

1.1 Create application, go to the App registrations site and register an app

1.2 Click New Registration

1.3 Fill the form as show in below ScreenShot

1.3.1 In "Supported account types" set Multitenant option (in strapi, single tenant is not supported by default, if you need to set single tenant you must create a custom provider, but multitenant is ok)

1.3.2 In the Redirect URI field, put "Web" and

/connect/microsoft/callback

(i.e. http://localhost:1337/connect/microsoft/callback or your strapi
production url https://mystrapiexample.com/connect/microsoft/callback)

1.3.3 Register and go to next page

1.4 Go to the "Authentication" page of your registered App (left menu) to enable the implicit grant flow (Access tokens)

1.5 Go to the "Certificate and secrets" page of your registered App (left menu) to create a "New client secret" and annotate the value, You will use it when you configure the provider on strapi.

1.6 Also note the "Application (client) ID" in the Overview page, You will use it when you configure the provider on strapi

2 - STRAPI ADMIN: (create application, configure, get params)

2.1 Go to "Roles and Permission" > Providers > Microsoft

2.2 Set Enable "ON" and your clientId and secret that you get in previous steps (1.5 and 1.6)

2.3 The redirect URI to your front-end app which gets and redirects the microsoft access_code (this step will be clearer later)

3 - FRONTEND APP:

Ready? At this point the flow begins, starts to jump to complete the authentication and obtain a strapi jwt to make the requests as an authenticated user.

3.1 Create a link in your frontend application to strapi microsoft sign-in

/connect/microsoft

(i.e. http://localhost:1337/connect/microsoft or your strapi
production url https://mystrapiexample.com/connect/microsoft)

3.2 Strapi redirects the user to microsoft authentication page, on success the user will be redirected on strapi with a microsoft access_code (this step is transparent for you)

3.3 Strapi redirects the access_code to the frontend url set in 2.3, which must redirect (with access_code) to strapi page auth

/auth/microsoft/callback

(i.e http://localhost:1337/auth/microsoft/callback or your strapi
production url https://mystrapiexample.com/auth/microsoft/callback ).....

3.4 At this point strapi creates its own JWT token which returns to the frontend application, which can store it (in localstorage, session storage...) to make requests to the strapi endpoints.

References

https://github.com/strapi/strapi-examples/blob/master/login-react/doc/microsoft_setup.md

https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow


问:
Discord.py private messages
I am trying to make a discord bot that sends a DM to someone with a command like:

```<code>!messagesteve hello world
</code>```

and it would send a message directly to the person I want.

I've tried the following, but to no avail:

```<code>@client.command(pass_context=True)
async def dm(ctx):
    user=await client.get_user_info("381870129706958")
    await client.send_message(user, "test")
</code>```

Any help is appreciated.

答:
It seems as though you're using the old docs of d.py (v0.16.x). The most recent version is on rewrite (v1.x).

One of the changes, amongst others, is that context is automatically implied (you don't need pass_context=True) and the syntax for sending messages has changed, as you'll see in the example:

@client.command()
async def dm(ctx, member: discord.Member, *, message):
    try:
        await member.send(message)
    except: # this will error if the user has blocked the bot or has server dms disabled
        await ctx.send("Sorry, that user had DMs disabled!")
    else:
        await ctx.send(f"Successfully sent {member} a DM!")
```

The usage, assuming a prefix of !, the usage of the command will be:

!dm @Skyonimous Hey there, I'm DMing you from a bot!

* in the arguments "consumes rest", which means that the argument that succeeds it (message) will act as one whole argument, no matter the number of spaces, so you can send a whole paragraph to a user if you want!

If there's anything that you want me to clarify, I'll be more than happy to!

References:

Major changes 0.16.x -> 1.x

Recent docs

Member.send()

Context.send()

Title: Discord.py private messages

Body:
I am trying to make a discord bot that sends a DM to someone with a command like:

!messagesteve hello world

and it would send a message directly to the person I want.

I've tried the following, but to no avail:

@client.command(pass_context=True)
async def dm(ctx):
    user=await client.get_user_info("381870129706958")
    await client.send_message(user, "test")

Any help is appreciated.

Body:
It seems as though you're using the old docs of d.py (v0.16.x). The most recent version is on rewrite (v1.x).

One of the changes, amongst others, is that context is automatically implied (you don't need pass_context=True) and the syntax for sending messages has changed, as you'll see in the example:

@client.command()
async def dm(ctx, member: discord.Member, *, message):
    try:
        await member.send(message)
    except: # this will error if the user has blocked the bot or has server dms disabled
        await ctx.send("Sorry, that user had DMs disabled!")
    else:
        await ctx.send(f"Successfully sent {member} a DM!")

The usage, assuming a prefix of !, the usage of the command will be:

!dm @Skyonimous Hey there, I'm DMing you from a bot!

* in the arguments "consumes rest", which means that the argument that succeeds it (message) will act as one whole argument, no matter the number of spaces, so you can send a whole paragraph to a user if you want!

If there's anything that you want me to clarify, I'll be more than happy to!

References:

Major changes 0.16.x -> 1.x

Recent docs

Member.send()

Context.send()


问:
Could I make an API for another website and use it to access that website’s functionality/commands?
For example, let’s say I wanted to create my own Instagram API (I’m aware Instagram has an API but let’s imagine they didn’t and I wanted to make my own for them). Could I make one to post, like photos, DM, etc? Or does Instagram themselves need to make an API to allow me to access these functionality and commands?</p>

答:
You can certainly make one but you could be in violation of the service's Terms of Service (ToS). If you violate the ToS, the service could shut down your access.

In the scenario where someone publishes an unofficial SDK, it can be taken down under DCMA. For example, such a private Instagram API was made and published on GitHub before Facebook filed a DCMA claim with GitHub to have it taken down:

Facebook DCMA Takedown Request:

https://github.com/github/dmca/blob/master/2020/01/2020-01-22-facebook.md

Discussion:

https://news.ycombinator.com/item?id=22209892

Here's an excerpt from the Takedown Request:

Instagram-API repository (and its forks) offers a tool expressly designed to circumvent the Company’s effective access controls and protection measures by avoiding, bypassing, removing, deactivating, or impairing the Company’s technological measures without the authority of the copyright owners or the Company. Mgp25’s Instagram-API is designed to emulate the official Instagram mobile app when communicating with Instagram’s servers, which allows users of mgp25’s Instagram-API to send and receive data (including receiving legitimate, copyrighted posts by Instagram’s users) through Instagram’s private API. Mgp25’s Instagram-API also permits other types of access to, and collection of, Instagram’s users’ copyrighted works in manners that exceed the scope of access and functionality that would be permitted by a user with a legitimate, authorized Instagram account.


问:
How to get source inside exec python
I currently have the problem that I cant use inspect.getsource (OSError: could not get source code) inside code executed through exec().

For example when i feed the following code as a string into exec(code)

import inspect

def sample(p1):
    print(p1)
    return 1

print(inspect.getsource(sample))
```

So does anyone know how i could get the source inside the exec()?

I use python 3.8 64 Bit

Thank you for your answers.

Edit: First of all, thanks for the answers and the help to get the right formating for my question, but the function and the inspect.getsource() have to be inside the exec() string.

答:
If your code is like this:

exec("""\
import inspect

def sample(p1):
    print(p1)
    return 1

print(inspect.getsource(sample))\
""")
```

<p>And the exception is <code>OSError: could not get source code</code> then that probably means that <code>inspect.getsource()</code> requires a
file's source to inspect. <code>exec</code> is a dynamic execution of python code so the <code>sample</code> function that's being defined from <code>exec</code> is not on the file's source!</p>

<p>Something like this:</p>

<pre class="lang-py prettyprint-override"><code>def sample(p1):
    print(p1)
    return 1

exec("""\
import inspect
print(inspect.getsource(sample))\
""")
</code>```

would work because the function sample is defined in the source!

Hope that makes sense and answers your question!

~ PanTrakX

Title: How to get source inside exec python

Body:
I currently have the problem that I cant use inspect.getsource (OSError: could not get source code) inside code executed through exec().

For example when i feed the following code as a string into exec(code)

import inspect

def sample(p1):
    print(p1)
    return 1

print(inspect.getsource(sample))

So does anyone know how i could get the source inside the exec()?

I use python 3.8 64 Bit

Thank you for your answers.

Edit: First of all, thanks for the answers and the help to get the right formating for my question, but the function and the inspect.getsource() have to be inside the exec() string.

Body:
If your code is like this:

exec("""\
import inspect

def sample(p1):
    print(p1)
    return 1

print(inspect.getsource(sample))\
""")

And the exception is OSError: could not get source code then that probably means that inspect.getsource() requires a
file's source to inspect. exec is a dynamic execution of python code so the sample function that's being defined from exec is not on the file's source!

Something like this:

def sample(p1):
    print(p1)
    return 1

exec("""\
import inspect
print(inspect.getsource(sample))\
""")

would work because the function sample is defined in the source!

Hope that makes sense and answers your question!

~ PanTrakX


问:
Read ORC file from S3 to Pandas
I'm trying to read an orc file from s3 into a Pandas dataframe.  In my version of pandas there is no pd.read_orc(...).

I tried to do this:

```<code>session = boto3.Session()
s3_client = session.client('s3')

s3_key = "my_object_key"

data = s3_client.get_object(
    Bucket='my_bucket',
    Key=s3_key
)

orc_bytes = data['Body'].read()
</code>```

Which reads the object as bytes.

Now I try to do this:

```<code>orc_data = pyorc.Reader(orc_bytes)
</code>```

But it fails because:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-deaabe8232ce> in <module>
----> 1 data = pyorc.Reader(orc_data)

/anaconda3/envs/linear_opt_3.7/lib/python3.7/site-packages/pyorc/reader.py in __init__(self, fileo, batch_size, column_indices, column_names, struct_repr, converters)
     65             conv = converters
     66         super().__init__(
---> 67             fileo, batch_size, column_indices, column_names, struct_repr, conv
     68         )
     69

TypeError: Parameter must be a file-like object, but `<class 'bytes'>` was provided
</code>```

Eventually I would like to land it as .csv or something I can read into pandas.   Is there a better way to do this?

答:
Try wrapping the S3 data in an io.BytesIO:

```<code>import io

orc_bytes = io.BytesIO(data['Body'].read())
orc_data = pyorc.Reader(orc_bytes)
</code>```

Title: Read ORC file from S3 to Pandas

Body:
I'm trying to read an orc file from s3 into a Pandas dataframe.  In my version of pandas there is no pd.read_orc(...).

I tried to do this:

session = boto3.Session()
s3_client = session.client('s3')

s3_key = "my_object_key"

data = s3_client.get_object(
    Bucket='my_bucket',
    Key=s3_key
)

orc_bytes = data['Body'].read()

Which reads the object as bytes.

Now I try to do this:

orc_data = pyorc.Reader(orc_bytes)

But it fails because:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-deaabe8232ce> in <module>
----> 1 data = pyorc.Reader(orc_data)

/anaconda3/envs/linear_opt_3.7/lib/python3.7/site-packages/pyorc/reader.py in __init__(self, fileo, batch_size, column_indices, column_names, struct_repr, converters)
     65             conv = converters
     66         super().__init__(
---> 67             fileo, batch_size, column_indices, column_names, struct_repr, conv
     68         )
     69

TypeError: Parameter must be a file-like object, but `<class 'bytes'>` was provided

Eventually I would like to land it as .csv or something I can read into pandas.   Is there a better way to do this?

Body:
Try wrapping the S3 data in an io.BytesIO:

import io

orc_bytes = io.BytesIO(data['Body'].read())
orc_data = pyorc.Reader(orc_bytes)


问:
outlook autocomplete emails in python
I have a list of IDs that I need to turn into emails, but all of the addresses are the same, but all the IDs are unique. If I was in outlook I could just press ctrl K and have the address autocompleted. Is there a way to have similar functionality in python if the address path isn't readily available?
This is what I currently have in a loop. It works if I add the @PATH.com, but not all the addresses are "@PATH.com"....</p>

```<code>import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = U_ID  #This is what the address path need to be completed
mail.Subject = 'auto email test'
mail.Body = "body"
mail.send
</code>```

答:
You need to use the Recipients property of the MailItem class which returns a Recipients collection that represents all the recipients for the Outlook item. The Add method creates a new recipient in the Recipients collection. A recipient can be specified by a string representing the recipient's display name, alias, or full SMTP email address. But in this case, you can use the Resolve method which attempts to resolve a Recipient object against the Address Book. For example, a sample VBA script look like this:

```<code>Sub AssignTask()
 Dim myItem As Outlook.TaskItem
 Dim myDelegate As Outlook.Recipient

 Set MyItem = Application.CreateItem(olTaskItem)

 MyItem.Assign

 Set myDelegate = MyItem.Recipients.Add("Eugene Astafiev")

 myDelegate.Resolve

 If myDelegate.Resolved Then
    myItem.Subject = "Prepare Agenda For Meeting"
    myItem.DueDate = Now + 30
    myItem.Display
    myItem.Send
 End If

End Sub
</code>```

Title: outlook autocomplete emails in python

Body:
I have a list of IDs that I need to turn into emails, but all of the addresses are the same, but all the IDs are unique. If I was in outlook I could just press ctrl K and have the address autocompleted. Is there a way to have similar functionality in python if the address path isn't readily available?
This is what I currently have in a loop. It works if I add the @PATH.com, but not all the addresses are "@PATH.com"....

import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = U_ID  #This is what the address path need to be completed
mail.Subject = 'auto email test'
mail.Body = "body"
mail.send

Body:
You need to use the Recipients property of the MailItem class which returns a Recipients collection that represents all the recipients for the Outlook item. The Add method creates a new recipient in the Recipients collection. A recipient can be specified by a string representing the recipient's display name, alias, or full SMTP email address. But in this case, you can use the Resolve method which attempts to resolve a Recipient object against the Address Book. For example, a sample VBA script look like this:

Sub AssignTask()
 Dim myItem As Outlook.TaskItem
 Dim myDelegate As Outlook.Recipient

 Set MyItem = Application.CreateItem(olTaskItem)

 MyItem.Assign

 Set myDelegate = MyItem.Recipients.Add("Eugene Astafiev")

 myDelegate.Resolve

 If myDelegate.Resolved Then
    myItem.Subject = "Prepare Agenda For Meeting"
    myItem.DueDate = Now + 30
    myItem.Display
    myItem.Send
 End If

End Sub


问:
Dynamic WHERE clause in a stored procedure
I'm trying to find the best possible way to have a dynamic WHERE clause in my stored proc.

I have a few parameters that are passed into the STORED PROC from another process, the one I need to use is called @Param and it can either be 'M' or 'D'

I'm trying to use the @Param to distinguish whether it is 'M' or 'D' and based on the value I want to be able to add a filter. Simplified query below:

```<code>Select Val1, Val2, Val3, Val4 from a tbl1
where 1=1 and SomeField in ('APPLE','HP')
--Now I'm thinking - One way of doing this - I'm not sure if I need all this...
AND 1 = (CASE WHEN (@Param='M' and Val1 <= @ParamDate) THEN 1
          WHEN (@Param='D' and Val1 <= DATEADD(mm,DATEDIFF(mm,-1,@ParamDate),-1)) THEN 1
          ELSE 0
     END)

--Another way I'm thinking is
AND ((Val1 <= @ParamDate and @Param = 'M') or NOT @Param='M')
AND ((Val1 <= DATEADD(mm,DATEDIFF(mm,-1,@ParamDate),-1) and @Param='D') or NOT @Param='D')

AND --Other parts of the where clause
</code>```

I'm trying to find the best possible way of doing this. Either one of them makes more sense or maybe there's a different way of accomplishing this. I'm looking to do this in the most practical way and to have it be readable as this is a very long query.

答:
I would recommend using boolean logic rather than a case expression. This makes the intent clearer. If I followed you correctly, the logic should be:

```<code>select val1, val2, val3, val4
from a tbl1
where
    somefield in ('apple','hp')
    and (
        (@param='m' and val1 <= @paramdate)
        or (@param='d' and val1 <= dateadd(mm,datediff(mm,-1,@paramdate),-1))
    )
</code>```

The inner parentheses around the and conditions are actually not needed, but using them makes it easier to understand how conditions intricate.

Body:
I'm trying to find the best possible way to have a dynamic WHERE clause in my stored proc.

I have a few parameters that are passed into the STORED PROC from another process, the one I need to use is called @Param and it can either be 'M' or 'D'

I'm trying to use the @Param to distinguish whether it is 'M' or 'D' and based on the value I want to be able to add a filter. Simplified query below:

Select Val1, Val2, Val3, Val4 from a tbl1
where 1=1 and SomeField in ('APPLE','HP')
--Now I'm thinking - One way of doing this - I'm not sure if I need all this...
AND 1 = (CASE WHEN (@Param='M' and Val1 <= @ParamDate) THEN 1
          WHEN (@Param='D' and Val1 <= DATEADD(mm,DATEDIFF(mm,-1,@ParamDate),-1)) THEN 1
          ELSE 0
     END)

--Another way I'm thinking is
AND ((Val1 <= @ParamDate and @Param = 'M') or NOT @Param='M')
AND ((Val1 <= DATEADD(mm,DATEDIFF(mm,-1,@ParamDate),-1) and @Param='D') or NOT @Param='D')

AND --Other parts of the where clause

I'm trying to find the best possible way of doing this. Either one of them makes more sense or maybe there's a different way of accomplishing this. I'm looking to do this in the most practical way and to have it be readable as this is a very long query.

Body:
I would recommend using boolean logic rather than a case expression. This makes the intent clearer. If I followed you correctly, the logic should be:

select val1, val2, val3, val4
from a tbl1
where
    somefield in ('apple','hp')
    and (
        (@param='m' and val1 <= @paramdate)
        or (@param='d' and val1 <= dateadd(mm,datediff(mm,-1,@paramdate),-1))
    )

The inner parentheses around the and conditions are actually not needed, but using them makes it easier to understand how conditions intricate.


问:
CSS banner not properly accommodating in page
I'm having a bit of CSS trouble with some banners.

I have two banners (not sticky) at the top and bottom of the page, the top banner works like a charm. I am having issues with the bottom banner.

The banner is not at the bottom of the page; here's what I've tried.

Wrapping my banner
 in the  tag - that didn't work.

Using position: relative;- now this sets the banner to the bottom of the page - but it doesn't extend the banner through all of the page and puts some kind of margin on the sides.

Setting it manually - but of course, only works for my screen.

Here's my CSS:

```<code>div#bannerbtm {
    position: absolute;
    bottom:0%;
    left:0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}
div#bannertop {
  position: absolute;
  top: 0;
  left: 0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}
</code>```

and, here's the relevant HTML:

```<code><body>

<div id="bannertop">
    <div id="banner-content"></div>
</div>

<div> <!-- Page Content --> </div>

<div id="bannerbtm">
    <div id="banner-content"></div>
</div>

</body>
</code>```

Thanks in advance for any and all input; this has been driving me nuts.

答:
The problem is that your body and html elements are not actually the full height of the page. The following css will ensure that your body tag is always at least the height of the screen, thereby ensuring that the bottom banner is at the bottom of the screen.

```<code>body {
  min-height: 100vh;
}
</code>```

Body:
I'm having a bit of CSS trouble with some banners.

I have two banners (not sticky) at the top and bottom of the page, the top banner works like a charm. I am having issues with the bottom banner.

The banner is not at the bottom of the page; here's what I've tried.

Wrapping my banner
 in the  tag - that didn't work.

Using position: relative;- now this sets the banner to the bottom of the page - but it doesn't extend the banner through all of the page and puts some kind of margin on the sides.

Setting it manually - but of course, only works for my screen.

Here's my CSS:

div#bannerbtm {
    position: absolute;
    bottom:0%;
    left:0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}
div#bannertop {
  position: absolute;
  top: 0;
  left: 0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}

and, here's the relevant HTML:

Thanks in advance for any and all input; this has been driving me nuts.

Body:
The problem is that your body and html elements are not actually the full height of the page. The following css will ensure that your body tag is always at least the height of the screen, thereby ensuring that the bottom banner is at the bottom of the screen.

body {
  min-height: 100vh;
}


问:
How to use Chrome Profiles through Headless Chrome using Selenium and Python
```<code>def __init__(self):
        options = webdriver.ChromeOptions()
        options.add_argument("user-data-dir=bot_data")
        options.add_argument("--headless") # Runs Chrome in headless mode.
        options.add_argument('--no-sandbox') # Bypass OS security model
        options.add_argument('--disable-gpu')  # applicable to windows os only
        options.add_argument('start-maximized') #
        options.add_argument('disable-infobars')
        options.add_argument("--disable-extensions")
        # self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
        self.driver = webdriver.Chrome('chromedriver.exe',
                                               options=options)
        self.driver.get('https://www.google.com')
        self.wait = WebDriverWait(self.driver, 10)
</code>```

There is have my codes. I want to change it to headless browser. But i am getting an error.

I added screenshot to show error.

答:
This error message...

```<code>ERROR:devtools_http_handler.cc(288)] Error writing DevTools active port to file
</code>```

...implies that there was an error while writing DevTools active port to the required file.

As per the discussion in How to open a Chrome Profile through Python instead of specifying only the directory name through user-data-dir, you need to pass the absolute path of the user-data-dir.

Solution

So you need to replace the line of code:

```<code>options.add_argument("user-data-dir=bot_data")
</code>```

With:

```<code>options.add_argument("user-data-dir=C:\\Users\\AtechM_03\\AppData\\Local\\Google\\Chrome\\User Data\\bot_data")
</code>```

Reference

You can find a couple of relevant discussions in:

How to use Chrome Profile in Selenium Webdriver Python 3

Selenium: Point towards default Chrome session

Outro

A couple of relevant documentations:

Session isolation in Headless Chrome

headless: Introduce a browser context

Save and restore browser sessions

Headless maintains a different profile folder structure to headful

Body:
def __init__(self):
        options = webdriver.ChromeOptions()
        options.add_argument("user-data-dir=bot_data")
        options.add_argument("--headless") # Runs Chrome in headless mode.
        options.add_argument('--no-sandbox') # Bypass OS security model
        options.add_argument('--disable-gpu')  # applicable to windows os only
        options.add_argument('start-maximized') #
        options.add_argument('disable-infobars')
        options.add_argument("--disable-extensions")
        # self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
        self.driver = webdriver.Chrome('chromedriver.exe',
                                               options=options)
        self.driver.get('https://www.google.com')
        self.wait = WebDriverWait(self.driver, 10)

There is have my codes. I want to change it to headless browser. But i am getting an error.

I added screenshot to show error.

Body:
This error message...

ERROR:devtools_http_handler.cc(288)] Error writing DevTools active port to file

...implies that there was an error while writing DevTools active port to the required file.

As per the discussion in How to open a Chrome Profile through Python instead of specifying only the directory name through user-data-dir, you need to pass the absolute path of the user-data-dir.

Solution

So you need to replace the line of code:

options.add_argument("user-data-dir=bot_data")

With:

options.add_argument("user-data-dir=C:\\Users\\AtechM_03\\AppData\\Local\\Google\\Chrome\\User Data\\bot_data")

Reference

You can find a couple of relevant discussions in:

How to use Chrome Profile in Selenium Webdriver Python 3

Selenium: Point towards default Chrome session

Outro

A couple of relevant documentations:

Session isolation in Headless Chrome

headless: Introduce a browser context

Save and restore browser sessions

Headless maintains a different profile folder structure to headful


问:
jupyter notebook won't show images
```<code>#%%

from Utils.ConfigProvider import ConfigProvider
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
config = ConfigProvider.config()
</code>```

and

```<code>#%%

inspected = cv2.imread(config.data.inspected_image_path, 0)
reference = cv2.imread(config.data.reference_image_path, 0)
diff = np.abs(inspected - reference)

plt.figure()
plt.title('inspected')
plt.imshow(inspected)

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

note config.data.inspected_image_path and config.data.reference_image_path are valid paths.

No errors appear, but no images are shown as well.

Running the same code from a python file does show the image.

I have something missing from the notebook.

This happens both when running using jupyter notebook and directly from PyCharm (pro)

How do I get to see images? all other answers I found just tell me to plt.show() but this obviously does not work.

I don't mind a cv2 solution as well.

答:
You need to set a matplotlib backend.

You can do this with

```<code>%matplotlib inline
</code>```

If you want to be able to interact with the plot, use

```<code>%matplotlib notebook
</code>```

Title: jupyter notebook won't show images

Body:
#%%

from Utils.ConfigProvider import ConfigProvider
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
config = ConfigProvider.config()

and

#%%

inspected = cv2.imread(config.data.inspected_image_path, 0)
reference = cv2.imread(config.data.reference_image_path, 0)
diff = np.abs(inspected - reference)

plt.figure()
plt.title('inspected')
plt.imshow(inspected)

plt.show()

note config.data.inspected_image_path and config.data.reference_image_path are valid paths.

No errors appear, but no images are shown as well.

Running the same code from a python file does show the image.

I have something missing from the notebook.

This happens both when running using jupyter notebook and directly from PyCharm (pro)

How do I get to see images? all other answers I found just tell me to plt.show() but this obviously does not work.

I don't mind a cv2 solution as well.

Body:
You need to set a matplotlib backend.

You can do this with

%matplotlib inline

If you want to be able to interact with the plot, use

%matplotlib notebook


问:
MSB3021 Unable to copy file could not find part of path error when running Service Fabric app in Visual Studio
I have a Service Fabric solution that contains multiple projects. I can run all but one of them on my local cluster without issue, but one particular project will not deploy due to the following issue:

MSB3021   Unable to copy file
  "C:\Path\To\Repo\src\MyProject\MyService\obj\Debug\netcoreapp2.1\win7-x64\PubTmp\Out\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll"
  to
  "C:\Path\To\Repo\src\MyProject\MyService\pkg\Debug\MyServicePkg\Code\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll".
  Could not find a part of the path
  'C:\Path\To\Repo\src\MyProject\MyService\pkg\Debug\MyServicePkg\Code\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll'.

There are two other errors reporting the same issue for Microsoft.Extensions.Configuration.EnvironmentVariables.dll and runtimeconfig.json and 30 warnings stating the same issue for random dlls.

I have done all the usual several times:

Deleted all bin, obj and pkg directories

Stopped local cluster

Restarted Visual Studio

Restarted machine

Checked out repo in a separate directory

The error states that it cannot find part of the path to the Code dir in pkg, but I have verified that it does exist.

It is strange that this only affects 1 out of several projects. Am I missing anything obvious here?

答:
PATH TOO LONG.

It is almost surely that those paths that are failing are suddenly TOO LONG.
That is why moving the repo to the root of your user directory did the trick.
It also explains the seeming random nature of the failures and the phenomenon of some projects working and others not; Some have paths that are to long while others don't.

If you copy the failing paths from your output window and paste them in to File Exploder they work fine.

But if you experiment with them from the command line or in a batch file they'll fail.
I'd put money on that being the problem.


问:
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>

答:
MSVC (the Visual Studio compiler/linker) can do this if you compile with /Gy and link with /OPT:REF.

GCC/binutils can do this if you compile with -ffunction-sections -fdata-sections and link with --gc-sections.

Don't know about other compilers.

Title: Do unused functions get optimized out?


问:
Value was either too large or too small for a UInt32 Error on iOS WKWebView & Uno 2.4
I have an Uno WebAssembly app at here, you can try it now.
Button click events not fire and doing nothing sometimes both on iOS and iPadOS WKWebview. They rarely work without problems. Sometimes cleaning web cache from Settings / Safari / Advanced Settings is solves problem. Unfortunately, this error is coming up again soon.

I have not any issue on desktop browser, the app running smoothly. I have iPhone X, iPad and iPhone 6. . The app works rarely without problems on X. Seems not run on others. The WebAssembly log on iOS is here.

Is it depends on device RAM size on Apple Device ? The app runs just perfectly on Android WebView.

答:
Make sure to update to Uno 2.4.4 or later, which contains a fix for pointers management for Safari on iOS.

Safari for iOS can return pointers being negative, which was causing trouble to the pointer management system in Uno. See this Pull Request for more information.


问:
Disable placeholder text to be read by all accessibility API(screen reader)
Some screen readers read placeholder value and some do not. Is there a way in which reading placeholder value can be disabled for All screen reader(in context with HTML input). Especially the IOS screen reader reads placeholder value, in that case, the same information repeated twice.

What I want is to show placeholders for screen users and hidden labels for screen reader users.

Edit: When I asked the question it was the first time working on accessibility, to just fix an issue. On further exploration, I find out that we can just use a hidden label and associate it with the input element using for the attribute. Here the w3 documentation link.

答:
According to Understanding Success Criterion 2.5.3: Label in Name

As such, in the absence of any other nearby text string (as described in the preceding list), if an input contains placeholder text, such text may be a candidate for Label in Name. This is supported both through the accessible name calculation (discussed later) and from the practical sense that where a visible label is not otherwise provided, it is likely that a speech-input user may attempt to use the placeholder text value as a means of interacting with the input.

As long as you do not provide a visual label, the placeholder text is used by assistive technologies (speech-input for instance). Disabling input-assistance to provide more user experience to output-assistance is counter-productive.

You perfectly can use a visual label which emulates the placeholder behaviour when the field is empty (with appropriate precautions to make the fields usable with input assistance once the field is filled).


问:
Expected '(', '{' or <string>, got 'GUI'
I was following a loading screen tutorial but it seems that a part of the code is wrong.</p>

```<code>game.ReplicatedFirst:RemoveDefaultLoadingScreen()

local PlayerGui = game.Players.LocalPlayer:WaitForChild("PlayerGui")
PlayerGui:SetTopBarTransparency(0)

local GUI = script.LoadingScreen:Clone
GUI.Parent = PlayerGui --<<-- This part of the script is the part that is causing it

repeat wait(1) until game:IsLoaded()

GUI.Frame:TweenPosition(UDim2.new(0, 0, 1,0),"InOut","Sine",0.5)
wait(0.5)
GUI:Destroy()
</code>```

答:
Your error message is telling you that it expected some parentheses, but instead found the next line.
Clone is a function, and needs to be called like one :

```<code>local GUI = script.LoadingScreen:Clone()
</code>```

Body:
I was following a loading screen tutorial but it seems that a part of the code is wrong.

game.ReplicatedFirst:RemoveDefaultLoadingScreen()

local PlayerGui = game.Players.LocalPlayer:WaitForChild("PlayerGui")
PlayerGui:SetTopBarTransparency(0)

local GUI = script.LoadingScreen:Clone
GUI.Parent = PlayerGui --<<-- This part of the script is the part that is causing it

repeat wait(1) until game:IsLoaded()

GUI.Frame:TweenPosition(UDim2.new(0, 0, 1,0),"InOut","Sine",0.5)
wait(0.5)
GUI:Destroy()

Body:
Your error message is telling you that it expected some parentheses, but instead found the next line.
Clone is a function, and needs to be called like one :

local GUI = script.LoadingScreen:Clone()