问:
Remove unwanted parts from strings in Dataframe
I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.

My dataframe:

```<code>     Passengers

1    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
2    Sally Muller, President, Mark Smith, Vicepresident
3    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    Sally Muller, President, John Doe, Chief of Staff, Peter Parker, Special Effects, Lydia Johnson, Vice Chief of Staff
...
</code>```

desired form of df:

```<code>     Passengers

1    Sally Muller, Mark Smith, John Doe
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...
</code>```

Up to now I did it with endless handmade copy/paste regex list:

```<code>df = df.replace(r'President,','', regex=True)
df = df.replace(r'Vicepresident,','', regex=True)
df = df.replace(r'Chief of Staff,','', regex=True)
df = df.replace(r'Special Effects,','', regex=True)
df = df.replace(r'Vice Chief of Staff,','', regex=True)
...
</code>```

Is there a more comfortable way to do this?

Edit

More accurate example of original df:

```<code>     Passengers

1    Sally Muller, President, EL Mark Smith, John Doe, Chief of Staff,  Peter Gordon, Director of Central Command
2    Sally Muller, President, EL Mark Smith, Vicepresident
3    Sally Muller, President, EL Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Gordon, Dir CC
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    President Sally Muller, John Doe Chief of Staff, Peter Parker, Special Effects, Lydia Johnson , Vice Chief of Staff
...
</code>```

desired form of df:

```<code>     Passengers

1    Sally Muller, Mark Smith, John Doe, Peter Gordon
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...
</code>```

Up to now I did it with endless handmade copy/paste regex list:

```<code>df = df.replace(r'President','', regex=True)
df = df.replace(r'Director of Central Command,','', regex=True)
df = df.replace(r'Dir CC','', regex=True)
df = df.replace(r'Vicepresident','', regex=True)
df = df.replace(r'Chief of Staff','', regex=True)
df = df.replace(r'Special Effects','', regex=True)
df = df.replace(r'Vice Chief of Staff','', regex=True)
...
</code>```

messy output is like:

```<code>     Passengers

1    Sally Muller, , Mark Smith, John Doe, , Peter Gordon,
2    Sally Muller, Mark Smith,
3    Sally Muller, Mark Smith,, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller,, John Doe, Peter Parker , Lydia Johnson,
...
</code>```

答:
We can create a full regex pattern match on every string you need to remove and replace.

This can handle situations were the passengers will not have a title.

```<code>df2 = df['Passengers'].str.replace("(President)|(Vicepresident)|(Chief of Staff)|(Special Effects)|(Vice Chief of Staff)", "",regex=True).replace("( ,)", "", regex=True).str.strip().str.rstrip(",")
</code>```

Body:
I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.

My dataframe:

     Passengers

1    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
2    Sally Muller, President, Mark Smith, Vicepresident
3    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    Sally Muller, President, John Doe, Chief of Staff, Peter Parker, Special Effects, Lydia Johnson, Vice Chief of Staff
...

desired form of df:

     Passengers

1    Sally Muller, Mark Smith, John Doe
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...

Up to now I did it with endless handmade copy/paste regex list:

df = df.replace(r'President,','', regex=True)
df = df.replace(r'Vicepresident,','', regex=True)
df = df.replace(r'Chief of Staff,','', regex=True)
df = df.replace(r'Special Effects,','', regex=True)
df = df.replace(r'Vice Chief of Staff,','', regex=True)
...

Is there a more comfortable way to do this?

Edit

More accurate example of original df:

     Passengers

1    Sally Muller, President, EL Mark Smith, John Doe, Chief of Staff,  Peter Gordon, Director of Central Command
2    Sally Muller, President, EL Mark Smith, Vicepresident
3    Sally Muller, President, EL Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Gordon, Dir CC
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    President Sally Muller, John Doe Chief of Staff, Peter Parker, Special Effects, Lydia Johnson , Vice Chief of Staff
...

desired form of df:

     Passengers

1    Sally Muller, Mark Smith, John Doe, Peter Gordon
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...

Up to now I did it with endless handmade copy/paste regex list:

df = df.replace(r'President','', regex=True)
df = df.replace(r'Director of Central Command,','', regex=True)
df = df.replace(r'Dir CC','', regex=True)
df = df.replace(r'Vicepresident','', regex=True)
df = df.replace(r'Chief of Staff','', regex=True)
df = df.replace(r'Special Effects','', regex=True)
df = df.replace(r'Vice Chief of Staff','', regex=True)
...

messy output is like:

     Passengers

1    Sally Muller, , Mark Smith, John Doe, , Peter Gordon,
2    Sally Muller, Mark Smith,
3    Sally Muller, Mark Smith,, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller,, John Doe, Peter Parker , Lydia Johnson,
...

Body:
We can create a full regex pattern match on every string you need to remove and replace.

This can handle situations were the passengers will not have a title.

df2 = df['Passengers'].str.replace("(President)|(Vicepresident)|(Chief of Staff)|(Special Effects)|(Vice Chief of Staff)", "",regex=True).replace("( ,)", "", regex=True).str.strip().str.rstrip(",")


来源: stackexchange

问:
Help loading images into Galleria dynamically
I am building a site with the gallery as the main feature, and I need the gallery to have "categories". I am going to load in the images via AJAX but at the moment just getting the Galleria gallery to load in different images is proving challenging. My code is as follows:

```<code>function swap_gallery() {
    var new_slideshow = [
        { image: '../images/slideshow/architecture_3.jpg' },
        { image: '../images/slideshow/report_1.jpg' }
    ];
    Galleria.get(0).load({
        data_source: new_slideshow
    });
}
</code>```

When I run this function I get this error in Firebug:

Error: Load failed: no data found.

For the life of me I can't work this one out.

答:
Just push the new values as you would do for an array.

Galleria.get(0).push({image: '../images/slideshow/architecture_3.jpg'});

Galleria API #Manipulation http://galleria.aino.se/docs/1.2/api/methods/

ContentLicense: CC BY-SA 3.0

Body:
I am building a site with the gallery as the main feature, and I need the gallery to have "categories". I am going to load in the images via AJAX but at the moment just getting the Galleria gallery to load in different images is proving challenging. My code is as follows:

function swap_gallery() {
    var new_slideshow = [
        { image: '../images/slideshow/architecture_3.jpg' },
        { image: '../images/slideshow/report_1.jpg' }
    ];
    Galleria.get(0).load({
        data_source: new_slideshow
    });
}

When I run this function I get this error in Firebug:

Error: Load failed: no data found.

For the life of me I can't work this one out.


问:
Screen is getting freezed when clicking on a drop down button using testcafe automation

Targeted element is //input[@id='add-to-wishlist-button']

When i click the element drop down box the screen gets hanged in both chrome and firefox browser.
Chrome Browsers verison is Version 97.0.4692.99
Testcafe version is testcafe@1.18.1

答: The information you provided is insufficient. Try updating to the latest TestCafe version.  If the problem still persists, i suggest you create an issue in the TestCafe GitHub repository and add required information and sample code to reproduce the issue.</p>

ContentLicense: CC BY-SA 4.0


问:
Can I add a "Counter" within a FOR loop?
I have a little batch file (see below) that does what the REM statement says.

When executed it displays each filename in turn as it's being processed (with a progress bar (of sorts) as the file is 're-written' to disk) but I would also like it to display a "counter" (starting at 1) that increments with each file processed so that when the final file is processed the counter will then display the total number of files that have been processed.

Is there any simple change I could make to achieve this?  (I am not a coder, the batch file was given to me by someone else with whom I have lost contact.)

```<code>REM --ooOO  This adds c.365ms silence to all mp4 video files in the folder (adding 364 bytes to file size)  OOoo--

for %%a in (*.mp4) do mp4box "%%a" -add 0.2sSilenceM.mp3
pause
</code>```

答:
To implement a counter is quite easy:

```<code>setlocal enabledelayedexpansion
set counter=0
for %%a in (*.mp4) do (
  set /a counter+=1
  echo processing file !counter!: %%a
  mp4box "%%a" -add 0.2sSilenceM.mp3
)
echo total processed files: %counter%
</code>```

You need delayed expansion to use the counter inside the loop.

Body:
I have a little batch file (see below) that does what the REM statement says.

When executed it displays each filename in turn as it's being processed (with a progress bar (of sorts) as the file is 're-written' to disk) but I would also like it to display a "counter" (starting at 1) that increments with each file processed so that when the final file is processed the counter will then display the total number of files that have been processed.

Is there any simple change I could make to achieve this?  (I am not a coder, the batch file was given to me by someone else with whom I have lost contact.)

REM --ooOO  This adds c.365ms silence to all mp4 video files in the folder (adding 364 bytes to file size)  OOoo--

for %%a in (*.mp4) do mp4box "%%a" -add 0.2sSilenceM.mp3
pause

Body:
To implement a counter is quite easy:

setlocal enabledelayedexpansion
set counter=0
for %%a in (*.mp4) do (
  set /a counter+=1
  echo processing file !counter!: %%a
  mp4box "%%a" -add 0.2sSilenceM.mp3
)
echo total processed files: %counter%

You need delayed expansion to use the counter inside the loop.


问:
How to get the intersection of two sets while recognizing equal set values/items not only by reference but by their equal structures and entries too?
I have two deal with two Set instances.

```<code>const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' },
]);

const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);
</code>```

Any object within a set will feature several and also distinct keys and values. The goal is to find structurally equal objects (same keys and values) in both sets, which is ... The intersection of equal data items in/of set1 and set2.

In the following example the expected result is [ { name: 'd' } ] ...

```<code>console.log([...set1].filter(item => set2.has(item)));
</code>```

... but it logs an empty array / [] instead.

An object features more than 20 keys so one has to compare them one by one, which can not be done in a hard coded way.

How could one achieve a generic approach for an intersection of two lists of structurally equal data items?

答:
You can do something like this:

const set1 = new Set([
    {name: 'a'},
    {name: 'b', lastname: 'bb'},
    {name: 'c'},
    {name: 'd'}
]);

