问:
what is the output this null character printing?
I am expecting a blank space for the printf("%c",i) while its clearly returning a value after the evaluation of the statement, So I think it should print a blank like or some other value for that matter as it's not null string it's null character.

All i am saying is printf returns some value when the call completes, as it is a function. so when printf("%c",i) is returning some value it should print something.

```<code>#include<stdio.h>
int main()
{
    int  i = 0;
    if(printf("%c",i))
        printf("inside if block");
    else
        printf("inside else block");
    return 0;
}
</code>```

答:
I am expecting a blank space for the printf("%c",i)

printf("%c",0) will print the null character.  What is seen on a terminal is implementation dependent.  It might be a space, nothing, ␀, �, ^@, etc.  It has nothing to do with C strings.

i am saying is printf returns some value when the call completes

The return value of printf("%c",i) is "... the number of characters transmitted, or a negative value if an output
or encoding error occurred." (C17dr § 7.21.6.3 3).  printf("inside if block"); is certainly executed as a 1 is likely returned from (printf("%c",i).

Body:
I am expecting a blank space for the printf("%c",i) while its clearly returning a value after the evaluation of the statement, So I think it should print a blank like or some other value for that matter as it's not null string it's null character.

All i am saying is printf returns some value when the call completes, as it is a function. so when printf("%c",i) is returning some value it should print something.

#include<stdio.h>
int main()
{
    int  i = 0;
    if(printf("%c",i))
        printf("inside if block");
    else
        printf("inside else block");
    return 0;
}


来源: stackexchange

问:
How to make greedy regex for heading text? [as against tailing text]
Consider the following text:

```<code><bla><bla text><bla>
</code>```

I want to get the regex to match exactly the middle <bla text>. I tried \<.*?text.*?\> but it is capturing the string right from the start, since it starts with '<'.

Thanks a lot.

答:
Here is your regexp.</p>

```<code>/>(<bla.*?>)/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Consider the following text:

<bla><bla text><bla>

I want to get the regex to match exactly the middle <bla text>. I tried \<.*?text.*?\> but it is capturing the string right from the start, since it starts with '<'.

Thanks a lot.

Body:
Here is your regexp.

/>(<bla.*?>)/


问:
Delete files with python through OS shell
Im Tyring to Delete all Files in E:.
with wildcard. </p>

```<code>E:\test\*.txt
</code>```

<p>I would ask rather than test the os.walk.
In windows.  </p>

答:
If you want to delete file with more than one extension then define those extensions in tuple like below</p>

```<code>import os

def purge(dir):
    files = os.listdir(dir)
    ext = ('.txt', '.xml', '.json')
    for file in files:
        if file.endswith(ext):
            print("File -> " + os.path.join(dir,file))
            os.remove(os.path.join(dir,file))
</code>```

Body:
Im Tyring to Delete all Files in E:.
with wildcard.

E:\test\*.txt

I would ask rather than test the os.walk.
In windows.

Body:
If you want to delete file with more than one extension then define those extensions in tuple like below

import os

def purge(dir):
    files = os.listdir(dir)
    ext = ('.txt', '.xml', '.json')
    for file in files:
        if file.endswith(ext):
            print("File -> " + os.path.join(dir,file))
            os.remove(os.path.join(dir,file))

ContentLicense: CC BY-SA 4.0


问:
Remove elements from lists, code is leaving just one
I'm working on a beginning python exercise with strings and methods.  (I know that there are some extra print statements and comments.)  The goal is to return every other item from the list.  So for the first example the goal is to return - # Should be ['a', 'c', 'e', 'g']

I'm struggling, because I can not figure out why my code won't delete 'b' from the list.  What am I missing? .

I've looked at the following specific StackOverflow questions.  (Plus others)

Need help on List of Strings

How to remove an element from a list by index

Remove empty strings from a list of strings

Difference between del, remove and pop on lists

```<code>def skip_elements(elements):
    L_elements = len(elements)
    for x in elements:
        print("This is L_elements: " , L_elements)
        #print(x)
        if (L_elements % 2 == 0):
          elements.pop((L_elements-1))
          print(elements)
        if (L_elements == 2):
          print("This is L_elements: " , L_elements, "Should equal 2")
        L_elements = L_elements - 1
    return elements

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
</code>```

答:
If you look at the debug output from your program you'll see that your loop doesn't get L_elements all the way down to 1 as it should. This is because you are shortening elements in the loop and so the loop (for x in elements) doesn't execute as often as you expect it to. If you change your for x in elements to for i in range(L_elements) it will work as expected.

It's much simpler though to write this as a list comprehension:

```<code>def skip_elements(elements):
    return [e for i, e in enumerate(elements) if i % 2 == 0]
</code>```

Body:
I'm working on a beginning python exercise with strings and methods.  (I know that there are some extra print statements and comments.)  The goal is to return every other item from the list.  So for the first example the goal is to return - # Should be ['a', 'c', 'e', 'g']

I'm struggling, because I can not figure out why my code won't delete 'b' from the list.  What am I missing? .

I've looked at the following specific StackOverflow questions.  (Plus others)

Need help on List of Strings

How to remove an element from a list by index

Remove empty strings from a list of strings

Difference between del, remove and pop on lists

def skip_elements(elements):
    L_elements = len(elements)
    for x in elements:
        print("This is L_elements: " , L_elements)
        #print(x)
        if (L_elements % 2 == 0):
          elements.pop((L_elements-1))
          print(elements)
        if (L_elements == 2):
          print("This is L_elements: " , L_elements, "Should equal 2")
        L_elements = L_elements - 1
    return elements

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

Body:
If you look at the debug output from your program you'll see that your loop doesn't get L_elements all the way down to 1 as it should. This is because you are shortening elements in the loop and so the loop (for x in elements) doesn't execute as often as you expect it to. If you change your for x in elements to for i in range(L_elements) it will work as expected.

It's much simpler though to write this as a list comprehension:

def skip_elements(elements):
    return [e for i, e in enumerate(elements) if i % 2 == 0]


问:
Where do I find Angular CLI 7.3.9 default generated webpack settings file so I can build my overrides based on it?
I want to extend webpack building process for a project generated by Angular CLI v7.3.9.

I found out I have to use this tool:
https://github.com/just-jeb/angular-builders/tree/7.x.x/packages/custom-webpack

It seems a good solution, but unfortunately I can't find any example about extending existing Angular CLI config file.

I mean - I want to see what Angular CLI already generates for me, before I can think of correct overrides I should use in my custom builder override config. Being somewhat new to webpack, I need to learn what's already there to be able to figure out what I can adjust to avoid totally breaking the project.

Where do I find Angular CLI default generated webpack settings file so I can build my overrides based on it?

To be more specific, the problem is that building the project for production takes about 25 minutes. It is a large project with a few hundreds of form and grid components, and I see that current build process is spending about 20 minutes in ModuleConcatenationPlugin and 5 minutes in TerserPlugin without any serious load on the computer resources. I've heard ModuleConcatenationPlugin is being deprecated and thought that maybe I could use something better instead (UglifyJS ? optimization.concatenateModules ?), but at first I have to find out how Angular CLI uses it, so I can override it correctly.

答:
You can use ngx-build-plus

Example:

Add ngx-build-plus: ng add ngx-build-plus

Add a file webpack.partial.js to the root of your (sub-)project:

```<code>     const webpack = require('webpack');

        module.exports = {
            plugins: [
                new webpack.DefinePlugin({
                    "VERSION": JSON.stringify("4711")
                })
            ]
        }
</code>```

Use the global variable VERSION in your app.component.ts:

```<code>import { Component } from '@angular/core';

