问:
Disable logging for one container in Docker-Compose
I have a web application launched using Docker compose that I want to disable all logging for (or at the very least print it out to syslog instead of a file).

When my web application works it can quickly generate an 11GB log file on startup so this eats up my disk space very fast.

I'm aware that normal docker has logging options for its run command but in Docker Compose I use

docker-compose up

in the application folder to start my application. How would I enable this functionality in my case? I'm not seeing a specific case anywhere online.

答:
Not exactly what is asked, but as of September 2021 (on Compose V2), the --attach parameter allows to select the services to listen to.

For example docker compose up --attach your-service will only display logs for your-service.


来源: stackexchange

问:
Viewport border
I want to have an 8px solid black border around the viewport of the webpage.
It doesn't scroll, content scrolls from "behind" it. it's transparent.
If I use a fixed div with a large z-index, it will prevent interaction with elements under it.

How can I do this?
I can make 4 divs, one for each side with a width of 8px for right and left and height of 8px for top and bottom, but that's seems like a bad way of solving this.

Thank you.

答:
There is a great article on css-tricks.com about that issue: http://css-tricks.com/body-border/

The first one is the one with four divs, but others are somewhat better.

ContentLicense: CC BY-SA 3.0

Title: Viewport border


问:
How to solve cargo build-bpf nor working?
I try to build a Rust project and when I try to execute cargo build-bpf --manifest-path=contracts/solana/program/Cargo.toml --bpf-out-dir=dist/solana/program on VS Code terminal I got this error: Can't get home directory path: environment variable not found.
Any ideas about how to solve it? I don't know how many details are needed for understanding the problem (I m new with Rust), but I can add more if you ask.

答:
cargo build-bpf requires the HOME environment variable to be set to work. To resolve this, you have a few options:

Switch VS Code to use a Bash-supported shell.  This will be your easiest option, and then HOME will always be set.  More information about how to do that at: How do I use Bash on Windows from the Visual Studio Code integrated terminal?

Set the HOME variable yourself in Powershell, using something like:

```<code>$Env:Home = "c:\path\to\my\work\dir"
</code>```

To be honest, I'm not 100% sure that the second option will work.

More information about the specific error you're seeing at the cargo-build-bpf source code: https://github.com/solana-labs/solana/blob/d5dec989b93fc94c9416a60193e52e8b68bd7133/sdk/cargo-build-bpf/src/main.rs#L474

ContentLicense: CC BY-SA 4.0

Body:
cargo build-bpf requires the HOME environment variable to be set to work. To resolve this, you have a few options:

Switch VS Code to use a Bash-supported shell.  This will be your easiest option, and then HOME will always be set.  More information about how to do that at: How do I use Bash on Windows from the Visual Studio Code integrated terminal?

Set the HOME variable yourself in Powershell, using something like:

$Env:Home = "c:\path\to\my\work\dir"

To be honest, I'm not 100% sure that the second option will work.

More information about the specific error you're seeing at the cargo-build-bpf source code: https://github.com/solana-labs/solana/blob/d5dec989b93fc94c9416a60193e52e8b68bd7133/sdk/cargo-build-bpf/src/main.rs#L474


问:
How can i set focus on a newly (automatically) rendered dom element?
I have an input field that gets replaced automatically with a textarea and same content depending on the number of characters the user has entered:

```<code><textarea v-if="myString.length > 20" v-model="myString"/>
<input type="text" v-if="myString.length <= 20" v-model="myString"/>
</code>```

The problem i have is that the focus gets lost when a user enters the 21st character. And thus the user gets irritated because when he types the 22nd character it does not appear in the textarea (no focus).
How can i set the focus on the newly rendered textarea then? Problem here is that it gets rendered automatically. Otherwise i could set a ref on the textarea and call focus().

Another issue is the removal of the 21st character and the switch-back from textarea to the input elment.

答:
You could wrap the textarea/input in a component, and use its mounted hook to call its focus(), as seen in this component:

<template>
  <component
    :is="comp"
    ref="input"
    v-bind="$attrs"
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>
```
<pre class="lang-html prettyprint-override"><code><AutoFocusedInput textarea v-if="myString.length > 20" v-model="myString" />
<AutoFocusedInput v-else v-model="myString" />
</code>```

demo

While this is technically possible, this UX is probably not ideal, and you should consider other designs that don't require focusing input like this (as indicated by @kien_coi_1997).

Body:
I have an input field that gets replaced automatically with a textarea and same content depending on the number of characters the user has entered:

<textarea v-if="myString.length > 20" v-model="myString"/>
<input type="text" v-if="myString.length <= 20" v-model="myString"/>

The problem i have is that the focus gets lost when a user enters the 21st character. And thus the user gets irritated because when he types the 22nd character it does not appear in the textarea (no focus).
How can i set the focus on the newly rendered textarea then? Problem here is that it gets rendered automatically. Otherwise i could set a ref on the textarea and call focus().

Another issue is the removal of the 21st character and the switch-back from textarea to the input elment.

Body:
You could wrap the textarea/input in a component, and use its mounted hook to call its focus(), as seen in this component:

<!-- AutoFocusedInput.vue -->
<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'

const input = ref()

onMounted(async () => {
  await nextTick()
  input.value.focus()
})

const props = defineProps({
  modelValue: String,
  textarea: Boolean,
})

const comp = computed(() => (props.textarea ? 'textarea' : 'input'))
</script>

<template>
  <component
    :is="comp"
    ref="input"
    v-bind="$attrs"
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>

<AutoFocusedInput textarea v-if="myString.length > 20" v-model="myString" />
<AutoFocusedInput v-else v-model="myString" />

demo

While this is technically possible, this UX is probably not ideal, and you should consider other designs that don't require focusing input like this (as indicated by @kien_coi_1997).


问:
Does my AMD-based machine use little endian or big endian?
I'm going though a computers system course and I'm trying to establish, for sure, if my AMD based computer is a little-endian machine? I believe it is because it would be Intel-compatible.

Specifically, my processor is an AMD 64 Athlon x2.

I understand that this can matter in C programming. I'm writing C programs and a method I'm using would be affected by this. I'm trying to figure out if I'd get the same results if I ran the program on an Intel based machine (assuming that is little endian machine).

Finally, let me ask this: Would any and all machines capable of running Windows (XP, Vista, 2000, Server 2003, etc) and, say, Ubuntu Linux desktop be little endian?

答:
We now have std::endian!

```<code>constexpr bool is_little = std::endian::native == std::endian::little;
</code>```

https://en.cppreference.com/w/cpp/types/endian

Body:
We now have std::endian!

constexpr bool is_little = std::endian::native == std::endian::little;

https://en.cppreference.com/w/cpp/types/endian


问:
Unable to connect to Google Cloud VM via SSH
I've been unable to connect to my VM via SSH since changing persistent disks. I had a VM set up with a Balance Persistent Disk 10gb and wanted to switch to a Standard 30gb. My procedure as been:

Create a disk image

Shutdown current VM and deleted the bootdisk

Loaded the saved disk image and switched to a Standard Persistent Disk

Now I am unable to connect via SSH. In Activity I'm getting this message: Invalid argument (HTTP 400): Supplied fingerprint does not match current metadata fingerprint. I've added the custom Metadata enable-os login: TRUE. Tech is still trying to figure it out.

Has anyone encountered this issue?

答: Second attempt with support - they determined the disk image was corrupt.</p>


问:
How to get rid of "git" from Android Studio Toolbar at the top? Screenshot attached

How do I get rid of this Git icons from the top toolbar of Android studio? It's taking too much space and I don't really use it. I tried to get rid of it from the preferences but did not work.

答:
Right Click on Git.

Customize menus and Toolbars : select it.It will pop new dialog

You can see minus '-' sig. you can manage this way

Edit


问:
Trying to autowire an interface. Error: Consider defining a bean of type "interface"
So I'm trying to autowire an interface.

MyApp:

```<code>@SpringBootApplication(scanBasePackages={"com.B","com.C"})
public class MyApp {
...
}
</code>```

MyController (which is in package com.B):

```<code>@RestController
@RequestMapping("/users")
public class UserController
{
    @Autowired
    MyInterface myInterface;
}
</code>```

MyInterface (which is in package com.C):

```<code>@Service
public interface MyInterface
{
...
}
</code>```

But I'm getting this error:

```<code>Consider defining a bean of type 'C.MyInterface' in your configuration.
</code>```

even though I have:

The package included here: @SpringBootApplication(scanBasePackages={"com.B","com.C"})

@Service in the interface

Is it even possible to autowire an interface?

答:
Yes you can inject an interface. But there should be at least one implementation that is declared as bean, so Spring manages it and will know what to inject. If you have more then one implementation you will need to specify which one you want. Read about annotation @Resource and about and it's property "name". A good article to read about it would be Wiring in Spring: @Autowired, @Resource and @Inject. Also, If you have many implementations of the same interface and want to inject them all you can do this:

```<code>@Autowired
private List<DataSource> dataSources;
</code>```

If DataSource is an interface the list will contain all of its implementations. You can read about it here and here