const set2 = new Set([
    {name: 'b'},
    {name: 'd'}
]);

set1.forEach((value) => {
    if (![...set2].some((o) => Object.entries(o).every(([k, v], _, arr) => (Object.keys(value).length === arr.length && value[k] === v)))) {
        set1.delete(value);
    }
})

console.log([...set1]);```

What this does, is to iterate through set1 and if the item at the current iteration is not the same as any item in set2 (![...set2].some(..)), it is deleted.
The items are considered the same if they have the same number of keys and if the values at the same key are strictly equal.

This only works if the values of the objects in the sets are primitives, if they are not, you'll have to change value[k] === v to an appropriate comparison.

Body:
I have two deal with two Set instances.

const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' },
]);

const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);

Any object within a set will feature several and also distinct keys and values. The goal is to find structurally equal objects (same keys and values) in both sets, which is ... The intersection of equal data items in/of set1 and set2.

In the following example the expected result is [ { name: 'd' } ] ...

console.log([...set1].filter(item => set2.has(item)));

... but it logs an empty array / [] instead.

An object features more than 20 keys so one has to compare them one by one, which can not be done in a hard coded way.

How could one achieve a generic approach for an intersection of two lists of structurally equal data items?

Body:
You can do something like this:

const set1 = new Set([
    {name: 'a'},
    {name: 'b', lastname: 'bb'},
    {name: 'c'},
    {name: 'd'}
]);

const set2 = new Set([
    {name: 'b'},
    {name: 'd'}
]);

set1.forEach((value) => {
    if (![...set2].some((o) => Object.entries(o).every(([k, v], _, arr) => (Object.keys(value).length === arr.length && value[k] === v)))) {
        set1.delete(value);
    }
})

console.log([...set1]);

What this does, is to iterate through set1 and if the item at the current iteration is not the same as any item in set2 (![...set2].some(..)), it is deleted.
The items are considered the same if they have the same number of keys and if the values at the same key are strictly equal.

This only works if the values of the objects in the sets are primitives, if they are not, you'll have to change value[k] === v to an appropriate comparison.


问:
Make Kotlin warn on assignment of flexible/platform type to non-null type?
When calling a non-nullability-annotated Java function from Kotlin, we get flexible-typed return values, denoted by exclamation marks, e.g. String!.

Kotlin silently allows assigning these flexible values to a normal non-null type, e.g. String, which can cause NullPointerExceptions at runtime.

I would prefer to get compiler warnings or errors for such assignments. Alternatively, treat platform types as equivalent to nullable types (e.g. String?).

As an example, with this Java code:

```<code>import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class NullTest {

    private String maybe() {
        if (SystemClock.elapsedRealtimeNanos() % 2 == 0) {
            return null;
        }
        return "ok";
    }

    public String annotatedNothing()            { return maybe(); }
    @Nullable public String annotatedNullable() { return maybe(); }
    @NonNull  public String annotatedNonNull()  { return "ok"; }

}
</code>```

...and the following Kotlin code, I'd like to get errors on two new lines (see comments):

```<code>fun testnulls() {
    val obj = NullTest()

    val nullExact: String  = obj.annotatedNullable() // already gives an error
    val nullMaybe: String? = obj.annotatedNullable()
    val nullInfer          = obj.annotatedNullable()

    val okayExact: String  = obj.annotatedNonNull()
    val okayMaybe: String? = obj.annotatedNonNull()
    val okayInfer          = obj.annotatedNonNull()

    val bareExact: String  = obj.annotatedNothing() // I want a compiler error here
    val bareMaybe: String? = obj.annotatedNothing()
    val bareInfer          = obj.annotatedNothing()

    print("length " + nullExact.length)
    print("length " + nullMaybe.length) // already gives an error
    print("length " + nullInfer.length) // already gives an error

    print("length " + okayExact.length)
    print("length " + okayMaybe.length) // already gives an error
    print("length " + okayInfer.length)

    print("length " + bareExact.length)
    print("length " + bareMaybe.length) // already gives an error
    print("length " + bareInfer.length) // I want a compiler error here
}
</code>```

The point is that this will force me to add null checks or !!, making sure that I at least have to be explicit about it.

Is this possible?

In the comments of this 2014 JetBrains blog post, when they introduced platform/flexible types, it sounds like they were planning to add an option to warn about exactly these situations, but I haven't been able to find any further information on that.

答:
I did some research and found some interesting links.

First as others have mentioned it seems like the Kotlin developers wants to avoid false positives and here is a discussion on adding a compile time option to mark platform type usage:
https://youtrack.jetbrains.com/issue/KTIJ-6891
Which the kotlin team seems reluctant to add.

However I found that the developers of detekt (a static code analysis tool for kotlin) have an open issue on adding detection of platform type usage:
https://github.com/detekt/detekt/issues/3603

And it seems like they are relatively close to adding this.
https://github.com/detekt/detekt/pull/4470/files

So hopefully that will help developers catch those NPE's before the users does.

Body:
When calling a non-nullability-annotated Java function from Kotlin, we get flexible-typed return values, denoted by exclamation marks, e.g. String!.

Kotlin silently allows assigning these flexible values to a normal non-null type, e.g. String, which can cause NullPointerExceptions at runtime.

I would prefer to get compiler warnings or errors for such assignments. Alternatively, treat platform types as equivalent to nullable types (e.g. String?).

As an example, with this Java code:

import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class NullTest {

    private String maybe() {
        if (SystemClock.elapsedRealtimeNanos() % 2 == 0) {
            return null;
        }
        return "ok";
    }

    public String annotatedNothing()            { return maybe(); }
    @Nullable public String annotatedNullable() { return maybe(); }
    @NonNull  public String annotatedNonNull()  { return "ok"; }

}

...and the following Kotlin code, I'd like to get errors on two new lines (see comments):

fun testnulls() {
    val obj = NullTest()

    val nullExact: String  = obj.annotatedNullable() // already gives an error
    val nullMaybe: String? = obj.annotatedNullable()
    val nullInfer          = obj.annotatedNullable()

    val okayExact: String  = obj.annotatedNonNull()
    val okayMaybe: String? = obj.annotatedNonNull()
    val okayInfer          = obj.annotatedNonNull()

    val bareExact: String  = obj.annotatedNothing() // I want a compiler error here
    val bareMaybe: String? = obj.annotatedNothing()
    val bareInfer          = obj.annotatedNothing()

    print("length " + nullExact.length)
    print("length " + nullMaybe.length) // already gives an error
    print("length " + nullInfer.length) // already gives an error

    print("length " + okayExact.length)
    print("length " + okayMaybe.length) // already gives an error
    print("length " + okayInfer.length)

    print("length " + bareExact.length)
    print("length " + bareMaybe.length) // already gives an error
    print("length " + bareInfer.length) // I want a compiler error here
}

The point is that this will force me to add null checks or !!, making sure that I at least have to be explicit about it.

Is this possible?

In the comments of this 2014 JetBrains blog post, when they introduced platform/flexible types, it sounds like they were planning to add an option to warn about exactly these situations, but I haven't been able to find any further information on that.


问:
Unable to verify message signed by sol-wallet-adapter
Having created a signed message I'm unsure how to use the resulting signature to verify the message using the publicKey.

My use case is, I'm wanting to use a Solana Wallet to login to an API server with a pattern like:

GET message: String (from API server)

sign message with privateKey

POST signature (to API server)

verify signature with stored publicKey

I've attempted to use nodeJS crypto.verify to decode the signed message on the API side but am a bit out of my depth digging into Buffers and elliptic curves:

// Front-end code
const toHexString = (buffer: Buffer) =>
  buffer.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");

const data = new TextEncoder().encode('message to verify');
const signed = await wallet.sign(data, "hex");
await setLogin({ // sends API post call to backend
  variables: {
    publicAddress: walletPublicKey,
    signature: toHexString(signed.signature),
  },
});

// Current WIP for backend code
const ALGORITHM = "ed25519";
const fromHexString = (hexString) =>
  new Uint8Array(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
const signature = fromHexString(args.signature);
const nonceUint8 = new TextEncoder().encode('message to verify');
const verified = crypto.verify(
  ALGORITHM,
  nonceUint8,
  `-----BEGIN PUBLIC KEY-----\n${user.publicAddress}\n-----END PUBLIC KEY-----`,
  signature
);
console.log("isVerified: ", verified);
```
<p>I'm pretty sure I'm going about this the wrong way and there must be an obvious method I'm missing.</p>
<p>As the space matures I expect a verify function or lib will appear to to consume the output of <code>const signed = await wallet.sign(data, "hex");</code></p>
<p>Something like:</p>
<pre class="lang-js prettyprint-override"><code>import { VerifyMessage } from '@solana/web3.js';