declare const VERSION: string;

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Version: ' + VERSION;
}
</code>```

Start your application with the --extra-webpack-config switch pointing to your partial webpack config:

```<code>ng serve --extra-webpack-config webpack.partial.js -o
</code>```

If your project is a CLI based sub project, use the --project switch too:

```<code>ng serve --project getting-started -o --extra-webpack-config webpack.partial.js
</code>```

Update you can take a look at their doc and here is the full config

Body:
You can use ngx-build-plus

Example:

Add ngx-build-plus: ng add ngx-build-plus

Add a file webpack.partial.js to the root of your (sub-)project:

     const webpack = require('webpack');

        module.exports = {
            plugins: [
                new webpack.DefinePlugin({
                    "VERSION": JSON.stringify("4711")
                })
            ]
        }

Use the global variable VERSION in your app.component.ts:

import { Component } from '@angular/core';

declare const VERSION: string;

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Version: ' + VERSION;
}

Start your application with the --extra-webpack-config switch pointing to your partial webpack config:

ng serve --extra-webpack-config webpack.partial.js -o

If your project is a CLI based sub project, use the --project switch too:

ng serve --project getting-started -o --extra-webpack-config webpack.partial.js

Update you can take a look at their doc and here is the full config


问:
Is view.leadingAnchor.constraint higher precedence than view.trailingAnchor.constraint?
I have my ViewController code as below

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = .white
        let titleLabel = UILabel()
        titleLabel.text = "Hello World!"

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
}
</code>```

I'm expecting my "Hello World!" to be center aligned. Why wasn't it center aligned? (Vertically it is centered, but horizontally it is aligned to left as shown below.)

p/s: If I remove itleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), then it is aligned right.

答:
In iOS 9 and later, the default value of textAlignment property of UILabel is NSTextAlignment.natural, prior to iOS 9, the default value was NSTextAlignment.left

If you want your label to cover the entire view with the text-centered then your constraints are perfect, just set

```<code>titleLabel.textAlignment = .center
</code>```

Body:
I have my ViewController code as below

class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = .white
        let titleLabel = UILabel()
        titleLabel.text = "Hello World!"

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
}

I'm expecting my "Hello World!" to be center aligned. Why wasn't it center aligned? (Vertically it is centered, but horizontally it is aligned to left as shown below.)

p/s: If I remove itleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), then it is aligned right.

Body:
In iOS 9 and later, the default value of textAlignment property of UILabel is NSTextAlignment.natural, prior to iOS 9, the default value was NSTextAlignment.left

If you want your label to cover the entire view with the text-centered then your constraints are perfect, just set

titleLabel.textAlignment = .center


问:
Performance of SELECT Query based on WHERE clause
I am having some data in the session table, which holds the user location along with some other data related to user

The session table consists of multiple columns like

id - PRIMARY KEY AUTO-INCREMENT

session_id - UNIQUE KEY(This will be unique for every time, even if user logs in multiple times, this will be generated UNIQUE)

user_id (This user id is unique to every user)

user_location (Holds the coordinates of the user)

Problem Statment

I wanted to know that is there any performance difference between the below two queries.

First Query

SELECT user_location FROM session WHERE session_id = 'some-session-id-goes-here';

Second Query

SELECT user_location FROM session WHERE session_id = 'some-session-id-goes-here' AND user_id ='usome-user-id';

Both the queries give correct data, but is there any effect on performance if suppose there is millions for data present in this session table.

Running both queries on smaller set of  data < 4000 did not give any difference in fetching time.

答:
Normally, when you declare a column with UNIQUE Key it is indexed by default.
As you have not mentioned if your user_id is declared unique or not(you said user_id is unique, I assume its values are but not defined in your create table script). So in that sense they will give same performance. But if you index your user_id too then the case can be different.
When you have multiple column indexed and you are querying using them, you must maintain their index-sequence after where clause and your query performance will be better than the current one. Otherwise, the effect will be negative for not maintaining the sequence order.
You can check columns index sequence by

show index from your_table_name

For some more insight, you can check here MySQL: unique field needs to be an index?


问:
Sequelize Errors
I'm new to using Sequelize, I attempted to create a currency system for a Discord Bot game I'm developing. Maybe I'm making the tables entirely wrong, but I thought this method would work for me too. I have a few more files such as dbInit.js, dbObjects.js, and in a models folder I have models/CurrencyShop.js, models/Users.js, models/UserItems.js if you need to see any of those let me know.

Here are the errors:

```<code>(node:5916) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: SQLITE_ERROR: no such table: users
    at Query.formatError (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:422:16)
    at Query._handleQueryResponse (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:73:18)
    at afterExecute (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:250:31)
    at Statement.errBack (C:\Users\ryang\node_modules\sqlite3\lib\sqlite3.js:16:21)
(node:5916) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5916) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Here is my app.js code:

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

const client = new Discord.Client();
const { Users, CurrencyShop } = require('./dbObjects');
const { Op } = require('sequelize');
const currency = new Discord.Collection();
const PREFIX = '!';

Reflect.defineProperty(currency, 'add', {
    value: async function add(id, amount) {
        const user = currency.get(id);
        if (user) {
            user.balance += Number(amount);
            return user.save();
        }
        const newUser = await Users.create({ user_id: id, balance: amount });
        currency.set(id, newUser);
        return newUser;
    },
});

Reflect.defineProperty(currency, 'getBalance', {
    value: function getBalance(id) {
        const user = currency.get(id);
        return user ? user.balance : 0;
    },
});

client.once('ready', async () => {
    const storedBalances = await Users.findAll();
    storedBalances.forEach(b => currency.set(b.user_id, b));
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', async message => {
    if (message.author.bot) return;
    currency.add(message.author.id, 1);

    if (!message.content.startsWith(PREFIX)) return;
    const input = message.content.slice(PREFIX.length).trim();
    if (!input.length) return;
    const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

    if (command === 'balance') {
        const target = message.mentions.users.first() || message.author;
        return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
    } else if (command === 'inventory') {
        const target = message.mentions.users.first() || message.author;
        const user = await Users.findOne({ where: { user_id: target.id } });
        const items = await user.getItems();

        if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
        return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);
    } else if (command === 'transfer') {
        const currentAmount = currency.getBalance(message.author.id);
        const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
        const transferTarget = message.mentions.users.first();

        if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
        if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
        if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);

        currency.add(message.author.id, -transferAmount);
        currency.add(transferTarget.id, transferAmount);

        return message.channel.send(`Successfully transferred ${transferAmount} to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}`);
    } else if (command === 'buy') {
        const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
        if (!item) return message.channel.send(`That item doesn't exist.`);
        if (item.cost > currency.getBalance(message.author.id)) {
            return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
        }

        const user = await Users.findOne({ where: { user_id: message.author.id } });
        currency.add(message.author.id, -item.cost);
        await user.addItem(item);

        message.channel.send(`You've bought: ${item.name}.`);
    } else if (command === 'shop') {
        const items = await CurrencyShop.findAll();
        return message.channel.send(items.map(item => `${item.name}: ${item.cost}`).join('\n'), { code: true });
    } else if (command === 'leaderboard') {
        return message.channel.send(
        currency.sort((a, b) => b.balance - a.balance)
            .filter(user => client.users.has(user.user_id))
            .first(10)
            .map((user, position) => `(${position + 1}) ${(client.users.get(user.user_id).tag)}: ${user.balance}`)
            .join('\n'),
        { code: true }
        );
    }
});

