问:
ModuleNotFoundError: No module named 'debug_toolbar'
In trying to make the migrations with python manage.py runserver, I got the following traceback :

```<code>Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'debug_toolbar'
</code>```

Here is a part of the setting file

```<code>from .common import *  # noqa

DEV = True
DEBUG = True
STAGE = 'dev'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

USERENA_USE_HTTPS = False

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

INSTALLED_APPS = INSTALLED_APPS + [
    'debug_toolbar',
    'django_extensions',
]

MIDDLEWARE = MIDDLEWARE + [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
]

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False,
}
</code>```

I can't explain why this app is never loaded. I am struggling with this problem for a good while now. Could anyone have some time to help me with that?

答:
Use below command :

python -m pip install -e git+https://github.com/jazzband/django-debug-toolbar.git#egg=django-debug-toolbar

$ python -m pip install -e git+https://github.com/jazzband/django-debug-toolbar.git#egg=django-debug-toolbar

Body:
In trying to make the migrations with python manage.py runserver, I got the following traceback :

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/home/infinity/.virtualenvs/project/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'debug_toolbar'

Here is a part of the setting file

from .common import *  # noqa

DEV = True
DEBUG = True
STAGE = 'dev'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

USERENA_USE_HTTPS = False

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

INSTALLED_APPS = INSTALLED_APPS + [
    'debug_toolbar',
    'django_extensions',
]

MIDDLEWARE = MIDDLEWARE + [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
]

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False,
}

I can't explain why this app is never loaded. I am struggling with this problem for a good while now. Could anyone have some time to help me with that?


来源: stackexchange

问:
Why Isn't My NodeJS Post Request Working? (From Django)
I am trying to send a request that I'm receiving in my Django view to my expressjs api on the same server and I am either getting 500 errors or empty response bodies on the express end.

Here is my express.js code:

```<code>var express = require('express');
var fs = require('file-saver');
var app = express();
var multer  = require('multer');
var upload = multer({ dest: 'json/' });
const router = express.Router();
const bodyParser = require('body-parser');
//app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/example', function (req, res) {
  res.send('Hello World!');
});

app.post('/example', async (req, res) => {
    await fs.saveAs(req.body, 'json.json');
    await console.log('Got body:', req.body);
    await res.sendStatus(200);
});

app.listen('8080', function () {
    console.log('Test');
});
</code>```

Here is my django view:

```<code>from django.http import HttpResponse
from django.core.mail import EmailMessage, send_mail
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import FileResponse
from rest_framework.decorators import api_view
import json
from reportsappapi.utilities import logip
import requests

@method_decorator(csrf_exempt, name='dispatch')
@api_view(['GET', 'POST'])
def sendMail(request):
    url = 'https://example.com/example'
    clockout = request.FILES['clockout']
    clockoutJSON = json.load(clockout)
    x = request.post(url, clockout)
return HttpResponse(status=204)
</code>```

答: Extra "s". as Arun pointed it out

ContentLicense: CC BY-SA 4.0

Body:
I am trying to send a request that I'm receiving in my Django view to my expressjs api on the same server and I am either getting 500 errors or empty response bodies on the express end.

Here is my express.js code:

var express = require('express');
var fs = require('file-saver');
var app = express();
var multer  = require('multer');
var upload = multer({ dest: 'json/' });
const router = express.Router();
const bodyParser = require('body-parser');
//app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/example', function (req, res) {
  res.send('Hello World!');
});

app.post('/example', async (req, res) => {
    await fs.saveAs(req.body, 'json.json');
    await console.log('Got body:', req.body);
    await res.sendStatus(200);
});

app.listen('8080', function () {
    console.log('Test');
});

Here is my django view:

from django.http import HttpResponse
from django.core.mail import EmailMessage, send_mail
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import FileResponse
from rest_framework.decorators import api_view
import json
from reportsappapi.utilities import logip
import requests

@method_decorator(csrf_exempt, name='dispatch')
@api_view(['GET', 'POST'])
def sendMail(request):
    url = 'https://example.com/example'
    clockout = request.FILES['clockout']
    clockoutJSON = json.load(clockout)
    x = request.post(url, clockout)
return HttpResponse(status=204)

Body: Extra "s". as Arun pointed it out


问:
how to structure objects within an array while scraping
I'm trying to structure this array to contain data for one golf hole in one object within the array. Example of what I'm trying to achieve.

Ex.

```<code>             let scorecard = [
                {
                    hole: 1,
                    par: 4,
                    blue: 375,
                    white: 300,
                    red: 250,
                    handicap: 1
                },
                {
                    hole: 2,
                    par: 3,
                    blue: 175,
                    white: 150,
                    red: 125,
                    handicap: 2
                },
            ]
</code>```

The issue is how I am collecting this data. Each data collection could either have 9 holes or 18 holes and will have multiple tee colors, ex. blue, white, red on one course. Just blue and white on another.

Example of scorecard. Each card is a separate table and each row is a  with cells being  within row.
scorecard

Here is what I have so far but I'm not good at structuring data within these complex arrays.

```<code>            const res = await page.$$eval("table > tbody > tr", (holeInfo) =>
            holeInfo.map((hole) => {
                let dataStructure = []
                let dataObj = {}
                let scoreInfo = hole.querySelector("td").innerText
                let holeInfo = hole.querySelectorAll("td")

                holeInfo.forEach((x) => {
                    dataStructure.push(
                        x.innerHTML
                    )
                })

                return dataStructure;
            }),
        );
</code>```

Output.

```<code>res [
[
    'Hole:', '1',   '2',
    '3',     '4',   '5',
    '6',     '7',   '8',
    '9',     'Out'
  ],
  [
    'Par:', '4',  '4',
    '4',    '4',  '4',
    '3',    '4',  '3',
    '5',    '35'
  ],
  [
    'Blue:', '372',
    '394',   '369',
    '361',   '317',
    '188',   '342',
    '184',   '570',
    '3097'
  ],
  [
    'Blue:', '372',
    '394',   '369',
    '361',   '297',
    '188',   '342',
    '184',   '570',
    '3077'
  ],
  [
    'White:', '330',
    '389',    '364',
    '291',    '285',
    '181',    '290',
    '166',    '549',
    '2845'
  ],
  [
    'White:', '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0'
  ],
  [
    'Red Intermediate:',
    '301',
    '370',
    '248',
    '275',
    '260',
    '167',
    '245',
    '99',
    '452',
    '2417'
  ],
  [
    'gold:', '0', '0',
    '0',     '0', '0',
    '0',     '0', '0',
    '0',     '0'
  ],
  [
    'Handicap:', '10',
    '4',         '5',
    '18',        '16',
    '13',        '12',
    '17',        '1',
    ''
  ],
  [
    'Hole:', '10', '11',
    '12',    '13', '14',
    '15',    '16', '17',
    '18',    'In', 'Total'
  ],
  [
    'Par:', '4',  '5',
    '4',    '4',  '4',
    '3',    '4',  '4',
    '4',    '35', '71'
  ],
  [
    'Blue:', '367',  '481',
    '352',   '313',  '323',
    '186',   '439',  '379',
    '318',   '3158', '6255'
  ],
  [
    'Blue:', '367',  '481',
    '352',   '313',  '323',
    '186',   '439',  '379',
    '318',   '3158', '6235'
  ],
  [
    'White:', '337',
    '467',    '337',
    '302',    '315',
    '14',     '429',
    '349',    '280',
    '2990',   '5835'
  ],
  [
    'White:', '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '5835'
  ],
  [
    'Red Intermediate:',
    '303',
    '443',
    '311',
    '264',
    '299',
    '156',
    '278',
    '333',
    '255',
    '2642',
    '5059'
  ],
  [
    'gold:', '0', '0',
    '0',     '0', '0',
    '0',     '0', '0',
    '0',     '0', '0'
  ],
  [
    'Handicap:', '7',
    '3',         '11',
    '15',        '14',
    '6',         '2',
    '9',         '8',
    '',          ''
  ]
]
</code>```

Body:
I'm trying to structure this array to contain data for one golf hole in one object within the array. Example of what I'm trying to achieve.

Ex.

             let scorecard = [
                {
                    hole: 1,
                    par: 4,
                    blue: 375,
                    white: 300,
                    red: 250,
                    handicap: 1
                },
                {
                    hole: 2,
                    par: 3,
                    blue: 175,
                    white: 150,
                    red: 125,
                    handicap: 2
                },
            ]

The issue is how I am collecting this data. Each data collection could either have 9 holes or 18 holes and will have multiple tee colors, ex. blue, white, red on one course. Just blue and white on another.

Example of scorecard. Each card is a separate table and each row is a  with cells being  within row.
scorecard

Here is what I have so far but I'm not good at structuring data within these complex arrays.

            const res = await page.$$eval("table > tbody > tr", (holeInfo) =>
            holeInfo.map((hole) => {
                let dataStructure = []
                let dataObj = {}
                let scoreInfo = hole.querySelector("td").innerText
                let holeInfo = hole.querySelectorAll("td")

                holeInfo.forEach((x) => {
                    dataStructure.push(
                        x.innerHTML
                    )
                })

                return dataStructure;
            }),
        );

Output.