Body:
So I'm trying to autowire an interface.

MyApp:

@SpringBootApplication(scanBasePackages={"com.B","com.C"})
public class MyApp {
...
}

MyController (which is in package com.B):

@RestController
@RequestMapping("/users")
public class UserController
{
    @Autowired
    MyInterface myInterface;
}

MyInterface (which is in package com.C):

@Service
public interface MyInterface
{
...
}

But I'm getting this error:

Consider defining a bean of type 'C.MyInterface' in your configuration.

even though I have:

The package included here: @SpringBootApplication(scanBasePackages={"com.B","com.C"})

@Service in the interface

Is it even possible to autowire an interface?

Body:
Yes you can inject an interface. But there should be at least one implementation that is declared as bean, so Spring manages it and will know what to inject. If you have more then one implementation you will need to specify which one you want. Read about annotation @Resource and about and it's property "name". A good article to read about it would be Wiring in Spring: @Autowired, @Resource and @Inject. Also, If you have many implementations of the same interface and want to inject them all you can do this:

@Autowired
private List<DataSource> dataSources;

If DataSource is an interface the list will contain all of its implementations. You can read about it here and here


问:
What is going on with CVSNT?
At our site, we currently use CVSNT running on Solaris as our source repository server. We use the ACL feature in CVSNT and depend upon TortoiseCVS being able to run the cvs ls command, so we can't run a regular CVS server.

I've recently noticed that March Hare has retired the community version of CVSNT, and now charges $426 as a distribution fee for all downloads. (The commercial version is only $85 per person).

TortioseCVS comes with CVSNT, and I notice that this version of CVSNT has an annoying habit of displaying a dialog box asking you to upgrade to the supported version and will occasionally append a commercial for upgrading in the CVS commit comments.

At the same time, there seems to be a new open source package called EVS that March Hare seems to be pushing as an alternative to the formally open source CVS.

Exactly what is going on? Is EVS a replacement for CVSNT that TortoiseCVS can use? If we upgrade our CVS repository to use EVS, will users notice?

Can I continue to use CVSNT without paying the $426 distribution fee?

We'll probably be moving over to Subversion as soon as we get a few other issues under control, but I know plenty of shops that still use CVS, and I wonder if there are any licensing issues using Tortoise with CVSNT or continuing using CVSNT for handling the source repository.

答:
You can still use CVSNT, only you won't get any new release directly from March Hare. Any previously released community edition is still usable without any license issues, because it was released under the GPL. If someone redistributes newer CVSNT code (as GPL permits so), you could get it and compile it yourself.

You can avoid the ad message in the logs following instructions here and using -M instead of -m (you may need to patch any cvsnt client/frontend you may be using). If you compile from sources, you can remove it altogether.

There is anyway an open question if March-Hare is violating the GPL itself. They release binary distribution (their trial...) without source code, and without any way to get it. GPL asks binary distribution to make source code available, and there's no exception for "trial edition".