const verified = VerifyMessage(message, publicKey, signature, 'hex');
</code>```

But after 3 days of pushing hard I'm starting to hit my limits and my brain is failing. Any help or direction where to look much appreciated

答:
For iOS, solana.request will cause error. Use solana.signMessage and base58 encode the signature.</p>
```<code>var _signature = '';
try {
  signedMessage = await window.solana.request({
    method: "signMessage",
    params: {
      message: encodedMessage
    },
  });
  _signature = signedMessage.signature;
} catch (e) {
  try {
    signedMessage = await window.solana.signMessage(encodedMessage);
    _signature = base58.encode(signedMessage.signature);
  } catch (e1) {
    alert(e1.message);
  }
}
//
try {
  signIn('credentials',
    {
      publicKey: signedMessage.publicKey,
      signature: _signature,
      callbackUrl: `${window.location.origin}/`
    }
  )
} catch (e) {
  alert(e.message);
}
</code>```

Body:
Having created a signed message I'm unsure how to use the resulting signature to verify the message using the publicKey.

My use case is, I'm wanting to use a Solana Wallet to login to an API server with a pattern like:

GET message: String (from API server)

sign message with privateKey

POST signature (to API server)

verify signature with stored publicKey

I've attempted to use nodeJS crypto.verify to decode the signed message on the API side but am a bit out of my depth digging into Buffers and elliptic curves:

// Front-end code
const toHexString = (buffer: Buffer) =>
  buffer.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");

const data = new TextEncoder().encode('message to verify');
const signed = await wallet.sign(data, "hex");
await setLogin({ // sends API post call to backend
  variables: {
    publicAddress: walletPublicKey,
    signature: toHexString(signed.signature),
  },
});

// Current WIP for backend code
const ALGORITHM = "ed25519";
const fromHexString = (hexString) =>
  new Uint8Array(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
const signature = fromHexString(args.signature);
const nonceUint8 = new TextEncoder().encode('message to verify');
const verified = crypto.verify(
  ALGORITHM,
  nonceUint8,
  `-----BEGIN PUBLIC KEY-----\n${user.publicAddress}\n-----END PUBLIC KEY-----`,
  signature
);
console.log("isVerified: ", verified);

I'm pretty sure I'm going about this the wrong way and there must be an obvious method I'm missing.

As the space matures I expect a verify function or lib will appear to to consume the output of const signed = await wallet.sign(data, "hex");

Something like:

import { VerifyMessage } from '@solana/web3.js';

const verified = VerifyMessage(message, publicKey, signature, 'hex');

But after 3 days of pushing hard I'm starting to hit my limits and my brain is failing. Any help or direction where to look much appreciated

Body:
For iOS, solana.request will cause error. Use solana.signMessage and base58 encode the signature.

var _signature = '';
try {
  signedMessage = await window.solana.request({
    method: "signMessage",
    params: {
      message: encodedMessage
    },
  });
  _signature = signedMessage.signature;
} catch (e) {
  try {
    signedMessage = await window.solana.signMessage(encodedMessage);
    _signature = base58.encode(signedMessage.signature);
  } catch (e1) {
    alert(e1.message);
  }
}
//
try {
  signIn('credentials',
    {
      publicKey: signedMessage.publicKey,
      signature: _signature,
      callbackUrl: `${window.location.origin}/`
    }
  )
} catch (e) {
  alert(e.message);
}


问:
React native Android Project Not starting in emulator
i just created a react native project on windows, using expo. After Creating the project i ran npm start and then expo start the next logical thing to do is to press the a button which will launch, the project on the android virtual device, but instead it gave me this error Couldn't start project on Android: Error running adb: Error running app. Error: Activity not started, unable to resolve Intent { act=android.intent.action.VIEW dat=exp://192.168.43.148:19000 flg=0x10000000 }

when i tried running it on my android phone with the expo android app it ran smoothly, i don't know what to do please help thanks

答:
I had the same problem and I got it fixed as follows:

Go to SDK Manager in Android studio > SDK Tools and check whether there is any update for Android SDK Build-Tools. If there is any, please make sure you update it.

Close any Android virtual device currently running and then go to Android Studio Virtual Device Manager and wipe the data of your Android virtual device.

Make sure you have enough internal storage allocated for your Android virtual device to install apps.

Check whether Android Debug Bridge utility is installed in your device. If not please install it. To install in mac, I used the below command (Assuming that you have HomeBrew installed in your mac device):

```<code>brew install android-platform-tools
</code>```

Start your Android virtual device ( This step should be done before running the expo development server)

In the Developer options menu of your Android virtual device, make sure USB debugging option is enabled.

Finally, try running the development server by expo start and press on the button to run on your Android emulator.

Body:
I had the same problem and I got it fixed as follows:

Go to SDK Manager in Android studio > SDK Tools and check whether there is any update for Android SDK Build-Tools. If there is any, please make sure you update it.

Close any Android virtual device currently running and then go to Android Studio Virtual Device Manager and wipe the data of your Android virtual device.

Make sure you have enough internal storage allocated for your Android virtual device to install apps.

Check whether Android Debug Bridge utility is installed in your device. If not please install it. To install in mac, I used the below command (Assuming that you have HomeBrew installed in your mac device):

brew install android-platform-tools

Start your Android virtual device ( This step should be done before running the expo development server)

In the Developer options menu of your Android virtual device, make sure USB debugging option is enabled.

Finally, try running the development server by expo start and press on the button to run on your Android emulator.


问:
Error: unable to locate asset entry in pubspec.yaml: "lib/fonts/IndieFlower-Regular.ttf"
Error: unable to locate asset entry in pubspec.yaml: "lib/fonts/IndieFlower-Regular.ttf".

FAILURE: Build failed with an exception.

Where:
Script 'D:\Flutter project\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'D:\Flutter project\flutter\bin\flutter.bat'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 12s
Exception: Gradle task assembleDebug failed with exit code 1

答:
You can add fonts like this way in the pubsec.yml file you can take reference through this article I am sharing with you.
https://soshace.com/how-to-add-custom-fonts-in-flutter/

https://youtu.be/fDRtpjHfOuw

```<code>flutter:
  fonts:
    - family: DancingScript
      fonts:
        - asset: assets/fonts/DancingScript-Regular.ttf
    - family: Langer
      fonts:
        - asset: assets/fonts/Langar-Regular.ttf
</code>```

Body:
You can add fonts like this way in the pubsec.yml file you can take reference through this article I am sharing with you.
https://soshace.com/how-to-add-custom-fonts-in-flutter/

https://youtu.be/fDRtpjHfOuw

flutter:
  fonts:
    - family: DancingScript
      fonts:
        - asset: assets/fonts/DancingScript-Regular.ttf
    - family: Langer
      fonts:
        - asset: assets/fonts/Langar-Regular.ttf


问:
Does SQL server 2019 allows to commit the data changes as similar to GIT
I am doing an analysis to check in MSSQL 2019 to confirm whether it allows to take data backup of recent changes as similar to Git.

I need to go back to older data version if there is an need.
Any way to do this ?

答:
I can only imagine

backup/restore

log table and trigger


问:
Convert a series of type string to type Date (not Datetime)
I have a dataframe with a Date column whose content is: years-months-days of type string. I want to convert this to Date type (not Datetime). The goal is to insert this dataframe into a bigquery table with the Date type.

I tried:

```<code>df['Date '] = [datetime.strptime(str(i), '%Y-%m-%d') for i in df['Date ']]
</code>```

But this still returns Datetime format Years-Months-Days Hours:Minutes:Seconds (2022-01-03 00:00:00)

Someone have an idea to convert this string to type Date:Y-m-d (not Datetime)

答:
Try pandas.to_datetime() and extract the date:

```<code>import pandas as pd
df = pd.DataFrame({'Dates':['2020-01-22', '2021-05-06', '2022-01-01']})
df.Dates.apply(lambda x: pd.to_datetime(x).date())
</code>```

outputs:

```<code>0    2020-01-22
1    2021-05-06
2    2022-01-01
Name: Dates, dtype: object
</code>```

Body:
I have a dataframe with a Date column whose content is: years-months-days of type string. I want to convert this to Date type (not Datetime). The goal is to insert this dataframe into a bigquery table with the Date type.

I tried:

df['Date '] = [datetime.strptime(str(i), '%Y-%m-%d') for i in df['Date ']]

But this still returns Datetime format Years-Months-Days Hours:Minutes:Seconds (2022-01-03 00:00:00)

Someone have an idea to convert this string to type Date:Y-m-d (not Datetime)

Body:
Try pandas.to_datetime() and extract the date:

import pandas as pd
df = pd.DataFrame({'Dates':['2020-01-22', '2021-05-06', '2022-01-01']})
df.Dates.apply(lambda x: pd.to_datetime(x).date())

outputs:

0    2020-01-22
1    2021-05-06
2    2022-01-01
Name: Dates, dtype: object


问:
Disable Browser Search and using my own search input on CTRL F
I am trying to disable the browser search functionlity and at the same time i want to focus my own custom search box in website.

here is code for the same.

```<code> document.addEventListener("keydown", function(e) {
      if (e.keyCode == 70 && e.ctrlKey || e.keyCode === 114) {
              document.getElementById("myInput").focus();
            }
        e.preventDefault();
    })
</code>```

it disable the browser search feature and focus my custom search bar but it does not allow me to type anything in my custom search input.

答:
keycode is now deprecated. Use this:</p>
```<code>window.addEventListener("keydown", function(e) {
  if ( (e.code == "0x0021" && e.key == "Control") || e.code == "0x003D") {
    document.getElementById("myInput").focus();
    e.preventDefault();
  }
})
</code>```
```<code><input id="myInput" />
</code>```

Body:
I am trying to disable the browser search functionlity and at the same time i want to focus my own custom search box in website.

here is code for the same.

 document.addEventListener("keydown", function(e) {
      if (e.keyCode == 70 && e.ctrlKey || e.keyCode === 114) {
              document.getElementById("myInput").focus();
            }
        e.preventDefault();
    })

it disable the browser search feature and focus my custom search bar but it does not allow me to type anything in my custom search input.

Body:
keycode is now deprecated. Use this:

window.addEventListener("keydown", function(e) {
  if ( (e.code == "0x0021" && e.key == "Control") || e.code == "0x003D") {
    document.getElementById("myInput").focus();
    e.preventDefault();
  }
})

<input id="myInput" />


问:
Determining, if a variable is a valid closure in PHP
Using the following function:

function is_closure($t) { return ( !is_string($t)  && is_callable($t)); }

Can this return true for anything else, than an anonymous closure function? If so, what would be the correct way to determine, if a variable is a closure?

Many thanks

答:
The most deterministic way to check if a callback is an actual closure is:

```<code>function is_closure($t) {
    return $t instanceof \Closure;
}
</code>```

All anonymous functions are represented as objects of the type Closure in PHP. (Which, coming back to above comment, happen to implement the __invoke() method.)

Body:
The most deterministic way to check if a callback is an actual closure is:

function is_closure($t) {
    return $t instanceof \Closure;
}

All anonymous functions are represented as objects of the type Closure in PHP. (Which, coming back to above comment, happen to implement the __invoke() method.)


问:
Invalid IPv6 URL error when using pip on Ubuntu
when I try to install a package out of my anaconda environment I get a "ValueError: Invalid IPv6 URL" error message (full error below). Specifically it looks like the error is in urlsplit.

I am behind a proxy, thus I have tried to explicitely set the proxy details both in the .pip/pip.conf and explicitely appending it to the command line. The error is slightly different in the two cases.
Note that in my password I have none of these special symbols @, $, -, #. I do have some special characters though since they are required by the system. I have tried to put them into quote, double quotes, backslahs... nothing.

```<code>$ cat .pip/pip.conf
[global]
timeout = 60
index-url = https://pypi.python.org/simple/
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org
proxy = http://username:password@ipadress:port