client.login('Njc4MTM2MzY1NTE0MzU4Nzg0.XkxHOQ.mx9sBQt0BlLlcCKn1NKP_GnbhIY');
</code>```

I'd appreciate either documentation, videos, or an explanation. Thanks!

答:
use try-catch</p>

```<code> client.on('message', async message => {
    try{

       if (message.author.bot) return;
        currency.add(message.author.id, 1);

        if (!message.content.startsWith(PREFIX)) return;
        const input = message.content.slice(PREFIX.length).trim();
        if (!input.length) return;
        const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

        if (command === 'balance') {
            const target = message.mentions.users.first() || message.author;
            return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
        } else if (command === 'inventory') {
            const target = message.mentions.users.first() || message.author;
            const user = await Users.findOne({ where: { user_id: target.id } });
            const items = await user.getItems();

            if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
            return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);
        } else if (command === 'transfer') {
            const currentAmount = currency.getBalance(message.author.id);
            const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
            const transferTarget = message.mentions.users.first();

            if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
            if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
            if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);

            currency.add(message.author.id, -transferAmount);
            currency.add(transferTarget.id, transferAmount);

            return message.channel.send(`Successfully transferred ${transferAmount} to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}`);
        } else if (command === 'buy') {
            const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
            if (!item) return message.channel.send(`That item doesn't exist.`);
            if (item.cost > currency.getBalance(message.author.id)) {
                return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
            }

            const user = await Users.findOne({ where: { user_id: message.author.id } });
            currency.add(message.author.id, -item.cost);
            await user.addItem(item);

            message.channel.send(`You've bought: ${item.name}.`);
        } else if (command === 'shop') {
            const items = await CurrencyShop.findAll();
            return message.channel.send(items.map(item => `${item.name}: ${item.cost}`).join('\n'), { code: true });
        } else if (command === 'leaderboard') {
            return message.channel.send(
            currency.sort((a, b) => b.balance - a.balance)
                .filter(user => client.users.has(user.user_id))
                .first(10)
                .map((user, position) => `(${position + 1}) ${(client.users.get(user.user_id).tag)}: ${user.balance}`)
                .join('\n'),
            { code: true }
            );
        }

    }catch(err){
     // handle all error here
     // Like SQLITE_ERROR: no such table: users
       console.log(err)
    }

    });
</code>```

Title: Sequelize Errors

Body:
I'm new to using Sequelize, I attempted to create a currency system for a Discord Bot game I'm developing. Maybe I'm making the tables entirely wrong, but I thought this method would work for me too. I have a few more files such as dbInit.js, dbObjects.js, and in a models folder I have models/CurrencyShop.js, models/Users.js, models/UserItems.js if you need to see any of those let me know.

Here are the errors:

(node:5916) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: SQLITE_ERROR: no such table: users
    at Query.formatError (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:422:16)
    at Query._handleQueryResponse (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:73:18)
    at afterExecute (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:250:31)
    at Statement.errBack (C:\Users\ryang\node_modules\sqlite3\lib\sqlite3.js:16:21)
(node:5916) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5916) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here is my app.js code:

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

const client = new Discord.Client();
const { Users, CurrencyShop } = require('./dbObjects');
const { Op } = require('sequelize');
const currency = new Discord.Collection();
const PREFIX = '!';

Reflect.defineProperty(currency, 'add', {
    value: async function add(id, amount) {
        const user = currency.get(id);
        if (user) {
            user.balance += Number(amount);
            return user.save();
        }
        const newUser = await Users.create({ user_id: id, balance: amount });
        currency.set(id, newUser);
        return newUser;
    },
});

Reflect.defineProperty(currency, 'getBalance', {
    value: function getBalance(id) {
        const user = currency.get(id);
        return user ? user.balance : 0;
    },
});

client.once('ready', async () => {
    const storedBalances = await Users.findAll();
    storedBalances.forEach(b => currency.set(b.user_id, b));
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', async message => {
    if (message.author.bot) return;
    currency.add(message.author.id, 1);

    if (!message.content.startsWith(PREFIX)) return;
    const input = message.content.slice(PREFIX.length).trim();
    if (!input.length) return;
    const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

    if (command === 'balance') {
        const target = message.mentions.users.first() || message.author;
        return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
    } else if (command === 'inventory') {
        const target = message.mentions.users.first() || message.author;
        const user = await Users.findOne({ where: { user_id: target.id } });
        const items = await user.getItems();

        if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
        return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);
    } else if (command === 'transfer') {
        const currentAmount = currency.getBalance(message.author.id);
        const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
        const transferTarget = message.mentions.users.first();

        if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
        if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
        if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);

        currency.add(message.author.id, -transferAmount);
        currency.add(transferTarget.id, transferAmount);

        return message.channel.send(`Successfully transferred ${transferAmount} to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}`);
    } else if (command === 'buy') {
        const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
        if (!item) return message.channel.send(`That item doesn't exist.`);
        if (item.cost > currency.getBalance(message.author.id)) {
            return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
        }

        const user = await Users.findOne({ where: { user_id: message.author.id } });
        currency.add(message.author.id, -item.cost);
        await user.addItem(item);

        message.channel.send(`You've bought: ${item.name}.`);
    } else if (command === 'shop') {
        const items = await CurrencyShop.findAll();
        return message.channel.send(items.map(item => `${item.name}: ${item.cost}`).join('\n'), { code: true });
    } else if (command === 'leaderboard') {
        return message.channel.send(
        currency.sort((a, b) => b.balance - a.balance)
            .filter(user => client.users.has(user.user_id))
            .first(10)
            .map((user, position) => `(${position + 1}) ${(client.users.get(user.user_id).tag)}: ${user.balance}`)
            .join('\n'),
        { code: true }
        );
    }
});

client.login('Njc4MTM2MzY1NTE0MzU4Nzg0.XkxHOQ.mx9sBQt0BlLlcCKn1NKP_GnbhIY');

I'd appreciate either documentation, videos, or an explanation. Thanks!

Body:
use try-catch

 client.on('message', async message => {
    try{

       if (message.author.bot) return;
        currency.add(message.author.id, 1);

        if (!message.content.startsWith(PREFIX)) return;
        const input = message.content.slice(PREFIX.length).trim();
        if (!input.length) return;
        const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

        if (command === 'balance') {
            const target = message.mentions.users.first() || message.author;
            return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
        } else if (command === 'inventory') {
            const target = message.mentions.users.first() || message.author;
            const user = await Users.findOne({ where: { user_id: target.id } });
            const items = await user.getItems();

            if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
            return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);
        } else if (command === 'transfer') {
            const currentAmount = currency.getBalance(message.author.id);
            const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
            const transferTarget = message.mentions.users.first();

            if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
            if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
            if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);

            currency.add(message.author.id, -transferAmount);
            currency.add(transferTarget.id, transferAmount);

            return message.channel.send(`Successfully transferred ${transferAmount} to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}`);
        } else if (command === 'buy') {
            const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
            if (!item) return message.channel.send(`That item doesn't exist.`);
            if (item.cost > currency.getBalance(message.author.id)) {
                return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
            }

            const user = await Users.findOne({ where: { user_id: message.author.id } });
            currency.add(message.author.id, -item.cost);
            await user.addItem(item);

            message.channel.send(`You've bought: ${item.name}.`);
        } else if (command === 'shop') {
            const items = await CurrencyShop.findAll();
            return message.channel.send(items.map(item => `${item.name}: ${item.cost}`).join('\n'), { code: true });
        } else if (command === 'leaderboard') {
            return message.channel.send(
            currency.sort((a, b) => b.balance - a.balance)
                .filter(user => client.users.has(user.user_id))
                .first(10)
                .map((user, position) => `(${position + 1}) ${(client.users.get(user.user_id).tag)}: ${user.balance}`)
                .join('\n'),
            { code: true }
            );
        }

    }catch(err){
     // handle all error here
     // Like SQLITE_ERROR: no such table: users
       console.log(err)
    }

    });


问:
create new RelativeLayout Programmatically in Android
my UI is like this :

every grid has some object , I want to no. seven is blank use RelativeLayout programmatically.

what do I do , Thanks.

答:
Try this. You can change button border color with backgroundTint attribute.