Their new "high performance" closed source proprietary server looks to be tied to the GPL CVS code in a way that probably violates the GPL (they themselves say one can't work without the other), and it could be a reason why they made source code so difficult to obtain.

Their now below the radar of any FSF supporter I guess, no one cares about CVS much today, and thereby I guess they feel free to milk the cow until it dies.

EVS is an attempt to write a new server using a database backend and supporting different clients (CVS, SVN, etc.), but as now it looks to have stalled, March-Hare no longer promotes it much, and anyway I would be very careful to buy anything from a company that has so little respect for someone else license.

ContentLicense: CC BY-SA 2.5

Title: What is going on with CVSNT?


问:
How To write a function to Check for a Sequence of integers in an array in python
I'm trying to figure out why the code I wrote to find a sequence of integers in any given array is not catching all the instances. Could you help, please?

Here's the code:

```<code>def array123(nums):
  if len(nums) < 3:
    return False
  else:
    for i in range(len(nums) - 1):
      if nums[i:i + 3] == [1, 2, 3]:
        return True
      return False
</code>```

答:
```<code>def array123(nums):
nums_to_string = str(nums)
if len(nums_to_string) < 3:
    return False
else:
    for i in range(len(nums_to_string) - 1):
        if nums_to_string[i:i + 3] == "123":
            return True
    return False
</code>```

Body:
I'm trying to figure out why the code I wrote to find a sequence of integers in any given array is not catching all the instances. Could you help, please?

Here's the code:

def array123(nums):
  if len(nums) < 3:
    return False
  else:
    for i in range(len(nums) - 1):
      if nums[i:i + 3] == [1, 2, 3]:
        return True
      return False


问:
TypeError: "Unsupported operand types: string * float"
I have the Error: TypeError Unsupported operand types: string * float
The Error is in this Line:
$pricere1 = $db_price * $validate->getIntervalFactor($runtime) * $mainrabatt_script;
I tried to find the Error but nothing worked for me :/

答:
One or more of the following is a String:

$db_price

$validate->getIntervalFactor($runtime)

$mainrabatt_script

When trying to multiply values, if PHP finds a String, then it will try to convert it into a numeric value. However, some String values are not numeric. I believe that $mainbratt_script is not numeric and PHP fails to convert it.

To solve your issue, make sure that you only multiply numeric values.


问:
I've been trying to make a Discord bot, but when I got to the embeds, some error keeps appearing. I've tried everything, and nothing works
This is my main.js file, I've searched through it and looked to see if there are any mistakes, and I've tried using different solutions I found here and in some of the comments of the tutorial I used, but nothing worked.

UPDATE: I've decided to just remove the embed.js file permanently for now, and for some reason none of my commands are working. (I only have one command.) It's the same error message, nothing has changed and I don't know what's causing the problem.

I have tried replacing client.on('message', message => { with client.on('messageCreate', message => { as the comments said but to no avail, the bot wouldn't even respond. At this point, I'm stumped.

And yes, I'm using the latest version of Node.js and Discord.js v13. I have no idea why this isn't working.

```<code>const Discord = require('discord.js');

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

const prefix = '/';

const fs = require('fs');

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
     const command = require(`./commands/${file}`)

     client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('BotOnlineStatus = True');
});

client.on('message', message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'command'){

       client.commands.get('command').execute(message, args, Discord);
    }
});

client.login('*CENSORED*')
</code>```

This is the error I keep receiving. I don't why I keep receiving this error, tried to fix it so many times but it's still busted. (I have very limited coding experience on Discord, so yeah.)

```<code>admins-iMac:DiscordBot admin$ node main.js
BotOnlineStatus = True
(node:22655) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
</code>```

If anyone has any solutions, please let me know.

答:
It is not an error, it is a warning.

Read the warning.

The message event is deprecated. Use messageCreate instead

Change client.on('message', to client.on('messageCreate',

Body:
This is my main.js file, I've searched through it and looked to see if there are any mistakes, and I've tried using different solutions I found here and in some of the comments of the tutorial I used, but nothing worked.

UPDATE: I've decided to just remove the embed.js file permanently for now, and for some reason none of my commands are working. (I only have one command.) It's the same error message, nothing has changed and I don't know what's causing the problem.

I have tried replacing client.on('message', message => { with client.on('messageCreate', message => { as the comments said but to no avail, the bot wouldn't even respond. At this point, I'm stumped.

And yes, I'm using the latest version of Node.js and Discord.js v13. I have no idea why this isn't working.

const Discord = require('discord.js');

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

const prefix = '/';

const fs = require('fs');

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
     const command = require(`./commands/${file}`)

     client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('BotOnlineStatus = True');
});

client.on('message', message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'command'){

       client.commands.get('command').execute(message, args, Discord);
    }
});

client.login('*CENSORED*')

This is the error I keep receiving. I don't why I keep receiving this error, tried to fix it so many times but it's still busted. (I have very limited coding experience on Discord, so yeah.)

admins-iMac:DiscordBot admin$ node main.js
BotOnlineStatus = True
(node:22655) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)

If anyone has any solutions, please let me know.


问:
How to fetch Amazon Cognito Identity ID (user_identity_id) for the user from the lambda function?
In the Amplify documentation, under the Storage/File access levels section there is a paragraph that states:

Files are stored under private/{user_identity_id}/ where the user_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.

How to fetch user_identity_id from the lambda function?

Request to the lambda is authorized, the event.requestContext.authorizer.claims object is available, I can see the user data, but not the user_identity_id.

EDIT: Now I see that there is a field event.requestContext.identity.cognitoIdentityId, but the value is null. Still need to find the way to fetch it.

答:
Ok, so there's no right way to map Cognito identity ID and Cognito user. There is a lengthy discussion here where a couple of workarounds can be found. For now, I'm going to use this solution where, instead of identity_id, you can specify a custom attribute (most likely a sub) as a folder name.

EDIT: There is another solution that might help (found somewhere on the internet, and I verified that it works)

```<code>const AWS = require('aws-sdk')
const cognitoIdentity = new AWS.CognitoIdentity();

function getCognitoIdentityId(jwtToken) {
  const params = getCognitoIdentityIdParams(jwtToken);
  return cognitoIdentity
    .getId(params)
    .promise()
    .then(data => {
      if (data.IdentityId) {
        return data.IdentityId;
      }
      throw new Error('Invalid authorization token.');
    });
}

function getCognitoIdentityIdParams(jwtToken) {
  const loginsKey = `cognito-idp.${process.env.REGION}.amazonaws.com/${process.env.USERPOOLID}`;
  return {
    IdentityPoolId: `${process.env.IDENTITY_POOL_ID}`,
    Logins: {
      [loginsKey]: jwtToken,
    },
  };
}
</code>```

Body:
Ok, so there's no right way to map Cognito identity ID and Cognito user. There is a lengthy discussion here where a couple of workarounds can be found. For now, I'm going to use this solution where, instead of identity_id, you can specify a custom attribute (most likely a sub) as a folder name.

EDIT: There is another solution that might help (found somewhere on the internet, and I verified that it works)

const AWS = require('aws-sdk')
const cognitoIdentity = new AWS.CognitoIdentity();

function getCognitoIdentityId(jwtToken) {
  const params = getCognitoIdentityIdParams(jwtToken);
  return cognitoIdentity
    .getId(params)
    .promise()
    .then(data => {
      if (data.IdentityId) {
        return data.IdentityId;
      }
      throw new Error('Invalid authorization token.');
    });
}

function getCognitoIdentityIdParams(jwtToken) {
  const loginsKey = `cognito-idp.${process.env.REGION}.amazonaws.com/${process.env.USERPOOLID}`;
  return {
    IdentityPoolId: `${process.env.IDENTITY_POOL_ID}`,
    Logins: {
      [loginsKey]: jwtToken,
    },
  };
}


问:
Custom layer misses input on plot_model
I'm following this tutorial https://www.tensorflow.org/guide/keras/train_and_evaluate#handling_losses_and_metrics_that_dont_fit_the_standard_signature.

The code in concern is this: (copied from the tutorial)

class LogisticEndpoint(keras.layers.Layer):
    def __init__(self, name=None):
        super(LogisticEndpoint, self).__init__(name=name)
        self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)
        self.accuracy_fn = keras.metrics.BinaryAccuracy()

    def call(self, targets, logits, sample_weights=None):
        # Compute the training-time loss value and add it
        # to the layer using `self.add_loss()`.
        loss = self.loss_fn(targets, logits, sample_weights)
        self.add_loss(loss)

        # Log accuracy as a metric and add it
        # to the layer using `self.add_metric()`.
        acc = self.accuracy_fn(targets, logits, sample_weights)
        self.add_metric(acc, name="accuracy")

        # Return the inference-time prediction tensor (for `.predict()`).
        return tf.nn.softmax(logits)

import numpy as np

inputs = keras.Input(shape=(3,), name="inputs")
targets = keras.Input(shape=(10,), name="targets")
logits = keras.layers.Dense(10)(inputs)

predictions = LogisticEndpoint(name="predictions")(logits, targets)

model = keras.Model(inputs=[inputs, targets], outputs=predictions)
model.compile(optimizer="adam")  # No loss argument!
```
<p>What I need is to plot the model, so I called</p>
```tf.keras.utils.plot_model(model, 'm.png', show_shapes=True)
```

Apprently from the tutorial code LogisticEndpoint takes two input, namely the return value of dense and targets. However in the plot, a link from target:InputLayer to predictions:LogisticEndpoint is missing.

How would I revise the tutorial code so that plot is correct?

答:
Inputs to your custom layer should be a list/tuple for two input tensors and not two separate inputs. Check the docs for more information. You could try something like this:

import tensorflow as tf

class LogisticEndpoint(tf.keras.layers.Layer):
    def __init__(self, name=None):
        super(LogisticEndpoint, self).__init__(name=name)
        self.loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True)
        self.accuracy_fn = tf.keras.metrics.BinaryAccuracy()

    def call(self, inputs, sample_weights=None):
        # Compute the training-time loss value and add it
        # to the layer using `self.add_loss()`.
        logits, targets = inputs
        loss = self.loss_fn(targets, logits, sample_weights)
        self.add_loss(loss)

        # Log accuracy as a metric and add it
        # to the layer using `self.add_metric()`.
        acc = self.accuracy_fn(targets, logits, sample_weights)
        self.add_metric(acc, name="accuracy")

        # Return the inference-time prediction tensor (for `.predict()`).
        return tf.nn.softmax(logits)

inputs = tf.keras.Input(shape=(3,), name="inputs")
targets = tf.keras.Input(shape=(10,), name="targets")
logits =tf. keras.layers.Dense(10)(inputs)

predictions = LogisticEndpoint(name="predictions")([logits, targets])

model = tf.keras.Model(inputs=[inputs, targets], outputs=predictions)
model.compile(optimizer="adam")  # No loss argument!

tf.keras.utils.plot_model(model, 'm.png', show_shapes=True)
```

Title: Custom layer misses input on plot_model

Body:
I'm following this tutorial https://www.tensorflow.org/guide/keras/train_and_evaluate#handling_losses_and_metrics_that_dont_fit_the_standard_signature.

The code in concern is this: (copied from the tutorial)

class LogisticEndpoint(keras.layers.Layer):
    def __init__(self, name=None):
        super(LogisticEndpoint, self).__init__(name=name)
        self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)
        self.accuracy_fn = keras.metrics.BinaryAccuracy()

    def call(self, targets, logits, sample_weights=None):
        # Compute the training-time loss value and add it
        # to the layer using `self.add_loss()`.
        loss = self.loss_fn(targets, logits, sample_weights)
        self.add_loss(loss)

        # Log accuracy as a metric and add it
        # to the layer using `self.add_metric()`.
        acc = self.accuracy_fn(targets, logits, sample_weights)
        self.add_metric(acc, name="accuracy")

        # Return the inference-time prediction tensor (for `.predict()`).
        return tf.nn.softmax(logits)

import numpy as np

inputs = keras.Input(shape=(3,), name="inputs")
targets = keras.Input(shape=(10,), name="targets")
logits = keras.layers.Dense(10)(inputs)

predictions = LogisticEndpoint(name="predictions")(logits, targets)

model = keras.Model(inputs=[inputs, targets], outputs=predictions)
model.compile(optimizer="adam")  # No loss argument!

What I need is to plot the model, so I called

tf.keras.utils.plot_model(model, 'm.png', show_shapes=True)

Apprently from the tutorial code LogisticEndpoint takes two input, namely the return value of dense and targets. However in the plot, a link from target:InputLayer to predictions:LogisticEndpoint is missing.

How would I revise the tutorial code so that plot is correct?


问:
using swift, I'm simply trying to turn an else block in to a ternary operator
```<code>   if bulletsOn == true {
            bullets -= 0.003
        } else {
            bullets += 0.001
        }
</code>```

when I put in form of ternary like so, I get error from compiler.

```<code>    bulletsOn ? bullets -= 0.003 : bullets += 0.001
</code>```

error: Result values in '? :' expression have mismatching types '()' and 'CGFloat'

答:
Ternary are just funny math operations so you need a value two be assigned to, a condition and the two values that can be assigned to it, but your two condition don't even return values, so

```<code>bullets += bulletsOn ? -0.003 : 0.001
</code>```

would work

Body:
   if bulletsOn == true {
            bullets -= 0.003
        } else {
            bullets += 0.001
        }

when I put in form of ternary like so, I get error from compiler.

    bulletsOn ? bullets -= 0.003 : bullets += 0.001

error: Result values in '? :' expression have mismatching types '()' and 'CGFloat'

Body:
Ternary are just funny math operations so you need a value two be assigned to, a condition and the two values that can be assigned to it, but your two condition don't even return values, so

bullets += bulletsOn ? -0.003 : 0.001

would work


问:
why did remix give a NOT FOUND error for @chainlink/contracts
Why did remix give a NOT FOUND error?

(I knew safemath is not necessary since v0.8.)

code:

```<code>// SPDX-License-Identifier: MIT

pragma solidity >=0.6.6 <0.9.0;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";

contract FundMe {
    using SafeMathChainlink for uint256;

    mapping(address => uint256) public addressToAmountFunded;
    address[] public funders;
    address public owner;

    constructor() public {
        owner = msg.sender;
    }

    function fund() public payable {
        uint256 minimumUSD = 50 * 10 ** 18;
        require(getConversionRate(msg.value) >= minimumUSD, "You need to spend more ETH!");
        addressToAmountFunded[msg.sender] += msg.value;
        funders.push(msg.sender);
    }

    function getVersion() public view returns (uint256){
        AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
        return priceFeed.version();
    }

    function getPrice() public view returns(uint256){
        AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
        (,int256 answer,,,) = priceFeed.latestRoundData();
         return uint256(answer * 10000000000);
    }

    // 1000000000
    function getConversionRate(uint256 ethAmount) public view returns (uint256){
        uint256 ethPrice = getPrice();
        uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1000000000000000000;
        return ethAmountInUsd;
    }

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    function withdraw() payable onlyOwner public {
        msg.sender.transfer(address(this).balance);

        for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){
            address funder = funders[funderIndex];
            addressToAmountFunded[funder] = 0;
        }
        funders = new address[](0);
    }
}
</code>```

Errror: not found "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"

I use  same code FundMe.sol via Patrick Collins github lesson3
here is the error

答:
If you came here following the "Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial" course by Patrick Collins; here's what you need to change to make this work:

If you get this error:

```<code>ParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version
 --> @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:
  |
2 | pragma solidity ^0.6.0;
  | ^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Make sure:

You use pragma solidity ^0.6.0; (or similar; i.e.: pragma solidity >=0.6.6 <0.9.0;) at the top of your contract,

Select a compiler version that fits what the AggregatorV3Interface.sol interface is expecting (pragma solidity ^0.6.0;)

And hit re-compile :)

Body:
Why did remix give a NOT FOUND error?

(I knew safemath is not necessary since v0.8.)

code:

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.6 <0.9.0;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";

contract FundMe {
    using SafeMathChainlink for uint256;

    mapping(address => uint256) public addressToAmountFunded;
    address[] public funders;
    address public owner;

    constructor() public {
        owner = msg.sender;
    }

    function fund() public payable {
        uint256 minimumUSD = 50 * 10 ** 18;
        require(getConversionRate(msg.value) >= minimumUSD, "You need to spend more ETH!");
        addressToAmountFunded[msg.sender] += msg.value;
        funders.push(msg.sender);
    }

    function getVersion() public view returns (uint256){
        AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
        return priceFeed.version();
    }

    function getPrice() public view returns(uint256){
        AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
        (,int256 answer,,,) = priceFeed.latestRoundData();
         return uint256(answer * 10000000000);
    }

    // 1000000000
    function getConversionRate(uint256 ethAmount) public view returns (uint256){
        uint256 ethPrice = getPrice();
        uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1000000000000000000;
        return ethAmountInUsd;
    }

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    function withdraw() payable onlyOwner public {
        msg.sender.transfer(address(this).balance);

        for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){
            address funder = funders[funderIndex];
            addressToAmountFunded[funder] = 0;
        }
        funders = new address[](0);
    }
}

Errror: not found "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"

I use  same code FundMe.sol via Patrick Collins github lesson3
here is the error

Body:
If you came here following the "Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial" course by Patrick Collins; here's what you need to change to make this work:

If you get this error:

ParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version
 --> @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:
  |
2 | pragma solidity ^0.6.0;
  | ^^^^^^^^^^^^^^^^^^^^^^^

Make sure:

You use pragma solidity ^0.6.0; (or similar; i.e.: pragma solidity >=0.6.6 <0.9.0;) at the top of your contract,

Select a compiler version that fits what the AggregatorV3Interface.sol interface is expecting (pragma solidity ^0.6.0;)

And hit re-compile :)


答:
The message event has been renamed to messageCreate.
I think this error is not stopping your bot ya ?

Anyway try to replace client.on('message', message => {
By client.on('messageCreate', message => {

Title: I've been trying to make a Discord bot, but when I got to the embeds, some error keeps appearing. I've tried everything, and nothing works


问:
Run update script from select result for each row
I have a table with thousands scripts that I would like to run them in a while loop, but the query result doesn't have an ID column that can use to count, do you know?

There is only on column with the scripts. See some sample data:

```<code>UPDATE CAT_SP_03476811013725_01_2009 SET COD_LEGAL = '' WHERE ISNULL(PRODUTO_EXCLUIDO,'') <> 'S'
UPDATE CAT_SP_03476811013725_02_2009 SET COD_LEGAL = '' WHERE ISNULL(PRODUTO_EXCLUIDO,'') <> 'S'
UPDATE CAT_SP_03476811013725_03_2009 SET COD_LEGAL = '' WHERE ISNULL(PRODUTO_EXCLUIDO,'') <> 'S'
</code>```

I need to run each script from each row in a store procedure, but I don't know how to do it and I wouldn't like to copy the result and past them in the query editor because there are thousands records in dozen of tables, so, can someone help me with some example of store procedure to reach out this goal?

Any help will be appreciated.

答:
I solved the issue replacing this

```<code>SET @cmd = 'select [@script] = script from #tabscrdia where id = [@count]'
</code>```

for this

```<code>SET @cmd = (select script from #tabscrdia where id = @count)
</code>```

Thanks very much

Body:
I have a table with thousands scripts that I would like to run them in a while loop, but the query result doesn't have an ID column that can use to count, do you know?

There is only on column with the scripts. See some sample data:

UPDATE CAT_SP_03476811013725_01_2009 SET COD_LEGAL = '' WHERE ISNULL(PRODUTO_EXCLUIDO,'') <> 'S'
UPDATE CAT_SP_03476811013725_02_2009 SET COD_LEGAL = '' WHERE ISNULL(PRODUTO_EXCLUIDO,'') <> 'S'
UPDATE CAT_SP_03476811013725_03_2009 SET COD_LEGAL = '' WHERE ISNULL(PRODUTO_EXCLUIDO,'') <> 'S'

I need to run each script from each row in a store procedure, but I don't know how to do it and I wouldn't like to copy the result and past them in the query editor because there are thousands records in dozen of tables, so, can someone help me with some example of store procedure to reach out this goal?

Any help will be appreciated.

Body:
I solved the issue replacing this

SET @cmd = 'select [@script] = script from #tabscrdia where id = [@count]'

for this

SET @cmd = (select script from #tabscrdia where id = @count)

Thanks very much


问:
When trying to save pgAdmin result to a file (TXT) the result is modified
When I launch my query into pgAdmin 4 v5's Query Tool I get this type of data representation (this is also what I would like to get in my export file).

Unfortunately this information is transformed when saving it to a .TXT file by clicking the following button and saving it as indicated in the subsequent image.

As you can see below, after double-clicking on the saved TXT document, it added '.0' and wrapped my long character by indicating 'e+29' up to a certain row.

Can you please indicate me how to remove those transformations ?

答:
All,

I found out the above problem is linked with the version of pgAdmin I was using, pgAdmin 4 v5 precisely.

After downloading pgAdmin 4 v6.4 the problem doesn't appear anymore.
I consider this thus as fixed, even if the cause of the problem remains unknown to me.

Thanks for your help.

Brieuc


问:
Global Object in singleton
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

```<code>class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};
</code>```

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

答:
If you make it a global object, then everyone has access to it, and anyone can use it without calling getInstance(). If so, then what is the purpose of getInstance() then? First time, you will call it to create the instance, then you wouldn't be required to call getInstance(), since after the first call, you can directly use instance.

A private static instance gives you more control how it can be accessed: only through by calling getInstance().

Now why you get multiple definition of instance error when compiling your code? Its because you've defined the global object in the header file itself, which is included in multiple .cpp files. This causes multiple definitions of the object, one definition in each translation unit (.obj  file).

What you actually should be doing is this:

```<code>//Singleton.h
class Singleton
{
private :
        Singleton();
        Singleton(const Singleton &);
       ~Singleton();

        static Singleton* instance; //declaration of static member!

public:
        static Singleton* getInstance();
       //..
};
</code>```

And then define the static member in the .cpp file as:

```<code>//Singleton.cpp
 Singleton *Singleton::instance = 0; //definition should go in .cpp file!

 Singleton::Singleton() {}

 Singleton* Singleton::getInstance()
 {
     if ( instance  == 0 ) instance  = new Singleton();
     return instance;
 }
 //...
</code>```

Title: Global Object in singleton

Body:
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

Body:
If you make it a global object, then everyone has access to it, and anyone can use it without calling getInstance(). If so, then what is the purpose of getInstance() then? First time, you will call it to create the instance, then you wouldn't be required to call getInstance(), since after the first call, you can directly use instance.

A private static instance gives you more control how it can be accessed: only through by calling getInstance().

Now why you get multiple definition of instance error when compiling your code? Its because you've defined the global object in the header file itself, which is included in multiple .cpp files. This causes multiple definitions of the object, one definition in each translation unit (.obj  file).

What you actually should be doing is this:

//Singleton.h
class Singleton
{
private :
        Singleton();
        Singleton(const Singleton &);
       ~Singleton();

        static Singleton* instance; //declaration of static member!

public:
        static Singleton* getInstance();
       //..
};

And then define the static member in the .cpp file as:

//Singleton.cpp
 Singleton *Singleton::instance = 0; //definition should go in .cpp file!

 Singleton::Singleton() {}

 Singleton* Singleton::getInstance()
 {
     if ( instance  == 0 ) instance  = new Singleton();
     return instance;
 }
 //...


问:
Unix Regex (ERE) for finding a lines with 4 or more numbers
I've tried so many variations but none seem to work, I have no idea what I don't understand.

The last one I've tried is (\<[[:digit:]]+\>.*){4,}.
But it doesn't even find lines like 123 123 123 123.
The input lines can be anything (even like hello 123 my 1 name 2 is 3).

I didn't specify it, sorry, but what I meant is: line "123 a2" has 1 number, line "1 2 3 45" has 4 numbers.

答:
With your shown samples, please try following awk code. We need NOT to use loop here. This awk code is written and tested in GNU awk.

```<code>awk -v FPAT='(^|[[:space:]]+)[0-9]+([[:space:]]+|$)' 'NF>3' Input_file
</code>```

Explanation: Adding detailed explanation for above.

Using GNU awk's option named FPAT to allow regex to make field separators.

Using regex (^|[[:space:]]+)[0-9]+([[:space:]]+|$) to match either starting spaces followed by digits OR digits followed by spaces or ending of line.

In main awk program checking condition NF>3 which means if number of fields are greater than 3 then print that line.

Body:
With your shown samples, please try following awk code. We need NOT to use loop here. This awk code is written and tested in GNU awk.

awk -v FPAT='(^|[[:space:]]+)[0-9]+([[:space:]]+|$)' 'NF>3' Input_file

Explanation: Adding detailed explanation for above.

Using GNU awk's option named FPAT to allow regex to make field separators.

Using regex (^|[[:space:]]+)[0-9]+([[:space:]]+|$) to match either starting spaces followed by digits OR digits followed by spaces or ending of line.

In main awk program checking condition NF>3 which means if number of fields are greater than 3 then print that line.


问:
Saving seeding data to database in Laravel
I am participating in a Laravel course. The course was supposed to be laravel 8, but it is 30/70 laravel 8, and laravel 5 was outdated and is slowly updated. The problem is saving seeding data to a database (MySQL). I can save Users to the database in the code but cannot save Blogposts Or comments. The blog posts are supposed to be saved with random user IDs from all user tables so that the specific user who made the post would be able to edit the post he made, not the others. Also, comments have the same story, but comments are randomly assigned to posts. Previously it has been tried to save posts to a database using PHP artisan tinker.

```<code>class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $users = User::factory()->count(20)->create();
        dd($users->count());
        $posts = BlogPost::factory()->count(50)->make()
            ->each(function ($post) use ($users) {
            $post->user()->associate($users->random())->save();
        });
        $comments = Comment::factory()->count(150)->make()
            ->each(function ($comment) use ($posts) {
            $comment->blog_post_id = $posts->random()->id;
        });
    }
}
</code>```

When making a migration, there are no errors shown. For migration, we use the following.

```<code>php artisan migrate:refresh --seed
</code>```

答:
Well, the meaning of dd() is dump and die. Therefore you are stoping the seed execution after the User factory.

Just remove the dd() and seed should be executed as expected

```<code><?php
namespace Database\Seeders;
use App\Models\User;
use App\Models\BlogPost;
use App\Models\Comment;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $users = User::factory()->count(20)->create();
        // dd($users->count()); <-- This stops the seed execution
        $posts = BlogPost::factory()->count(50)->make()->each(function($post) use ($users) {
            $post->user()->associate($users->random())->save();
        });
        $comments = Comment::factory()->count(150)->make()->each(function ($comment) use ($posts){
            $comment->blog_post_id = $posts->random()->id;
        });
    }
}
</code>```

Body:
I am participating in a Laravel course. The course was supposed to be laravel 8, but it is 30/70 laravel 8, and laravel 5 was outdated and is slowly updated. The problem is saving seeding data to a database (MySQL). I can save Users to the database in the code but cannot save Blogposts Or comments. The blog posts are supposed to be saved with random user IDs from all user tables so that the specific user who made the post would be able to edit the post he made, not the others. Also, comments have the same story, but comments are randomly assigned to posts. Previously it has been tried to save posts to a database using PHP artisan tinker.

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $users = User::factory()->count(20)->create();
        dd($users->count());
        $posts = BlogPost::factory()->count(50)->make()
            ->each(function ($post) use ($users) {
            $post->user()->associate($users->random())->save();
        });
        $comments = Comment::factory()->count(150)->make()
            ->each(function ($comment) use ($posts) {
            $comment->blog_post_id = $posts->random()->id;
        });
    }
}

When making a migration, there are no errors shown. For migration, we use the following.

php artisan migrate:refresh --seed

Body:
Well, the meaning of dd() is dump and die. Therefore you are stoping the seed execution after the User factory.

Just remove the dd() and seed should be executed as expected

<?php
namespace Database\Seeders;
use App\Models\User;
use App\Models\BlogPost;
use App\Models\Comment;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $users = User::factory()->count(20)->create();
        // dd($users->count()); <-- This stops the seed execution
        $posts = BlogPost::factory()->count(50)->make()->each(function($post) use ($users) {
            $post->user()->associate($users->random())->save();
        });
        $comments = Comment::factory()->count(150)->make()->each(function ($comment) use ($posts){
            $comment->blog_post_id = $posts->random()->id;
        });
    }
}


答:
So you are multiplying string with float. One of your variable is holding string value.
You can var_dump() to see which variable hold the string data, and change the value to float. Otherwise you can cast those variable to float.

```<code>$pricere1 = (float)$db_price * (float)$validate->getIntervalFactor($runtime) * (float)$mainrabatt_script;
</code>```

Title: TypeError: "Unsupported operand types: string * float"

Body:
I have the Error: TypeError Unsupported operand types: string * float
The Error is in this Line:
$pricere1 = $db_price * $validate->getIntervalFactor($runtime) * $mainrabatt_script;
I tried to find the Error but nothing worked for me :/

Body:
So you are multiplying string with float. One of your variable is holding string value.
You can var_dump() to see which variable hold the string data, and change the value to float. Otherwise you can cast those variable to float.

$pricere1 = (float)$db_price * (float)$validate->getIntervalFactor($runtime) * (float)$mainrabatt_script;


问:
Drop down widget is not showing in flutter
I am design a screen in which I need to opening a drop down list when user click on textfield till now I am using CupertinoActionSheetAction sheet which is correctly working now I need to replace it with DropdownButton but when I am doing it is not displaying on screen I don't know why.

Here is my code focus on line number 136 (function for CupertinoActionSheetAction is working code) and line 138 where (function for drop not working code) according to me may be it due to build context but I m not sure how to use 'build context' in this context can any one help me out to fix that.

Thanks in advance, And any suggestion for making my code more reusable will be helpful as well :)

```<code>import 'dart:ffi';