res [
[
    'Hole:', '1',   '2',
    '3',     '4',   '5',
    '6',     '7',   '8',
    '9',     'Out'
  ],
  [
    'Par:', '4',  '4',
    '4',    '4',  '4',
    '3',    '4',  '3',
    '5',    '35'
  ],
  [
    'Blue:', '372',
    '394',   '369',
    '361',   '317',
    '188',   '342',
    '184',   '570',
    '3097'
  ],
  [
    'Blue:', '372',
    '394',   '369',
    '361',   '297',
    '188',   '342',
    '184',   '570',
    '3077'
  ],
  [
    'White:', '330',
    '389',    '364',
    '291',    '285',
    '181',    '290',
    '166',    '549',
    '2845'
  ],
  [
    'White:', '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0'
  ],
  [
    'Red Intermediate:',
    '301',
    '370',
    '248',
    '275',
    '260',
    '167',
    '245',
    '99',
    '452',
    '2417'
  ],
  [
    'gold:', '0', '0',
    '0',     '0', '0',
    '0',     '0', '0',
    '0',     '0'
  ],
  [
    'Handicap:', '10',
    '4',         '5',
    '18',        '16',
    '13',        '12',
    '17',        '1',
    ''
  ],
  [
    'Hole:', '10', '11',
    '12',    '13', '14',
    '15',    '16', '17',
    '18',    'In', 'Total'
  ],
  [
    'Par:', '4',  '5',
    '4',    '4',  '4',
    '3',    '4',  '4',
    '4',    '35', '71'
  ],
  [
    'Blue:', '367',  '481',
    '352',   '313',  '323',
    '186',   '439',  '379',
    '318',   '3158', '6255'
  ],
  [
    'Blue:', '367',  '481',
    '352',   '313',  '323',
    '186',   '439',  '379',
    '318',   '3158', '6235'
  ],
  [
    'White:', '337',
    '467',    '337',
    '302',    '315',
    '14',     '429',
    '349',    '280',
    '2990',   '5835'
  ],
  [
    'White:', '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '5835'
  ],
  [
    'Red Intermediate:',
    '303',
    '443',
    '311',
    '264',
    '299',
    '156',
    '278',
    '333',
    '255',
    '2642',
    '5059'
  ],
  [
    'gold:', '0', '0',
    '0',     '0', '0',
    '0',     '0', '0',
    '0',     '0', '0'
  ],
  [
    'Handicap:', '7',
    '3',         '11',
    '15',        '14',
    '6',         '2',
    '9',         '8',
    '',          ''
  ]
]

Body:
let res = [
[
    'Hole:', '1',   '2',
    '3',     '4',   '5',
    '6',     '7',   '8',
    '9',     'Out'
  ],
  [
    'Par:', '4',  '4',
    '4',    '4',  '4',
    '3',    '4',  '3',
    '5',    '35'
  ],
  [
    'Blue:', '372',
    '394',   '369',
    '361',   '317',
    '188',   '342',
    '184',   '570',
    '3097'
  ],
  [
    'Blue:', '372',
    '394',   '369',
    '361',   '297',
    '188',   '342',
    '184',   '570',
    '3077'
  ],
  [
    'White:', '330',
    '389',    '364',
    '291',    '285',
    '181',    '290',
    '166',    '549',
    '2845'
  ],
  [
    'White:', '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0'
  ],
  [
    'Red Intermediate:',
    '301',
    '370',
    '248',
    '275',
    '260',
    '167',
    '245',
    '99',
    '452',
    '2417'
  ],
  [
    'gold:', '0', '0',
    '0',     '0', '0',
    '0',     '0', '0',
    '0',     '0'
  ],
  [
    'Handicap:', '10',
    '4',         '5',
    '18',        '16',
    '13',        '12',
    '17',        '1',
    ''
  ],
  [
    'Hole:', '10', '11',
    '12',    '13', '14',
    '15',    '16', '17',
    '18',    'In', 'Total'
  ],
  [
    'Par:', '4',  '5',
    '4',    '4',  '4',
    '3',    '4',  '4',
    '4',    '35', '71'
  ],
  [
    'Blue:', '367',  '481',
    '352',   '313',  '323',
    '186',   '439',  '379',
    '318',   '3158', '6255'
  ],
  [
    'Blue:', '367',  '481',
    '352',   '313',  '323',
    '186',   '439',  '379',
    '318',   '3158', '6235'
  ],
  [
    'White:', '337',
    '467',    '337',
    '302',    '315',
    '14',     '429',
    '349',    '280',
    '2990',   '5835'
  ],
  [
    'White:', '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '0',
    '0',      '5835'
  ],
  [
    'Red Intermediate:',
    '303',
    '443',
    '311',
    '264',
    '299',
    '156',
    '278',
    '333',
    '255',
    '2642',
    '5059'
  ],
  [
    'gold:', '0', '0',
    '0',     '0', '0',
    '0',     '0', '0',
    '0',     '0', '0'
  ],
  [
    'Handicap:', '7',
    '3',         '11',
    '15',        '14',
    '6',         '2',
    '9',         '8',
    '',          ''
  ]
]

function getHolesAmount(arr) {
  let holesAmount = 0;
  for (let i = 1; i < arr.length; i++) {
    if (parseInt(res[0][i])) {
      holesAmount += 1;
    } else {
      break;
    };
  };
  return holesAmount;
};

function fillScorecard(holesAmount, jStart, jEnd) {
  for (let i = 1; i <= holesAmount; i++) {
    let holeData = {};
    for (let j = jStart; j < jEnd; j++) {
      // remove ":" from the key and get value as integer
      holeData[res[j][0].slice(0, -1)] = parseInt(res[j][i]);
    };
    scorecard.push(holeData);
  };
};

// get first holes amount
let firstHolesAmount = getHolesAmount(res[0]);

// get second holes starting index
let secondHolesStart = 0;
for (let i = 1; i < res.length; i++) {
  if (res[i][0] === res[0][0]) {
    secondHolesStart = i;
    break;
  };
};
// get second holes amount
let secondHolesAmount = getHolesAmount(res[secondHolesStart]);

let scorecard = [];
// fill scorecard with first holes data
fillScorecard(firstHolesAmount, 0, secondHolesStart);
// fill scorecard with second holes data
fillScorecard(secondHolesAmount, secondHolesStart, res.length);

console.log(scorecard);


问:
FFMPEG errors with non-English characters
When I tried to use the command-line to catch a chrome window with non-English characters such as ¥, or any other 中文页面, an I/O error will occur with the message "Can't find window "¥中文页面。 - Google Chrome", aborting." When the non-English characters are replaced by English ones, the errors will disappear. Environment: Windows 10, ffmpeg version 2021-03-24

This works fine:
ffmpeg -f gdigrab -i title="$ English Page - Google Chrome" -pix_fmt yuv420p grab.mp4

This has errors:
ffmpeg -f gdigrab -i title="¥中文页面。 - Google Chrome" -pix_fmt yuv420p grab.mp4

"Can't find window "¥中文页面。 - Google Chrome", aborting."

Any ideas to solve this?

答: I had this problem too but duo to old version of ffmpeg which I was used changing Windows default page code to UTF-8 was not work for me. This was a bug in ffmpeg and is fixed from this commit. so updating to newer ffmpeg and chcp 65001 solved my problem together.


问:
Django can' t load Module 'debug_toolbar': No module named 'debug_toolbar'
When I try running the project, Django can not load the django-debug-toolbar plugin for some reason. Error message says:

```<code>web_1  | ModuleNotFoundError: No module named 'debug_toolbar'
</code>```

Here is my settings.py

```<code>INSTALLED_APPS = [
    # ...
    'django.contrib.staticfiles',
    # ...
    'debug_toolbar',
]

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    # ...
]

INTERNAL_IPS = ('127.0.0.1', '192.168.0.1',)
</code>```

答:
You can use the below command which worked perfectly for me:

$ python -m pip install -e git+https://github.com/jazzband/django-debug-toolbar.git#egg=django-debug-toolbar
```

Body:
When I try running the project, Django can not load the django-debug-toolbar plugin for some reason. Error message says:

web_1  | ModuleNotFoundError: No module named 'debug_toolbar'

Here is my settings.py

INSTALLED_APPS = [
    # ...
    'django.contrib.staticfiles',
    # ...
    'debug_toolbar',
]

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    # ...
]

INTERNAL_IPS = ('127.0.0.1', '192.168.0.1',)


问:
One-To-Many where One can reference already existing Many in EF5?
I have a table called Products that have a Collection of Categories, giving the models like this:

```<code>public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}
</code>```

Entity base provides some additional properties like Id

When running the migrations, EF creates a ProductId FK in the Category SQL table, so it can't hold multiple products.

The desired functionality is to have multiple Products referecing the same Category, how can be this done with One-To-Many relationship?

答:
if you want one category has many product you should do :</p>
```<code>public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
    public ICollection<Product > Products { get; set; }
}
</code>```

Body:
I have a table called Products that have a Collection of Categories, giving the models like this:

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}

Entity base provides some additional properties like Id

When running the migrations, EF creates a ProductId FK in the Category SQL table, so it can't hold multiple products.

The desired functionality is to have multiple Products referecing the same Category, how can be this done with One-To-Many relationship?

Body:
if you want one category has many product you should do :

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
    public ICollection<Product > Products { get; set; }
}


问:
Show 'please wait' during web service call
I have an activity which checks username availability via .net web services, I need to show a 'please wait' message during the call as it can take a second or two - I have experimented with AsyncTask and Threading but the problem I have is I actually want to block the main (and only) thread until the web service call has completed as I am depending on the result from it to process other logic.

I have tried allsorts but no joy - can anyone help please?

As requested, here is a section of my code :

```<code>private OnClickListener RegistrationListener = new OnClickListener() {
    public void onClick(View v) {
        ClearFieldHighlighting();
        if (ValidateData()) {
            if (IsOnline()) {
                if (UsernameIsAvailable()) {
                    try {
                        iNETUserID = CreateOnlineUser();
                    } catch (Exception e) {
                    }
</code>```

..more code..
}

Here is the 'UsernameIsAvailable' function :

public boolean UsernameIsAvailable() {

```<code>    Boolean bUsernameIsAvailable = false;

    SoapObject request = new SoapObject(TA.sNAMESPACE,
            TA.METHOD_IsUsernameAvailable);
    request.addProperty("sUsername", sEmail);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(
            TA.WEBSERVICES_URL);

    try {
        androidHttpTransport.call(TA.SOAP_ACTION_IsUsernameAvailable,
                envelope);
        SoapObject thisresponse = (SoapObject) envelope.bodyIn;

        for (int i = 0; i < thisresponse.getPropertyCount(); i++) {
            Object obj = thisresponse.getProperty(i);
            SoapPrimitive soapPrimitive = (SoapPrimitive) obj;
            bUsernameIsAvailable = Boolean.parseBoolean(soapPrimitive
                    .toString());
        }
    } catch (Exception e) {
    }

    return bUsernameIsAvailable;
}
</code>```

I am using KSoap2 which is an external jar file to handle the web service stuff

Thanks
Mike

答:
You should never ever ever block the main-ui thread. Just show a dialog with a message about what is going on. Make sure that the user can't close the dialog. As soon as the AsyncTask or runnable finishes its task just close the dialog.

Use Dialog setCancelable(false) to make sure the user can't close the dialog

ContentLicense: CC BY-SA 3.0

Body:
I have an activity which checks username availability via .net web services, I need to show a 'please wait' message during the call as it can take a second or two - I have experimented with AsyncTask and Threading but the problem I have is I actually want to block the main (and only) thread until the web service call has completed as I am depending on the result from it to process other logic.

I have tried allsorts but no joy - can anyone help please?

As requested, here is a section of my code :

private OnClickListener RegistrationListener = new OnClickListener() {
    public void onClick(View v) {
        ClearFieldHighlighting();
        if (ValidateData()) {
            if (IsOnline()) {
                if (UsernameIsAvailable()) {
                    try {
                        iNETUserID = CreateOnlineUser();
                    } catch (Exception e) {
                    }

..more code..
}

Here is the 'UsernameIsAvailable' function :

public boolean UsernameIsAvailable() {

    Boolean bUsernameIsAvailable = false;

    SoapObject request = new SoapObject(TA.sNAMESPACE,
            TA.METHOD_IsUsernameAvailable);
    request.addProperty("sUsername", sEmail);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(
            TA.WEBSERVICES_URL);

    try {
        androidHttpTransport.call(TA.SOAP_ACTION_IsUsernameAvailable,
                envelope);
        SoapObject thisresponse = (SoapObject) envelope.bodyIn;

        for (int i = 0; i < thisresponse.getPropertyCount(); i++) {
            Object obj = thisresponse.getProperty(i);
            SoapPrimitive soapPrimitive = (SoapPrimitive) obj;
            bUsernameIsAvailable = Boolean.parseBoolean(soapPrimitive
                    .toString());
        }
    } catch (Exception e) {
    }

    return bUsernameIsAvailable;
}

I am using KSoap2 which is an external jar file to handle the web service stuff

Thanks
Mike


问:
A function similar to split()
I was wondering what the A != "" does in this code.

```<code>def mysplit(strng):
A = ""
B = []
for i in strng:
    if i != " ":
        A += i
    elif A != "":
        B.append(A)
        A = ""
# Append last word
if A != "":
    B.append(A)

return(B)
</code>```

This is the code that I found for a uni project that i need, but that piece of code doesn't make sense to me, isnt it just empty? how are you gonna get an empty character in your text apart from the spaces?

also, do strings have positions?

答:
Explanation:

What this function will do is accept a string as an argument, and then loop through each character of the string.

The first if will add character by character to A until it reaches a space and when this occurs it will dump the contents of A into B as a [list], which will be a full word, and then RESET A to '', that way it will continue to read char by char the next word.

By the end of the loop, B will contain each word of the string as items in a list and return.

To answer your other question, yes strings do have index positions. If you

print('Hello World'[0:5])
```
<p><strong>This will return: <code>Hello</code></strong></p>
<h3>Code:</h3>
<pre class="lang-py prettyprint-override"><code>def mysplit(strng):
    A = ""
    B = []
    for i in strng: #Loop through each char in string
        if i != " ": #if char is not a space
            A += i #add character to A
        elif A != "": #if A is not empty
            B.append(A) #add whatever is in A to B as a list (full word)
            A = "" #resets A to be empty
    if A != "": #if A is empty
        B.append(A)
    return B #return is a statement, so it doesn't require parenthesis.
</code>```

Title: A function similar to split()

Body:
I was wondering what the A != "" does in this code.

def mysplit(strng):
A = ""
B = []
for i in strng:
    if i != " ":
        A += i
    elif A != "":
        B.append(A)
        A = ""
# Append last word
if A != "":
    B.append(A)

return(B)

This is the code that I found for a uni project that i need, but that piece of code doesn't make sense to me, isnt it just empty? how are you gonna get an empty character in your text apart from the spaces?

also, do strings have positions?

Body:
Explanation:

What this function will do is accept a string as an argument, and then loop through each character of the string.

The first if will add character by character to A until it reaches a space and when this occurs it will dump the contents of A into B as a [list], which will be a full word, and then RESET A to '', that way it will continue to read char by char the next word.

By the end of the loop, B will contain each word of the string as items in a list and return.

To answer your other question, yes strings do have index positions. If you

print('Hello World'[0:5])

This will return: Hello

Code:

def mysplit(strng):
    A = ""
    B = []
    for i in strng: #Loop through each char in string
        if i != " ": #if char is not a space
            A += i #add character to A
        elif A != "": #if A is not empty
            B.append(A) #add whatever is in A to B as a list (full word)
            A = "" #resets A to be empty
    if A != "": #if A is empty
        B.append(A)
    return B #return is a statement, so it doesn't require parenthesis.


问:
Why is a cell value coming as a series when you do dataframe[dataframe[ColumnName]==some_value]?
I am having the same problem as described here Cell value coming as series in pandas
While a solution is provided there is no explanation on why a cell would be a dataseries when I would expect that to be a string (which I understand that it is dtype=object)
My dataframe has columns as below

```<code>Serial Number          object
Device ID               int64
Device Name            object
</code>```

I am extracting a

```<code>device=s_devices[s_devices['Device ID']==17177529]
print(device['Device ID'])
</code>```

prints fine as I would expect

```<code> 17177529
</code>```
```<code>print(device['Device Name'])
</code>```

prints like below, like a Series:

```<code> 49    10.112.165.182
Name: Device Name, dtype: object
</code>```

What can be done ? I could see that I could use ".values" to get the IP only 10.112.165.182 but I am wondering what is causing the difference between dtype float and dtype object at import or elsewhere. I am reading from excel.

答:
As far as I understand, your code should always output a Series. So the problem is probably in the code you are not describing. Also, the question you are referring to uses ix (which doesn't exist in the latest version of pandas), which indicates pandas version may also be an issue.

By the way, I don't think values is a good choice for your case, because it is used when you want an array, not an element. (Also values is not recommended anymore)

If you just want to extract an element, try:

# If there are multiple elements, the first one will be extracted.
print(device['Device Name'].iloc[0])
```
<p>or</p>
<pre class="lang-py prettyprint-override"><code># If there are multiple elements, ValueError will be raised.
print(device['Device Name'].item())
</code>```

Body:
I am having the same problem as described here Cell value coming as series in pandas
While a solution is provided there is no explanation on why a cell would be a dataseries when I would expect that to be a string (which I understand that it is dtype=object)
My dataframe has columns as below

Serial Number          object
Device ID               int64
Device Name            object

I am extracting a

device=s_devices[s_devices['Device ID']==17177529]
print(device['Device ID'])

prints fine as I would expect

 17177529

print(device['Device Name'])

prints like below, like a Series:

 49    10.112.165.182
Name: Device Name, dtype: object

What can be done ? I could see that I could use ".values" to get the IP only 10.112.165.182 but I am wondering what is causing the difference between dtype float and dtype object at import or elsewhere. I am reading from excel.

Body:
As far as I understand, your code should always output a Series. So the problem is probably in the code you are not describing. Also, the question you are referring to uses ix (which doesn't exist in the latest version of pandas), which indicates pandas version may also be an issue.

By the way, I don't think values is a good choice for your case, because it is used when you want an array, not an element. (Also values is not recommended anymore)

If you just want to extract an element, try:

# If there are multiple elements, the first one will be extracted.
print(device['Device Name'].iloc[0])

or

# If there are multiple elements, ValueError will be raised.
print(device['Device Name'].item())


问:
Fabric.js cannot have the background of a canvas transparent
I would like to have the canvas (see image) to have a background (around the gabarit) to look like this:

I have tested to save the canvas with background color set to null and background image set to null, but it's always white.

The URL of the site is https://linkmx.fr/accueil/307-plaque-downhill-odi-100-perso.html then you have to click on "Personnalisez"

答:
You can set the canvas background to transparent like this:</p>
```<code>canvas.set('backgroundColor', 'transparent').requestRenderAll();
</code>```

Body:
You can set the canvas background to transparent like this:

canvas.set('backgroundColor', 'transparent').requestRenderAll();


答:
Yes, strings have index from 0 to n-1 just like in a string.
Eg: A = "abcd", print(a[2]) //output: "c"

As for your code, i iterates through every element in the input string, and it is appended to A if i is not a "space". When it is a "space", A is appended to B list and A is cleared in order to get the next word. For the last word, since there is no space in the end, the string A does not get appended to B list, so it is done separately outside the for loop.

Title: A function similar to split()


问:
Detecting CSS capabilities with Javascript
Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

```<code>input[type='text'] { }
</code>```

答:
Modernizr is designed to detect browser features and may well be able to help in this instance.
http://www.modernizr.com/</p>

Body:
Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

input[type='text'] { }


问:
How to remove dynamically created div elements in JQuery after deleting a record from db?
I have created a dynamic Div(s) based on records from database and want to remove any of the specific div and its elements after removal a record from db. I have written  deleteFile(id) function where ajax removes the div tag on getting response from php file.

But the specific div is not being removed from front end in my Code. How to properly access the closest div of element. Here is the code. Thank you

```<code>        $sql2 = "SELECT * FROM table where
        obj_id=".$idObjDetails;
        $result2= mysqli_query($con,$sql2);
        $count_file_rows = mysqli_num_rows($result2);
        $index=1;
        if($count_file_rows>0)
        {
         while ($row2 = mysqli_fetch_assoc($result2))
        {?>
         <div class="form-row">
          <div class="form-group col-md-12 fileDiv">
            <i class="fa fa-remove float-right" id="e_removeBtn" type="button" onclick=" deleteFile(<?php echo $row2['id'];?>)"></i>
                   <input type="text"  name="e_fileGet" id="e_get_file_<?php echo $index ?>" class="form-control fileClass" readonly value="<?php echo $row2['file_name'];?>"/>
       </div>
       </div>
        <?php
         $index++;
        }
     }
    ?>
</code>```

// DELETE Objection -
    function deleteFile(id)
    {
        if(confirm("Are You Sure, You Want to Delete This Objection? "))
        {

        var del_file_id=id;
        var element=this;

        $.ajax({
      url:"deleteFile.php",
      type:"POST",
      data: {'id':del_file_id},
      success : function(data){
        ;
        if(data==1)
        {
            //$("#e_get_file_1").remove();
         $(element).closest(".fileDiv").remove();
          //window.location.reload();
        }
        else
        {
          $("#error-message").html("cant del").slideDown();
          $("#Success-message").slideUp();
        }
      }

    });

        }
        //add alert - later

    }```

答:
to remove the whole element</p>
```<code>// DELETE Objection -
    function deleteFile(id)
    {
        if(confirm("Are You Sure, You Want to Delete This Objection? "))
        {

        var del_file_id=id;
        var element=this;
        var selector = '#e_get_file_'+id;

        $.ajax({
      url:"deleteFile.php",
      type:"POST",
      data: {'id':del_file_id},
      success : function(data){
        ;
        if(data==1)
        {
            // parent().parent() to reach the .form-row div
            $(selector).parent().parent().remove();
        }
        else
        {
          $("#error-message").html("cant del").slideDown();
          $("#Success-message").slideUp();
        }
      }

    });

        }
        //add alert - later

    }
</code>```

Body:
I have created a dynamic Div(s) based on records from database and want to remove any of the specific div and its elements after removal a record from db. I have written  deleteFile(id) function where ajax removes the div tag on getting response from php file.

But the specific div is not being removed from front end in my Code. How to properly access the closest div of element. Here is the code. Thank you

        $sql2 = "SELECT * FROM table where
        obj_id=".$idObjDetails;
        $result2= mysqli_query($con,$sql2);
        $count_file_rows = mysqli_num_rows($result2);
        $index=1;
        if($count_file_rows>0)
        {
         while ($row2 = mysqli_fetch_assoc($result2))
        {?>

            <i class="fa fa-remove float-right" id="e_removeBtn" type="button" onclick=" deleteFile(<?php echo $row2['id'];?>)">
                   <input type="text"  name="e_fileGet" id="e_get_file_<?php echo $index ?>" class="form-control fileClass" readonly value="<?php echo $row2['file_name'];?>"/>

        <?php
         $index++;
        }
     }
    ?>

// DELETE Objection -
    function deleteFile(id)
    {
        if(confirm("Are You Sure, You Want to Delete This Objection? "))
        {

        var del_file_id=id;
        var element=this;

        $.ajax({
      url:"deleteFile.php",
      type:"POST",
      data: {'id':del_file_id},
      success : function(data){
        ;
        if(data==1)
        {
            //$("#e_get_file_1").remove();
         $(element).closest(".fileDiv").remove();
          //window.location.reload();
        }
        else
        {
          $("#error-message").html("cant del").slideDown();
          $("#Success-message").slideUp();
        }
      }

    });

        }
        //add alert - later

    }

Body:
to remove the whole element

// DELETE Objection -
    function deleteFile(id)
    {
        if(confirm("Are You Sure, You Want to Delete This Objection? "))
        {

        var del_file_id=id;
        var element=this;
        var selector = '#e_get_file_'+id;

        $.ajax({
      url:"deleteFile.php",
      type:"POST",
      data: {'id':del_file_id},
      success : function(data){
        ;
        if(data==1)
        {
            // parent().parent() to reach the .form-row div
            $(selector).parent().parent().remove();
        }
        else
        {
          $("#error-message").html("cant del").slideDown();
          $("#Success-message").slideUp();
        }
      }

    });

        }
        //add alert - later

    }


问:
getSelectedText on inactive InputConnection flutter
I have this weird problem,When i try to enter value to textfield the keyboard comes up when i try to type the the keyboard  goes away , i am also doing fill up Username,Place,mobile that i fetching from sharedprefrence and  it's working,but when i try to enter age,height,weight  keyboard comes up & goes with in seconds,this is the error/warning i am getting,there is no problem in flutter doctor,

```<code>W/IInputConnectionWrapper(23904): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(23904): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper( 8756): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper( 8756): endBatchEdit on inactive InputConnection
</code>```

Code & View

```<code>class RegistrationScreenState extends State<RegistrationScreen> {

 TextEditingController mobile = TextEditingController();
  TextEditingController Username = TextEditingController();
  TextEditingController Place = TextEditingController();
  TextEditingController age = TextEditingController();
  TextEditingController height = TextEditingController();
  TextEditingController weight = TextEditingController();

  void initState() {
    getDetails();

  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery
        .of(context)
        .size;
    return Scaffold(
      appBar: AppBar(
        title: Text("Registration", style: TextStyle(color: Colors.black)),
        backgroundColor: Colors.orange,
      ),
      body: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              children: [
                Container(
                  child: Image.asset('assets/images/gym.png',
                      height: 150,
                      width: double.infinity,
                      fit: BoxFit.fitWidth),
                ),
                SizedBox(
                  height: 50,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: Username,
                          decoration: InputDecoration(
                            prefixIcon: Icon(Icons.perm_identity),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: mobile,
                          decoration: InputDecoration(
                            prefixIcon: Icon(Icons.mobile_screen_share),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        "User Information",
                        style: TextStyle(
                            fontSize: 15, fontWeight: FontWeight.bold),
                      )),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: Place,
                          decoration: InputDecoration(),
                        ),

                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: age,
                          decoration: InputDecoration(
                            hintText: 'Age',
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: height,
                          decoration: InputDecoration(
                            hintText: 'Height(in cm)',
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: weight,
                          decoration: InputDecoration(
                            hintText: 'Weight(in kg)',
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //  get & fill Shareprefrece data to textfield
  getDetails() async {
    Future user = SharedPrefrence().getUserMobile();
    Future name = SharedPrefrence().getUserName();
    Future place = SharedPrefrence().getUserPlace();

    user.then((data) async {
      var mobile_no = data;
      setState(() {
        if (mobile_no.isNotEmpty) {
          mobile.text = mobile_no;
        }
        else
          {
            mobile.text = "";
          }
      });
    });

    name.then((data) async {
      var user_name = data;
      setState(() {
        if (user_name.isNotEmpty) {
          Username.text = user_name;
        }
      });
    });

    place.then((data) async {
      var user_place = data;
      setState(() {
        if (user_place.isNotEmpty) {
          Place.text = user_place;
        }
      });
    });
  }

}
</code>```

答: In my case, I was using a global navigation key for navigation. when I was on an inner page the moment I touch Textfeild or TextFormFeild it pop to the navigation initial root, the problem that cause this problem was I declared the Navigation module inside a Stateless widget. When I changed it to stateful the issue is solved.

Body:
I have this weird problem,When i try to enter value to textfield the keyboard comes up when i try to type the the keyboard  goes away , i am also doing fill up Username,Place,mobile that i fetching from sharedprefrence and  it's working,but when i try to enter age,height,weight  keyboard comes up & goes with in seconds,this is the error/warning i am getting,there is no problem in flutter doctor,

W/IInputConnectionWrapper(23904): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(23904): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper( 8756): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper( 8756): endBatchEdit on inactive InputConnection

Code & View

class RegistrationScreenState extends State<RegistrationScreen> {

 TextEditingController mobile = TextEditingController();
  TextEditingController Username = TextEditingController();
  TextEditingController Place = TextEditingController();
  TextEditingController age = TextEditingController();
  TextEditingController height = TextEditingController();
  TextEditingController weight = TextEditingController();

  void initState() {
    getDetails();

  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery
        .of(context)
        .size;
    return Scaffold(
      appBar: AppBar(
        title: Text("Registration", style: TextStyle(color: Colors.black)),
        backgroundColor: Colors.orange,
      ),
      body: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              children: [
                Container(
                  child: Image.asset('assets/images/gym.png',
                      height: 150,
                      width: double.infinity,
                      fit: BoxFit.fitWidth),
                ),
                SizedBox(
                  height: 50,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: Username,
                          decoration: InputDecoration(
                            prefixIcon: Icon(Icons.perm_identity),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: mobile,
                          decoration: InputDecoration(
                            prefixIcon: Icon(Icons.mobile_screen_share),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        "User Information",
                        style: TextStyle(
                            fontSize: 15, fontWeight: FontWeight.bold),
                      )),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: Place,
                          decoration: InputDecoration(),
                        ),

                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: age,
                          decoration: InputDecoration(
                            hintText: 'Age',
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: height,
                          decoration: InputDecoration(
                            hintText: 'Height(in cm)',
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: weight,
                          decoration: InputDecoration(
                            hintText: 'Weight(in kg)',
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //  get & fill Shareprefrece data to textfield
  getDetails() async {
    Future user = SharedPrefrence().getUserMobile();
    Future name = SharedPrefrence().getUserName();
    Future place = SharedPrefrence().getUserPlace();

    user.then((data) async {
      var mobile_no = data;
      setState(() {
        if (mobile_no.isNotEmpty) {
          mobile.text = mobile_no;
        }
        else
          {
            mobile.text = "";
          }
      });
    });

    name.then((data) async {
      var user_name = data;
      setState(() {
        if (user_name.isNotEmpty) {
          Username.text = user_name;
        }
      });
    });

    place.then((data) async {
      var user_place = data;
      setState(() {
        if (user_place.isNotEmpty) {
          Place.text = user_place;
        }
      });
    });
  }

}


问:
sqlite3 c++: retrieving a blob
I have a sqlite3 DB with a .png image stored in it as a BLOB

I am trying to retrieve the raw data via the C++ interface like so

```<code>RawImageWrapper* obj = 0;
int rc = sqlite3_exec(db, action.c_str(), imageSelectCallback, obj, &errMsg);
</code>```

Where action is just my SQL statement (it returns the correct record) and RawImageWrapper looks like this

```<code>struct RawImageWrapper
{
    int callback(int argc, char **argv, char **azColName) {
        for (int i = 0; i < argc; i++) {
            if (strcmp(azColName[i], "Image") == 0) {
                buff = std::string(argv[i]);
                return 0;
            }
        }
        return 1;
    }

    std::string buff;
};
</code>```

Using a string to hold the image data probably isn't the best but I just wanted a quick object to wrap the char[]. However this fails with an access violation when it tries to construct buff.

What is the proper way to retrieve this image blob from my database and load it into some container? I am planning on reconstituting the image from it's raw data at a later point

答:
The issue with sqlite3 blob data is if you don't know the size of the blob then you can't construct a string or any other object from char*. Because blob data can have null values and when you generate string it will stop as soon as it gets a null, ignoring rest of the data.

I know two solutions to address this problem:

Add an extra output to your SELECT statement of the form LENGTH(BLOB_COLUMN), which gives you the size of the blob column in bytes.

convert the blob column to hex value using select hex(BLOB_COLUMN) from ... and now you get a normal hex string, which thereafter you've to convert to get a raw byte array.

Title: sqlite3 c++: retrieving a blob

Body:
I have a sqlite3 DB with a .png image stored in it as a BLOB

I am trying to retrieve the raw data via the C++ interface like so

RawImageWrapper* obj = 0;
int rc = sqlite3_exec(db, action.c_str(), imageSelectCallback, obj, &errMsg);

Where action is just my SQL statement (it returns the correct record) and RawImageWrapper looks like this

struct RawImageWrapper
{
    int callback(int argc, char **argv, char **azColName) {
        for (int i = 0; i < argc; i++) {
            if (strcmp(azColName[i], "Image") == 0) {
                buff = std::string(argv[i]);
                return 0;
            }
        }
        return 1;
    }

    std::string buff;
};

Using a string to hold the image data probably isn't the best but I just wanted a quick object to wrap the char[]. However this fails with an access violation when it tries to construct buff.

What is the proper way to retrieve this image blob from my database and load it into some container? I am planning on reconstituting the image from it's raw data at a later point


问:
Upgrade v2.2 to v2.3.4.1 after getting Admin Error in Oscommerce
I have upgraded OSCommerce v2.2 to v2.3.4.1 after the front store completely works. But admin getting errors like below:

Warning: Use of undefined constant ENABLE_SSL - assumed 'ENABLE_SSL'
(this will throw an Error in a future version of PHP) in
/home/inceptio/public_html/curtispayments/test-os/admin/includes/functions/html_output.php
on line 14

Warning: Cannot modify header information - headers already sent by
(output started at
/home/inceptio/public_html/curtispayments/test-os/admin/includes/functions/html_output.php:14)
in
/home/inceptio/public_html/curtispayments/test-os/admin/includes/functions/general.php
on line 25

I have already SSL enabled on my website. also, add the below code in both configure.php files

```<code>define('ENABLE_SSL', true);
</code>```

When I insert the above code in admin configure.php getting me:

This page isn’t working

Admin: https://inceptionsystem.com/curtispayments/test-os/admin/

Front: https://inceptionsystem.com/curtispayments/test-os/

How can I solve this? Does anyone suggest for very appreciate?

Thank you

答:
OK easy to find the file and line like this
crate a file in the store root
in bash shell
You must be in the directory above "catalog"
Copy and paste this into the bash shell

```<code>BA=$(cat <<-ENDBA
#!/bin/bash
file="allcode"
catalog="catalog"
today="\`date -u +\"%Y%m%d%H%M%S\"\`"
if [ -s "\$file" ]
then
   echo "File \$file exists and is not empty "
   FILE="\$file_pre_\$today"
   echo "Preserving older allcode File to: \$FILE"
   mv \$file \$FILE
   echo "....creating New \$file file"
else
   FILE="\$file"
   echo " file \$file does not exist, or is empty "
   echo "....creating file \$file"
fi
grep -I  -n  -r "." \$catalog  | egrep  -e ".php*:" -e ".js:" -e ".sql:" -e ".css:" -e ".xml:" -e ".crt:" -e ".ht*:" >\$FILE
ENDBA
)
BL=$(cat <<-ENDBL
#!/bin/bash
if [ \$# -eq 0 ]; then
    echo "No arguments provided"
    echo -n " Enter Search String "
    read search
    if [ -z "\$search" ]
    then
        exit 1
    else
        echo " Searching for string \$search "
    fi
else
  search=\$1
  echo " Searching for string \$search "
fi
cat allcode | egrep -e \$search| egrep  -e ".php*:" >\$search.found
#cat allcode | egrep -e "\$search"| egrep  -e ".php*:" -e ".js:" -e ".sql:" -e ".css:" -e ".xml:" -e ".crt:" -e ".ht*:">\$search.found
echo -n "Matching Lines Found "; wc -l \$search.found
cat \$search.found | sed -e "s/:.*/:/g" | sort -u>\$search.files
echo -n "Matching Files Found are "; wc -l  \$search.files
#comment out line 7 and un-comment line 8 for looking in all code not just PHP
ENDBL
)
echo -e "$BL" >bl
echo -e "$BA" >ba
sudo chmod u+x ba bl
./ba
#now all  your code is backed up and you can search it
</code>```

Hope I got all the escapes right :(

Body:
I have upgraded OSCommerce v2.2 to v2.3.4.1 after the front store completely works. But admin getting errors like below:

Warning: Use of undefined constant ENABLE_SSL - assumed 'ENABLE_SSL'
(this will throw an Error in a future version of PHP) in
/home/inceptio/public_html/curtispayments/test-os/admin/includes/functions/html_output.php
on line 14

Warning: Cannot modify header information - headers already sent by
(output started at
/home/inceptio/public_html/curtispayments/test-os/admin/includes/functions/html_output.php:14)
in
/home/inceptio/public_html/curtispayments/test-os/admin/includes/functions/general.php
on line 25

I have already SSL enabled on my website. also, add the below code in both configure.php files

define('ENABLE_SSL', true);

When I insert the above code in admin configure.php getting me:

This page isn’t working

Admin: https://inceptionsystem.com/curtispayments/test-os/admin/

Front: https://inceptionsystem.com/curtispayments/test-os/

How can I solve this? Does anyone suggest for very appreciate?

Thank you

Body:
OK easy to find the file and line like this
crate a file in the store root
in bash shell
You must be in the directory above "catalog"
Copy and paste this into the bash shell

BA=$(cat <<-ENDBA
#!/bin/bash
file="allcode"
catalog="catalog"
today="\`date -u +\"%Y%m%d%H%M%S\"\`"
if [ -s "\$file" ]
then
   echo "File \$file exists and is not empty "
   FILE="\$file_pre_\$today"
   echo "Preserving older allcode File to: \$FILE"
   mv \$file \$FILE
   echo "....creating New \$file file"
else
   FILE="\$file"
   echo " file \$file does not exist, or is empty "
   echo "....creating file \$file"
fi
grep -I  -n  -r "." \$catalog  | egrep  -e ".php*:" -e ".js:" -e ".sql:" -e ".css:" -e ".xml:" -e ".crt:" -e ".ht*:" >\$FILE
ENDBA
)
BL=$(cat <<-ENDBL
#!/bin/bash
if [ \$# -eq 0 ]; then
    echo "No arguments provided"
    echo -n " Enter Search String "
    read search
    if [ -z "\$search" ]
    then
        exit 1
    else
        echo " Searching for string \$search "
    fi
else
  search=\$1
  echo " Searching for string \$search "
fi
cat allcode | egrep -e \$search| egrep  -e ".php*:" >\$search.found
#cat allcode | egrep -e "\$search"| egrep  -e ".php*:" -e ".js:" -e ".sql:" -e ".css:" -e ".xml:" -e ".crt:" -e ".ht*:">\$search.found
echo -n "Matching Lines Found "; wc -l \$search.found
cat \$search.found | sed -e "s/:.*/:/g" | sort -u>\$search.files
echo -n "Matching Files Found are "; wc -l  \$search.files
#comment out line 7 and un-comment line 8 for looking in all code not just PHP
ENDBL
)
echo -e "$BL" >bl
echo -e "$BA" >ba
sudo chmod u+x ba bl
./ba
#now all  your code is backed up and you can search it

Hope I got all the escapes right :(


问:
Spark structured streaming metrics are confusing
I start a structured streaming(spark 3.1.2) which writes to kafka (1 driver, 5 executor on K8s)

```<code>dataFrame
      .writeStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "kafka-host:9092")
      .option("topic", "my-topic")
</code>```

By the time all the inputs are processed the Kafka topic 'my-topic' consists 38087 new messages. So 38087 rows were written into Kafka.
Metrics are written to the ConsoleSink and on the SparkUI.

Now let's see the actual Spark metrics:

```<code>spark.streaming.states-rowsTotal: 3600  (Gauge)
spark.streaming.states-rowsUpdated: 0   (Gauge)
executor.recordsWritten:  0             (Counter)
</code>```

Makes no sense...

Now lets check all the ConsoleSink entries:

```<code>spark.streaming.states-rowsTotal: 41687,3600, 3600...n
spark.streaming.states-rowsUpdated: 41687,0,0...n
executor.recordsWritten:  0...n
</code>```

As you can see rowsTotal was 41687 at first since then it is 3600. RecordsWritten is still 0.

But if I check recordsWritten on the SparkUi:

```<code>driver-ip/api/v1/app-id/stages/stage-id
</code>```

For all the stage-id there are 400piece of entries with 0 value, except for one which has the value of 41687

Magic math: If I perform x=41687-3600 then I get 38087 which is the number of new rows in Kafka. What the heck is going on?

So the questions are:

what rowsTotal,rowsUpdated represent and why are they Guage types?

what recordsWritten represents?

Why the value of recordsWritten in a Sink and on SparkUI are different?

What is the reason behind the magis substraction above? Makes no sense at all

How to get/create a single metric which shows the total number of rows written into Kafka

答:
spark.streaming.states-rowsTotal means the number of rows in state store if you used some stateful operators. It has no relations with output records.

The sum of executor.recordsWritten for all executors should return total records writen to sink. But unforuntately, most streaming sink doesn't correctly updates this metrics(at least for console, kafka sink).

One workaround I can think of is:

```<code>streamingDF.writeStream.foreachBatch { (batchDF: DataFrame, batchId: Long) =>
  batchDF.persist()
  batchDF.count()  // write count to some where
  batchDF.write.format(...).save(...)  // write into kafka
  batchDF.unpersist()
}
</code>```

Body:
I start a structured streaming(spark 3.1.2) which writes to kafka (1 driver, 5 executor on K8s)

dataFrame
      .writeStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "kafka-host:9092")
      .option("topic", "my-topic")

By the time all the inputs are processed the Kafka topic 'my-topic' consists 38087 new messages. So 38087 rows were written into Kafka.
Metrics are written to the ConsoleSink and on the SparkUI.

Now let's see the actual Spark metrics:

spark.streaming.states-rowsTotal: 3600  (Gauge)
spark.streaming.states-rowsUpdated: 0   (Gauge)
executor.recordsWritten:  0             (Counter)

Makes no sense...

Now lets check all the ConsoleSink entries:

spark.streaming.states-rowsTotal: 41687,3600, 3600...n
spark.streaming.states-rowsUpdated: 41687,0,0...n
executor.recordsWritten:  0...n

As you can see rowsTotal was 41687 at first since then it is 3600. RecordsWritten is still 0.

But if I check recordsWritten on the SparkUi:

driver-ip/api/v1/app-id/stages/stage-id

For all the stage-id there are 400piece of entries with 0 value, except for one which has the value of 41687

Magic math: If I perform x=41687-3600 then I get 38087 which is the number of new rows in Kafka. What the heck is going on?

So the questions are:

what rowsTotal,rowsUpdated represent and why are they Guage types?

what recordsWritten represents?

Why the value of recordsWritten in a Sink and on SparkUI are different?

What is the reason behind the magis substraction above? Makes no sense at all

How to get/create a single metric which shows the total number of rows written into Kafka

Body:
spark.streaming.states-rowsTotal means the number of rows in state store if you used some stateful operators. It has no relations with output records.

The sum of executor.recordsWritten for all executors should return total records writen to sink. But unforuntately, most streaming sink doesn't correctly updates this metrics(at least for console, kafka sink).

One workaround I can think of is:

streamingDF.writeStream.foreachBatch { (batchDF: DataFrame, batchId: Long) =>
  batchDF.persist()
  batchDF.count()  // write count to some where
  batchDF.write.format(...).save(...)  // write into kafka
  batchDF.unpersist()
}


问:
Add Percentage Sign in Table in R
How do I add percentage sign to this table?
table(sample.1$Department)/50*100

I want to add the percentage sign to the numbers here. E.g. 28%, 46%, 8%, etc.

答:
Recreating data

I didnt see a reproducible dataset, so I created one for now:

```<code># Create rows and columns:
names <- c("Boston Fire Department",
           "Boston Police Department",
           "Boston Public Library",
           "BPS Facility Management",
           "BPS Special Education")
counts <- c(28,46,8,10,8)

# Turn into data frame:
df <- data.frame(names,
                 counts)
</code>```

Get proportions/percentages:

From there you will just need to create a new column for the percentages, here thus called "props":

```<code>df$prop <- paste(df$counts, "%", sep = "")
df
</code>```

Which will print this:

```<code>                     names counts prop
1   Boston Fire Department     28  28%
2 Boston Police Department     46  46%
3    Boston Public Library      8   8%
4  BPS Facility Management     10  10%
5    BPS Special Education      8   8%
</code>```

Or if you just wanna change the counts to percentages, you can save over the column already there:

```<code>df$counts <- paste(df$counts, "%", sep = "")
df
</code>```

Which gives you this:

```<code>                    names counts
1   Boston Fire Department    28%
2 Boston Police Department    46%
3    Boston Public Library     8%
4  BPS Facility Management    10%
5    BPS Special Education     8%
</code>```

Title: Add Percentage Sign in Table in R

Body:
Recreating data

I didnt see a reproducible dataset, so I created one for now:

# Create rows and columns:
names <- c("Boston Fire Department",
           "Boston Police Department",
           "Boston Public Library",
           "BPS Facility Management",
           "BPS Special Education")
counts <- c(28,46,8,10,8)

# Turn into data frame:
df <- data.frame(names,
                 counts)

Get proportions/percentages:

From there you will just need to create a new column for the percentages, here thus called "props":

df$prop <- paste(df$counts, "%", sep = "")
df

Which will print this:

                     names counts prop
1   Boston Fire Department     28  28%
2 Boston Police Department     46  46%
3    Boston Public Library      8   8%
4  BPS Facility Management     10  10%
5    BPS Special Education      8   8%

Or if you just wanna change the counts to percentages, you can save over the column already there:

df$counts <- paste(df$counts, "%", sep = "")
df

Which gives you this:

                    names counts
1   Boston Fire Department    28%
2 Boston Police Department    46%
3    Boston Public Library     8%
4  BPS Facility Management    10%
5    BPS Special Education     8%


问:
Check if a process is running or not on Windows?
I am trying to create a python script which I will later run as a service. Now I want to run a particular part of the code only when iTunes is running. I understand from some research that polling the entire command list and then searching for the application for that list is expensive.

I found out that processes on UNIX-based operating systems create a lock file to notify that a program is currently running, at which point we can use os.stat(location_of_file) to check if the file exists to determine if a program is running or not.

Is there a similar lock file created on Windows?

If not what are the various ways in Python by which we can determine if a process is running or not?

I am using python 2.7 and iTunes COM interface.

答:
I liked the solution of @ewerybody with this little change</p>
```<code>import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()

    # check in last line for process name
    last_line = output.split('\r\n')

    #first result is 3 because the headers
    #or in case more than one, you can use the last one using [-2] index
    data = " ".join(last_line[3].split()).split()

    #return a list with the name and pid
    return( [data[0], data[1]] )
</code>```

Body:
I liked the solution of @ewerybody with this little change

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()

    # check in last line for process name
    last_line = output.split('\r\n')

    #first result is 3 because the headers
    #or in case more than one, you can use the last one using [-2] index
    data = " ".join(last_line[3].split()).split()

    #return a list with the name and pid
    return( [data[0], data[1]] )


答:
try to add

```<code>public Product Product { get; set; }
</code>```

property to Category

and add a method in Product for categories

```<code>public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }

    public Product ()
    {
        Categories = new Collection<Category>();
    }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}
</code>```

then

```<code>modelBuilder.Entity<Category>().HasRequired(n => n.Product)
            .WithMany(n=>n.Categories)
            .HasForeignKey(n => n.ProductId)
            .WillCascadeOnDelete(true);
</code>```

in OnModelCreating(DbModelBuilder modelBuilder) in the context definition

Then regenerate Database

Title: One-To-Many where One can reference already existing Many in EF5?

Body:
I have a table called Products that have a Collection of Categories, giving the models like this:

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}

Entity base provides some additional properties like Id

When running the migrations, EF creates a ProductId FK in the Category SQL table, so it can't hold multiple products.

The desired functionality is to have multiple Products referecing the same Category, how can be this done with One-To-Many relationship?

Body:
try to add

public Product Product { get; set; }

property to Category

and add a method in Product for categories

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }

    public Product ()
    {
        Categories = new Collection<Category>();
    }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}

then

modelBuilder.Entity<Category>().HasRequired(n => n.Product)
            .WithMany(n=>n.Categories)
            .HasForeignKey(n => n.ProductId)
            .WillCascadeOnDelete(true);

in OnModelCreating(DbModelBuilder modelBuilder) in the context definition

Then regenerate Database


问:
React Router not passing params through useParams onto my page
I am building a web page that I want to be dynamically routed with the react-router-dom, and useParams() does not hold the passed-in value on the final page that the route ends on.

Here are my routes:

```<code>import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@mui/material/CssBaseline";
import {
  BrowserRouter,
  Routes,
  Route,
  } from "react-router-dom";
import "./index.css";
import App from "./App";
import Items from "./routes/items";
import TextContentPage from "./routes/textContentPage";
import reportWebVitals from "./reportWebVitals";
import HomePage from "./routes/homePage";
import TopicPage from "./routes/topicPage";

ReactDOM.render(
  <React.StrictMode>
    <CssBaseline />
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="trees" element={<App />} />
        <Route path="items" element={<Items />} />
        <Route path="text-content" element={<TextContentPage />} />
        <Route path ="topics/:id" element={<TopicPage />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);
</code>```

And here is the page I am trying to render:

```<code>import { useParams } from "react-router-dom"
import Container from "@mui/material/Container";
import Header from "../components/Header";
import Card from '@mui/material/Card'
const topics = [
    {
        id: 1,
        name: "Environement",
        fund: 0
    },
    {
        id: 2,
        name: "Education",
        fund: 0
    },
    {
        id: 3,
        name: "International affairs",
        fund: 0
    }
]

export default function TopicPage(){

    const topicId = useParams()
    let topic = topics.find(topic => topic.id === topicId)
    return (
        <Container maxWidth = "sm">
            <Header title = "Map The Future">
            </Header>
            <main>
                <Card><h2>{topic.name}</h2></Card>
            </main>
        </Container>

    );

}
</code>```

Any Help figuring out how to get useParams() to work would be greatly appreciated!!

答:
useParams returns an object of key/value pairs of URL parameters.

And since you've define path as:
<Route path ="topics/:id" element={<TopicPage />} />
While accessing useParams since it returns an object you'll get key/value pair so use object destructuring const {id} = useParams() and since it's of type String you need to parseInt the returned value.

```<code>export default function TopicPage(){

    const {id} = useParams()
    let topic = topics.find(topic => topic.id === parseInt(id)) // Change here
    return (
        <Container maxWidth = "sm">
            <Header title = "Map The Future">
            </Header>
            <main>
                <Card><h2>{topic.name}</h2></Card>
            </main>
        </Container>

    );

}
</code>```

Body:
I am building a web page that I want to be dynamically routed with the react-router-dom, and useParams() does not hold the passed-in value on the final page that the route ends on.

Here are my routes:

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@mui/material/CssBaseline";
import {
  BrowserRouter,
  Routes,
  Route,
  } from "react-router-dom";
import "./index.css";
import App from "./App";
import Items from "./routes/items";
import TextContentPage from "./routes/textContentPage";
import reportWebVitals from "./reportWebVitals";
import HomePage from "./routes/homePage";
import TopicPage from "./routes/topicPage";

ReactDOM.render(
  <React.StrictMode>
    <CssBaseline />
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="trees" element={<App />} />
        <Route path="items" element={<Items />} />
        <Route path="text-content" element={<TextContentPage />} />
        <Route path ="topics/:id" element={<TopicPage />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

And here is the page I am trying to render:

import { useParams } from "react-router-dom"
import Container from "@mui/material/Container";
import Header from "../components/Header";
import Card from '@mui/material/Card'
const topics = [
    {
        id: 1,
        name: "Environement",
        fund: 0
    },
    {
        id: 2,
        name: "Education",
        fund: 0
    },
    {
        id: 3,
        name: "International affairs",
        fund: 0
    }
]

export default function TopicPage(){

    const topicId = useParams()
    let topic = topics.find(topic => topic.id === topicId)
    return (
        <Container maxWidth = "sm">

                <Card>
{topic.name}
</Card>

        </Container>

    );

}

Any Help figuring out how to get useParams() to work would be greatly appreciated!!

Body:
useParams returns an object of key/value pairs of URL parameters.

And since you've define path as:
<Route path ="topics/:id" element={<TopicPage />} />
While accessing useParams since it returns an object you'll get key/value pair so use object destructuring const {id} = useParams() and since it's of type String you need to parseInt the returned value.

export default function TopicPage(){

    const {id} = useParams()
    let topic = topics.find(topic => topic.id === parseInt(id)) // Change here
    return (
        <Container maxWidth = "sm">
            <Header title = "Map The Future">
            </Header>
            <main>
                <Card><h2>{topic.name}</h2></Card>
            </main>
        </Container>

    );

}


问:
Expected non-nullable value for MutableLiveData
```<code>private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> get() = _users

fun getUsers() {
    viewModelScope.launch {
        _users.value = users()
    }
}

suspend fun users(): List<User> {
    TODO("Not implemented")
}
</code>```

I get following error on _users.value = users()

Expected non-nullable value. Inspection info:
This check ensures that LiveData values are not null when explicitly declared as non-nullable.

I'm using lifecycle version 2.3.1. The problem seems to be with suspend function users(). If I remove the suspend modifier it works fine.

答: Try this._users.value = users(). Adding this at the front works for me. Not sure why. In your case you might need this@yourModel._users.value = users() since you are calling it in the viewModelScope.

Body:
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> get() = _users

fun getUsers() {
    viewModelScope.launch {
        _users.value = users()
    }
}

suspend fun users(): List<User> {
    TODO("Not implemented")
}

I get following error on _users.value = users()

Expected non-nullable value. Inspection info:
This check ensures that LiveData values are not null when explicitly declared as non-nullable.

I'm using lifecycle version 2.3.1. The problem seems to be with suspend function users(). If I remove the suspend modifier it works fine.


问:
How can I add a voice recorder in webpage from user and save it in filefield at django model?
I am studying for a long on a voice recorder from the webpage and I need that to send this data to the backend.

I don't know how to do that.
If someone can guide me that would be a great help.

Thanks in advance.

答:
Well. Finally, I found a successful solution to this question.
So, I am keeping it here for my future use and anyone's help.

I found a blog where John Idogun solved the exact problem of mine here is the link
So, if anyone needs a solution can follow this.

Thanks


问:
Reasons and benefits for using a literal in asp over html
I am fairly new to asp.net so this may seem like a stupid question, but:

I am attempting to modify a pre-exsiting help menu in a web-app.

In this menu the previous developer, just used three literals seperated by paragraphs and a button linking to a 100 page manual. (i know doesn't seem to be much help, hence why i was planning to update and fix this)

What i had in mind was setting something up like a menu that would link to the different section of the page when the title is clicked.

So something along these lines:

```<code><h1>Menu Contents</h1>
<ol>
<li>section1</li>
<li>section2</li>
<li>etc</li>
 </ol>
</code>```

After the contents section i would have the first section with it's details.

What i am wondering is why would i use asp-literals over just sticking to html?
So basically i would like to know what are the benefits or reasons for using asp literals and i guess when is it that i should use them?

I've attempted to find the solution to this on my own, but the only related matters i have been able to find have to deal with people arguing whether literals or labels are the best option so it's not entirely helpful.

Any help or suggestions are greatly appreciated.
Thanks.

答:
Maybe it's been done that way so it would allow the links to be built dynamically, something like:

```<code>litMenuItem1.Text = "<a href=\"section1.aspx\">section1</a>";
</code>```

thus giving full control over the output? There are better ways to do that however.

Body:
I am fairly new to asp.net so this may seem like a stupid question, but:

I am attempting to modify a pre-exsiting help menu in a web-app.

In this menu the previous developer, just used three literals seperated by paragraphs and a button linking to a 100 page manual. (i know doesn't seem to be much help, hence why i was planning to update and fix this)

What i had in mind was setting something up like a menu that would link to the different section of the page when the title is clicked.

So something along these lines:

Menu Contents

section1

section2

etc

After the contents section i would have the first section with it's details.

What i am wondering is why would i use asp-literals over just sticking to html?
So basically i would like to know what are the benefits or reasons for using asp literals and i guess when is it that i should use them?

I've attempted to find the solution to this on my own, but the only related matters i have been able to find have to deal with people arguing whether literals or labels are the best option so it's not entirely helpful.

Any help or suggestions are greatly appreciated.
Thanks.

Body:
Maybe it's been done that way so it would allow the links to be built dynamically, something like:

litMenuItem1.Text = "<a href=\"section1.aspx\">section1</a>";

thus giving full control over the output? There are better ways to do that however.


问:
Minimum replacements in a string to make all 'X' chars to the left of all 'Y chars
Hey everyone had this problem in an interview and can't seem to figure out the best way to do it. Any help would be much appreciated.

Problem:

You are given a string S. Each character of the string is either 'W' or 'R'.

W represents a white-colored flower.

R represents a red-colored flower

A string is considered beautiful if all the white-colored flowers are on the left of all the red-colored flowers. You can replace any white-colored flower with a red-colored flower and vice versa.

Your task is to find the minimum number of replacements that must be made to make string S beautiful.

sample cases:

1.) input: "RWRW"

output: 2 ("WWRR" or "WWWW" or “RRRR”)

2.) input: "RRRR"

output: 0 ("RRRR")

3.) input: "RWWWRR"

output: 1 ("WWWWRR")

答:
This looks like a dynamic programming problem. Let

dp[i][0] = minimum number of changes if the i-th flower is white
dp[i][1] = minimum number of changes if the i-th flower is white
```
<p>Base state:</p>
<pre class="lang-py prettyprint-override"><code>dp[0][0] = int(arr[0] != “W”)
dp[0][1] = int(arr[0] != “R”)
</code>```

Now, to calculate the values for dp[i], we look at the cases:

If arr[i] == “R”

If arr[i-1] == “R”, then arr[i] has to be “R”.

If arr[i-1] == “W”, then arr[i] can be “R” or “W”.

arr[i][1] = min(arr[i-1][0], arr[i-1][1])

arr[i][0] = arr[i-1][0] + 1

If arr[i] == “W”

If arr[i-1] == “R”, then arr[i] has to be “R” (so we’ll have to modify current flower).

If arr[i-1] == “W”, then arr[i] can be “R” (which needs modification) or “W” (no modification needed).

arr[i][0] = arr[i-1][0]

arr[i][1] = min(arr[i-1][0], arr[i-1][1]) + 1

In the end, your answer becomes min(dp[n-1][0], dp[n-1][1])

Simple Python implementation:

s = "RWWWRR"
n = len(s)
dp = [[0,0] for i in range(n)]
dp[0][0] = int(s[0] != "W")
dp[0][1] = int(s[0] != "R")
for i in range(1,n):
    if s[i] == "R":
        dp[i][1] = min(dp[i-1])
        dp[i][0] = dp[i-1][0] + 1
    else:
        dp[i][1] = min(dp[i-1]) + 1
        dp[i][0] = dp[i-1][0]

print(min(dp[n-1]))
```

Body:
This looks like a dynamic programming problem. Let

dp[i][0] = minimum number of changes if the i-th flower is white
dp[i][1] = minimum number of changes if the i-th flower is white

Base state:

dp[0][0] = int(arr[0] != “W”)
dp[0][1] = int(arr[0] != “R”)

Now, to calculate the values for dp[i], we look at the cases:

If arr[i] == “R”

If arr[i-1] == “R”, then arr[i] has to be “R”.

If arr[i-1] == “W”, then arr[i] can be “R” or “W”.

arr[i][1] = min(arr[i-1][0], arr[i-1][1])

arr[i][0] = arr[i-1][0] + 1

If arr[i] == “W”

If arr[i-1] == “R”, then arr[i] has to be “R” (so we’ll have to modify current flower).

If arr[i-1] == “W”, then arr[i] can be “R” (which needs modification) or “W” (no modification needed).

arr[i][0] = arr[i-1][0]

arr[i][1] = min(arr[i-1][0], arr[i-1][1]) + 1

In the end, your answer becomes min(dp[n-1][0], dp[n-1][1])

Simple Python implementation:

s = "RWWWRR"
n = len(s)
dp = [[0,0] for i in range(n)]
dp[0][0] = int(s[0] != "W")
dp[0][1] = int(s[0] != "R")
for i in range(1,n):
    if s[i] == "R":
        dp[i][1] = min(dp[i-1])
        dp[i][0] = dp[i-1][0] + 1
    else:
        dp[i][1] = min(dp[i-1]) + 1
        dp[i][0] = dp[i-1][0]

print(min(dp[n-1]))


问:
Quasar 2 Vue 3 how to access app.config.globalProperties through "this" object in .vue files?
I am using Quasar 2 Vue 3. Currently I need to import app from "../boot/firebaseConfig"; in every .vue files and access global variables using app.config.globalProperties.<foo> syntax. Is there anyway to shorten this to just using this.<foo>?

答:
```<code>  data() {
    return {
      db: app.config.globalProperties.$db
    }
  },
  methods: {
    method1() { this.db ...}
  }
</code>```


问:
What is Boto3 Inspector v2 list_findings' nextToken initial value?
I am using boto3 Python to list findings from Inspector v2, using the list_findings() method inside a loop, according to AWS Boto3 Inspector2 Docs I have to set the value of this parameter to null for the first request to a list action but keep getting error in all these cases for variable next_token:

nextToken = None: botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter nextToken, value: None, type: <class 'NoneType'>, valid types: <class 'str'>

nextToken = 'null': botocore.errorfactory.ValidationException: An error occurred (ValidationException) when calling the ListFindings operation: Pagination token exception in operation 'ListFindings': invalid payload wrapping schema -24855

nextToken = empty string: An error occurred (ValidationException) when calling the ListFindings operation: Pagination token exception in operation 'ListFindings': invalid payload (no encryption schema version)

here is my code:

```<code>import boto3
inspector = boto3.client("inspector2")
next_token = "" # I change the value of this variable
while True:
    response = inspector.list_findings(
            filterCriteria={
                'findingStatus': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'ACTIVE'
                    },
                ],
                'findingType': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'PACKAGE_VULNERABILITY'
                    },
                ],
            },
        nextToken=next_token
    )
    next_token= response.get("nextToken")

    # Some Code Here

    if next_token == None:
        break

</code>```

I am confused about what should the value of nextToken be for the first request?

答:
It would be easier to use paginate as explained in AWS docs:</p>
```<code># Create a client
inspector = boto3.client("inspector2")

# Create a reusable Paginator
paginator = inspector.get_paginator('list_findings')

# Create a PageIterator from the Paginator
page_iterator = paginator.paginate(filterCriteria={
                'findingStatus': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'ACTIVE'
                    },
                ],
                'findingType': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'PACKAGE_VULNERABILITY'
                    },
                ],
            })

for page in page_iterator:
    print(page)
</code>```

Body:
I am using boto3 Python to list findings from Inspector v2, using the list_findings() method inside a loop, according to AWS Boto3 Inspector2 Docs I have to set the value of this parameter to null for the first request to a list action but keep getting error in all these cases for variable next_token:

nextToken = None: botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter nextToken, value: None, type: <class 'NoneType'>, valid types: <class 'str'>

nextToken = 'null': botocore.errorfactory.ValidationException: An error occurred (ValidationException) when calling the ListFindings operation: Pagination token exception in operation 'ListFindings': invalid payload wrapping schema -24855

nextToken = empty string: An error occurred (ValidationException) when calling the ListFindings operation: Pagination token exception in operation 'ListFindings': invalid payload (no encryption schema version)

here is my code:

import boto3
inspector = boto3.client("inspector2")
next_token = "" # I change the value of this variable
while True:
    response = inspector.list_findings(
            filterCriteria={
                'findingStatus': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'ACTIVE'
                    },
                ],
                'findingType': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'PACKAGE_VULNERABILITY'
                    },
                ],
            },
        nextToken=next_token
    )
    next_token= response.get("nextToken")

    # Some Code Here

    if next_token == None:
        break

I am confused about what should the value of nextToken be for the first request?

Body:
It would be easier to use paginate as explained in AWS docs:

# Create a client
inspector = boto3.client("inspector2")

# Create a reusable Paginator
paginator = inspector.get_paginator('list_findings')

# Create a PageIterator from the Paginator
page_iterator = paginator.paginate(filterCriteria={
                'findingStatus': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'ACTIVE'
                    },
                ],
                'findingType': [
                    {
                        'comparison': 'EQUALS',
                        'value': 'PACKAGE_VULNERABILITY'
                    },
                ],
            })

for page in page_iterator:
    print(page)


问:
Django FileField with upload_to determined at runtime
I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:

```<code>class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to='.')
</code>```

So what I want is instead of '.' as the upload_to, have it be the user's name.

I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.

Thanks for the help!

答:
I wanted to change the upload path in runtime, and none of the solutions were suitable for this need.

this is what I've done:

```<code>class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=DynamicUploadPath.get_file_path)

class ContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Content
        fields = '__all__'

class UploadDir(models.TextChoices):
    PRODUCT = 'PRD', _('Product')
    USER_PROFILE = 'UP', _('User Profile')

class DynamicUploadPath:
    dir: UploadDir = None

    @classmethod
    def get_file_path(cls, instance, filename):
        return str(cls.dir.name.lower() + '/' + filename)

def set_DynamicUploadPath(dir: UploadDir):
    DynamicUploadPath.dir = dir

class UploadFile(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request):
        # file save path: MEDIA_ROOT/product/filename
        set_DynamicUploadPath(UploadDir.PRODUCT)

        # file save path: MEDIA_ROOT/user_profile/filename
        # set_DynamicUploadPath(UploadDir.USER_PROFILE)

        serializer = ContentSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to='.')

So what I want is instead of '.' as the upload_to, have it be the user's name.

I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.

Thanks for the help!

Body:
I wanted to change the upload path in runtime, and none of the solutions were suitable for this need.

this is what I've done:

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=DynamicUploadPath.get_file_path)

class ContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Content
        fields = '__all__'

class UploadDir(models.TextChoices):
    PRODUCT = 'PRD', _('Product')
    USER_PROFILE = 'UP', _('User Profile')

class DynamicUploadPath:
    dir: UploadDir = None

    @classmethod
    def get_file_path(cls, instance, filename):
        return str(cls.dir.name.lower() + '/' + filename)

def set_DynamicUploadPath(dir: UploadDir):
    DynamicUploadPath.dir = dir

class UploadFile(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request):
        # file save path: MEDIA_ROOT/product/filename
        set_DynamicUploadPath(UploadDir.PRODUCT)

        # file save path: MEDIA_ROOT/user_profile/filename
        # set_DynamicUploadPath(UploadDir.USER_PROFILE)

        serializer = ContentSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)