[install]
index-url = https://pypi.python.org/simple/

</code>```

The original commnadnd + error message is here:

```<code>$ pip3 install Cython
Collecting Cython
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 328, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 748, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 360, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 512, in _prepare_file
    finder, self.upgrade, require_hashes)
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 273, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 442, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 400, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 545, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 648, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 757, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 492, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3/dist-packages/pip/download.py", line 378, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 588, in send
    r = adapter.send(request, **kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 343, in send
    conn = self.get_connection(request.url, proxies)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 253, in get_connection
    proxy = prepend_scheme_if_needed(proxy, 'http')
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/utils.py", line 666, in prepend_scheme_if_needed
    scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
  File "/usr/lib/python3.5/urllib/parse.py", line 295, in urlparse
    splitresult = urlsplit(url, scheme, allow_fragments)
  File "/usr/lib/python3.5/urllib/parse.py", line 363, in urlsplit
    raise ValueError("Invalid IPv6 URL")
ValueError: Invalid IPv6 URL
</code>```

By appending the proxy to the command line, I get a slightly shorter message:

```<code>$ pip install Cython --proxy = https://username:password@ipadress:port
ERROR: Exception:
Traceback (most recent call last):
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 164, in exc_logging_wrapper
    status = run_func(*args)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 205, in wrapper
    return func(self, options, args)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 305, in run
    reqs = self.get_requirements(args, options, finder, session)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 385, in get_requirements
    user_supplied=True,
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 366, in install_req_from_line
    parts = parse_req_from_line(name, line_source)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 281, in parse_req_from_line
    link = Link(name)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/models/link.py", line 73, in __init__
    self._parsed_url = urllib.parse.urlsplit(url)
  File "/home/mdi0316/anaconda3/lib/python3.6/urllib/parse.py", line 460, in urlsplit
    raise ValueError("Invalid IPv6 URL")
ValueError: Invalid IPv6 URL

</code>```

What else can I try?

Thank you.

PS, why am I using pip3 instead of pip? For some reason my default pip is the anaconda one, thus I can also anaconda3/pip install it, but then /usr/bin/python would not recognize it.

```<code>$which python
> /usr/bin/python
$ python --version
> Python 3.5.2

$ which pip
> /usr/bin/pip
$ pip --version
> pip 21.3.1 from /home/userid/anaconda3/lib/python3.6/site-packages/pip (python 3.6)

$ which python3
> /usr/bin/python3
$ python3 --version
> Python 3.5.2

$ which pip3
> /usr/bin/pip3
$ pip3 --version
> pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

</code>```

I then tryed to sudo apt-get remove python-pip and sudo apt install python-pip but I got the same anaconda3 version back:

```<code>$ which pip
> /usr/bin/pip
$ pip --version
> pip 21.3.1 from /home/userid/anaconda3/lib/python3.6/site-packages/pip (python 3.6)
</code>```

答: I removed all symbols from my password, kept only alphanumerics and it is now working.</p>

Body:
when I try to install a package out of my anaconda environment I get a "ValueError: Invalid IPv6 URL" error message (full error below). Specifically it looks like the error is in urlsplit.

I am behind a proxy, thus I have tried to explicitely set the proxy details both in the .pip/pip.conf and explicitely appending it to the command line. The error is slightly different in the two cases.
Note that in my password I have none of these special symbols @, $, -, #. I do have some special characters though since they are required by the system. I have tried to put them into quote, double quotes, backslahs... nothing.

$ cat .pip/pip.conf
[global]
timeout = 60
index-url = https://pypi.python.org/simple/
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org
proxy = http://username:password@ipadress:port

[install]
index-url = https://pypi.python.org/simple/

The original commnadnd + error message is here:

$ pip3 install Cython
Collecting Cython
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 328, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 748, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 360, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 512, in _prepare_file
    finder, self.upgrade, require_hashes)
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 273, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 442, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 400, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 545, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 648, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 757, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 492, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3/dist-packages/pip/download.py", line 378, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 588, in send
    r = adapter.send(request, **kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 343, in send
    conn = self.get_connection(request.url, proxies)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 253, in get_connection
    proxy = prepend_scheme_if_needed(proxy, 'http')
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/utils.py", line 666, in prepend_scheme_if_needed
    scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
  File "/usr/lib/python3.5/urllib/parse.py", line 295, in urlparse
    splitresult = urlsplit(url, scheme, allow_fragments)
  File "/usr/lib/python3.5/urllib/parse.py", line 363, in urlsplit
    raise ValueError("Invalid IPv6 URL")
ValueError: Invalid IPv6 URL

By appending the proxy to the command line, I get a slightly shorter message:

$ pip install Cython --proxy = https://username:password@ipadress:port
ERROR: Exception:
Traceback (most recent call last):
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 164, in exc_logging_wrapper
    status = run_func(*args)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 205, in wrapper
    return func(self, options, args)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 305, in run
    reqs = self.get_requirements(args, options, finder, session)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 385, in get_requirements
    user_supplied=True,
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 366, in install_req_from_line
    parts = parse_req_from_line(name, line_source)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 281, in parse_req_from_line
    link = Link(name)
  File "/home/mdi0316/anaconda3/lib/python3.6/site-packages/pip/_internal/models/link.py", line 73, in __init__
    self._parsed_url = urllib.parse.urlsplit(url)
  File "/home/mdi0316/anaconda3/lib/python3.6/urllib/parse.py", line 460, in urlsplit
    raise ValueError("Invalid IPv6 URL")
ValueError: Invalid IPv6 URL

What else can I try?

Thank you.

PS, why am I using pip3 instead of pip? For some reason my default pip is the anaconda one, thus I can also anaconda3/pip install it, but then /usr/bin/python would not recognize it.

$which python
> /usr/bin/python
$ python --version
> Python 3.5.2

$ which pip
> /usr/bin/pip
$ pip --version
> pip 21.3.1 from /home/userid/anaconda3/lib/python3.6/site-packages/pip (python 3.6)

$ which python3
> /usr/bin/python3
$ python3 --version
> Python 3.5.2

$ which pip3
> /usr/bin/pip3
$ pip3 --version
> pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

I then tryed to sudo apt-get remove python-pip and sudo apt install python-pip but I got the same anaconda3 version back:

$ which pip
> /usr/bin/pip
$ pip --version
> pip 21.3.1 from /home/userid/anaconda3/lib/python3.6/site-packages/pip (python 3.6)


问:
How can I make the right margin in QToolButton for the indicator?
I have QToolButton with left icon and right indicator (MenuButtonPopup mode). How do I change this distance by qss? Attention to the picture

tool button:

答:
Let's suppose you setup your QToolButton like this:

```<code>QToolButton* button {new QToolButton()};
button->setText("Button");
button->setToolButtonStyle(Qt::ToolButtonTextOnly);
button->setPopupMode(QToolButton::MenuButtonPopup);
QMenu* menu = new QMenu("Test menu", button);
menu->addAction("Test action");
button->setMenu(menu);

</code>```

When in MenuButtonPopup mode, the "arrow" used to open the menu for this QToolButton is a subcontrol (think of it as a button inside a button). You can control its position within the control like this:

```<code>button->setStyleSheet(
    "QToolButton { "
    "    padding-left: 5px;"
    "    padding-right: 60px;"
    "    border: 1px solid grey;"
    "}"
    ""
    "QToolButton::menu-button {"
    "    border: 2px solid red;"
    "    width: 36px;"
    "    right: 20px;"
    "    subcontrol-position: right center;"
    "    image: url(:/icons/down.png);"
    "}"
);
</code>```

This assumes you have setup the "/icons/down.png" image file inside a resource file.

I have made the border of the subcontrol red to make it easier to see where the subcontrol is being drawn.

Of course, you could load the style sheet from a file instead of inlining it as in the example.

Note that because you are replacing the widget's default style, you will need to specify the rest of the style as per your needs. Be aware that, for some reason, if you completely remove the borders for either the QToolButton widget itself or its subcontrol, the styling will go wrong.

Body:
Let's suppose you setup your QToolButton like this:

QToolButton* button {new QToolButton()};
button->setText("Button");
button->setToolButtonStyle(Qt::ToolButtonTextOnly);
button->setPopupMode(QToolButton::MenuButtonPopup);
QMenu* menu = new QMenu("Test menu", button);
menu->addAction("Test action");
button->setMenu(menu);

When in MenuButtonPopup mode, the "arrow" used to open the menu for this QToolButton is a subcontrol (think of it as a button inside a button). You can control its position within the control like this:

button->setStyleSheet(
    "QToolButton { "
    "    padding-left: 5px;"
    "    padding-right: 60px;"
    "    border: 1px solid grey;"
    "}"
    ""
    "QToolButton::menu-button {"
    "    border: 2px solid red;"
    "    width: 36px;"
    "    right: 20px;"
    "    subcontrol-position: right center;"
    "    image: url(:/icons/down.png);"
    "}"
);

This assumes you have setup the "/icons/down.png" image file inside a resource file.

I have made the border of the subcontrol red to make it easier to see where the subcontrol is being drawn.

Of course, you could load the style sheet from a file instead of inlining it as in the example.

Note that because you are replacing the widget's default style, you will need to specify the rest of the style as per your needs. Be aware that, for some reason, if you completely remove the borders for either the QToolButton widget itself or its subcontrol, the styling will go wrong.


问:
Vuetify grid of cards aligned with a divider
I'm trying to make a grid of cards that hold an image and a title using Vuetify.

I have managed to make a grid with the help of a few examples and managed to make this (This is on breakpoint XL):

But the problem is that, if the screen goes smaller, the grid isn't much of a grid anymore, but rather looks like this (this is on breakpoint LG):

I'm using justification: space-between but if I use start this is the result:

My goal is to have a grid aligned with the v-divider above and also is justified in the start without the awkward gap in the second row in the LG breakpoint.

Here's my code:

<v-container>
    <v-row justify="space-between">
      <v-col md="6" cols="12">

Grid

      </v-col>

      <v-col md="6" cols="12">
        <v-text-field
          outlined
          dense
          hide-details
          :placeholder="$t('search')"
          prepend-inner-icon="mdi-magnify"
          :class="$vuetify.breakpoint.smAndUp ? 'mt-2' : ''"
        ></v-text-field>
      </v-col>
    </v-row>

    <v-row justify="space-between">
      <v-col cols="12">
        <v-divider></v-divider>
      </v-col>
    </v-row>

    <v-row :justify="$vuetify.breakpoint.smAndDown ? 'center' : 'start'">
        <v-col cols="auto" v-for="(item, index) in machines" :key="index">
          <v-hover v-slot="{ hover }">
            <v-card class="mb-4" :elevation="hover ? 5 : 2">
              <v-card-text>
                <v-img
                src="https://static.wikia.nocookie.net/bc87eadb-62dd-4748-bcb6-cc4f38594988"
                contain
                :width="$vuetify.breakpoint.lgAndUp ? '300' : '385'"
                height="250"
              ></v-img>
              </v-card-text>

              <v-card-actions>
                <v-btn text color="deep-orange">
                  Arthur Morgan
                </v-btn>
              </v-card-actions>
            </v-card>
          </v-hover>
        </v-col>
    </v-row>
  </v-container>
```

答:
Like the second v-row write below condition for first v-row:

```<code><v-row :justify="$vuetify.breakpoint.lgAndUp ? 'space-between' : 'start'">
</code>```

hope this helped you.

Body:
Like the second v-row write below condition for first v-row:

<v-row :justify="$vuetify.breakpoint.lgAndUp ? 'space-between' : 'start'">

hope this helped you.


问:
Prestashop 1.7.8.0 problem disable scroll up after changing the attributes
I have a problem in Prestashop 1.7.8.0 I want to disable the scroll up after changing the attributes how to do it?
Moves the page up every time
I have core.js file combined and i dont know where to change this behaviour.</p>

答:
The best solution I found is to install prestashop with local environments and edit _dev folder inside theme. Go to inside folder: themes/classic/_dev/js/listing.js and remove window.scrollTo(0, 0); from:</p>
```<code>prestashop.on('updateProductList', (data) => {
   updateProductListDOM(data);
   window.scrollTo(0, 0);
});
</code>```

Body:
The best solution I found is to install prestashop with local environments and edit _dev folder inside theme. Go to inside folder: themes/classic/_dev/js/listing.js and remove window.scrollTo(0, 0); from:

prestashop.on('updateProductList', (data) => {
   updateProductListDOM(data);
   window.scrollTo(0, 0);
});


问:
angular validation for selecting option from drop down and accordingly inputting next field
I am new to Angular and got stuck in validation.

My problem is that I have dropdown menu with 4 options to select. when user selected one option I want an input field to change validation in such a way that:

If user select option 1 in the drop down than I want in the next input field to have the validation required and maximum length 8 numbers. likewise If the user select option 2 in the drop down. I want the input field to have the validation required and maximum length of 5 number. so i got stuck in validation how to do it. Any help and idea would be greatly appreciated

答:
html:

```<code> <form [formGroup]="selectForm">
 <div class="form-group">
 <label class="float-left">option</label>
 <select class="form-control" (change)="selection($event)" name="select"
 id="select" formControlName="select">
 <option value="option1">option1</option>
 <option value="option2">option2</option>
 <option value="option3">option3</option>
 </select>
 </div>

 <div class="form-group">
<label class="float-left">Input:</label>
<input type="number" class="form-control" formControlName="input">
</div>
</form>
</code>```

ts:

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from
'@angular/forms';

@Component({
 selector: 'app-select',
 templateUrl: './select.component.html',
 styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnInit {
}

 selectForm:FormGroup;
 select:null;
 input:any = '';

 constructor(
  private formBuilder: FormBuilder,
  ) { }

 ngOnInit(): void {
  this.createForm();
 }

  createForm(){

   this.selectForm = this.formBuilder.group({

   input:["",Validators.required],
  })
 }

 selection(event){
  let option = event.target.value;
  console.log('id:', option);
  this.selectForm.controls['input'].clearValidators();

 if (option == "option1") {
  this.selectForm.controls['input'].setValidators([
    Validators.required,
    Validators.maxLength(8),
   ]);
 }
 if (option == "option2") {
  this.selectForm.controls['input'].setValidators([
    Validators.required,
    Validators.maxLength(8),
  ]);
}
if (option == "option3") {
  this.selectForm.controls['input'].setValidators([
    Validators.required,
    Validators.maxLength(8),
  ]);
}

this.selectForm.updateValueAndValidity();
}
</code>```

Body:
html:

 <form [formGroup]="selectForm">
 <div class="form-group">
 <label class="float-left">option</label>
 <select class="form-control" (change)="selection($event)" name="select"
 id="select" formControlName="select">
 <option value="option1">option1</option>
 <option value="option2">option2</option>
 <option value="option3">option3</option>
 </select>
 </div>

 <div class="form-group">
<label class="float-left">Input:</label>
<input type="number" class="form-control" formControlName="input">
</div>
</form>

ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from
'@angular/forms';

@Component({
 selector: 'app-select',
 templateUrl: './select.component.html',
 styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnInit {
}

 selectForm:FormGroup;
 select:null;
 input:any = '';

 constructor(
  private formBuilder: FormBuilder,
  ) { }

 ngOnInit(): void {
  this.createForm();
 }

  createForm(){

   this.selectForm = this.formBuilder.group({

   input:["",Validators.required],
  })
 }

 selection(event){
  let option = event.target.value;
  console.log('id:', option);
  this.selectForm.controls['input'].clearValidators();

 if (option == "option1") {
  this.selectForm.controls['input'].setValidators([
    Validators.required,
    Validators.maxLength(8),
   ]);
 }
 if (option == "option2") {
  this.selectForm.controls['input'].setValidators([
    Validators.required,
    Validators.maxLength(8),
  ]);
}
if (option == "option3") {
  this.selectForm.controls['input'].setValidators([
    Validators.required,
    Validators.maxLength(8),
  ]);
}

this.selectForm.updateValueAndValidity();
}


问:
Subdomain to point to subdirectory of main site?
I have my website running at:

www.example.com

I also have this other domain:

www.example.net

Is it possible to point "www.example.net" to a subdirectory of "www.example.com"? For example:

www.example.net-> www.example.com/other

?

It's not just a redirect, I need to serve the pages and see "www.example.net" in the user's browser.

What do you think?

We use IIS7 and everything is ASP.NET (aspx pages, ascx controls, etc).

答:
Two questions for you:

Can you set them up as two different web sites in IIS?

If someone visited example.net/page.htm, would that be the same as example.com/other/page.htm?

If the answer is yes to both of those, why not just setup a new web site in IIS and point it to the "other" file path.

OwnerDisplayName: AnonUser

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Micky McQuade


问:
Diffing two folders (like the diff tool in Linux) with Python
I'm trying to write a project that will have some autonomous components. One of these is the need to diff two folders and spit out the different files into an array of strings. Dircmp does part of this - it spits out the different files. But it would appear it doesn't actually go into the remaining files to see which are different when compared against the same file in a different folder.

Currently I've played with difflib and filecmp, and unless I'm doing something entirely wrong I can't find a way to achieve what I'm looking for without writing it all from scratch. The reason I need this is because this python script will be deployed on windows boxen where the standard linux diff tools will not be available.

My only other thought would be to just call diff and such from the command line, but that doesn't solve either of my problems (getting the files in an array AND not requiring GNU tools).

Can anyone help me? I'm still a total scrub at python and would really appreciate the expert advice. Thank you!

答:
It seems that filecmp.dircmp does what you want already. If you compare two directories, diff_files will be a list of files which are in both directories, but whose contents differ:

```<code>>>> dc = filecmp.dircmp('dir1', 'dir2')
>>> dc.diff_files
<<< ['foo']
</code>```

As pointed out by Jonathanb, if you want actual diffs, it's easy to use difflib at this point to do so.

Body:
It seems that filecmp.dircmp does what you want already. If you compare two directories, diff_files will be a list of files which are in both directories, but whose contents differ:

>>> dc = filecmp.dircmp('dir1', 'dir2')
>>> dc.diff_files
<<< ['foo']

As pointed out by Jonathanb, if you want actual diffs, it's easy to use difflib at this point to do so.


问:
Change color of "tab header" in ttk.Notebook
Gretings!

I want to change the color displayed in a tab header, created using ttk.Notebook.
After search for a while I've found that to change the style of ttk widgets, we can use ttk. Styling, because Notebook apparently do not have configuration options to change its colors. However, I only found how to change the background and the foreground of a NoteBook object, but not how to configure the "tab header", whose background is either white (when selected) or grey (when not selected).

Anybody can help me with this?

This is the code that I have for now, related with what I'm trying to do

```<code>import Tkinter as tki
import ttk

...
##Other code. Not relevant here
...

#create tabs and associate the apropriate frames to it
tabs = ttk.Notebook(parent.master)
ttk.Style().configure("TNotebook", background=mainWcolor, foreground='green')   #configure "tabs" background color

paramsFrame = tki.Frame(tabs, bg=mainWcolor)   #frame with control parameters
comsFrame = tki.Frame(tabs, bg=mainWcolor)     #frame with communication parameters.
ssInfoFrame = tki.Frame(tabs, bg=mainWcolor)   #frame with start and stop messages and procedures

tabs.add(paramsFrame, text = "Control")
tabs.add(comsFrame, text = "Communications")
tabs.add(ssInfoFrame, text = "Start & Stop info")
tabs.pack()
</code>```

Thanks in advance.

答:
change the color of a Tab header:
when selecting a tab header.
when upon hovering over a Tab header.
removing the dotted line around the text in a tab header.</p>
```<code>from tkinter import *
from tkinter import ttk

root = Tk()
#background color
color='#21252b'
root.configure(background = color)
root.resizable(False, False)
#Notebook color
sky_color = "sky blue"
gold_color = "gold"
color_tab = "#ccdee0"
#style
style = ttk.Style()
style.theme_create( "beautiful", parent = "alt", settings ={
        "TNotebook": {
            "configure": {"tabmargins": [10, 10, 20, 10], "background":sky_color }},
        "TNotebook.Tab": {
            "configure": {"padding": [30, 15], "background": sky_color, "font":('consolas italic', 14), "borderwidth":[0]},
            "map":       {"background": [("selected", gold_color), ('!active', sky_color), ('active', color_tab)],
                          "expand": [("selected", [1, 1, 1, 0])]}}})
style.theme_use("beautiful")
style.layout("Tab",
                    [('Notebook.tab', {'sticky': 'nswe', 'children':
                        [('Notebook.padding', {'side': 'top', 'sticky': 'nswe', 'children':
                            #[('Notebook.focus', {'side': 'top', 'sticky': 'nswe', 'children':
                                [('Notebook.label', {'side': 'top', 'sticky': ''})],
                            #})],
                        })],
                    })]
                 )
style.configure('TLabel', background = color , foreground = 'white')
style.configure('TFrame', background = color)
#frame
frame_main_notebook = ttk.Frame(root, width = 200, height = 100)
frame_main_notebook.pack()
#note book
main_notebook = ttk.Notebook(frame_main_notebook, width = 200, height = 100)
main_notebook.pack(side = TOP, expand = 1, fill = 'both')
#first tab
frame_one = ttk.Frame(main_notebook, width = 200, height = 100)
frame_one.pack(side = TOP)
main_notebook.add(frame_one, text = '    tab one    ')
ttk.Label(frame_one, text = "this is inside of tab one").pack()
#second tab
frame_two = ttk.Frame(main_notebook, width = 200, height = 100)
frame_two.pack(side = TOP)
ttk.Label(frame_two, text = "this is inside of tab two").pack()
main_notebook.add(frame_two, text = '    tab two    ')

root.mainloop()
</code>```

Body:
Gretings!

I want to change the color displayed in a tab header, created using ttk.Notebook.
After search for a while I've found that to change the style of ttk widgets, we can use ttk. Styling, because Notebook apparently do not have configuration options to change its colors. However, I only found how to change the background and the foreground of a NoteBook object, but not how to configure the "tab header", whose background is either white (when selected) or grey (when not selected).

Anybody can help me with this?

This is the code that I have for now, related with what I'm trying to do

import Tkinter as tki
import ttk

...
##Other code. Not relevant here
...

#create tabs and associate the apropriate frames to it
tabs = ttk.Notebook(parent.master)
ttk.Style().configure("TNotebook", background=mainWcolor, foreground='green')   #configure "tabs" background color

paramsFrame = tki.Frame(tabs, bg=mainWcolor)   #frame with control parameters
comsFrame = tki.Frame(tabs, bg=mainWcolor)     #frame with communication parameters.
ssInfoFrame = tki.Frame(tabs, bg=mainWcolor)   #frame with start and stop messages and procedures

tabs.add(paramsFrame, text = "Control")
tabs.add(comsFrame, text = "Communications")
tabs.add(ssInfoFrame, text = "Start & Stop info")
tabs.pack()

Thanks in advance.

Body:
change the color of a Tab header:
when selecting a tab header.
when upon hovering over a Tab header.
removing the dotted line around the text in a tab header.

from tkinter import *
from tkinter import ttk

root = Tk()
#background color
color='#21252b'
root.configure(background = color)
root.resizable(False, False)
#Notebook color
sky_color = "sky blue"
gold_color = "gold"
color_tab = "#ccdee0"
#style
style = ttk.Style()
style.theme_create( "beautiful", parent = "alt", settings ={
        "TNotebook": {
            "configure": {"tabmargins": [10, 10, 20, 10], "background":sky_color }},
        "TNotebook.Tab": {
            "configure": {"padding": [30, 15], "background": sky_color, "font":('consolas italic', 14), "borderwidth":[0]},
            "map":       {"background": [("selected", gold_color), ('!active', sky_color), ('active', color_tab)],
                          "expand": [("selected", [1, 1, 1, 0])]}}})
style.theme_use("beautiful")
style.layout("Tab",
                    [('Notebook.tab', {'sticky': 'nswe', 'children':
                        [('Notebook.padding', {'side': 'top', 'sticky': 'nswe', 'children':
                            #[('Notebook.focus', {'side': 'top', 'sticky': 'nswe', 'children':
                                [('Notebook.label', {'side': 'top', 'sticky': ''})],
                            #})],
                        })],
                    })]
                 )
style.configure('TLabel', background = color , foreground = 'white')
style.configure('TFrame', background = color)
#frame
frame_main_notebook = ttk.Frame(root, width = 200, height = 100)
frame_main_notebook.pack()
#note book
main_notebook = ttk.Notebook(frame_main_notebook, width = 200, height = 100)
main_notebook.pack(side = TOP, expand = 1, fill = 'both')
#first tab
frame_one = ttk.Frame(main_notebook, width = 200, height = 100)
frame_one.pack(side = TOP)
main_notebook.add(frame_one, text = '    tab one    ')
ttk.Label(frame_one, text = "this is inside of tab one").pack()
#second tab
frame_two = ttk.Frame(main_notebook, width = 200, height = 100)
frame_two.pack(side = TOP)
ttk.Label(frame_two, text = "this is inside of tab two").pack()
main_notebook.add(frame_two, text = '    tab two    ')

root.mainloop()


问:
JPA QUERY Update data with dynamic column name
I've a long list and according to it's substring, I'll update my table which has 10 columns. It will be like if substring is 2 update column 2 etc. So that's why I need to use dynamic column name. Is there any way to do it because :keyName for example doesn't work.</p>
```<code>@Modifying
@Query("UPDATE Students s SET s.key2 = :key")
void updateKey(Integer key);
</code>```

答:
Here is a general pattern which might be along the lines of what you want.  We can write an update involving all columns, except that we will use CASE expressions to no-op in the event that no input parameter be set for that column.  For example, for a 3 column update we can try:

update SomeEntity e
set e.field1 = case when :val1 is not null then :val1 else e.field1 end,
    e.field2 = case when :val2 is not null then :val2 else e.field2 end,
    e.field3 = case when :val3 is not null then :val3 else e.field3 end;
```

Note the behavior here is that if say :val1 be not null, then we update field1 with that value, otherwise we just set field1 back to its original value (i.e. do a no-op).  For example, if you only wanted to update the second and third fields, you would bind NULL for :val1, and the two respective values you want to set for :val2 and :val3.

Body:
I've a long list and according to it's substring, I'll update my table which has 10 columns. It will be like if substring is 2 update column 2 etc. So that's why I need to use dynamic column name. Is there any way to do it because :keyName for example doesn't work.

@Modifying
@Query("UPDATE Students s SET s.key2 = :key")
void updateKey(Integer key);

Body:
Here is a general pattern which might be along the lines of what you want.  We can write an update involving all columns, except that we will use CASE expressions to no-op in the event that no input parameter be set for that column.  For example, for a 3 column update we can try:

update SomeEntity e
set e.field1 = case when :val1 is not null then :val1 else e.field1 end,
    e.field2 = case when :val2 is not null then :val2 else e.field2 end,
    e.field3 = case when :val3 is not null then :val3 else e.field3 end;

Note the behavior here is that if say :val1 be not null, then we update field1 with that value, otherwise we just set field1 back to its original value (i.e. do a no-op).  For example, if you only wanted to update the second and third fields, you would bind NULL for :val1, and the two respective values you want to set for :val2 and :val3.


问:
How to reverse a string in JavaScript using a "for...in" loop?
I have a piece of JavaScript code using a for loop to reverse a string. However, I would like to know if it is possible to use a for in loop instead and how would I go about that?</p>

```<code>     function reverse(str){
         var reversedString = '';
         for (var i = str.length - 1; i >= 0; i--){
            reversedString = reversedString + str[i];
     }
     return reversedString;
   }

   alert(reverse('hello'));
</code>```

答:
function reverse(str) {
  let reversed = "";
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

console.log("stefana")```

Body:
I have a piece of JavaScript code using a for loop to reverse a string. However, I would like to know if it is possible to use a for in loop instead and how would I go about that?

     function reverse(str){
         var reversedString = '';
         for (var i = str.length - 1; i >= 0; i--){
            reversedString = reversedString + str[i];
     }
     return reversedString;
   }

   alert(reverse('hello'));


问:
Mysql slow query log Errcode: 13 - Permission denied
I want to enable slow query log.
When I execute the following query

set global slow_query_log = 'ON';

I get :

```<code>#29 - File '/var/log/mysqld_slow.log' not found (Errcode: 13 - Permission denied)
</code>```

I tried solution here :
https://bugs.mysql.com/bug.php?id=98340 but I have issue on last command :

```<code>touch /var/log/mysqld_slow.log
chown mysql:mysql /var/log/mysqld_slow.log (also tried mysql:adm)
chmod 640 /var/log/mysqld_slow.log (also tried 666)
chcon -t mysqld_log_t /var/log/mysqld_slow.log
chcon: can't apply partial context to unlabeled file '/var/log/mysqld_slow.log'
</code>```

答:
Just rename the file in MySQL variables to some new name, I have just renamed the file from a variable and it is working properly. And MySQL automatically created the file for me in the path.
The defautl path is: /var/log/mysql/slow_query.log - rename the file to slow_query_log or something else

Hope it may work for you.

Body:
I want to enable slow query log.
When I execute the following query

set global slow_query_log = 'ON';

I get :

#29 - File '/var/log/mysqld_slow.log' not found (Errcode: 13 - Permission denied)

I tried solution here :
https://bugs.mysql.com/bug.php?id=98340 but I have issue on last command :

touch /var/log/mysqld_slow.log
chown mysql:mysql /var/log/mysqld_slow.log (also tried mysql:adm)
chmod 640 /var/log/mysqld_slow.log (also tried 666)
chcon -t mysqld_log_t /var/log/mysqld_slow.log
chcon: can't apply partial context to unlabeled file '/var/log/mysqld_slow.log'


问:
Mount host directory with a symbolic link inside in docker container
I mounted the container with this parameter:

-v /home/test/:/home/test

Inside /home/test in the host there is a symbolic link pointing to a /mnt/ folder.

But that link, although can be seen where is pointing to, seems broken inside the container:

```<code>root@f93f72b45013:/var/www/html# cd /home/test/
root@f93f72b45013:/home/test# ls -lrt
total 11956
lrwxrwxrwx. 1 root root 40 Jul 20 15:55 file -> /mnt/mountedfile/
root@f93f72b45013:/home/test# ls -lrt file/*
ls: cannot access file/*: No such file or directory
</code>```

Is that even possible to be done in docker? I am not sure if is there a way to do it.

I know I can just directly mount where the symbolic link is pointing at but I was just wondering if this is possibe.

答:
Hello thanks for your help In my case I was struggling activating https on my angular nginx app

```<code>docker run -p 80:80 -p 443:443 \
   --name test \
   -v /etc/letsencrypt/live/exemple.com:/etc/nginx/certs \
   -v /home/admin/nginx-default.conf:/etc/nginx/conf.d/default.conf:ro test
</code>```

Does not mount links cert.pem and privkey.pem inside docker

But if I use all file path explicitly like that

```<code>docker run -p 80:80 -p 443:443 \
   --name test \
   -v /etc/letsencrypt/live/example.com/cert.pem:/etc/nginx/certs/cert.pem \
   -v /etc/letsencrypt/live/example.com/privkey.pem:/etc/nginx/certs/privkey.pem \
   -v /home/admin/nginx-default.conf:/etc/nginx/conf.d/default.conf:ro test
</code>```

Everything worked
I suppose you could do it exactly the same thing with docker-compose

Body:
I mounted the container with this parameter:

-v /home/test/:/home/test

Inside /home/test in the host there is a symbolic link pointing to a /mnt/ folder.

But that link, although can be seen where is pointing to, seems broken inside the container:

root@f93f72b45013:/var/www/html# cd /home/test/
root@f93f72b45013:/home/test# ls -lrt
total 11956
lrwxrwxrwx. 1 root root 40 Jul 20 15:55 file -> /mnt/mountedfile/
root@f93f72b45013:/home/test# ls -lrt file/*
ls: cannot access file/*: No such file or directory

Is that even possible to be done in docker? I am not sure if is there a way to do it.

I know I can just directly mount where the symbolic link is pointing at but I was just wondering if this is possibe.

Body:
Hello thanks for your help In my case I was struggling activating https on my angular nginx app

docker run -p 80:80 -p 443:443 \
   --name test \
   -v /etc/letsencrypt/live/exemple.com:/etc/nginx/certs \
   -v /home/admin/nginx-default.conf:/etc/nginx/conf.d/default.conf:ro test

Does not mount links cert.pem and privkey.pem inside docker

But if I use all file path explicitly like that

docker run -p 80:80 -p 443:443 \
   --name test \
   -v /etc/letsencrypt/live/example.com/cert.pem:/etc/nginx/certs/cert.pem \
   -v /etc/letsencrypt/live/example.com/privkey.pem:/etc/nginx/certs/privkey.pem \
   -v /home/admin/nginx-default.conf:/etc/nginx/conf.d/default.conf:ro test

Everything worked
I suppose you could do it exactly the same thing with docker-compose


问:
Vert.x: How to send a post request?
My first Vertx Web app :

I expect To get the index.html at localhost.8080/Test then find a way to retrieve the data, but the page doesn't show

I have a RequestResponseExample class:

```<code>public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        Router router = Router.router(vertx);

        router.post("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}
</code>```

And My Html Code index.html

  <meta charSet="UTF-8">
  <title>OTP Authenticator Verification Example Page</title>

<form action="/" method="post" encType="multipart/form-data">

    Code:
    <input type="text" name="code"/>

    <input type="submit" value="Submit"/>

</form>

```

答:
Solution

Change router.post( to router.get(.

Description

Currently, you are configuring the Router to only handle HTTP POST request. That means, it is configured to respond to such an HTTP request:

```<code>POST /Test
</code>```

But when you try to open localhost.8080/Test in your browser, it will send such a request to your server:

```<code>GET /Test
</code>```

This is why you have to tell the router to handle GET and not POST requests.

Additional information: GET and POST are so called HTTP request methods. If you want to learn more about that, I recommend you to read the following article: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

About Verticles

In your code, you can remove extends AbstractVerticle and it will work the same way. If you want your code to get executed in the context of a verticle you have to create an instance of your class and then you have to deploy it:

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        vertx.deployVerticle(new RequestResponseExample());
    }

    @Override
    public void start(){
        Router router = Router.router(vertx);

        router.get("/Test").handler(rc -> rc.response().sendFile("index.html"));
        router.post().handler(BodyHandler.create());
        router.post("/").handler(rc -> System.out.println(rc.request().formAttributes().get("code")));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}
```

Since I see a bit of confusion on your side, you may want to also read the following article about Verticles: https://vertx.io/docs/vertx-core/java/#_verticles

Title: Vert.x: How to send a post request?

Body:
My first Vertx Web app :

I expect To get the index.html at localhost.8080/Test then find a way to retrieve the data, but the page doesn't show

I have a RequestResponseExample class:

public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        Router router = Router.router(vertx);

        router.post("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}

And My Html Code index.html

  <meta charSet="UTF-8">
  <title>OTP Authenticator Verification Example Page</title>

<form action="/" method="post" encType="multipart/form-data">

    Code:
    <input type="text" name="code"/>

    <input type="submit" value="Submit"/>

</form>

Body:
Solution

Change router.post( to router.get(.

Description

Currently, you are configuring the Router to only handle HTTP POST request. That means, it is configured to respond to such an HTTP request:

POST /Test

But when you try to open localhost.8080/Test in your browser, it will send such a request to your server:

GET /Test

This is why you have to tell the router to handle GET and not POST requests.

Additional information: GET and POST are so called HTTP request methods. If you want to learn more about that, I recommend you to read the following article: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

About Verticles

In your code, you can remove extends AbstractVerticle and it will work the same way. If you want your code to get executed in the context of a verticle you have to create an instance of your class and then you have to deploy it:

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        vertx.deployVerticle(new RequestResponseExample());
    }

    @Override
    public void start(){
        Router router = Router.router(vertx);

        router.get("/Test").handler(rc -> rc.response().sendFile("index.html"));
        router.post().handler(BodyHandler.create());
        router.post("/").handler(rc -> System.out.println(rc.request().formAttributes().get("code")));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}

Since I see a bit of confusion on your side, you may want to also read the following article about Verticles: https://vertx.io/docs/vertx-core/java/#_verticles


问:
Azure ad graph api
I'm testing Azure Graph API.

and I'm trying to find an API that allows me to retrieve only users that are assigned to a specific app I created.

In app registration page, I gave a user.read.all permission, but the get user API gives me all users that are in the AD and not only that are assigned to the app I created. Should I change the permissions? or to access an another API?

Does anybody know what to do?

Thanks

答:
Additionally, This object id should be based on service principal and not the application registration here.
You can retrieve the object Id from Azure AD->Enterprise Applications->Your app->object ID.

You need to have at least Application.Read.All and Directory.AccessAsUser.All for delegated permissions or Application.Read.All for application permission based on user or application context.

For specific details, you can add $select parameter to show only the displayName of the users assigned to the app.

https://graph.microsoft.com/v1.0/servicePrincipals/{object Id}/appRoleAssignedTo?$select=principalDisplayName

Title: Azure ad graph api


答:
I think you can use instanceof Closure though the manual states this should not be relied upon. I guess it works for now.

Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon.

Update
The Closure manual page has updated its guidance on this. It appears that this behaviour can now be relied upon.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon.

Title: Determining, if a variable is a valid closure in PHP

Body:
Using the following function:

function is_closure($t) { return ( !is_string($t)  && is_callable($t)); }

Can this return true for anything else, than an anonymous closure function? If so, what would be the correct way to determine, if a variable is a closure?

Many thanks


问:
React application has "Element type is invalid" error on production, but is working on development
In my React application, I got the following error using react-multi-carousel. However, it is only happening on Google Firebase hosting. It is working fine locally.

My project is created with Vite and Tailwind CSS.

The error:

Error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=object&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

which translates to:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

home.jsx

```<code>    import React, { useState, useEffect } from "react";
    import { useQuery } from "@apollo/client";
    import GitaCarousel from "../../components/gita_carousel";
    import { getHome, getHomeVariable } from "../../gql/home";

    const HomePage = () => {
      const [artists, setArtists] = useState();

      const { loading, error, data } = useQuery(getHome, {
        variables: getHomeVariable(10),
      });

      useEffect(() => {
        if (!loading && !error) {
           const a1 = data?.artists.map((artist) => ({
            id: artist.id,
            title: artist.name,
            subTitle: "",
            imageUrl: artist.profile_picture,
          }));
          setArtists(a1);
         }
      }, [loading, error]);

      return (
    <div>
      {artists && artists.length > 0 ? (
        <div className="flex flex-col my-5 items-center">
          <div className="flex-1 px-2 mx-2">
            {/* <div className="text-lg font-bold">{constants.latest_monks}</div> */}
          </div>
          <div>
            <GitaCarousel data={artists} />
          </div>
        </div>
      ) : (
        <div></div>
      )}
    </div>
     );
    };

    export default HomePage;