import 'package:fleet_management/AppContants/Contants.dart';
import 'package:fleet_management/Controllers/NewFuelExpenseController.dart';
import 'package:fleet_management/Models/NewFuelExpenseModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AddFuelView extends StatefulWidget {
  const AddFuelView({Key? key}) : super(key: key);
  @override
  _AddFuelView createState() {
    return _AddFuelView();
  }

}

// MyTripHistoryView
class _AddFuelView extends State<AddFuelView> {
  NewFuelExpenseModel fuelExpense =
      NewFuelExpenseController().getNewFuelExpense();

  DateTime _selectedDate = DateTime.now();

  String dropdownvalue = 'Item 1';

  // List of items in our dropdown menu
  var items = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
  ];

  TextStyle _titleTextStyle = const TextStyle();
  TextStyle _valueTextStyle = const TextStyle();
  final GlobalKey newFuelExpenseFormField = GlobalKey<FormState>();
  final TextEditingController _dateEditingController = TextEditingController();
  final TextEditingController _priceTextEditingController =
      TextEditingController();
  final TextEditingController _gallonsTextEditingController =
      TextEditingController();
  final TextEditingController _totalTextEditingController =
      TextEditingController();
  final TextEditingController _odometerTextEditingController =
      TextEditingController();
  final TextEditingController _fuelTypeTextEditingController =
      TextEditingController();
  final TextEditingController _vendorTextEditingController =
      TextEditingController();

  @override
  void initState() {
    super.initState();
    _titleTextStyle =
        const TextStyle(fontSize: 16, fontWeight: FontWeight.w600);
    _valueTextStyle = const TextStyle(
        fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black38);
    _dateEditingController.text =
        "${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
  }

  @override
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      appBar: AppBar(
        title: Text(StringsConstants.newFuelExpense),
        backgroundColor: AppColorsConstants.primaryColor,
        actions: <Widget>[
          FlatButton(
            textColor: Colors.white,
            onPressed: () {
              print("SAVE Button Clicked");
            },
            child: Text("Save", style: _titleTextStyle),
          ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Form(
              key: newFuelExpenseFormField,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  showDateRow(context),

                  addTextFieldInput(
                      StringsConstants.priceGallon,
                      "\u{20B9}0.00",
                      false,
                      _priceTextEditingController,
                      TextInputType.datetime,
                      null,
                      null),

                  addTextFieldInput(
                      StringsConstants.gallons,
                      "",
                      false,
                      _gallonsTextEditingController,
                      TextInputType.number,
                      null,
                      null),

                  addTextFieldInput(
                      StringsConstants.total,
                      "\u{20B9}0.00",
                      false,
                      _totalTextEditingController,
                      TextInputType.number,
                      null,
                      null),

                  addTextFieldInput(
                      StringsConstants.odometer,
                      "",
                      false,
                      _odometerTextEditingController,
                      TextInputType.number,
                      null,
                      null),

                  // show action sheet
                  addTextFieldInput(
                      StringsConstants.fuelType,
                      "",
                      true,
                      _fuelTypeTextEditingController,
                      TextInputType.none,
                      null, () {
                    // Working. - >>>> HERE <<<<<
                    showActionSheet(context);
                    // Not Working >>>> HERE <<<<< Uncomment following function before
                    // showDropDown();
                  }),
                  addTextFieldInput(
                      StringsConstants.vendor,
                      "",
                      false,
                      _vendorTextEditingController,
                      TextInputType.text,
                      null,
                      null),
                  const SizedBox(
                    height: 50,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      ElevatedButton(
                          onPressed: () {
                            print("Submit button pressed!");
                          },
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(horizontal: 24),
                            primary: AppColorsConstants.primaryColor,
                            textStyle:
                                const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          child: Text(StringsConstants.submit)),
                      ElevatedButton(
                          onPressed: () {
                            print("Cancel button pressed!");

                          },
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(horizontal: 24),
                            primary: AppColorsConstants.primaryColor,
                            textStyle:
                                const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          child: Text(StringsConstants.cancel))
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
    return scaffold;
  }
  void showDropDown() {
    DropdownButton<String>(
      items: <String>['A', 'B', 'C', 'D'].map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (_) {},
    );
  }

  Future<dynamic> showActionSheet(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
          title: const Text('Choose Options'),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: const Text('Oil'),
              onPressed: () {
                _fuelTypeTextEditingController.text = "Oil";
                Navigator.pop(context, 'Oil');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('Petrol'),
              onPressed: () {
                _fuelTypeTextEditingController.text = "Petrol";
                Navigator.pop(context, 'Petrol');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('diesel'),
              onPressed: () {
                _fuelTypeTextEditingController.text = "diesel";
                Navigator.pop(context, 'diesel');
              },
            )
          ],
          cancelButton: CupertinoActionSheetAction(
            child: const Text('Cancel'),
            isDefaultAction: true,
            onPressed: () {
              Navigator.pop(context, 'Cancel');
            },
          )),
    );
  }

  Container addTextFieldInput(
    String title,
    String initialValue,
    bool isEditable,
    TextEditingController textfieldController,
    TextInputType keyboardType,
    FormFieldValidator<String>? validator,
    GestureTapCallback? tabCallback,
  ) {
    return Container(
      padding: const EdgeInsets.fromLTRB(0, 16, 0, 8),
      child: SizedBox(
        child: TextFormField(
          onTap: tabCallback,
          keyboardType: keyboardType,
          cursorHeight: 16,
          cursorWidth: 1.4,
          readOnly: isEditable,
          controller: textfieldController,
          validator: validator,
          decoration: InputDecoration(
              isDense: true,
              floatingLabelStyle:
                  TextStyle(color: AppColorsConstants.primaryColor),
              labelText: title,
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(
                    color: AppColorsConstants.primaryColor, width: 1.5),
              ),
              enabledBorder: const OutlineInputBorder(
                borderSide: BorderSide(color: Colors.black38, width: 1.5),
              ),
              border: const OutlineInputBorder()),
          style: const TextStyle(fontSize: 18),
          cursorColor: Colors.black38,
          showCursor: true,
          autofocus: true,
        ),
      ),
    );
  }

  Container showDateRow(BuildContext context) {
    return Container(
      child: TextFormField(
        onTap: () => {_selectDate(context)},
        cursorHeight: 16,
        cursorWidth: 1.4,
        readOnly: true,
        enableInteractiveSelection: false,
        controller: _dateEditingController,
        decoration: InputDecoration(
            isDense: true,
            labelStyle: const TextStyle(color: Colors.orangeAccent),
            labelText: StringsConstants.date,
            focusedBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.orangeAccent, width: 1.5),
            ),
            enabledBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.black38, width: 1.5),
            ),
            border: const OutlineInputBorder()),
        style: const TextStyle(fontSize: 18),
        cursorColor: Colors.black38,
        showCursor: true,
        autofocus: true,
      ),
    );
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate,
        firstDate: DateTime(1990),
        lastDate: DateTime.now());
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        this._dateEditingController.text =
            "${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
      });
    }
  }
}