```<code><RelativeLayout ...>
         <LinearLayout ...
                android:orientation="horizontal"
                android:weightSum="0.9">
                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>
         </LinearLayout>

         <LinearLayout ...
                android:orientation="horizontal"
                android:weightSum="0.9">
                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>
         </LinearLayout>

         <LinearLayout ...
                android:orientation="horizontal"
                android:weightSum="0.9">
                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>
         </LinearLayout>
</RelativeLayout>
</code>```

Create border.xml in drawable folder.

```<code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#FFFFFF"/>
    <stroke
        android:width="3dp"
        android:color="#0FECFF"/>
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp"/>
</shape>
</code>```

Body:
Try this. You can change button border color with backgroundTint attribute.

<RelativeLayout ...>
         <LinearLayout ...
                android:orientation="horizontal"
                android:weightSum="0.9">
                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>
         </LinearLayout>

         <LinearLayout ...
                android:orientation="horizontal"
                android:weightSum="0.9">
                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>
         </LinearLayout>

         <LinearLayout ...
                android:orientation="horizontal"
                android:weightSum="0.9">
                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>

                  <Button android:width="match_parent"
                          android:height="wrap_content"
                          android:layout_weight="0.3"
                          android:background="@drawable/border"/>
         </LinearLayout>
</RelativeLayout>

Create border.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#FFFFFF"/>
    <stroke
        android:width="3dp"
        android:color="#0FECFF"/>
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp"/>
</shape>


问:
How to open new activity by clicking on SearchView
I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

```<code>searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
});
</code>```

My XML:

```<code><SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>
</code>```

答:
use this code,</p>

```<code>searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(A.this, B.class));
        }
    });
</code>```

Body:
I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
});

My XML:

<SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>

Body:
use this code,

searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(A.this, B.class));
        }
    });


问:
For each loop not working in App Script runtime powered by Chrome V8
[Sorry Guys. Already edited my question.]

For each loop resulted into an error if I enable the Chrome V8 in my Apps Script. Any way to solve this issue beside disabling it? A lot of my functions use the said syntax.

For example I have a sheet containing columns week name, start date and end date (refer on the attached image). Once I read them on my codes I would like to access each items using for each loop but an error occur due to v8.

```<code>function weeks(){

  SS = SpreadsheetApp;
  SHEET = SS.getActiveSpreadsheet();

  var sheet = SHEET.getSheetByName("Weeks");
  var row = sheet.getLastRow();
  var range = "A2:D" + row;
  var arrWeeks = sheet.getRange(range).getValues();

  for each(var week in arrWeeks){

    Logger.log("week: " + week[0])
    Logger.log("start date: " + week[1])
    Logger.log("end date: " + week[2])

  }

}

</code>```

Source

Error

答:
Read the migration documentation: for each (var ___ in ____)  is not supported and should never be used:

https://developers.google.com/apps-script/guides/v8-runtime/migration#avoid_for_eachvariable_in_object

When migrating your script to V8, avoid using for each (variable in object) statements.

Instead, use for (variable in object)

Body:
[Sorry Guys. Already edited my question.]

For each loop resulted into an error if I enable the Chrome V8 in my Apps Script. Any way to solve this issue beside disabling it? A lot of my functions use the said syntax.

For example I have a sheet containing columns week name, start date and end date (refer on the attached image). Once I read them on my codes I would like to access each items using for each loop but an error occur due to v8.

function weeks(){

  SS = SpreadsheetApp;
  SHEET = SS.getActiveSpreadsheet();

  var sheet = SHEET.getSheetByName("Weeks");
  var row = sheet.getLastRow();
  var range = "A2:D" + row;
  var arrWeeks = sheet.getRange(range).getValues();

  for each(var week in arrWeeks){

    Logger.log("week: " + week[0])
    Logger.log("start date: " + week[1])
    Logger.log("end date: " + week[2])

  }

}

Source

Error


问:
Azure Pipeline trigger on reopening a PR
Currently my azure pipeline triggers when I create a new PR in github, however I would like it to trigger also when I reopen a closed PR, I couldn't find any documentation related to this scenario, hence I am unsure if it's possible.

This is the current configuration

```<code>pr:
  autoCancel: false
  branches:
    include:
    - master
</code>```

答:
Azure Pipeline trigger on reopening a PR

Yes, it is possible!

Our document does not mentioned very clearly, it only described:

This configuration triggers a build when any pull request is created,
  and when commits come into the source branch of any active pull
  request.

In fact, it does create one new commit to source branch once you reopen the PR. So obviously it can trigger the pipeline.

As result show, this is my triggered history by github PR. (You can see the commit id was changed)

And here is the operations history in github. You can see the PR reopen trigger the pipeline successfully.

Body:
Currently my azure pipeline triggers when I create a new PR in github, however I would like it to trigger also when I reopen a closed PR, I couldn't find any documentation related to this scenario, hence I am unsure if it's possible.

This is the current configuration

pr:
  autoCancel: false
  branches:
    include:
    - master


问:
How to check if a remote server supports PHP?
I often have clients who do not know if their server supports PHP (their website is HTML web site). At the moment, I send them hello.php file, they upload it and then I check it remotely if their server supports PHP. As you see this takes day or two and it's just a waste of time.

Can I myself any how check if their server supports PHP (via web browser or console tool)? If the domain is for example www.my-client.com, what would be the syntax?

Thanks

PS. I have an access to Linux console so I could use it as well

答:
Can also try with

```<code>http://www.example.com/?=PHPE9568F36-D428-11d2-A769-00AA001ACF42
</code>```

Some servers will respond with a PHP image then. If you have shell access, it is more reliable to test whether php in installed directly on the system though. Whether PHP exposes if it is installed via this Easter Egg or via the Response Headers can be disabled in the PHP.ini.

Read more at

php_logo_guid — Gets the logo guid and

expose_php ini setting

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.

Body:
Can also try with

http://www.example.com/?=PHPE9568F36-D428-11d2-A769-00AA001ACF42

Some servers will respond with a PHP image then. If you have shell access, it is more reliable to test whether php in installed directly on the system though. Whether PHP exposes if it is installed via this Easter Egg or via the Response Headers can be disabled in the PHP.ini.

Read more at

php_logo_guid — Gets the logo guid and

expose_php ini setting

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.


问:
How to make EditText ediable but disable no keyboard?
I made a calculator. Its working fine. I want to have touch focus in edittext but the problem is when i touch it the keyboard popup. How to disable keyboard?

Screenshot of Calculator

```<code><EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="bottom|end"
    android:textSize="40sp"
    android:enabled="true"
    android:singleLine="true"
    android:textIsSelectable="true"
    android:scrollHorizontally="true"
    android:id="@+id/tvExpression_ID"/>
</code>```

答:
use this three line code to solve your issue</p>

```<code>etText = findViewById(R.id.etText);
etText.setRawInputType(InputType.TYPE_CLASS_TEXT);
etText.setTextIsSelectable(true);
</code>```

Body:
I made a calculator. Its working fine. I want to have touch focus in edittext but the problem is when i touch it the keyboard popup. How to disable keyboard?

Screenshot of Calculator

<EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="bottom|end"
    android:textSize="40sp"
    android:enabled="true"
    android:singleLine="true"
    android:textIsSelectable="true"
    android:scrollHorizontally="true"
    android:id="@+id/tvExpression_ID"/>

Body:
use this three line code to solve your issue

etText = findViewById(R.id.etText);
etText.setRawInputType(InputType.TYPE_CLASS_TEXT);
etText.setTextIsSelectable(true);


问:
Error while setting up a multi-broker cluster on Local Machine
Using Kafka on Ubuntu:
Zookeeper started
Kafka started
Topic Created
Producer started
Consumer started
Messages are delivering fine from producer to consumer