</code>```

gita_carousel.jsx

```<code>    import React from "react";
    import Carousel from "react-multi-carousel";
    import "react-multi-carousel/lib/styles.css";
    import { PlayIcon } from "../assets/icons/svg_icons";

    const responsive = {
      superLargeDesktop: {
        // the naming can be any, depends on you.
        breakpoint: { max: 4000, min: 3000 },
        items: 5,
      },
      desktop: {
        breakpoint: { max: 3000, min: 1024 },
        items: 5,
      },
      tablet: {
        breakpoint: { max: 1024, min: 464 },
        items: 2,
      },
      mobile: {
        breakpoint: { max: 464, min: 0 },
        items: 1,
      },
    };

    const GitaCarousel = (props) => {
      const { data } = props;

      return (
    <div className="container mx-auto px-4 md:px-12">
      <div className="flex flex-wrap -mx-1 lg:-mx-4">
        <Carousel
          swipeable={false}
          draggable={false}
          showDots={true}
          responsive={responsive}
          ssr={true}
          infinite={true}
          autoPlaySpeed={1000}
          keyBoardControl={true}
          customTransition="all .5"
          transitionDuration={500}
          containerClass="carousel-container"
          removeArrowOnDeviceType={["tablet", "mobile"]}
          deviceType="desktop"
        >
          {data.map((slide, index) => {
            return (
              <div
                key={index}
                className="group my-1 px-1 w-full cursor-pointer"
                onClick={() => {
                  onClickHandler(slide.id);
                }}
              >
                <article className="overflow-hidden rounded-lg shadow-lg">
                  <div className="relative cursor-pointer">
                    <img
                      alt="Placeholder"
                      className="block object-cover h-48 w-96"
                      src={slide.imageUrl}
                    />
                    <button className="absolute top-1/2 right-1/2 -mr-3 -mt-3 rounded-lg opacity-0 group-hover:opacity-100">
                      <PlayIcon className="text-primary" />
                    </button>
                  </div>

                  <header className="items-center justify-between leading-tight p-2 md:p-4">
                    <h1 className="text-sm">{slide.title}</h1>
                    <h2 className="text-xs text-gray-400">{slide.subTitle}</h2>
                  </header>

                </article>
              </div>
            );
          })}
        </Carousel>
        </div>
        </div>
      );
    };

    export default GitaCarousel;