</code>```

答:
For DropDown in flutter you need

an initail value,

a list to be shown just

String selectedvalue='myvalue';

/// be sure you add the variable value in the 0 index of you list other wise it will thrown error or exception..

```<code>List<String> myList=[
 'myvalue',/// the value is same as variable value
 'othe value', ....
];

DropDownButton(
 onChanged: (resultValue){
  /// you can get selected value from here
 },
 items: myList.map((e){
  retrun DropdownMenuItem(
     value: e,
     child: Text(e));
 }).toList(),
 value: selectedvalue,
),
</code>```

Body:
I am design a screen in which I need to opening a drop down list when user click on textfield till now I am using CupertinoActionSheetAction sheet which is correctly working now I need to replace it with DropdownButton but when I am doing it is not displaying on screen I don't know why.

Here is my code focus on line number 136 (function for CupertinoActionSheetAction is working code) and line 138 where (function for drop not working code) according to me may be it due to build context but I m not sure how to use 'build context' in this context can any one help me out to fix that.

Thanks in advance, And any suggestion for making my code more reusable will be helpful as well :)

import 'dart:ffi';

import 'package:fleet_management/AppContants/Contants.dart';
import 'package:fleet_management/Controllers/NewFuelExpenseController.dart';
import 'package:fleet_management/Models/NewFuelExpenseModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AddFuelView extends StatefulWidget {
  const AddFuelView({Key? key}) : super(key: key);
  @override
  _AddFuelView createState() {
    return _AddFuelView();
  }

}

// MyTripHistoryView
class _AddFuelView extends State<AddFuelView> {
  NewFuelExpenseModel fuelExpense =
      NewFuelExpenseController().getNewFuelExpense();

  DateTime _selectedDate = DateTime.now();

  String dropdownvalue = 'Item 1';

  // List of items in our dropdown menu
  var items = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
  ];

  TextStyle _titleTextStyle = const TextStyle();
  TextStyle _valueTextStyle = const TextStyle();
  final GlobalKey newFuelExpenseFormField = GlobalKey<FormState>();
  final TextEditingController _dateEditingController = TextEditingController();
  final TextEditingController _priceTextEditingController =
      TextEditingController();
  final TextEditingController _gallonsTextEditingController =
      TextEditingController();
  final TextEditingController _totalTextEditingController =
      TextEditingController();
  final TextEditingController _odometerTextEditingController =
      TextEditingController();
  final TextEditingController _fuelTypeTextEditingController =
      TextEditingController();
  final TextEditingController _vendorTextEditingController =
      TextEditingController();

  @override
  void initState() {
    super.initState();
    _titleTextStyle =
        const TextStyle(fontSize: 16, fontWeight: FontWeight.w600);
    _valueTextStyle = const TextStyle(
        fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black38);
    _dateEditingController.text =
        "${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
  }

  @override
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      appBar: AppBar(
        title: Text(StringsConstants.newFuelExpense),
        backgroundColor: AppColorsConstants.primaryColor,
        actions: <Widget>[
          FlatButton(
            textColor: Colors.white,
            onPressed: () {
              print("SAVE Button Clicked");
            },
            child: Text("Save", style: _titleTextStyle),
          ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Form(
              key: newFuelExpenseFormField,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  showDateRow(context),

                  addTextFieldInput(
                      StringsConstants.priceGallon,
                      "\u{20B9}0.00",
                      false,
                      _priceTextEditingController,
                      TextInputType.datetime,
                      null,
                      null),

                  addTextFieldInput(
                      StringsConstants.gallons,
                      "",
                      false,
                      _gallonsTextEditingController,
                      TextInputType.number,
                      null,
                      null),

                  addTextFieldInput(
                      StringsConstants.total,
                      "\u{20B9}0.00",
                      false,
                      _totalTextEditingController,
                      TextInputType.number,
                      null,
                      null),

                  addTextFieldInput(
                      StringsConstants.odometer,
                      "",
                      false,
                      _odometerTextEditingController,
                      TextInputType.number,
                      null,
                      null),

                  // show action sheet
                  addTextFieldInput(
                      StringsConstants.fuelType,
                      "",
                      true,
                      _fuelTypeTextEditingController,
                      TextInputType.none,
                      null, () {
                    // Working. - >>>> HERE <<<<<
                    showActionSheet(context);
                    // Not Working >>>> HERE <<<<< Uncomment following function before
                    // showDropDown();
                  }),
                  addTextFieldInput(
                      StringsConstants.vendor,
                      "",
                      false,
                      _vendorTextEditingController,
                      TextInputType.text,
                      null,
                      null),
                  const SizedBox(
                    height: 50,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      ElevatedButton(
                          onPressed: () {
                            print("Submit button pressed!");
                          },
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(horizontal: 24),
                            primary: AppColorsConstants.primaryColor,
                            textStyle:
                                const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          child: Text(StringsConstants.submit)),
                      ElevatedButton(
                          onPressed: () {
                            print("Cancel button pressed!");

                          },
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(horizontal: 24),
                            primary: AppColorsConstants.primaryColor,
                            textStyle:
                                const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          child: Text(StringsConstants.cancel))
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
    return scaffold;
  }
  void showDropDown() {
    DropdownButton<String>(
      items: <String>['A', 'B', 'C', 'D'].map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (_) {},
    );
  }

  Future<dynamic> showActionSheet(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
          title: const Text('Choose Options'),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: const Text('Oil'),
              onPressed: () {
                _fuelTypeTextEditingController.text = "Oil";
                Navigator.pop(context, 'Oil');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('Petrol'),
              onPressed: () {
                _fuelTypeTextEditingController.text = "Petrol";
                Navigator.pop(context, 'Petrol');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('diesel'),
              onPressed: () {
                _fuelTypeTextEditingController.text = "diesel";
                Navigator.pop(context, 'diesel');
              },
            )
          ],
          cancelButton: CupertinoActionSheetAction(
            child: const Text('Cancel'),
            isDefaultAction: true,
            onPressed: () {
              Navigator.pop(context, 'Cancel');
            },
          )),
    );
  }

  Container addTextFieldInput(
    String title,
    String initialValue,
    bool isEditable,
    TextEditingController textfieldController,
    TextInputType keyboardType,
    FormFieldValidator<String>? validator,
    GestureTapCallback? tabCallback,
  ) {
    return Container(
      padding: const EdgeInsets.fromLTRB(0, 16, 0, 8),
      child: SizedBox(
        child: TextFormField(
          onTap: tabCallback,
          keyboardType: keyboardType,
          cursorHeight: 16,
          cursorWidth: 1.4,
          readOnly: isEditable,
          controller: textfieldController,
          validator: validator,
          decoration: InputDecoration(
              isDense: true,
              floatingLabelStyle:
                  TextStyle(color: AppColorsConstants.primaryColor),
              labelText: title,
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(
                    color: AppColorsConstants.primaryColor, width: 1.5),
              ),
              enabledBorder: const OutlineInputBorder(
                borderSide: BorderSide(color: Colors.black38, width: 1.5),
              ),
              border: const OutlineInputBorder()),
          style: const TextStyle(fontSize: 18),
          cursorColor: Colors.black38,
          showCursor: true,
          autofocus: true,
        ),
      ),
    );
  }

  Container showDateRow(BuildContext context) {
    return Container(
      child: TextFormField(
        onTap: () => {_selectDate(context)},
        cursorHeight: 16,
        cursorWidth: 1.4,
        readOnly: true,
        enableInteractiveSelection: false,
        controller: _dateEditingController,
        decoration: InputDecoration(
            isDense: true,
            labelStyle: const TextStyle(color: Colors.orangeAccent),
            labelText: StringsConstants.date,
            focusedBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.orangeAccent, width: 1.5),
            ),
            enabledBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.black38, width: 1.5),
            ),
            border: const OutlineInputBorder()),
        style: const TextStyle(fontSize: 18),
        cursorColor: Colors.black38,
        showCursor: true,
        autofocus: true,
      ),
    );
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate,
        firstDate: DateTime(1990),
        lastDate: DateTime.now());
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        this._dateEditingController.text =
            "${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
      });
    }
  }
}

Body:
For DropDown in flutter you need

an initail value,

a list to be shown just

String selectedvalue='myvalue';

/// be sure you add the variable value in the 0 index of you list other wise it will thrown error or exception..

List<String> myList=[
 'myvalue',/// the value is same as variable value
 'othe value', ....
];

DropDownButton(
 onChanged: (resultValue){
  /// you can get selected value from here
 },
 items: myList.map((e){
  retrun DropdownMenuItem(
     value: e,
     child: Text(e));
 }).toList(),
 value: selectedvalue,
),


问:
Setting an attribute from a parents attribute
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

```<code><ul id="menu">
    <li id="home" class="tab_selected"><a href="home.php">Home</a></li>
    <li id="portfolio"><a href="portfolio.php">Portfolio</a></li>
    <li id="music"><a href="music.php">Music</a></li>
    <li id="video"><a href="video.php">Video</a></li>
    <li id="photo"><a href="photo.php">Photo</a></li>