I created 2 new server.properties files as:
server-1.properties as:

```<code>broker.id=1
listeners=PLAINTEXT://:9093
log.dir=C:\kafka\kafka-logs-1
</code>```

server-2.properties as:

```<code>broker.id=2
listeners=PLAINTEXT://:9094
log.dir=C:\kafka\kafka-logs-2
</code>```

When i started the new broker as:

```<code>bin\windows\kafka-server-start.sh config\server-1.properties &
</code>```

Got Error as:

```<code>kafka.common.KafkaException: Socket server failed to bind to 0.0.0.0:9092: Address already in use: bind
</code>```

答:
if you are using multiple brokers then use the following type of broker declaration on the

server.properties

```<code>broker.id=0
listeners=PLAINTEXT://:9092
log.dirs=/tmp/kafka-logs
</code>```

server.1.properties

```<code>broker.id=1
listeners=PLAINTEXT://:9093
log.dirs=/tmp/kafka-logs1
</code>```

server.2.properties

```<code>broker.id=2
listeners=PLAINTEXT://:9094
log.dirs=/tmp/kafka-logs2
</code>```

server.3.properties

```<code>broker.id=3
listeners=PLAINTEXT://:9095
log.dirs=/tmp/kafka-logs3
</code>```

Body:
Using Kafka on Ubuntu:
Zookeeper started
Kafka started
Topic Created
Producer started
Consumer started
Messages are delivering fine from producer to consumer

I created 2 new server.properties files as:
server-1.properties as:

broker.id=1
listeners=PLAINTEXT://:9093
log.dir=C:\kafka\kafka-logs-1

server-2.properties as:

broker.id=2
listeners=PLAINTEXT://:9094
log.dir=C:\kafka\kafka-logs-2

When i started the new broker as:

bin\windows\kafka-server-start.sh config\server-1.properties &

Got Error as:

kafka.common.KafkaException: Socket server failed to bind to 0.0.0.0:9092: Address already in use: bind

Body:
if you are using multiple brokers then use the following type of broker declaration on the

server.properties

broker.id=0
listeners=PLAINTEXT://:9092
log.dirs=/tmp/kafka-logs

server.1.properties

broker.id=1
listeners=PLAINTEXT://:9093
log.dirs=/tmp/kafka-logs1

server.2.properties

broker.id=2
listeners=PLAINTEXT://:9094
log.dirs=/tmp/kafka-logs2

server.3.properties

broker.id=3
listeners=PLAINTEXT://:9095
log.dirs=/tmp/kafka-logs3


问:
How does an MVC 5 view request with parameter data a controller to launch another view
This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method.
I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):

```<code>   $(document).ready(function () {
        $('#PurchaseOrderLineItemAddId').click(function () {
            var aPurchaseOrderViewModel = @Html.Raw(Json.Encode(Model));
            var selectedVendorText = $('#ddlvendors option:selected').text();
            var selectedVendorValue = $('#ddlvendors option:selected').val();
            var LineItemReqJsonObj = {};

            LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
            LineItemReqJsonObj.VendorText = selectedVendorText;
            LineItemReqJsonObj.VendorValue = selectedVendorValue;

            var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';

                $.ajax(
                    {
                        type: "POST",
                        //data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
                        //data: aPurchaseOrderViewModelStr,
                        data: dataToPass,
                        url: '@Url.Action("PurchaseOrderAddItem")',
                        contentType: "application/json; charset=utf-8",
                        datatype: "json"
                    })
               .done(function (aNewLineItemViewModel) {
                    AddNewLineItemReceived(aNewLineItemViewModel);
                    })
                    .fail(function (xhr) {
                        alert('error', xhr);
                    });
        });
    });
</code>```

Below is the action method in the controller which receives the above ajax request:

```<code>[HttpPost]
public ActionResult PurchaseOrderAddItem(LineItemReqJsonObj aLineItemReqJsonObj)
{
  LineItemViewModel aLineItemViewModel = new LineItemViewModel();

  aLineItemViewModel.PurchaseOrderId = aLineItemReqJsonObj.PurchaseOrderId;
  aLineItemViewModel.VendorId = Convert.ToInt32(aLineItemReqJsonObj.VendorValue);

  return View(aLineItemViewModel);
}
</code>```

Below is the class in the controller which gets data filled into it as it is passed in from the JavaScript:

```<code>   public class LineItemJsonObj
    {
      public string PurchaseOrderId {get;set;}
      public string VendorText { get; set; }
      public string VendorValue { get; set; }
    };
</code>```

The below diagram illustrates what I am trying to do:

As the diagram shows, I am unable to get the PurchaseOrderAddItem View to be shown. How do I get the PurchaseOrderAddItem View to show, receiving parameter data, after the PurchaseOrder View has invoked the PurchaseOrderAddItem Action From the controller?
  Thanks in advance.

-- UPDATE 2/17/2020 1:38PST--
I am probably incorrect in thinking the controller could start the PurchaseOrderAddItem View which when
closed could get the resulting new model data somehow back to the PurchaseOrder
View with the JavaScript that started this.

I am beginning to think this approach using the JavaScript $Ajax to
reach the controller is not the right way to do this. I'm checking now to see
if maybe I should of just loaded another web page from the PurcahseOrder View
with parameter data to create a new PurchaseOrderAddItem View.  The challenge here though would
be to probably pack up the entire PurchaseOrder view model data to go with the
PurchaseOrderAddItem View request. If I have the entire PurchaseOrder View Model
data when I exit the PurchaseOrderAddItem View I will be able to load a new
PurchaseOrder View and pass it all the data that was in the first instance so it
is repopulated to include the newly added line items. I'm not sure this is
the right way to do this. I have not seen any examples yet of how this type of
application view presentation problem is handled. I would appreciate it if anyone can
point me to any internet articles that perhaps cover how to design this type of
MVC application. This is very easy to do in desktop apps but web development
with MVC makes this very different and needing a lot more work than something
in WPF or WinForms.

答: The solution for me in this case was to use the TempData dictionary object to help transport data from the PurchaseOrder View request to the LineItem View and back. There is no sensitive data in this data transport so using TempData should be fine. Additionally, to launch the LineItem view to create a new Line Item worked better for me to just us the standard submit action from within an Html.BeginForm block. The standard post operation provided by the submit button is what I used in this case rather than a button to run $.Ajax code in a JavaScript. Ajax was really not needed in this case since the whole PurchaseOrder View was to be replaced by the LineItem create view.</p>

Body:
This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method.
I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):

   $(document).ready(function () {
        $('#PurchaseOrderLineItemAddId').click(function () {
            var aPurchaseOrderViewModel = @Html.Raw(Json.Encode(Model));
            var selectedVendorText = $('#ddlvendors option:selected').text();
            var selectedVendorValue = $('#ddlvendors option:selected').val();
            var LineItemReqJsonObj = {};

            LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
            LineItemReqJsonObj.VendorText = selectedVendorText;
            LineItemReqJsonObj.VendorValue = selectedVendorValue;

            var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';

                $.ajax(
                    {
                        type: "POST",
                        //data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
                        //data: aPurchaseOrderViewModelStr,
                        data: dataToPass,
                        url: '@Url.Action("PurchaseOrderAddItem")',
                        contentType: "application/json; charset=utf-8",
                        datatype: "json"
                    })
               .done(function (aNewLineItemViewModel) {
                    AddNewLineItemReceived(aNewLineItemViewModel);
                    })
                    .fail(function (xhr) {
                        alert('error', xhr);
                    });
        });
    });

Below is the action method in the controller which receives the above ajax request:

[HttpPost]
public ActionResult PurchaseOrderAddItem(LineItemReqJsonObj aLineItemReqJsonObj)
{
  LineItemViewModel aLineItemViewModel = new LineItemViewModel();

  aLineItemViewModel.PurchaseOrderId = aLineItemReqJsonObj.PurchaseOrderId;
  aLineItemViewModel.VendorId = Convert.ToInt32(aLineItemReqJsonObj.VendorValue);

  return View(aLineItemViewModel);
}

Below is the class in the controller which gets data filled into it as it is passed in from the JavaScript:

   public class LineItemJsonObj
    {
      public string PurchaseOrderId {get;set;}
      public string VendorText { get; set; }
      public string VendorValue { get; set; }
    };

The below diagram illustrates what I am trying to do:

As the diagram shows, I am unable to get the PurchaseOrderAddItem View to be shown. How do I get the PurchaseOrderAddItem View to show, receiving parameter data, after the PurchaseOrder View has invoked the PurchaseOrderAddItem Action From the controller?
  Thanks in advance.

-- UPDATE 2/17/2020 1:38PST--
I am probably incorrect in thinking the controller could start the PurchaseOrderAddItem View which when
closed could get the resulting new model data somehow back to the PurchaseOrder
View with the JavaScript that started this.

I am beginning to think this approach using the JavaScript $Ajax to
reach the controller is not the right way to do this. I'm checking now to see
if maybe I should of just loaded another web page from the PurcahseOrder View
with parameter data to create a new PurchaseOrderAddItem View.  The challenge here though would
be to probably pack up the entire PurchaseOrder view model data to go with the
PurchaseOrderAddItem View request. If I have the entire PurchaseOrder View Model
data when I exit the PurchaseOrderAddItem View I will be able to load a new
PurchaseOrder View and pass it all the data that was in the first instance so it
is repopulated to include the newly added line items. I'm not sure this is
the right way to do this. I have not seen any examples yet of how this type of
application view presentation problem is handled. I would appreciate it if anyone can
point me to any internet articles that perhaps cover how to design this type of
MVC application. This is very easy to do in desktop apps but web development
with MVC makes this very different and needing a lot more work than something
in WPF or WinForms.


问:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)
Im facing problem with this line of code in keras with backend Tensorflow 2.0:

loss_out = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))([y_pred, Y_train, X_train_length, label_length])
```

Y_train, X_train_length are numpy.ndarrays
y_pred and label_length are class 'tensorflow.python.framework.ops.Tensor'

答:
You can create dummy inputs

```<code># you have defined the rest of your graph somewhere here

Y_train = Input(shape=...)
X_train_length = Input(shape=...)

loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,)
              )([y_pred, Y_train, X_train_length, label_length])

# defining the model is slightly different with multiple inputs
training_model = Model(inputs=[image_input, Y_train, X_train_length], outputs=[loss])
</code>```

And when you want to train your model you will pass the parameter x as a list of length 3, such as

```<code>x = [<images - np.ndarray shape (batch, h, w, c)>, <Y_train inputs - np.ndarray>,
     <X_train_length inputs - np.ndarray>]
</code>```

And of course dummy values for y

```<code>y = np.zeros((batch, 1))
</code>```

And it's never been simpler finally than training_model.train_on_batch(x, y)

Alternatively make a generator that generates x and y in the form described above and use training_model.fit_generator(data_generator)

Body:
Im facing problem with this line of code in keras with backend Tensorflow 2.0:

loss_out = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))([y_pred, Y_train, X_train_length, label_length])

Y_train, X_train_length are numpy.ndarrays
y_pred and label_length are class 'tensorflow.python.framework.ops.Tensor'

Body:
You can create dummy inputs

# you have defined the rest of your graph somewhere here

Y_train = Input(shape=...)
X_train_length = Input(shape=...)

loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,)
              )([y_pred, Y_train, X_train_length, label_length])

# defining the model is slightly different with multiple inputs
training_model = Model(inputs=[image_input, Y_train, X_train_length], outputs=[loss])

And when you want to train your model you will pass the parameter x as a list of length 3, such as

x = [<images - np.ndarray shape (batch, h, w, c)>, <Y_train inputs - np.ndarray>,
     <X_train_length inputs - np.ndarray>]

And of course dummy values for y

y = np.zeros((batch, 1))

And it's never been simpler finally than training_model.train_on_batch(x, y)

Alternatively make a generator that generates x and y in the form described above and use training_model.fit_generator(data_generator)


问:
C# Compiler Warning 1685
So, (seemingly) out of the blue, my project starts getting compiler warning 1685:

The predefined type
  'System.Runtime.CompilerServices.ExtensionAttribute'
  is defined in multiple assemblies in
  the global alias; using definition
  from 'c:\Program Files\Reference
  Assemblies\Microsoft\Framework\v3.5\System.Core.dll'

Perplexed, I researched the MSDN article to figure out its cause. Here's the information I found:

Visual C# Reference: Errors and
  Warnings Compiler Warning (level 1)
  CS1685

Error Message The predefined type
  'System.type name' is defined in
  multiple assemblies in the global
  alias; using definition from 'File
  Name'

This error occurs when a predefined
  system type such as System.int32 is
  found in two assemblies. One way this
  can happen is if you are referencing
  mscorlib from two different places,
  such as trying to run the.Net
  Framework versions 1.0 and 1.1
  side-by-side.

The compiler will use the definition
  from only one of the assemblies. The
  compiler searches only global aliases,
  does not search libraries defined
  /reference. If you have specified
  /nostdlib, the compiler will search
  for Object, and in the future start
  all searches for predefined types in
  the file where it found Object.

Now I'm really scratching my head.

I'm not running two different
versions of the .NET Framework
(unless you count 2.0 and 3.5).

I'm not referencing any bizarre
assemblies that might make me
suspicious.

I don't recall making any changes to my application that would spur this change.

I've verified that all components target .NET Framework version v2.0.50727.

I'm open to suggestions, or ideas on how to correct this. I treat warnings as errors, and it's driving me crazy.

What really bugs me about it is that I don't know why it's occurring. Things that happen should have a discernable cause, and I should know why they happened. If I can't explain it, I can't accurately remedy it. Guesswork is never satisfactory.

The application is straightforward, consisting of a class library, and a windows forms application.

A C# class library DLL providing basic functionality encapsulating database access. This DLL references the following components:

System

System.Core

System.Core.Data

System.Data

System.Data.DataSetExtensions

System.Data.OracleClient

System.Drawing

System.Windows.Forms

System.Xml

System.Xml.Linq

A C# Windows Forms application providing the UI. This application references the following components:

CleanCode

CleanCodeControls (both of these provide syntax editor support, and are locally built against .NET 3.5).

LinqBridge

Roswell.Framework (the class library above)

System

System.Core

System.Data

System.Data.DataSetExtensions

System.Data.OracleClient

System.Deployment

System.Design

System.Drawing

System.Windows.Forms

System.Xml

System.Xml.Linq

Let me know if you need further information and I'll gladly provide it.

答: LINQBridge makes me immediately suspicious. The entire intent of this is to provide extension attribute/methods etc for 2.0 users. If you have 3.5 (System.Core.dll), don't use LINQBridge. If you do need LINQBridge in 3.5 for some obscure reason (and I can't think of one), then you might have to use an extern alias. But I really doubt you need it!

OwnerDisplayName: Mike Hofer

Title: C# Compiler Warning 1685

OwnerDisplayName: Marc Gravell

ContentLicense: CC BY-SA 2.5


问:
checking for at least 1 number between 0-9 in a given password using c#
I'm trying to cycle through each char in a string to see if any of them are a number between 0-9. I'm getting an index out of bounds error for the numCheck array, so I know that my issue is that when I attempt to run, the IDE expects the length of txt_Pass.Text to = the number of chars I have in my array. This is wrong, but I'm not sure how to fix it. Would I need to use a vector since I'm not sure how long the input password will be? Or am I totally off?

```<code>        char[] numCheck = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        for (int i = 0; i < txt_Pass.Text.Length; i++)
        {
            if (txt_Pass.Text[i] != numCheck[i])
            {
                lbl_Form1_NumError.Visible = true;
            }
            lbl_Form1_NumError.Visible = false;
        }