</code>```

答:
OK, I fixed the issue. It is happening because of the export default or export typical issue, but I have no idea how the plugin is exporting.

Below is the fix and it worked for me.

```<code>import Carousel from "react-multi-carousel";

const RMCarousel = Carousel.default? Carousel.default: Carousel;
<RMCarousel></RMCarousel>
</code>```

Body:
In my React application, I got the following error using react-multi-carousel. However, it is only happening on Google Firebase hosting. It is working fine locally.

My project is created with Vite and Tailwind CSS.

The error:

Error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=object&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

which translates to:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

home.jsx

    import React, { useState, useEffect } from "react";
    import { useQuery } from "@apollo/client";
    import GitaCarousel from "../../components/gita_carousel";
    import { getHome, getHomeVariable } from "../../gql/home";

    const HomePage = () => {
      const [artists, setArtists] = useState();

      const { loading, error, data } = useQuery(getHome, {
        variables: getHomeVariable(10),
      });

      useEffect(() => {
        if (!loading && !error) {
           const a1 = data?.artists.map((artist) => ({
            id: artist.id,
            title: artist.name,
            subTitle: "",
            imageUrl: artist.profile_picture,
          }));
          setArtists(a1);
         }
      }, [loading, error]);

      return (

      {artists && artists.length > 0 ? (

            {/*
{constants.latest_monks}
 */}

            <GitaCarousel data={artists} />

      ) : (

      )}

     );
    };

    export default HomePage;

gita_carousel.jsx

    import React from "react";
    import Carousel from "react-multi-carousel";
    import "react-multi-carousel/lib/styles.css";
    import { PlayIcon } from "../assets/icons/svg_icons";

    const responsive = {
      superLargeDesktop: {
        // the naming can be any, depends on you.
        breakpoint: { max: 4000, min: 3000 },
        items: 5,
      },
      desktop: {
        breakpoint: { max: 3000, min: 1024 },
        items: 5,
      },
      tablet: {
        breakpoint: { max: 1024, min: 464 },
        items: 2,
      },
      mobile: {
        breakpoint: { max: 464, min: 0 },
        items: 1,
      },
    };

    const GitaCarousel = (props) => {
      const { data } = props;

      return (

        <Carousel
          swipeable={false}
          draggable={false}
          showDots={true}
          responsive={responsive}
          ssr={true}
          infinite={true}
          autoPlaySpeed={1000}
          keyBoardControl={true}
          customTransition="all .5"
          transitionDuration={500}
          containerClass="carousel-container"
          removeArrowOnDeviceType={["tablet", "mobile"]}
          deviceType="desktop"
        >
          {data.map((slide, index) => {
            return (

 {
                  onClickHandler(slide.id);
                }}
              >

                    <button className="absolute top-1/2 right-1/2 -mr-3 -mt-3 rounded-lg opacity-0 group-hover:opacity-100">
                      <PlayIcon className="text-primary" />
                    </button>

{slide.title}

{slide.subTitle}

            );
          })}
        </Carousel>

      );
    };

    export default GitaCarousel;

Body:
OK, I fixed the issue. It is happening because of the export default or export typical issue, but I have no idea how the plugin is exporting.

Below is the fix and it worked for me.

import Carousel from "react-multi-carousel";

const RMCarousel = Carousel.default? Carousel.default: Carousel;
<RMCarousel></RMCarousel>


问:
How to differentiate between Svelte dev mode and build mode?
The dev mode using npm run dev, the release mode using npm build

How could i know that it's currently built on dev mode or not in the code, for example:

```