</ul>
</code>```

I have been trying something like this:

```<code>$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));
</code>```

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.

答:
All jQuery

```<code>$('#menu li a').each(function () {
    var a = $(this);
    a.attr('href', "#" + a.parent().attr('id');
});
</code>```

Part jQuery

```<code>$('#menu li a').each(function () {
    this.href = "#" + $(this).parent()[0].id;
});
</code>```

Less Part jQuery

```<code>$('#menu li a').each(function () {
    this.href = "#" + this.parentNode.id;
});
</code>```

Take your pick :)

Body:
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

Home

Portfolio

Music

Video

Photo

I have been trying something like this:

$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.

Body:
All jQuery

$('#menu li a').each(function () {
    var a = $(this);
    a.attr('href', "#" + a.parent().attr('id');
});

Part jQuery

$('#menu li a').each(function () {
    this.href = "#" + $(this).parent()[0].id;
});

Less Part jQuery

$('#menu li a').each(function () {
    this.href = "#" + this.parentNode.id;
});

Take your pick :)


问:
How to parameterize verilog attribute (* *)?
How can I declare a signal with a verilog attribute depending on module's parameter?

I tried:

```<code>if (KEEP_VERILOG) begin
  (*keep="true"*)reg mysig;
end else begin
  reg mysig;
end

// doing something with mysig
</code>```

I get a synthesis error: mysig is not declared

答:
Attribute spec allows using constant expressions. Therefore you can use module parameter directly in the attribute:

```<code>(*keep=KEEP_VERILOG*) reg mysig;
</code>```

The value of the attribute will have the value of the parameter.

Body:
How can I declare a signal with a verilog attribute depending on module's parameter?

I tried:

if (KEEP_VERILOG) begin
  (*keep="true"*)reg mysig;
end else begin
  reg mysig;
end

// doing something with mysig

I get a synthesis error: mysig is not declared

Body:
Attribute spec allows using constant expressions. Therefore you can use module parameter directly in the attribute:

(*keep=KEEP_VERILOG*) reg mysig;

The value of the attribute will have the value of the parameter.


问:
Is it possible to draw 3d segments with CGAL?
I want to draw 3d segments, and the camera can rotate, so that I can observe the segments from various perspectives. I wonder if there is a way to draw them with CGAL? I know that CGAL is not specific for visualization, so the question itself may be some kind of silly. But it will be really helpful for me if it has this function, because I have some experience with CGAL.
I have tried to learn OpenGL, but it's not possible for me to master it in a short time. And I don't want to spend much time to learn OpenGL, because I will not use it again in future work.

If CGAL doesn't have this function, could you please recommend some lightweight open source libraries which can draw 3d segments? I don't need a very feature-rich, but huge library. One easy to use and lightweight is best for me. Thanks a lot!

答:
CGAL::Basic_viewer_qt allows to draw points, segments and faces in 2D/3D.
You can define your own viewer inheriting from this class.

As suggested by Marc, have a look at the different draw_XXX.h files to see how this is achieved for several viewers in CGAL.


问:
Get Spotify access token with spotipy on Django and Python
I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify.

To do it I have a button that opens the view below

views.py

```<code>@authenticated_user
def spotify_login(request):

    sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                           client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                           redirect_uri="http://127.0.0.1:8000/",
                           scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    auth_token = sp_auth.get_access_token()
    print(auth_token)
    print("----- this is the AUTH_TOKEN url -------", auth_token)
    return HttpResponseRedirect(redirect_url)
</code>```

If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever.

Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser?

答:
The solution was to create a new view to access the URL

views.py

```<code>from .utils import is_user_already_auth_spotify, spotify_oauth2

@authenticated_user
def spotify_login(request):

    if is_user_already_auth_spotify(request.user.username):
        messages.error(request, "You have already linked your Spotify account")
        return HttpResponseRedirect('account/' + str(request.user.username))

    sp_auth = spotify_oauth2()
    redirect_url = sp_auth.get_authorize_url()
    return HttpResponseRedirect(redirect_url)

@authenticated_user
def spotify_callback(request):
    full_path = request.get_full_path()
    parsed_url = urlparse(full_path)
    spotify_code = parse_qs(parsed_url.query)['code'][0]

    sp_auth = spotify_oauth2()
    token = sp_auth.get_access_token(spotify_code)

    data = {
        str(request.user.username): token
    }
    with open('spotify_auth.json', 'w') as f:
        json.dump(data, f)

    messages.success(request, "You have correctly linked your Spotify account")

    return HttpResponseRedirect('account/' + str(request.user.username))
</code>```

urls.py

```<code>urlpatterns = [
    path('account/<str:username>/', views.account_user, name="account"),
    path('spotify_login', views.spotify_login, name="spotify_login"),
    path('spotify_callback', views.spotify_callback, name="spotify_callback"),
]
</code>```

utils.py

```<code>import json
from spotipy import oauth2
import os

def is_user_already_auth_spotify(username):
    my_loaded_dict = {}
    with open('spotify_auth.json', 'r') as f:
        try:
            my_loaded_dict = json.load(f)
        except:
            # file vuoto
            pass
    if str(username) in my_loaded_dict:
        # controllare scadenza token ed in caso rinnovarlo
        return True
    else:
        return False

def spotify_oauth2():
    sp_auth = oauth2.SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                                  client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                                  redirect_uri="http://127.0.0.1:8000/members/spotify_callback",
                                  scope="user-library-read")
    return sp_auth