</code>```

'''

答:
You will get an array index problem for any string with more than ten characters, since you iterate over all those values and use that iteration index to look into the numCheck array as well. Since this only has ten elements, accessing the 11th is a no-no.

A naive approach would be to have two nested loops to check if any character in numCheck is equal to any character of the input string, something like (this could be optimised somewhat but I haven't bothered since, as you'll find out below, it's totally unnecessary)

```<code>bool hasADigit = false;
for (int i = 0; i < txt_Pass.Text.Length; i++) {
    for (int j = 0; j < numCheck.Length; j++) {
        if (txt_Pass.Text[i] == numCheck[j]) {
            hasADigit = true;
        }
    }
}
// hasADigit is true if it, well, has a digit :-)
</code>```

But, as stated, this isn't really necessary when C# provides all sorts of wondrous library functions to do the heavy lifting for you:

```<code>bool hasADigit = (txt_Pass.Text.indexOfAny(numCheck) != -1);
</code>```

In summary, your entire code block can be reduced to:

```<code>char[] numCheck = {'0','1','2','3','4','5','6','7','8','9'};
lbl_Form1_NumError.Visible = (txt_Pass.Text.indexOfAny(numCheck) == -1);
</code>```

Body:
I'm trying to cycle through each char in a string to see if any of them are a number between 0-9. I'm getting an index out of bounds error for the numCheck array, so I know that my issue is that when I attempt to run, the IDE expects the length of txt_Pass.Text to = the number of chars I have in my array. This is wrong, but I'm not sure how to fix it. Would I need to use a vector since I'm not sure how long the input password will be? Or am I totally off?

        char[] numCheck = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        for (int i = 0; i < txt_Pass.Text.Length; i++)
        {
            if (txt_Pass.Text[i] != numCheck[i])
            {
                lbl_Form1_NumError.Visible = true;
            }
            lbl_Form1_NumError.Visible = false;
        }

'''

Body:
You will get an array index problem for any string with more than ten characters, since you iterate over all those values and use that iteration index to look into the numCheck array as well. Since this only has ten elements, accessing the 11th is a no-no.

A naive approach would be to have two nested loops to check if any character in numCheck is equal to any character of the input string, something like (this could be optimised somewhat but I haven't bothered since, as you'll find out below, it's totally unnecessary)

bool hasADigit = false;
for (int i = 0; i < txt_Pass.Text.Length; i++) {
    for (int j = 0; j < numCheck.Length; j++) {
        if (txt_Pass.Text[i] == numCheck[j]) {
            hasADigit = true;
        }
    }
}
// hasADigit is true if it, well, has a digit :-)

But, as stated, this isn't really necessary when C# provides all sorts of wondrous library functions to do the heavy lifting for you:

bool hasADigit = (txt_Pass.Text.indexOfAny(numCheck) != -1);

In summary, your entire code block can be reduced to:

char[] numCheck = {'0','1','2','3','4','5','6','7','8','9'};
lbl_Form1_NumError.Visible = (txt_Pass.Text.indexOfAny(numCheck) == -1);


问:
Unable to find an entry point named 'rd_kafka_producev' in shared library 'librdkafka'
I'm working on a .NET Core application that uses the Nuget package - Confluent.Kafka, Version 0.11.3

I'm using it to instantiate a Producer, then calling the myProducer.ProduceAsync method. I get an error in the application logs stating - Unable to find an entry point named 'rd_kafka_producev' in shared library 'librdkafka'.

I'm running Kafka in a container running on Debian v9. The docker container that's running the .NET Core application that uses Kafka has librdkafka1 - v0.9.3-1 installed. I needed to manually install it in the container as part of the Docker image, using:

RUN apt-get update -y
RUN apt-get install -y librdkafka-dev

I don't understand why I needed to install it manually anyway - this was to fix an error where the library wasn't being found at all. Shouldn't it already exist on the image? I'm using the standard wurstmeister/kafka Docker image.

Everything is working on a different server, where the exact same Confluent.Kafka package version is being used, and the exact same librdkafka1 is installed. Any ideas on how to fix this?

答:
I removed this from the Docker file:

RUN apt-get update -y
RUN apt-get install -y librdkafka-dev

Then, deleted librdkafka1 from the Debian container running my application. Redeployed my application to the container and now it works. The strange thing is, librdkafka1 now doesn't exist as a package on the container.

I found out that the librdkafka1 is a C++ library needed by the .NET Confluent.Kafka dependency within my .NET Core project. I also raised this Github issue, and Magnus Edenhill, the creator of librdkafka kindly provided this info:

confluent-kafka-dotnet depends on the librdkafka.redist nuget package
  which contains librdkafka, so you typically don't have to manually
  install librdkafka on the system (there are some cases where you
  might, such as when using GSSAPI).

So in most cases, as long as you have the Confluent.Kafka nuget package as a dependency in your solution, librdkafka should be installed somehow. So if you're getting similar issues to mine, it may be worth clearing out your deployment/container and any explicitly installed instances of librdkafka1, and redeploying to install the dependencies.


问:
How to run pure java code in Android Studio?
I am used to Android Studio and don't want to use other ide for Java development. How do I run pure java in Android Studio?</p>

答:
See this post.

In main menu-bar, go to File -> New -> New Module

Now scroll down to the bottom and select Java Library in the window that pops up

click next and set the package name in next screen

Click Finish. Android Studio will create Java Library Module for you. You are ready to code. All the short-cuts, key-mappings, auto-complete and scaffolding of IntelliJ platform is available for you to speed up your coding.

You can find your newly created Java Library in the Android scope in Project Navigator

You can add as many classes and packages you need.

Enter psvm (short for public static void main) and press enter to create your main method.

Once the method is created you will see green play button next to method and class to allow you to run your program.

Happy Coding!!!


问:
How to answer a pending or incoming call using its callSid on Twilio client using PHP?
I'm deploying Twilio on my website following Javascript Quickstart:  https://www.twilio.com/docs/voice/client/javascript/quickstart

I receive multiple calls and register info to my database, if I don't want my Twilio client answers an incoming call, I can hangup using the callSid according to this url: https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-update-a-call-resource-to-end-the-call&code-language=PHP&code-sdk-version=5.x

Code:

```<code><?php

include "../../../twilio_client/vendor/autoload.php";

use Twilio\Rest\Client;

$callsid = $_POST['callsid'];

// put your Twilio API credentials here
$accountSid = 'AC2XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = '67XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$twilio = new Client($accountSid, $authToken);

$call = $twilio->calls($callsid)->update(array("status" => "canceled"));
$calla = $twilio->calls($callsid)->fetch();
$parentCall = $calla->parentCallSid;
$call = $twilio->calls($parentCall)->update(array("status" => "completed"));

?>
</code>```

This works great, so in the same way but If I want to answer an incoming call using the callSid I tried with this according to this url: https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-update-a-call-in-progress-with-twiml

Code:

```<code><?php

include "../../../twilio_client/vendor/autoload.php";

use Twilio\Rest\Client;

$callsid = $_POST['callsid']; //callSid
$usrclient = $_POST['usrclient'];//client connected to receive calls

// put your Twilio API credentials here
$accountSid = 'AC2XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = '67XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$twilio = new Client($accountSid, $authToken);

$call = $twilio->calls($callsid)->update(array("twiml" => "<Response><Dial><Client>".$usrclient."</Client></Dial></Response>"));