答:
When using Svelte (not svelte-kit), this worked for me inside svelte components:

```<code><script>
    let isProduction = import.meta.env.MODE === 'production';

    if (!isProduction) {
       console.log("Developement Mode");
    } else {
       console.log("Production Mode");
    }
</script>
</code>```

Thanks timdeschryver for the reference

Body:
When using Svelte (not svelte-kit), this worked for me inside svelte components:

<script>
    let isProduction = import.meta.env.MODE === 'production';

    if (!isProduction) {
       console.log("Developement Mode");
    } else {
       console.log("Production Mode");
    }
</script>

Thanks timdeschryver for the reference


问:
React won't load local images
I am building a small react app and my local images won't load. Images like placehold.it/200x200 loads. I thought maybe it could be something with the server?

Here is my App.js

```<code>import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div className="home-container">
                <div className="home-content">
                    <div className="home-text">
                        <h1>foo</h1>
                    </div>
                    <div className="home-arrow">
                        <p className="arrow-text">
                            Vzdělání
                        </p>
                        <img src={"/images/resto.png"} />
                    </div>
                </div>
            </div>
        );
    }
}

export default App;
</code>```

index.js:

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';

let history = createHistory();

render(
    <Router history={history} >
        <Route path="/" component={App} >
            <Route path="vzdelani" component="" />
            <Route path="znalosti" component="" />
            <Route path="prace" component="" />
            <Route path="kontakt" component="" />
        </Route>
        <Route path="*" component="" />
    </Router>,
    document.getElementById('app')
);
</code>```

and server.js:

```<code>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
</code>```

答:
Ohhh yeahhh I had the same problem a few minutes ago and this worked for me:</p>
```<code>import React from "react" import logo from "../images/logo.png"