</code>```

The code also saves the token in a JSON and search for it if it has already been saved

Body:
I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify.

To do it I have a button that opens the view below

views.py

@authenticated_user
def spotify_login(request):

    sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                           client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                           redirect_uri="http://127.0.0.1:8000/",
                           scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    auth_token = sp_auth.get_access_token()
    print(auth_token)
    print("----- this is the AUTH_TOKEN url -------", auth_token)
    return HttpResponseRedirect(redirect_url)

If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever.

Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser?

Body:
The solution was to create a new view to access the URL

views.py

from .utils import is_user_already_auth_spotify, spotify_oauth2

@authenticated_user
def spotify_login(request):

    if is_user_already_auth_spotify(request.user.username):
        messages.error(request, "You have already linked your Spotify account")
        return HttpResponseRedirect('account/' + str(request.user.username))

    sp_auth = spotify_oauth2()
    redirect_url = sp_auth.get_authorize_url()
    return HttpResponseRedirect(redirect_url)

@authenticated_user
def spotify_callback(request):
    full_path = request.get_full_path()
    parsed_url = urlparse(full_path)
    spotify_code = parse_qs(parsed_url.query)['code'][0]

    sp_auth = spotify_oauth2()
    token = sp_auth.get_access_token(spotify_code)

    data = {
        str(request.user.username): token
    }
    with open('spotify_auth.json', 'w') as f:
        json.dump(data, f)

    messages.success(request, "You have correctly linked your Spotify account")

    return HttpResponseRedirect('account/' + str(request.user.username))

urls.py

urlpatterns = [
    path('account/<str:username>/', views.account_user, name="account"),
    path('spotify_login', views.spotify_login, name="spotify_login"),
    path('spotify_callback', views.spotify_callback, name="spotify_callback"),
]

utils.py

import json
from spotipy import oauth2
import os

def is_user_already_auth_spotify(username):
    my_loaded_dict = {}
    with open('spotify_auth.json', 'r') as f:
        try:
            my_loaded_dict = json.load(f)
        except:
            # file vuoto
            pass
    if str(username) in my_loaded_dict:
        # controllare scadenza token ed in caso rinnovarlo
        return True
    else:
        return False

def spotify_oauth2():
    sp_auth = oauth2.SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                                  client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                                  redirect_uri="http://127.0.0.1:8000/members/spotify_callback",
                                  scope="user-library-read")
    return sp_auth

The code also saves the token in a JSON and search for it if it has already been saved


问:
How do I change the color of these svg icons of the selected tab?
I'm wondering how I can most efficiently change the color of the icon of the selected tab.</p>
```<code>  const [trainColor, setTrainColor] = React.useState('')
  const [busColor, setBusColor] = React.useState('')

  return (
    <StyledSectionContainer>
      <InnerContainer>
        <Tabs.Root defaultValue="tab1">
          <StyledTabsList aria-label="tabs example">
            <StyledTabsTrigger value="tab2">
              <Train
                color={trainColor}
                onClick={() => setTrainColor(theme.color.orange)}
              />
            </StyledTabsTrigger>
            <StyledTabsTrigger value="tab3">
              <Bus
                color={busColor}
                onClick={() => setBusColor(theme.color.orange)}
              />
            </StyledTabsTrigger>
          </StyledTabsList>
</code>```

答:
Radix icons use currentColor so, try wrapping you icons with a div that provides the color:

```<code><div style={{ color: trainColor}}><Train onClick={...} /></div>
</code>```

Body:
I'm wondering how I can most efficiently change the color of the icon of the selected tab.

  const [trainColor, setTrainColor] = React.useState('')
  const [busColor, setBusColor] = React.useState('')

  return (

          </StyledTabsList>

Body:
Radix icons use currentColor so, try wrapping you icons with a div that provides the color:

<div style={{ color: trainColor}}><Train onClick={...} /></div>


问:
Deploy ElasticSearch Docker Container to AWS Fargate
I'm trying to deploy non custom single node elasticsearch:7.8.1 docker container to AWS ECS Fargate.

On my local I simply executed:

```<code>docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.8.1
</code>```

And it spined up ES container for me which my app utilises. I want do have the same container available in the cloud.

How can I do it?

Update: I was able to deploy ES to Fargate but it fails in attempt to access it with error message:

```<code>ERROR: [3] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
[3]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured
</code>```

After short googling I found this post where they fixed the problem by turning single node mode on. I dont quite understand how I can turn it on in Fargate, is it in task definition or how?

Another question would be what is the most common way of running ES in AWS? in EC2 or AWS ES service? My aim is to setup infra as quickly as I can. I have got .net core app running in docker using elastic search.

答:
You can solve the first issue with setting ulimits - I'm using task definition from within Terraform:

```<code>ulimits = [
    {
      name      = "nofile"
      softLimit = 65535
      hardLimit = 65535
    }]
</code>```

For the vm.max_map_count you can disable checking via setting ES_SETTING_NODE_STORE_ALLOW__MMAP to false.

Body:
I'm trying to deploy non custom single node elasticsearch:7.8.1 docker container to AWS ECS Fargate.

On my local I simply executed:

docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.8.1

And it spined up ES container for me which my app utilises. I want do have the same container available in the cloud.

How can I do it?

Update: I was able to deploy ES to Fargate but it fails in attempt to access it with error message:

ERROR: [3] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
[3]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured

After short googling I found this post where they fixed the problem by turning single node mode on. I dont quite understand how I can turn it on in Fargate, is it in task definition or how?

Another question would be what is the most common way of running ES in AWS? in EC2 or AWS ES service? My aim is to setup infra as quickly as I can. I have got .net core app running in docker using elastic search.

Body:
You can solve the first issue with setting ulimits - I'm using task definition from within Terraform:

ulimits = [
    {
      name      = "nofile"
      softLimit = 65535
      hardLimit = 65535
    }]

For the vm.max_map_count you can disable checking via setting ES_SETTING_NODE_STORE_ALLOW__MMAP to false.


问:
jQuery/JavaScript "this" pointer confusion
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

```<code>// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("<div>click me</div>").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}
</code>```

答:
You might find this:

Controlling the value of 'this' in a jQuery event

or this:

http://www.learningjquery.com/2007/08/what-is-this

Useful.

OwnerDisplayName: I. J. Kennedy

Body:
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("
click me
").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}

OwnerDisplayName: Will Dean


问:
Spring - import jpa repositories from another module
I have two gradle modules: common and app

The common module contains a JpaRepository named OutboxJpaMessageRepository.

The app module contains another JpaRepository named RentRepository.

The common has the following configuration class, which is auto-imported by the other module (using a spring.factories file):

@Configuration
@EntityScan("path.to.common.module")
@EnableJpaRepositories("path.to.common.module")
@ComponentScan("path.to.common.module")
public class OutboxMessagingAutoConfig {
}
```

The problem is that @EnableJpaRepositories("path.to.common.module") overrides the default auto-configuration of the application, and the app can't find RentRepository (different package).

Can a library exports jpa repositories without override the default configuration of the client?

I don't want to re-configure all apps which use the common module

答:
The boot module must contain multi path lick this:

@ComponentScan({"path.to.common.module", "path.to.app.module"})

Body:
I have two gradle modules: common and app

The common module contains a JpaRepository named OutboxJpaMessageRepository.

The app module contains another JpaRepository named RentRepository.

The common has the following configuration class, which is auto-imported by the other module (using a spring.factories file):

@Configuration
@EntityScan("path.to.common.module")
@EnableJpaRepositories("path.to.common.module")
@ComponentScan("path.to.common.module")
public class OutboxMessagingAutoConfig {
}

The problem is that @EnableJpaRepositories("path.to.common.module") overrides the default auto-configuration of the application, and the app can't find RentRepository (different package).

Can a library exports jpa repositories without override the default configuration of the client?

I don't want to re-configure all apps which use the common module


问:
Is there a way to reset password with Firebase Auth INSIDE a flutter app?
Firebase Auth has a method to send a verification email so the user can reset his/her password. This link redirects the user to a website where the new password will be written and saved.

Is there a way to reset a user's password using flutter and firebase inapp? I mean, could I send a verification code through SMS or email that would be then typed into the app and the user would choose a new password all inside the app?

Thank you!

答:
You can do so by using custom email handlers along with dynamic links to open them in your app. This might require a custom domain to do so. Once the user visits your application on the custom route/page, you can then use applyActionCode method to process the email action. Checkout my answer here for a detailed explanation on processing the email actions:

How to build a custom Email action handler in Flutter for Firebase Authentication