?>
</code>```

But it doesn't work, It shows me this error:
[Wed Jan 15 23:14:06.493068 2020] [:error] [pid 30189] [client 190.239.139.220:18718] PHP Fatal error:  Uncaught exception 'Twilio\\Exceptions\\RestException' with message '[HTTP 400] Unable to update record: Call is not in-progress.

How can I fix it?

I'd like your help.

Thanks.

答:
You are getting a HTTP 400 error which is a BAD REQUEST. Twilio defines it as: The data given in the POST or PUT failed validation. Inspect the response body for details. https://www.twilio.com/docs/usage/your-request-to-twilio

And you have the error: call is not in-progress

As far as I can tell, your $_POST['usrclient'] is not correct. Check your POST to ensure it is valid.

You could also test your script by changing the Twiml to something simple and calling it yourself. Then you'll know if it's the script or the usrclient

```<code><Response><Say>Ahoy there</Say></Response>
</code>```

Body:
I'm deploying Twilio on my website following Javascript Quickstart:  https://www.twilio.com/docs/voice/client/javascript/quickstart

I receive multiple calls and register info to my database, if I don't want my Twilio client answers an incoming call, I can hangup using the callSid according to this url: https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-update-a-call-resource-to-end-the-call&code-language=PHP&code-sdk-version=5.x

Code:

<?php

include "../../../twilio_client/vendor/autoload.php";

use Twilio\Rest\Client;

$callsid = $_POST['callsid'];

// put your Twilio API credentials here
$accountSid = 'AC2XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = '67XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$twilio = new Client($accountSid, $authToken);

$call = $twilio->calls($callsid)->update(array("status" => "canceled"));
$calla = $twilio->calls($callsid)->fetch();
$parentCall = $calla->parentCallSid;
$call = $twilio->calls($parentCall)->update(array("status" => "completed"));

?>

This works great, so in the same way but If I want to answer an incoming call using the callSid I tried with this according to this url: https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-update-a-call-in-progress-with-twiml

Code:

<?php

include "../../../twilio_client/vendor/autoload.php";

use Twilio\Rest\Client;

$callsid = $_POST['callsid']; //callSid
$usrclient = $_POST['usrclient'];//client connected to receive calls

// put your Twilio API credentials here
$accountSid = 'AC2XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = '67XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$twilio = new Client($accountSid, $authToken);

$call = $twilio->calls($callsid)->update(array("twiml" => "<Response><Dial><Client>".$usrclient."</Client></Dial></Response>"));

?>

But it doesn't work, It shows me this error:
[Wed Jan 15 23:14:06.493068 2020] [:error] [pid 30189] [client 190.239.139.220:18718] PHP Fatal error:  Uncaught exception 'Twilio\\Exceptions\\RestException' with message '[HTTP 400] Unable to update record: Call is not in-progress.

How can I fix it?

I'd like your help.

Thanks.

Body:
You are getting a HTTP 400 error which is a BAD REQUEST. Twilio defines it as: The data given in the POST or PUT failed validation. Inspect the response body for details. https://www.twilio.com/docs/usage/your-request-to-twilio

And you have the error: call is not in-progress

As far as I can tell, your $_POST['usrclient'] is not correct. Check your POST to ensure it is valid.

You could also test your script by changing the Twiml to something simple and calling it yourself. Then you'll know if it's the script or the usrclient

<Response><Say>Ahoy there</Say></Response>


问:
node js webpack scss not showing up correctly
I'm trying to get my scss to show up correctly.  Most of it is working fine, but for some reason the footer isn't showing up correctly.  I'm using node js and webpack, both of which I am relatively new to.  I'm using the modules style-loader, css-loader and sass-loader.  Most of the page's' scss is working but for some reason the footer is not.  This is the relevant code.

footer.scss:

```<code>$font-stack: 'Montserrat', sans-serif;

footer{
    display: flex;
    justify-content: space-between;
    padding: 10px 40px;
    p{
        font: 50% $font-stack;
    }
}
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" href="/styles/style.scss">
        <link rel="stylesheet" href="/styles/form.scss">
        <link rel="stylesheet" href="/styles/header.scss">
        <link rel="stylesheet" href="/styles/footer.scss">

        <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
    </head>

    <body>

        <header>
            <div class="logo">
                News Article Processing
            </div>
        </header>

        <main>
            <section>
                <div class="holder">
                <form class="form" onsubmit="return handleSubmit(event)">
                    <input id="URL" type="text" name="input" value="" onblur="onBlur()" placeholder="URL" size="48">
                    <input type="submit" id="input" class="button" name="" value="submit" onclick="return handleSubmit(event)" onsubmit="return handleSubmit(event)">
                </form>
                </div>
            <section>

            <section>
                <div class="results">
                    <div class="box">
                        <strong>Results:</strong>
                    </div>
                    <div class="box">
                        Polarity: <div id="polarity"></div>
                    </div>
                    <div class="box">
                        Subjectivity: <div id="subjectivity"></div>
                    </div>
                    <div class="box">
                        Text: <div id="text"></div>
                    </div>
                    <div class="box">
                        Polarity Confidence: <div id="polarityConfidence"></div>
                    </div>
                    <div class="box">
                        Subjectivity Confidence: <div id="subjectivityConfidence"></div>
                    </div>
                </div>
            </section>
        </main>

        <footer>
            <p>Michael Wycklendt      Udacity</p>
        </footer>

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

Any help would be greatly appreciated.

Thank you,
Michael

答:
Your approach is not correct because sass is need to be compiled to css in order to run in web browser so you need to config your webpack like this

```<code>module: {
        rules: [{
                test: /\.scss$/,
                use: [
                    'style-loader',
                    MiniCssExtractPlugin.loader,
                    {
                        loader: "css-loader",
                        options: {
                            minimize: true,
                            sourceMap: true
                        }
                    },
                    {
                        loader: "sass-loader"
                    }
                ]
            }
        ]
    }
</code>```

You can find full code here

And change in your html

```<code><link rel="stylesheet" href="/styles/style.css">
</code>```

Body:
I'm trying to get my scss to show up correctly.  Most of it is working fine, but for some reason the footer isn't showing up correctly.  I'm using node js and webpack, both of which I am relatively new to.  I'm using the modules style-loader, css-loader and sass-loader.  Most of the page's' scss is working but for some reason the footer is not.  This is the relevant code.

footer.scss:

$font-stack: 'Montserrat', sans-serif;

footer{
    display: flex;
    justify-content: space-between;
    padding: 10px 40px;
    p{
        font: 50% $font-stack;
    }
}

index.html:

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" href="/styles/style.scss">
        <link rel="stylesheet" href="/styles/form.scss">
        <link rel="stylesheet" href="/styles/header.scss">
        <link rel="stylesheet" href="/styles/footer.scss">

        <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

                News Article Processing

                <form class="form" onsubmit="return handleSubmit(event)">
                    <input id="URL" type="text" name="input" value="" onblur="onBlur()" placeholder="URL" size="48">
                    <input type="submit" id="input" class="button" name="" value="submit" onclick="return handleSubmit(event)" onsubmit="return handleSubmit(event)">
                </form>

                        Results:

                        Polarity:

                        Subjectivity:

                        Text:

                        Polarity Confidence:

                        Subjectivity Confidence:

Michael Wycklendt      Udacity

Any help would be greatly appreciated.

Thank you,
Michael

Body:
Your approach is not correct because sass is need to be compiled to css in order to run in web browser so you need to config your webpack like this

module: {
        rules: [{
                test: /\.scss$/,
                use: [
                    'style-loader',
                    MiniCssExtractPlugin.loader,
                    {
                        loader: "css-loader",
                        options: {
                            minimize: true,
                            sourceMap: true
                        }
                    },
                    {
                        loader: "sass-loader"
                    }
                ]
            }
        ]
    }

You can find full code here

And change in your html

<link rel="stylesheet" href="/styles/style.css">