export default function Navbar() {
    return(
        <nav>
            {/* <img className="nav--logo" src="../images/logo.png"/> */}
            <img className="nav--logo" src={logo} alt="logo"/>
        </nav>
    ) }
</code>```

Title: React won't load local images

Body:
I am building a small react app and my local images won't load. Images like placehold.it/200x200 loads. I thought maybe it could be something with the server?

Here is my App.js

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (

foo

                            Vzdělání

        );
    }
}

export default App;

index.js:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';

let history = createHistory();

render(
    <Router history={history} >
        <Route path="/" component={App} >
            <Route path="vzdelani" component="" />
            <Route path="znalosti" component="" />
            <Route path="prace" component="" />
            <Route path="kontakt" component="" />
        </Route>
        <Route path="*" component="" />
    </Router>,
    document.getElementById('app')
);

and server.js:

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});

Body:
Ohhh yeahhh I had the same problem a few minutes ago and this worked for me:

import React from "react" import logo from "../images/logo.png"

export default function Navbar() {
    return(
        <nav>
            {/* <img className="nav--logo" src="../images/logo.png"/> */}
            <img className="nav--logo" src={logo} alt="logo"/>
        </nav>
    ) }


问:
Google OAuth Application Verification without Website
I am using the OAuth Functionality in a local Console Program to request the Videos for my Youtube Channel and upload Videos to Youtube.

For the Example which Google gives OAuth is used to authenticate to be able to retrieve the wanted data. But the Videos I am uploading keep getting put to private because my API Service is not verified.

Now I want to verify my API Service but I dont have a website for it so I can't provide any links for data security information or the main page of it. I mean it is a desktop app which only I am using and which is not meant to be publicly available.

How can I fulfill the verification process without any option to provide this informations?

答:
private videos

If you check the top of the page for Videos: insert  you will find that your videos are being uploaded private because your app has not been though a security audit.

app verification

In order to apply for app verification there are a number of urls that you need to supply

You will need to register a domain and claim it in web masters and then you will be able to add them.

If you want to be able to upload public videos via the YouTube Data api your app needs to be verified.  In order to verify it you need to be able to show the TOS, privacy policy and the application home page. There is no way around this even if its a desktop app. Even if its single user you still need to do this.

I have a video which shows you what you need to know to verify your app.

What you need to know about Google verification in 2021.