问:
npm run start results in blank page only on Server
I have just installed a vue Landing page on my Mac. Terminal to folder and was running "npm install" and "npm run dev" it worked just fine.

But on the managed Server npm install works after sometimes only because it often gets killed with code 137. I created a subdomain for the project folder.

running npm run start gives me no errors but the url "subdomain.domain.legal" returns in blank page. The main  Is not getting replaced by anything. Port 8080 gives "Website not available"

Any ideas what specs or settings could be wrong on the managed Server?

index.js

```<code>'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')
module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: 'subdomain.domain.legal', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: true,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },
</code>```

error after npm run start (sometimes)

```<code> I  Your application is running here: http://subdomain.domain.legal:8080                                        Killed
npm ERR! code ELIFECYCLE
npm ERR! errno 137
npm ERR! tovo_vue@1.0.0 dev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js`
npm ERR! Exit status 137
npm ERR!
npm ERR! Failed at the tovo_vue@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /usr/home/user/.npm/_logs/2019-05-31T11_47_21_305Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 137
npm ERR! tovo_vue@1.0.0 start: `npm run dev`
npm ERR! Exit status 137
npm ERR!
npm ERR! Failed at the tovo_vue@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /usr/home/user/.npm/_logs/2019-05-31T11_47_21_313Z-debug.log
</code>```

HTML code of (blank) page

```<code><html><head>
    <title>Title</title>
    <meta charset="utf-8">
    <meta name="author" content="pixelstrap">
    <meta name="description" content="xy">
    <meta name="keywords" content="xy">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Fav icon -->
    <link rel="shortcut icon" hre="/static/favicon.png">
    <!-- Font Family-->
    <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700" rel="stylesheet">
  </head>
  <body id="nav-scroller" data-spy="scroll" data-target=".navbar" data-offset="0">

  <div id="app"></div>

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

free -g:

```<code>              total        used        free      shared  buff/cache   available
Mem:             31           7          10           0          12          22
Swap:             3           0           3
</code>```

ps aux | grep node

```<code>user 1422  0.0  0.0  16712   968 pts/1    S+   14:18   0:00 grep node
</code>```

答:
Once kill everything and start again below the code.

```<code> ps aux | grep node
 sudo kill -9
</code>```

Also,

```<code>sudo lsof -i:<PORT_NO>
</code>```

close the instance for present time but unable to stop the process in background. So for one time,

```<code>sudo kill <PID>
</code>```

works, but again when we update our code and save, this problem occurs again as with Nodemon.

So exit the terminal will solve the problem. OR

```<code>killall -9 node
</code>```

Body:
I have just installed a vue Landing page on my Mac. Terminal to folder and was running "npm install" and "npm run dev" it worked just fine.

But on the managed Server npm install works after sometimes only because it often gets killed with code 137. I created a subdomain for the project folder.

running npm run start gives me no errors but the url "subdomain.domain.legal" returns in blank page. The main  Is not getting replaced by anything. Port 8080 gives "Website not available"

Any ideas what specs or settings could be wrong on the managed Server?

index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')
module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: 'subdomain.domain.legal', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: true,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

error after npm run start (sometimes)

 I  Your application is running here: http://subdomain.domain.legal:8080                                        Killed
npm ERR! code ELIFECYCLE
npm ERR! errno 137
npm ERR! tovo_vue@1.0.0 dev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js`
npm ERR! Exit status 137
npm ERR!
npm ERR! Failed at the tovo_vue@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /usr/home/user/.npm/_logs/2019-05-31T11_47_21_305Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 137
npm ERR! tovo_vue@1.0.0 start: `npm run dev`
npm ERR! Exit status 137
npm ERR!
npm ERR! Failed at the tovo_vue@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /usr/home/user/.npm/_logs/2019-05-31T11_47_21_313Z-debug.log

HTML code of (blank) page

    <title>Title</title>
    <meta charset="utf-8">
    <meta name="author" content="pixelstrap">
    <meta name="description" content="xy">
    <meta name="keywords" content="xy">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link rel="shortcut icon" hre="/static/favicon.png">

    <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700" rel="stylesheet">

free -g:

              total        used        free      shared  buff/cache   available
Mem:             31           7          10           0          12          22
Swap:             3           0           3

ps aux | grep node

user 1422  0.0  0.0  16712   968 pts/1    S+   14:18   0:00 grep node

Body:
Once kill everything and start again below the code.

 ps aux | grep node
 sudo kill -9

Also,

sudo lsof -i:<PORT_NO>

close the instance for present time but unable to stop the process in background. So for one time,

sudo kill <PID>

works, but again when we update our code and save, this problem occurs again as with Nodemon.

So exit the terminal will solve the problem. OR

killall -9 node


来源: stackexchange

问:
Why this code doesn't work, how do I grab a specific part of url?
I have the following url http://localhost:8000/enthusiastically-synergize-optimal-results-after-proactive-total-linkage/edit/ and would like to access that slug from this url in this function so I can use it. In class based view I could use self.kwargs.get('smthng') and grab that but don't know how do I do that here:

```<code>def permission_of_user_for_posts(request):
post = get_object_or_404(Blog, slug= request.GET.get('blog_slug'))
if request.user.username == post.author:
    return True
return False

@user_passes_test(permission_of_user_for_posts)
def blog_update(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
if request.method == 'POST':
    form = BlogForm(request.POST, request.FILES, instance=blog)
    if form.is_valid():
        form.instance.author = request.user
        form.save()
        return redirect('/')

form = BlogForm(instance=blog)
context= {
    'form': form
}
return render(request, 'blogs/form.html', context)
</code>```

or is there something else that I am doing it wrong in permission_of_user_for_posts function? please help me thank you

edit: this is url

```<code>urlpatterns = [
    path('', blogs_view.home, name='home'),
    path('blogs/', blogs_view.blogs, name='blogs'),
    path('<slug:blog_slug>', blogs_view.blog_detail, name='blog_detail'),
    path('post/', blogs_view.blog_create, name='blog_create'),
    path('<slug:blog_slug>/edit/', blogs_view.blog_update, name='blog_update'),
    path('<slug:blog_slug>/delete/', blogs_view.blog_delete, name='blog_delete'),
]
</code>```

答:
The way to do this is not to use the decorator or a separate function at all. Just check the post in the view:</p>

```<code>def blog_update(request, blog_slug):
    blog = get_object_or_404(Blog, slug=blog_slug)
    if not request.user == blog.author:
        raise PermissionDenied
    if request.method == 'POST':
        ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following url http://localhost:8000/enthusiastically-synergize-optimal-results-after-proactive-total-linkage/edit/ and would like to access that slug from this url in this function so I can use it. In class based view I could use self.kwargs.get('smthng') and grab that but don't know how do I do that here:

def permission_of_user_for_posts(request):
post = get_object_or_404(Blog, slug= request.GET.get('blog_slug'))
if request.user.username == post.author:
    return True
return False

@user_passes_test(permission_of_user_for_posts)
def blog_update(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
if request.method == 'POST':
    form = BlogForm(request.POST, request.FILES, instance=blog)
    if form.is_valid():
        form.instance.author = request.user
        form.save()
        return redirect('/')

form = BlogForm(instance=blog)
context= {
    'form': form
}
return render(request, 'blogs/form.html', context)

or is there something else that I am doing it wrong in permission_of_user_for_posts function? please help me thank you

edit: this is url

urlpatterns = [
    path('', blogs_view.home, name='home'),
    path('blogs/', blogs_view.blogs, name='blogs'),
    path('<slug:blog_slug>', blogs_view.blog_detail, name='blog_detail'),
    path('post/', blogs_view.blog_create, name='blog_create'),
    path('<slug:blog_slug>/edit/', blogs_view.blog_update, name='blog_update'),
    path('<slug:blog_slug>/delete/', blogs_view.blog_delete, name='blog_delete'),
]

Body:
The way to do this is not to use the decorator or a separate function at all. Just check the post in the view:

def blog_update(request, blog_slug):
    blog = get_object_or_404(Blog, slug=blog_slug)
    if not request.user == blog.author:
        raise PermissionDenied
    if request.method == 'POST':
        ...


问:
I am finding the second largest number from the array list, but I get runtime-error when the input arr is 6,6,6,6,6,6,6,6,6,5
when i compiled this program in VSCode, I got IndexError. Is there any other solution?</p>

```<code>#here is my sample code
if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    x = len(arr)
    arr.sort()
    for i in range(0, x-1):
        #removing redundant values
        if arr[i] == max(arr):
            arr.remove(arr[i])

    arr.remove(max(arr))
    print(max(arr))
</code>```

答:
Seeing as you're not updating the length after the first iteration you will end up, thinking you have a bigger array than you do, as you remove them all. Resulting in an IndexError.

If you make a copy of the array you can always iterate over that allowing you to edit the original list meanwhile.

Body:
when i compiled this program in VSCode, I got IndexError. Is there any other solution?

#here is my sample code
if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    x = len(arr)
    arr.sort()
    for i in range(0, x-1):
        #removing redundant values
        if arr[i] == max(arr):
            arr.remove(arr[i])

    arr.remove(max(arr))
    print(max(arr))


问:
Any Way to "Safely" Call assembly.GetTypes()?
I've searched high and low, but I can't come up with a solution for this.

I need to get all the interface types from an assembly with code like this:

```<code>IEnumerable<Type> interfaces = _assembly.GetTypes().Where(x => x.IsInterface);
</code>```

The problem is, for certain assemblies I run into the following error:

Unable to load one or more of the
  requested types. Retrieve the
  LoaderExceptions property for more
  information.

I'm completely clear on why this happens (dependant assemblies are not loaded), and how it can be worked around if I want to troubleshoot a specific assembly.  In my case, I don't know the assembly up front (the user will select it).

What I'd like to know is whether there is any way to allow the code to continue past any types that can't be retrieved, and still pull the ones that don't fail.

答:
It looks like this is a vexing API for which the exception cannot be avoided (as far as I know).

Try something like this:

```<code>IEnumerable<Type> interfaces;
try
{
    interfaces = _assembly.GetTypes().Where(x => x.IsInterface);
}
catch (ReflectionTypeLoadException ex)
{
    interfaces = ex.Types.Where(x => x != null && x.IsInterface);
}
</code>```

UPDATE

Actually, this is so ugly that I would probably hide it somewhere. This must be a very old part of the .NET Framework, because I’m pretty sure they wouldn't design it like this nowadays.

```<code>private static IEnumerable<Type> GetTypesSafely(Assembly assembly)
{
    try
    {
        return assembly.GetTypes();
    }
    catch(ReflectionTypeLoadException ex)
    {
        return ex.Types.Where(x => x != null);
    }
}

...
IEnumberable<Type> interfaces = GetTypesSafely(_assembly).Where(x => x.IsInterface);
</code>```

If you think you'll be doing this very often, then an extension method might be more appropriate.

ContentLicense: CC BY-SA 3.0

Body:
I've searched high and low, but I can't come up with a solution for this.

I need to get all the interface types from an assembly with code like this:

IEnumerable<Type> interfaces = _assembly.GetTypes().Where(x => x.IsInterface);

The problem is, for certain assemblies I run into the following error:

Unable to load one or more of the
  requested types. Retrieve the
  LoaderExceptions property for more
  information.

I'm completely clear on why this happens (dependant assemblies are not loaded), and how it can be worked around if I want to troubleshoot a specific assembly.  In my case, I don't know the assembly up front (the user will select it).

What I'd like to know is whether there is any way to allow the code to continue past any types that can't be retrieved, and still pull the ones that don't fail.

Body:
It looks like this is a vexing API for which the exception cannot be avoided (as far as I know).

Try something like this:

IEnumerable<Type> interfaces;
try
{
    interfaces = _assembly.GetTypes().Where(x => x.IsInterface);
}
catch (ReflectionTypeLoadException ex)
{
    interfaces = ex.Types.Where(x => x != null && x.IsInterface);
}

UPDATE

Actually, this is so ugly that I would probably hide it somewhere. This must be a very old part of the .NET Framework, because I’m pretty sure they wouldn't design it like this nowadays.

private static IEnumerable<Type> GetTypesSafely(Assembly assembly)
{
    try
    {
        return assembly.GetTypes();
    }
    catch(ReflectionTypeLoadException ex)
    {
        return ex.Types.Where(x => x != null);
    }
}

...
IEnumberable<Type> interfaces = GetTypesSafely(_assembly).Where(x => x.IsInterface);

If you think you'll be doing this very often, then an extension method might be more appropriate.


问:
Javascript check if string contains only certain character
I want to return true if a given string has only a certain character but any number of occurrences of that character.
Examples:

```<code>// checking for 's'
'ssssss' -> true
'sss s'  -> false
'so'     -> false
</code>```

答:
first, convert the string into an array using split,

```<code>const letters ='string'.split('')
</code>```

then, use the Set data structure and pass the array as an argument to the constructer. Set will only have unique values.

```<code>const unique = new Set(letters)
</code>```

this unique will have only the unique characters, so, when you pass sss then this will have only a single s.

finally, if the unique array contains only one element, then we can say this string only contains the same letter.

```<code>if (unique.size === 1) { // the string contains only the same letters
</code>```

Your function should look like this,

```<code>function isIdentile(string) {
    const letters = string.split('');
    const unique = new Set(letters)

    return unique.size === 1 ? true: false;
}
</code>```

Body:
I want to return true if a given string has only a certain character but any number of occurrences of that character.
Examples:

// checking for 's'
'ssssss' -> true
'sss s'  -> false
'so'     -> false

Body:
first, convert the string into an array using split,

const letters ='string'.split('')

then, use the Set data structure and pass the array as an argument to the constructer. Set will only have unique values.

const unique = new Set(letters)

this unique will have only the unique characters, so, when you pass sss then this will have only a single s.

finally, if the unique array contains only one element, then we can say this string only contains the same letter.

if (unique.size === 1) { // the string contains only the same letters

Your function should look like this,

function isIdentile(string) {
    const letters = string.split('');
    const unique = new Set(letters)

    return unique.size === 1 ? true: false;
}


问:
Why does Kruskal's algorithm find the minimum spanning tree if it's greedy?
Why does Kruskal's algorithm find the minimum spanning tree if it's greedy? Isn't a minimum spanning tree a global optimization problem? Isn't the point of being greedy is that there is a chance you won't find the most optimal solution? So how can Kruskal be able to find the minimum spanning tree while also being greedy?</p>

答: There are some greedy algorithms that produce globally optimal solutions. There are some greedy algorithms that do not. Kruskal's algorithm happens to be in the first category (which requires a standard proof as shown in other answers).


问:
Angular file upload to Teamwork API
here is my issue...

I'm trying to upload a file via Angular 6 to Teamwork API
https://developer.teamwork.com/projects/file-uploading/upload-a-file
however no matter what file I try to upload I always get the error message
"the form field 'file' did not contain a valid file"

I've tried sending without content-type, content-type: undefined etc
I've tried adding the file object into formdata

Here is some code:

--- template file ---

```<code><input type="file" [id]="question.id" class="form-control" (change)="onUpload($event)">
<button class="btn btn-update"><i class="icon-success file-continue" (click)="onUpdate($event)"></i></button>
</code>```

--- component ---

```<code>onUpload(event: any) {
  this.uploadObject = event.target.files[0];
  this.uploadName = event.target.files[0].name;
}
onUpdate(event: any) {
  this.twApiService.uploadFile(this.uploadObject).subscribe(
    (response: any) => {
      console.log(response);
    },
    (error: any) => {
      console.log(error);
    }
  );
}
</code>```

--- service ---

```<code>uploadFile(uploadObject: any) {
  const url = 'https://[hidden].teamwork.com/pendingfiles.json';
  const fileObject = { file: uploadObject };
  const headers = new HttpHeaders({'Content-Type': 'multipart/form-data', 'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
  return this.http.post(url, fileObject, {headers});
}
</code>```

I tried many versions of this code with everything I found across the internet in the past 3 days and nothing worked. I always get this error:
"the form field 'file' did not contain a valid file"

Can someone give my some instructions how to fix this or at least to try something different?

Regards, Ivo.

答:
I check the teamwork API and its weird because them expect a request body application/json (when usually file upload is handling via formdata request)

So try this first and check in network tab that it is application/json request:

```<code>uploadFile(uploadObject: any) {
  const url = 'https://[hidden].teamwork.com/pendingfiles.json';
  const fileObject = { file: uploadObject };
  const headers = new HttpHeaders({'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
  return this.http.post(url, fileObject, {headers});
}
</code>```

If that not work try formData way
Here is important that not set manually formData type because it automatically recognise it.

```<code>uploadFile(uploadObject: any) {
  const url = 'https://[hidden].teamwork.com/pendingfiles.json';
  const formData = new FormData();
  formData.append('file', uploadobject);
  const headers = new HttpHeaders({'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
  return this.http.post(url, formData, {headers});
}
</code>```

Title: Angular file upload to Teamwork API

Body:
here is my issue...

I'm trying to upload a file via Angular 6 to Teamwork API
https://developer.teamwork.com/projects/file-uploading/upload-a-file
however no matter what file I try to upload I always get the error message
"the form field 'file' did not contain a valid file"

I've tried sending without content-type, content-type: undefined etc
I've tried adding the file object into formdata

Here is some code:

--- template file ---

<input type="file" [id]="question.id" class="form-control" (change)="onUpload($event)">
<button class="btn btn-update"></button>

--- component ---

onUpload(event: any) {
  this.uploadObject = event.target.files[0];
  this.uploadName = event.target.files[0].name;
}
onUpdate(event: any) {
  this.twApiService.uploadFile(this.uploadObject).subscribe(
    (response: any) => {
      console.log(response);
    },
    (error: any) => {
      console.log(error);
    }
  );
}

--- service ---

uploadFile(uploadObject: any) {
  const url = 'https://[hidden].teamwork.com/pendingfiles.json';
  const fileObject = { file: uploadObject };
  const headers = new HttpHeaders({'Content-Type': 'multipart/form-data', 'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
  return this.http.post(url, fileObject, {headers});
}

I tried many versions of this code with everything I found across the internet in the past 3 days and nothing worked. I always get this error:
"the form field 'file' did not contain a valid file"

Can someone give my some instructions how to fix this or at least to try something different?

Regards, Ivo.

Body:
I check the teamwork API and its weird because them expect a request body application/json (when usually file upload is handling via formdata request)

So try this first and check in network tab that it is application/json request:

uploadFile(uploadObject: any) {
  const url = 'https://[hidden].teamwork.com/pendingfiles.json';
  const fileObject = { file: uploadObject };
  const headers = new HttpHeaders({'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
  return this.http.post(url, fileObject, {headers});
}

If that not work try formData way
Here is important that not set manually formData type because it automatically recognise it.

uploadFile(uploadObject: any) {
  const url = 'https://[hidden].teamwork.com/pendingfiles.json';
  const formData = new FormData();
  formData.append('file', uploadobject);
  const headers = new HttpHeaders({'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
  return this.http.post(url, formData, {headers});
}


问:
how to restore soft delete with one more column?
I have a table named data and I am using soft delete to delete the record.i have one more field in my data table which is also updated when a record is deleted. but when I restore that soft deleted record, it updates my deleted_at field but doesn't update the other field.
I use this code

```<code>Data::withTrashed()->find($id)->restore();
</code>```

How can I do this?

答:
```<code>Data::withTrashed()->find($id)->restore();
</code>```

meant this only for restoring which is set the deleted_at column to null
so if you want update the other field, just do the usual things for updating fields after you restore it

like this one

```<code>Data::withTrashed()->find($id)->restore();
Data::find($id)->update($array);
</code>```

Body:
I have a table named data and I am using soft delete to delete the record.i have one more field in my data table which is also updated when a record is deleted. but when I restore that soft deleted record, it updates my deleted_at field but doesn't update the other field.
I use this code

Data::withTrashed()->find($id)->restore();

How can I do this?

Body:
Data::withTrashed()->find($id)->restore();

meant this only for restoring which is set the deleted_at column to null
so if you want update the other field, just do the usual things for updating fields after you restore it

like this one

Data::withTrashed()->find($id)->restore();
Data::find($id)->update($array);


问:
How to pass values from view.py to index.html in Django?
I have all these variables in my view.py on Django.
And I want to put in on the index.html

def current_database(request):
    contador = Post.objects.count()
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["prueba2"]
    mycol = mydb["miapp_post"]
    template = loader.get_template('miapp/index.html')

    for x in mycol.find():
        dominio = x['dominio']
        porcentaje_movil = x['porcentaje_movil']
        orportunidades_movil = x['orportunidades_movil']
        diagnosticos_movil = x['diagnosticos_movil']
        porcentaje_ordenador = x['porcentaje_ordenador']
        oportunidades_ordenador = x['oportunidades_ordenador']
        diagnosticos_ordenador = x['diagnosticos_ordenador']
        return HttpResponse(template.render(dominio, porcentaje_movil, orportunidades_movil, diagnosticos_movil, porcentaje_ordenador, oportunidades_ordenador, diagnosticos_ordenador))
```

<p>When i go to my index.html all go fine the conecction its fine, no problem with that, but for exmple y put:</p>

<pre class="lang-py prettyprint-override"><code><p>Dominio: {{ dominio }}</p>
</code>```

or

Dominio: {% dominio %}

```

and I always get and error and i dont know how to pass these values to mi html.
Thanks.

答:
Solve, I made this:

```<code>def current_database(request):
    contador = Post.objects.count()
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["prueba2"]
    mycol = mydb["miapp_post"]
    template = loader.get_template('miapp/index.html')

    for x in mycol.find():
        dominio = x['dominio']
        porcentaje_movil = x['porcentaje_movil']
        orportunidades_movil = x['orportunidades_movil']
        diagnosticos_movil = x['diagnosticos_movil']
        porcentaje_ordenador = x['porcentaje_ordenador']
        oportunidades_ordenador = x['oportunidades_ordenador']
        diagnosticos_ordenador = x['diagnosticos_ordenador']
        context = {
            'dominio': dominio,
            'porcentaje_movil': porcentaje_movil,
            'orportunidades_movil': orportunidades_movil,
            'diagnosticos_movil': diagnosticos_movil,
            'porcentaje_ordenador': porcentaje_ordenador,
            'oportunidades_ordenador': oportunidades_ordenador,
            'diagnosticos_ordenador': diagnosticos_ordenador,
        }
        return render(request, 'miapp/index.html', context)

</code>```

and in the html I just put that:

Dominio: {{ dominio }}

```

Body:
I have all these variables in my view.py on Django.
And I want to put in on the index.html

def current_database(request):
    contador = Post.objects.count()
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["prueba2"]
    mycol = mydb["miapp_post"]
    template = loader.get_template('miapp/index.html')

    for x in mycol.find():
        dominio = x['dominio']
        porcentaje_movil = x['porcentaje_movil']
        orportunidades_movil = x['orportunidades_movil']
        diagnosticos_movil = x['diagnosticos_movil']
        porcentaje_ordenador = x['porcentaje_ordenador']
        oportunidades_ordenador = x['oportunidades_ordenador']
        diagnosticos_ordenador = x['diagnosticos_ordenador']
        return HttpResponse(template.render(dominio, porcentaje_movil, orportunidades_movil, diagnosticos_movil, porcentaje_ordenador, oportunidades_ordenador, diagnosticos_ordenador))

When i go to my index.html all go fine the conecction its fine, no problem with that, but for exmple y put:

Dominio: {{ dominio }}

or

Dominio: {% dominio %}

and I always get and error and i dont know how to pass these values to mi html.
Thanks.

Body:
Solve, I made this:

def current_database(request):
    contador = Post.objects.count()
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["prueba2"]
    mycol = mydb["miapp_post"]
    template = loader.get_template('miapp/index.html')

    for x in mycol.find():
        dominio = x['dominio']
        porcentaje_movil = x['porcentaje_movil']
        orportunidades_movil = x['orportunidades_movil']
        diagnosticos_movil = x['diagnosticos_movil']
        porcentaje_ordenador = x['porcentaje_ordenador']
        oportunidades_ordenador = x['oportunidades_ordenador']
        diagnosticos_ordenador = x['diagnosticos_ordenador']
        context = {
            'dominio': dominio,
            'porcentaje_movil': porcentaje_movil,
            'orportunidades_movil': orportunidades_movil,
            'diagnosticos_movil': diagnosticos_movil,
            'porcentaje_ordenador': porcentaje_ordenador,
            'oportunidades_ordenador': oportunidades_ordenador,
            'diagnosticos_ordenador': diagnosticos_ordenador,
        }
        return render(request, 'miapp/index.html', context)

and in the html I just put that:

<p>Dominio: {{ dominio }}</p>


问:
Pivoting tables in SQL Server in 2019 year and future
Are there any ways to achieve dynamic pivoting tables in SQL Server through an elegant function? Pivoting tables is a basic utility which theoretically might be done in one line of code. All we need is to define parameters: column variable to pivot (change its values into column names), variable to aggregate, aggregate function, and table on which we perform the pivoting.

I look for alternatives to the syntax Microsoft proposes for pivoting tables in SQL Server in the 2019 year.

A practical alternative I found here:
https://stackoverflow.com/a/45065584/1903793

All complex code is wrapped with a stored procedure. In this elegant one-liner, we define all parameters which are needed for pivoting.

```<code>exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'
</code>```

But the caveat of that solution is that it is a stored procedure so it requires a static table as input and it outputs also a static table. Would be better if it might be a sort of TVF from which we can select.

Update after comments.
Until I started using SQL Server I did not even know that pivoting might be static. The need is to do dynamic pivoting. Lots of other applications do pivoting tables on the fly (Excel, Power BI, R) without constraint that column names must be known apriori. It might be a problem in 2005 to realize that pivoting might be done as a function with parameters. But, hey, we are going to the future, and it is ridiculous that we are heading next decades with the complex constrained syntax for this basic table transformation utility.

答:
You may use dynamic SQL queries  and execute your  desired result in single query. But first we'll prepare different component of our query in different variables after that combine all of them together to make a single query as per our desired output result.

You'll declare your query in a variable like @query of varchar type. By adding different component in your query you'll create any dynamic query which is not depend on single table but perform similar operations for any table name or parameters pass in it.

After building your query you can execute your query by using exec or exec sp_executesql and get the desired result.

Body:
Are there any ways to achieve dynamic pivoting tables in SQL Server through an elegant function? Pivoting tables is a basic utility which theoretically might be done in one line of code. All we need is to define parameters: column variable to pivot (change its values into column names), variable to aggregate, aggregate function, and table on which we perform the pivoting.

I look for alternatives to the syntax Microsoft proposes for pivoting tables in SQL Server in the 2019 year.

A practical alternative I found here:
https://stackoverflow.com/a/45065584/1903793

All complex code is wrapped with a stored procedure. In this elegant one-liner, we define all parameters which are needed for pivoting.

exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'

But the caveat of that solution is that it is a stored procedure so it requires a static table as input and it outputs also a static table. Would be better if it might be a sort of TVF from which we can select.

Update after comments.
Until I started using SQL Server I did not even know that pivoting might be static. The need is to do dynamic pivoting. Lots of other applications do pivoting tables on the fly (Excel, Power BI, R) without constraint that column names must be known apriori. It might be a problem in 2005 to realize that pivoting might be done as a function with parameters. But, hey, we are going to the future, and it is ridiculous that we are heading next decades with the complex constrained syntax for this basic table transformation utility.


问:
How to input a String in java except using nextLine() and I need to print the whole statement/sentences with spaces
So, below in my code, I want to input a string but without using the function nextLine() and I need to print the whole statement with statement. And I have already tried the alternative keyword next() it only prints the first word and because of a space it stops. But I need to print the whole statement.

SO, in that case what should be the solution?

```<code>import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s = scan.next();

        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
</code>```

答:
you need to put an extra scan.nextLine before your string input scanner to consume the extra \n like

```<code>int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.next();
</code>```

Body:
So, below in my code, I want to input a string but without using the function nextLine() and I need to print the whole statement with statement. And I have already tried the alternative keyword next() it only prints the first word and because of a space it stops. But I need to print the whole statement.

SO, in that case what should be the solution?

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s = scan.next();

        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

Body:
you need to put an extra scan.nextLine before your string input scanner to consume the extra \n like

int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.next();


问:
How to use control operator after a heredoc in bash
I'm writing a bash script to create MySQL database automatically. The bash script is like the following (please ignore those variable $db_name, $db_pwd...):

```<code>#!/bin/bash
sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF
printf "Done"
</code>```

I want the database creation to be completed successfully and the print command runs afterwards. But I can not put the && after EOF, like:

```<code>#!/bin/bash
sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF &&
printf "Done"
</code>```

It will show the error like:

```<code>invalid command name "EOF"
    while executing
"EOF &&"
</code>```

How can I do it?

答:
The parsing is strange, but can be used to. Newlines (and comments) after | && || are ignored. So you just write on the end of the line with the command, but after << EOF

```<code>#!/bin/bash
sudo mysql -u root << EOF &&
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF
printf "Done"
</code>```

Example:

```<code>grep -q bla << EOF &&
bla bla
EOF
# this comment is ignored

# lines with spaces, tabs and newlines and comments only are ignored
# until the first line with something is encountered
# the following will execute only if grep returns zero status
# it can be misleading

# Because you can write a LOT here, but bash stil just sees `grep && printf`
printf "grep matched successfully"
</code>```

Example at tutorialspoint.

Body:
I'm writing a bash script to create MySQL database automatically. The bash script is like the following (please ignore those variable $db_name, $db_pwd...):

#!/bin/bash
sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF
printf "Done"

I want the database creation to be completed successfully and the print command runs afterwards. But I can not put the && after EOF, like:

#!/bin/bash
sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF &&
printf "Done"

It will show the error like:

invalid command name "EOF"
    while executing
"EOF &&"

How can I do it?

Body:
The parsing is strange, but can be used to. Newlines (and comments) after | && || are ignored. So you just write on the end of the line with the command, but after << EOF

#!/bin/bash
sudo mysql -u root << EOF &&
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF
printf "Done"

Example:

grep -q bla << EOF &&
bla bla
EOF
# this comment is ignored

# lines with spaces, tabs and newlines and comments only are ignored
# until the first line with something is encountered
# the following will execute only if grep returns zero status
# it can be misleading

# Because you can write a LOT here, but bash stil just sees `grep && printf`
printf "grep matched successfully"

Example at tutorialspoint.


问:
group function is not allowed here (sql-oracle)
I want to update saboloo with the following table

```<code>update sagani
set saboloo=sum(sagani.qula + sagani.shualeduri + sagani.finaluri)
where sagnis_id='9';
</code>```

答:
Aggregation is not allowed in an update, because update changes values in the rows in the table; once the data is aggregated, the connection to the original rows is lost.

I can imagine that you mean one of two things.  The first would be a simple sum within the row:

```<code>update sagani
    set saboloo = (sagani.qula + sagani.shualeduri + sagani.finaluri)
where sagnis_id = 9;  -- looks like a number so I assume it is a number
</code>```

Alternatively, you may want to update multiple rows with the same value added up from all those rows:

```<code>update sagani s
    set saboloo = (select sum(s2.qula + s2.shualeduri + s2.finaluri)
                   from sagani s2
                   where s2.sagnis_id = s.sagnis_id
                  )
where s.sagnis_id = 9;
</code>```

Your question doesn't have enough information to infer your intention, although the use of sagnis_id suggests that there is only one row and you don't want aggregation at all.

Body:
I want to update saboloo with the following table

update sagani
set saboloo=sum(sagani.qula + sagani.shualeduri + sagani.finaluri)
where sagnis_id='9';

Body:
Aggregation is not allowed in an update, because update changes values in the rows in the table; once the data is aggregated, the connection to the original rows is lost.

I can imagine that you mean one of two things.  The first would be a simple sum within the row:

update sagani
    set saboloo = (sagani.qula + sagani.shualeduri + sagani.finaluri)
where sagnis_id = 9;  -- looks like a number so I assume it is a number

Alternatively, you may want to update multiple rows with the same value added up from all those rows:

update sagani s
    set saboloo = (select sum(s2.qula + s2.shualeduri + s2.finaluri)
                   from sagani s2
                   where s2.sagnis_id = s.sagnis_id
                  )
where s.sagnis_id = 9;

Your question doesn't have enough information to infer your intention, although the use of sagnis_id suggests that there is only one row and you don't want aggregation at all.


答:
To achieve this you can create function in your Data model which will do that for you.

```<code>public function restoreItem()
{
    $this->deleted_at = null;
    $this->other_field = null;
    $this->save();
}
</code>```

Now you need to call this in your controller:-

```<code>Data::withTrashed()->find($id)->restoreItem();
</code>```

That's it.

Title: how to restore soft delete with one more column?

Body:
To achieve this you can create function in your Data model which will do that for you.

public function restoreItem()
{
    $this->deleted_at = null;
    $this->other_field = null;
    $this->save();
}

Now you need to call this in your controller:-

Data::withTrashed()->find($id)->restoreItem();

That's it.


问:
TypeError: o.element is undefined - jquery ui
I'm using jquery-ui. I cannot solve this after 2 weeks.

I don't know why I got this error after clicking on sliders:

console Firefox:

```<code>TypeError: o.element is undefined[Learn More]  jquery-ui.min.js:6:6058
</code>```

console chrome:

```<code>jquery-ui.min.js:6 Uncaught TypeError: Cannot read property 'toggleClass' of undefined
    at t.(anonymous function).(anonymous function)._toggleClass (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:6067)
    at t.(anonymous function).(anonymous function)._addClass (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:5877)
    at t.(anonymous function).(anonymous function)._mouseCapture (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:14171)
    at t.(anonymous function).(anonymous function)._mouseCapture (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:1111)
    at t.(anonymous function).(anonymous function)._mouseDown (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:9414)
    at t.(anonymous function).(anonymous function)._mouseDown (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:1111)
    at HTMLDivElement.<anonymous> (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:8701)
    at HTMLDivElement.dispatch (http://localhost:8000/assets/frontend/_js/jquery-3.1.1.min.js:3:10315)
    at HTMLDivElement.q.handle (http://localhost:8000/assets/frontend/_js/jquery-3.1.1.min.js:3:8342)
</code>```

```<code><script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/jquery-3.1.1.min.js"></script>
<!-- http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js -->
<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/bootstrap.min.js"></script>
<!-- https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js -->
<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/jasny-bootstrap.min.js"></script>
<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/persian-datepicker.min.js"></script>
<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/script.js"></script>

<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://localhost:8000/assets/frontend/_js/jquery.ui.touch-punch.min.js"></script>
<script>

    $(document).ready(function(){

        $( "#slider" ).slider({
            range: true,
            min: -10000000,
            max: -1000,
            values: [ -8000000, -2000 ],
            slide: function(event, ui) {
                $(".amount .min-price").text(addCommas (ui.values[1]*-1) + " ریال ");
                $(".amount .max-price").text(addCommas (ui.values[0]*-1) + " ریال ");
            }
        });

        $(".amount .min-price").text(addCommas ($("#slider").slider( "values", 1 )*-1  ) + " ریال ");
        $(".amount .max-price").text(addCommas ($("#slider").slider( "values", 0 )*-1  ) + " ریال ");
        // Hover states on the static widgets
        $( "#dialog-link, #icons li" ).hover(
            function() {
                $( this ).addClass( "ui-state-hover" );
            },
            function() {
                $( this ).removeClass( "ui-state-hover" );
            }
        );

    });

</script>
</code>```

My HTML code:

```<code><div class="col-md-12">
    <div id="slider" class="ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content">
        <div class="ui-slider-range ui-corner-all ui-widget-header">

        </div>
        <span tabindex="1" class="ui-slider-handle ui-corner-all ui-state-default">

        </span>
        <span tabindex="2" class="ui-slider-handle ui-corner-all ui-state-default" >

        </span>
    </div>
</div>
</code>```

```<code>//used in slider
function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</code>```

My site address:

http://tahrircenter.com/products

I removed extra codes but I got the same error:

It works fine on jsfiddle !!!:

https://jsfiddle.net/Twisty/3gm3sfem/

.toggleClass() is a function of jQuery, so if you're getting an error
that it's undefined, then it's possible another version of jQuery may
be loaded elsewhere. Or it's not being loaded at all.

答:
I had this problem, and solved it.

I accidentally set the slider to a value which was undefined.
At that point, no error was produced.

But, when I later tried to move the slider, I got the error o.element is undefined.

When I set the slider to a good value, the problem disappeared.

Body:
I'm using jquery-ui. I cannot solve this after 2 weeks.

I don't know why I got this error after clicking on sliders:

console Firefox:

TypeError: o.element is undefined[Learn More]  jquery-ui.min.js:6:6058

console chrome:

jquery-ui.min.js:6 Uncaught TypeError: Cannot read property 'toggleClass' of undefined
    at t.(anonymous function).(anonymous function)._toggleClass (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:6067)
    at t.(anonymous function).(anonymous function)._addClass (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:5877)
    at t.(anonymous function).(anonymous function)._mouseCapture (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:14171)
    at t.(anonymous function).(anonymous function)._mouseCapture (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:1111)
    at t.(anonymous function).(anonymous function)._mouseDown (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:9414)
    at t.(anonymous function).(anonymous function)._mouseDown (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:1111)
    at HTMLDivElement.<anonymous> (http://localhost:8000/assets/frontend/_js/jquery-ui.min.js:6:8701)
    at HTMLDivElement.dispatch (http://localhost:8000/assets/frontend/_js/jquery-3.1.1.min.js:3:10315)
    at HTMLDivElement.q.handle (http://localhost:8000/assets/frontend/_js/jquery-3.1.1.min.js:3:8342)

My HTML code:

//used in slider
function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

My site address:

http://tahrircenter.com/products

I removed extra codes but I got the same error:

It works fine on jsfiddle !!!:

https://jsfiddle.net/Twisty/3gm3sfem/

.toggleClass() is a function of jQuery, so if you're getting an error
that it's undefined, then it's possible another version of jQuery may
be loaded elsewhere. Or it's not being loaded at all.


问:
Flutter Keyboard makes textfield hide
I'm new to flutter. I've added a form with a text field and when I clicked the textfield and keyboard comes, the textfield goes up.

This is my code :

```<code>Widget build(BuildContext context) {

MediaQueryData mediaQuery = MediaQuery.of(context);
return new Scaffold(
  body:  new Container(
      color: Colors.purple,
      constraints: new BoxConstraints.expand(),
      padding: EdgeInsets.only(top: 10.0,left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom, ),
      child: SingleChildScrollView(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(height: 12.0),
                  Text(
                    'What is your Business Name?',
                    style: TextStyle(fontSize: 24.0),
                  ),
                  AppForm(),
                ],
              ),
            padding: EdgeInsets.only(left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(30.0)),
              color: Colors.white,
                ),
              )
          )
      ),
    );
  }
</code>```

This is the result without opening the keyboard:
Image without keyboard

This is the image after opening the keyboard:
Image after opening the keyboard

Here is my flutter doctor output.

```<code>Doctor summary (to see all details, run flutter doctor -v): [√] Flutter
(Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.17134.165], locale
en-US) [√] Android toolchain - develop for Android devices (Android SDK
28.0.0) [√] Android Studio (version 3.1) [!] VS Code, 64-bit edition (version
1.25.1) [!] Connected devices ! No devices available ! Doctor found issues in
2 categories.
</code>```

any idea how to fix this?

Title: Flutter Keyboard makes textfield hide

Body:
I'm new to flutter. I've added a form with a text field and when I clicked the textfield and keyboard comes, the textfield goes up.

This is my code :

Widget build(BuildContext context) {

MediaQueryData mediaQuery = MediaQuery.of(context);
return new Scaffold(
  body:  new Container(
      color: Colors.purple,
      constraints: new BoxConstraints.expand(),
      padding: EdgeInsets.only(top: 10.0,left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom, ),
      child: SingleChildScrollView(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(height: 12.0),
                  Text(
                    'What is your Business Name?',
                    style: TextStyle(fontSize: 24.0),
                  ),
                  AppForm(),
                ],
              ),
            padding: EdgeInsets.only(left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(30.0)),
              color: Colors.white,
                ),
              )
          )
      ),
    );
  }

This is the result without opening the keyboard:
Image without keyboard

This is the image after opening the keyboard:
Image after opening the keyboard

Here is my flutter doctor output.

Doctor summary (to see all details, run flutter doctor -v): [√] Flutter
(Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.17134.165], locale
en-US) [√] Android toolchain - develop for Android devices (Android SDK
28.0.0) [√] Android Studio (version 3.1) [!] VS Code, 64-bit edition (version
1.25.1) [!] Connected devices ! No devices available ! Doctor found issues in
2 categories.

any idea how to fix this?

Body:
This answer is not specific the question above but may be useful to those who are still having issues with the keyboard covering the selected text field, no matter what they do. I got to this page while trying to resolve such an issue.

Prior to the problem I had been making some changes to try and improve my splash screen on app startup. As per someone's recommendation, I had included the following line in the <resources><style> section of the styles.xml file in the android/app/src/main/res/values folder

<item name="android:windowFullscreen">true</item>

This had the unexpected effect of stopping any fields scrolling up in the main app when the keyboard is displayed. This might be obvious to some, but it wasn't to me.

Hope this info helps someone.


问:
QT Unresolved External Symbol when using Layer Class
I am new to QT so please be kind. I keep having unresolved external symbol when I run the project. I do not know what else to do in here. I am mostly doing projects on c# so I'm only applying the object references or declarations as I know in C#. I have been searching for so long on finding a solution for but I had no luck.

It's occuring on the layer->AddLayer() in the main.cpp

..............................................................................................................................................................

Here's my Main.cpp:

```<code>#include <QCoreApplication>
#include <QFile>
#include <QXmlStreamReader>
#include <QDebug>
#include <iostream>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
#include "layer.h"

QFile* xmlFile;
QXmlStreamReader* xmlReader;
Layer *layer;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

xmlFile = new QFile("D://composition.svg");

if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text))
                qDebug() << ("Load XML File Problem");

xmlReader = new QXmlStreamReader(xmlFile);

//QList<Layer> layerList;

//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument)
                continue;
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement)
        {
            if(xmlReader->name() == "g")
            {
                foreach(const QXmlStreamAttribute &attr, xmlReader->attributes())
                {
                    layer->AddLayer();
                    int x = 0;
                    if (attr.name().toString() == QLatin1String("id")){
                        *layer->layerId = QString(attr.value().toString());
                        x++;
                    }
                }
            }
            if(xmlReader->name() == "polygon")
            {
                foreach(const QXmlStreamAttribute &attr, xmlReader->attributes())
                {
                    if (attr.name().toString() == QLatin1String("points"))
                    {
                        //Space
                        //QRegExp rx("( )");
                        QStringList query = attr.value().toString().split(QRegExp("( )"));
                        //QString* pointList =  new QString[query.length()];
                        for(int i =0; i<query.length(); i++) {
                            qDebug() << query[i].toLatin1();
                            QString x = "Hi";
                        }
                    }
                }
            }
        }
}

return a.exec();
</code>```

}

My layer.h

```<code>#ifndef LAYER_H
#define LAYER_H

#include <QCoreApplication>
#include <QFile>
#include <QXmlStreamReader>
#include <QDebug>
#include <iostream>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>

class Layer
{
public:
    Layer();
    QString *layerId;
    QList<Layer> *layerList;
    void *AddLayer();
};
class Polygon
{
public:
    Polygon();
    QString style;
    QPointF points[2];
    QString polygonColor;
    QList<Polygon> polygonList;
    void AddPolygon();
};
#endif // LAYER_H
</code>```

Layer.cpp:

```<code>    #include "layer.h"

Layer::Layer()
{

}
Polygon::Polygon()
{

}
void AddLayer()
{
    Layer* layer =  new Layer();
    //layer->layerList.append(*layer);
}

void AddPolygon()
{
    Polygon* polygon = new Polygon();
    polygon->polygonList.append(*polygon);
}
</code>```

XMLParse.pro:

```<code>    QT += core
QT -= gui

CONFIG += c++11

TARGET = XMLParse
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp \
    layer.cpp

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

HEADERS += \
    layer.h
</code>```

答:
You need to define AddLayer as a memberfunction from Layer . Add Layer::

```<code>   void Layer::AddLayer()
    {
        Layer* layer =  new Layer();
        //layer->layerList.append(*layer);
    }
</code>```

Body:
I am new to QT so please be kind. I keep having unresolved external symbol when I run the project. I do not know what else to do in here. I am mostly doing projects on c# so I'm only applying the object references or declarations as I know in C#. I have been searching for so long on finding a solution for but I had no luck.

It's occuring on the layer->AddLayer() in the main.cpp

..............................................................................................................................................................

Here's my Main.cpp:

#include <QCoreApplication>
#include <QFile>
#include <QXmlStreamReader>
#include <QDebug>
#include <iostream>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
#include "layer.h"

QFile* xmlFile;
QXmlStreamReader* xmlReader;
Layer *layer;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

xmlFile = new QFile("D://composition.svg");

if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text))
                qDebug() << ("Load XML File Problem");

xmlReader = new QXmlStreamReader(xmlFile);

//QList<Layer> layerList;

//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument)
                continue;
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement)
        {
            if(xmlReader->name() == "g")
            {
                foreach(const QXmlStreamAttribute &attr, xmlReader->attributes())
                {
                    layer->AddLayer();
                    int x = 0;
                    if (attr.name().toString() == QLatin1String("id")){
                        *layer->layerId = QString(attr.value().toString());
                        x++;
                    }
                }
            }
            if(xmlReader->name() == "polygon")
            {
                foreach(const QXmlStreamAttribute &attr, xmlReader->attributes())
                {
                    if (attr.name().toString() == QLatin1String("points"))
                    {
                        //Space
                        //QRegExp rx("( )");
                        QStringList query = attr.value().toString().split(QRegExp("( )"));
                        //QString* pointList =  new QString[query.length()];
                        for(int i =0; i<query.length(); i++) {
                            qDebug() << query[i].toLatin1();
                            QString x = "Hi";
                        }
                    }
                }
            }
        }
}

return a.exec();

}

My layer.h

#ifndef LAYER_H
#define LAYER_H

#include <QCoreApplication>
#include <QFile>
#include <QXmlStreamReader>
#include <QDebug>
#include <iostream>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>

class Layer
{
public:
    Layer();
    QString *layerId;
    QList<Layer> *layerList;
    void *AddLayer();
};
class Polygon
{
public:
    Polygon();
    QString style;
    QPointF points[2];
    QString polygonColor;
    QList<Polygon> polygonList;
    void AddPolygon();
};
#endif // LAYER_H

Layer.cpp:

    #include "layer.h"

Layer::Layer()
{

}
Polygon::Polygon()
{

}
void AddLayer()
{
    Layer* layer =  new Layer();
    //layer->layerList.append(*layer);
}

void AddPolygon()
{
    Polygon* polygon = new Polygon();
    polygon->polygonList.append(*polygon);
}

XMLParse.pro:

    QT += core
QT -= gui

CONFIG += c++11

TARGET = XMLParse
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp \
    layer.cpp

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

HEADERS += \
    layer.h

Body:
You need to define AddLayer as a memberfunction from Layer . Add Layer::

   void Layer::AddLayer()
    {
        Layer* layer =  new Layer();
        //layer->layerList.append(*layer);
    }


问:
How lambda function executes background timers?
When setTimeout is wrapped in Promise that code executed in aws lamda but normal setTimeout function not executed. How Nodejs event loop is handled inside aws lamda execution environment?</p>

```<code>exports.handler = async (event) => {
    setTimeout(function() {
           // This part not executed
    }, 1*1000);

    return new Promise((resolve)=>{
        setTimeout(function() {
            // This part executed
            resolve('works');
        }, 3*1000);
    });
}
</code>```

答:
The Timer starts fine, but the execution of the Lambda finish before it resolves - everything not packed in the returned Promise is ignored.

In the second case a Promise is returned and because the whole handler function is declared as async, which packs its result always into a Promise, the returned Promise result is flatted and returned correctly.

Body:
When setTimeout is wrapped in Promise that code executed in aws lamda but normal setTimeout function not executed. How Nodejs event loop is handled inside aws lamda execution environment?

exports.handler = async (event) => {
    setTimeout(function() {
           // This part not executed
    }, 1*1000);

    return new Promise((resolve)=>{
        setTimeout(function() {
            // This part executed
            resolve('works');
        }, 3*1000);
    });
}


问:
BrowserStack, WDIO, Cucumber, TypeScript
I'm trying to get up with my automation tests using Cucumber, typescript, webdriverio and browserstack.

It seems like there is no up to date setup guide for this kind of stack and I encountered some problem with the TS. When I set up all the configs and features for the tests I keep getting TS error Error:(7, 54) TS2339: Property 'element' does not exist on type 'BrowserObject'.

I believe there is some problem with the TS config or so.

Is anyone able to point me what's wrong?

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "./tsrc",
    "strict": true,
    "typeRoots": [ "./node_modules/@types" ],
    "types": [
      "node",
      "chai",
      "@wdio/sync",
      "webdriverio",
      "cucumber"
    ],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "exclude": [
    "node_modules",
    "./tests/tsrc"
  ],
  "compileOnSave": false
}
</code>```

wdio.conf.js

```<code>exports.config = {

  //
  // =================
  // Service Providers
  // =================
  // WebdriverIO supports Sauce Labs, Browserstack, and Testing Bot (other cloud providers
  // should work too though). These services define specific user and key (or access key)
  // values you need to put in here in order to connect to these services.
  //
  user: process.env.BROWSERSTACK_USER_NAME,
  key: process.env.BROWSERSTACK_KEY,

  //
  // ==================
  // Specify Test Files
  // ==================
  // Define which test specs should run. The pattern is relative to the directory
  // from which `wdio` was called. Notice that, if you are calling `wdio` from an
  // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
  // directory is where your package.json resides, so `wdio` will be called from there.
  //
  specs: [
    './tests/features/*.feature'
  ],
  // Patterns to exclude.
  exclude: [
    // 'path/to/excluded/files'
  ],
  //
  // ============
  // Capabilities
  // ============
  // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
  // time. Depending on the number of capabilities, WebdriverIO launches several test
  // sessions. Within your capabilities you can overwrite the spec and exclude options in
  // order to group specific specs to a specific capability.
  //
  // First, you can define how many instances should be started at the same time. Let's
  // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
  // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
  // files and you set maxInstances to 10, all spec files will get tested at the same time
  // and 30 processes will get spawned. The property handles how many capabilities
  // from the same test should run tests.
  //
  maxInstances: 1,
  //
  // If you have trouble getting all important capabilities together, check out the
  // Sauce Labs platform configurator - a great tool to configure your capabilities:
  // https://docs.saucelabs.com/reference/platforms-configurator
  //
  capabilities: [{
    // maxInstances can get overwritten per capability. So if you have an in-house Selenium
    // grid with only 5 firefox instances available you can make sure that not more than
    // 5 instances get started at a time.
    maxInstances: 1,
    //
    browserName: 'chrome'
  }],
  //
  // ===================
  // Test Configurations
  // ===================
  // Define all options that are relevant for the WebdriverIO instance here
  //
  // By default WebdriverIO commands are executed in a synchronous way using
  // the wdio-sync package. If you still want to run your tests in an async way
  // e.g. using promises you can set the sync option to false.
  sync: true,
  //
  // Level of logging verbosity: silent | verbose | command | data | result | error
  logLevel: 'verbose',
  //
  // Enables colors for log output.
  coloredLogs: true,
  //
  // Warns when a deprecated command is used
  deprecationWarnings: true,
  //
  // If you only want to run your tests until a specific amount of tests have failed use
  // bail (default is 0 - don't bail, run all tests).
  bail: 0,
  //
  // Saves a screenshot to a given path if a command fails.
  screenshotPath: './errorShots/',
  //
  // Set a base URL in order to shorten url command calls. If your `url` parameter starts
  // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
  // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
  // gets prepended directly.
  baseUrl: 'http://localhost:3000',
  //
  // Default timeout for all waitFor* commands.
  waitforTimeout: 10000,
  //
  // Default timeout in milliseconds for request
  // if Selenium Grid doesn't send response
  connectionRetryTimeout: 90000,
  //
  // Default request retries count
  connectionRetryCount: 3,
  //
  // Initialize the browser instance with a WebdriverIO plugin. The object should have the
  // plugin name as key and the desired plugin options as properties. Make sure you have
  // the plugin installed before running any tests. The following plugins are currently
  // available:
  // WebdriverCSS: https://github.com/webdriverio/webdrivercss
  // WebdriverRTC: https://github.com/webdriverio/webdriverrtc
  // Browserevent: https://github.com/webdriverio/browserevent
  // plugins: {
  //     webdrivercss: {
  //         screenshotRoot: 'my-shots',
  //         failedComparisonsRoot: 'diffs',
  //         misMatchTolerance: 0.05,
  //         screenWidth: [320,480,640,1024]
  //     },
  //     webdriverrtc: {},
  //     browserevent: {}
  // },
  //
  // Test runner services
  // Services take over a specific job you don't want to take care of. They enhance
  // your test setup with almost no effort. Unlike plugins, they don't add new
  // commands. Instead, they hook themselves up into the test process.
  services: ['browserstack'],
  //
  // Framework you want to run your specs with.
  // The following are supported: Mocha, Jasmine, and Cucumber
  // see also: http://webdriver.io/guide/testrunner/frameworks.html
  //
  // Make sure you have the wdio adapter package for the specific framework installed
  // before running any tests.
  framework: 'cucumber',
  //
  // Test reporter for stdout.
  // The only one supported by default is 'dot'
  // see also: http://webdriver.io/guide/reporters/dot.html
  reporters: ['spec', 'junit'],
  //
  // If you are using Cucumber you need to specify the location of your step definitions.
  cucumberOpts: {
    require: ['./tests/steps/*.ts'],        // <string[]> (file/dir) require files before executing features
    backtrace: false,   // <boolean> show full backtrace for errors
    compiler: ['ts:ts-node/register'],       // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
    dryRun: false,      // <boolean> invoke formatters without executing steps
    failFast: false,    // <boolean> abort the run on first failure
    format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
    colors: true,       // <boolean> disable colors in formatter output
    snippets: true,     // <boolean> hide step definition snippets for pending steps
    source: true,       // <boolean> hide source uris
    profile: [],        // <string[]> (name) specify the profile to use
    strict: false,      // <boolean> fail if there are any undefined or pending steps
    tags: [],           // <string[]> (expression) only execute the features or scenarios with tags matching the expression
    timeout: 20000,     // <number> timeout for step definitions
    ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
  },

  //
  // =====
  // Hooks
  // =====
  // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
  // it and to build services around it. You can either apply a single function or an array of
  // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
  // resolved to continue.
  /**
   * Gets executed once before all workers get launched.
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   */
  onPrepare: function (config, capabilities) {
    console.log('<<< BROWSER TESTS STARTED >>>');
  },
  /**
   * Gets executed just before initialising the webdriver session and test framework. It allows you
   * to manipulate configurations depending on the capability or spec.
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that are to be run
   */
  // beforeSession: function (config, capabilities, specs) {
  // },
  /**
   * Gets executed before test execution begins. At this point you can access to all global
   * variables like `browser`. It is the perfect place to define custom commands.
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that are to be run
   */
  before: function (capabilities, specs) {
    require('ts-node').register({ files: true });
  },
  /**
   * Runs before a WebdriverIO command gets executed.
   * @param {String} commandName hook command name
   * @param {Array} args arguments that command would receive
   */
  // beforeCommand: function (commandName, args) {
  // },

  /**
   * Runs before a Cucumber feature
   * @param {Object} feature feature details
   */
  // beforeFeature: function (feature) {
  // },
  /**
   * Runs before a Cucumber scenario
   * @param {Object} scenario scenario details
   */
  // beforeScenario: function (scenario) {
  // },
  /**
   * Runs before a Cucumber step
   * @param {Object} step step details
   */
  // beforeStep: function (step) {
  // },
  /**
   * Runs after a Cucumber step
   * @param {Object} stepResult step result
   */
  // afterStep: function (stepResult) {
  // },
  /**
   * Runs after a Cucumber scenario
   * @param {Object} scenario scenario details
   */
  // afterScenario: function (scenario) {
  // },
  /**
   * Runs after a Cucumber feature
   * @param {Object} feature feature details
   */
  // afterFeature: function (feature) {
  // },

  /**
   * Runs after a WebdriverIO command gets executed
   * @param {String} commandName hook command name
   * @param {Array} args arguments that command would receive
   * @param {Number} result 0 - command success, 1 - command error
   * @param {Object} error error object if any
   */
  // afterCommand: function (commandName, args, result, error) {
  // },
  /**
   * Gets executed after all tests are done. You still have access to all global variables from
   * the test.
   * @param {Number} result 0 - test pass, 1 - test fail
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that ran
   */
  // after: function (result, capabilities, specs) {
  // },
  /**
   * Gets executed right after terminating the webdriver session.
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that ran
   */
  // afterSession: function (config, capabilities, specs) {
  // },
  /**
   * Gets executed after all workers got shut down and the process is about to exit.
   * @param {Object} exitCode 0 - success, 1 - fail
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   */
  onComplete: function(exitCode, config, capabilities) {
    console.log('<<< BROWSER TESTING FINISHED >>>');
  }
};
</code>```

答: try adding 'wdio-cucumber-framework' to your types inside the tsconfig.json file</p>

Body:
I'm trying to get up with my automation tests using Cucumber, typescript, webdriverio and browserstack.

It seems like there is no up to date setup guide for this kind of stack and I encountered some problem with the TS. When I set up all the configs and features for the tests I keep getting TS error Error:(7, 54) TS2339: Property 'element' does not exist on type 'BrowserObject'.

I believe there is some problem with the TS config or so.

Is anyone able to point me what's wrong?

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "./tsrc",
    "strict": true,
    "typeRoots": [ "./node_modules/@types" ],
    "types": [
      "node",
      "chai",
      "@wdio/sync",
      "webdriverio",
      "cucumber"
    ],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "exclude": [
    "node_modules",
    "./tests/tsrc"
  ],
  "compileOnSave": false
}

wdio.conf.js

exports.config = {

  //
  // =================
  // Service Providers
  // =================
  // WebdriverIO supports Sauce Labs, Browserstack, and Testing Bot (other cloud providers
  // should work too though). These services define specific user and key (or access key)
  // values you need to put in here in order to connect to these services.
  //
  user: process.env.BROWSERSTACK_USER_NAME,
  key: process.env.BROWSERSTACK_KEY,

  //
  // ==================
  // Specify Test Files
  // ==================
  // Define which test specs should run. The pattern is relative to the directory
  // from which `wdio` was called. Notice that, if you are calling `wdio` from an
  // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
  // directory is where your package.json resides, so `wdio` will be called from there.
  //
  specs: [
    './tests/features/*.feature'
  ],
  // Patterns to exclude.
  exclude: [
    // 'path/to/excluded/files'
  ],
  //
  // ============
  // Capabilities
  // ============
  // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
  // time. Depending on the number of capabilities, WebdriverIO launches several test
  // sessions. Within your capabilities you can overwrite the spec and exclude options in
  // order to group specific specs to a specific capability.
  //
  // First, you can define how many instances should be started at the same time. Let's
  // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
  // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
  // files and you set maxInstances to 10, all spec files will get tested at the same time
  // and 30 processes will get spawned. The property handles how many capabilities
  // from the same test should run tests.
  //
  maxInstances: 1,
  //
  // If you have trouble getting all important capabilities together, check out the
  // Sauce Labs platform configurator - a great tool to configure your capabilities:
  // https://docs.saucelabs.com/reference/platforms-configurator
  //
  capabilities: [{
    // maxInstances can get overwritten per capability. So if you have an in-house Selenium
    // grid with only 5 firefox instances available you can make sure that not more than
    // 5 instances get started at a time.
    maxInstances: 1,
    //
    browserName: 'chrome'
  }],
  //
  // ===================
  // Test Configurations
  // ===================
  // Define all options that are relevant for the WebdriverIO instance here
  //
  // By default WebdriverIO commands are executed in a synchronous way using
  // the wdio-sync package. If you still want to run your tests in an async way
  // e.g. using promises you can set the sync option to false.
  sync: true,
  //
  // Level of logging verbosity: silent | verbose | command | data | result | error
  logLevel: 'verbose',
  //
  // Enables colors for log output.
  coloredLogs: true,
  //
  // Warns when a deprecated command is used
  deprecationWarnings: true,
  //
  // If you only want to run your tests until a specific amount of tests have failed use
  // bail (default is 0 - don't bail, run all tests).
  bail: 0,
  //
  // Saves a screenshot to a given path if a command fails.
  screenshotPath: './errorShots/',
  //
  // Set a base URL in order to shorten url command calls. If your `url` parameter starts
  // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
  // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
  // gets prepended directly.
  baseUrl: 'http://localhost:3000',
  //
  // Default timeout for all waitFor* commands.
  waitforTimeout: 10000,
  //
  // Default timeout in milliseconds for request
  // if Selenium Grid doesn't send response
  connectionRetryTimeout: 90000,
  //
  // Default request retries count
  connectionRetryCount: 3,
  //
  // Initialize the browser instance with a WebdriverIO plugin. The object should have the
  // plugin name as key and the desired plugin options as properties. Make sure you have
  // the plugin installed before running any tests. The following plugins are currently
  // available:
  // WebdriverCSS: https://github.com/webdriverio/webdrivercss
  // WebdriverRTC: https://github.com/webdriverio/webdriverrtc
  // Browserevent: https://github.com/webdriverio/browserevent
  // plugins: {
  //     webdrivercss: {
  //         screenshotRoot: 'my-shots',
  //         failedComparisonsRoot: 'diffs',
  //         misMatchTolerance: 0.05,
  //         screenWidth: [320,480,640,1024]
  //     },
  //     webdriverrtc: {},
  //     browserevent: {}
  // },
  //
  // Test runner services
  // Services take over a specific job you don't want to take care of. They enhance
  // your test setup with almost no effort. Unlike plugins, they don't add new
  // commands. Instead, they hook themselves up into the test process.
  services: ['browserstack'],
  //
  // Framework you want to run your specs with.
  // The following are supported: Mocha, Jasmine, and Cucumber
  // see also: http://webdriver.io/guide/testrunner/frameworks.html
  //
  // Make sure you have the wdio adapter package for the specific framework installed
  // before running any tests.
  framework: 'cucumber',
  //
  // Test reporter for stdout.
  // The only one supported by default is 'dot'
  // see also: http://webdriver.io/guide/reporters/dot.html
  reporters: ['spec', 'junit'],
  //
  // If you are using Cucumber you need to specify the location of your step definitions.
  cucumberOpts: {
    require: ['./tests/steps/*.ts'],        // <string[]> (file/dir) require files before executing features
    backtrace: false,   // <boolean> show full backtrace for errors
    compiler: ['ts:ts-node/register'],       // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
    dryRun: false,      // <boolean> invoke formatters without executing steps
    failFast: false,    // <boolean> abort the run on first failure
    format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
    colors: true,       // <boolean> disable colors in formatter output
    snippets: true,     // <boolean> hide step definition snippets for pending steps
    source: true,       // <boolean> hide source uris
    profile: [],        // <string[]> (name) specify the profile to use
    strict: false,      // <boolean> fail if there are any undefined or pending steps
    tags: [],           // <string[]> (expression) only execute the features or scenarios with tags matching the expression
    timeout: 20000,     // <number> timeout for step definitions
    ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
  },

  //
  // =====
  // Hooks
  // =====
  // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
  // it and to build services around it. You can either apply a single function or an array of
  // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
  // resolved to continue.
  /**
   * Gets executed once before all workers get launched.
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   */
  onPrepare: function (config, capabilities) {
    console.log('<<< BROWSER TESTS STARTED >>>');
  },
  /**
   * Gets executed just before initialising the webdriver session and test framework. It allows you
   * to manipulate configurations depending on the capability or spec.
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that are to be run
   */
  // beforeSession: function (config, capabilities, specs) {
  // },
  /**
   * Gets executed before test execution begins. At this point you can access to all global
   * variables like `browser`. It is the perfect place to define custom commands.
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that are to be run
   */
  before: function (capabilities, specs) {
    require('ts-node').register({ files: true });
  },
  /**
   * Runs before a WebdriverIO command gets executed.
   * @param {String} commandName hook command name
   * @param {Array} args arguments that command would receive
   */
  // beforeCommand: function (commandName, args) {
  // },

  /**
   * Runs before a Cucumber feature
   * @param {Object} feature feature details
   */
  // beforeFeature: function (feature) {
  // },
  /**
   * Runs before a Cucumber scenario
   * @param {Object} scenario scenario details
   */
  // beforeScenario: function (scenario) {
  // },
  /**
   * Runs before a Cucumber step
   * @param {Object} step step details
   */
  // beforeStep: function (step) {
  // },
  /**
   * Runs after a Cucumber step
   * @param {Object} stepResult step result
   */
  // afterStep: function (stepResult) {
  // },
  /**
   * Runs after a Cucumber scenario
   * @param {Object} scenario scenario details
   */
  // afterScenario: function (scenario) {
  // },
  /**
   * Runs after a Cucumber feature
   * @param {Object} feature feature details
   */
  // afterFeature: function (feature) {
  // },

  /**
   * Runs after a WebdriverIO command gets executed
   * @param {String} commandName hook command name
   * @param {Array} args arguments that command would receive
   * @param {Number} result 0 - command success, 1 - command error
   * @param {Object} error error object if any
   */
  // afterCommand: function (commandName, args, result, error) {
  // },
  /**
   * Gets executed after all tests are done. You still have access to all global variables from
   * the test.
   * @param {Number} result 0 - test pass, 1 - test fail
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that ran
   */
  // after: function (result, capabilities, specs) {
  // },
  /**
   * Gets executed right after terminating the webdriver session.
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that ran
   */
  // afterSession: function (config, capabilities, specs) {
  // },
  /**
   * Gets executed after all workers got shut down and the process is about to exit.
   * @param {Object} exitCode 0 - success, 1 - fail
   * @param {Object} config wdio configuration object
   * @param {Array.<Object>} capabilities list of capabilities details
   */
  onComplete: function(exitCode, config, capabilities) {
    console.log('<<< BROWSER TESTING FINISHED >>>');
  }
};


问:
Pandas groupby scatter plot in a single plot
This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that's not the case.

```<code>import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)
</code>```

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

```<code>df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df)
</code>```

It throws following error,

ValueError: Invalid RGBA argument: 'yes'

During handling of the above exception, another exception occurred:

答:
Incase we have a grouped data already, then I find the following solution could be useful.

```<code>df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(7,3))

def plot_grouped_df(grouped_df,
                    ax,  x='x', y='y', cmap = plt.cm.autumn_r):

    colors = cmap(np.linspace(0.5, 1, len(grouped_df)))

    for i, (name,group) in enumerate(grouped_df):
        group.plot(ax=ax,
                   kind='scatter',
                   x=x, y=y,
                   color=colors[i],
                   label = name)

# now we can use this function to plot the groupby data with categorical values
plot_grouped_df(df.groupby('label'),ax)
</code>```

Body:
This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that's not the case.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df)

It throws following error,

ValueError: Invalid RGBA argument: 'yes'

During handling of the above exception, another exception occurred:

Body:
Incase we have a grouped data already, then I find the following solution could be useful.

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(7,3))

def plot_grouped_df(grouped_df,
                    ax,  x='x', y='y', cmap = plt.cm.autumn_r):

    colors = cmap(np.linspace(0.5, 1, len(grouped_df)))

    for i, (name,group) in enumerate(grouped_df):
        group.plot(ax=ax,
                   kind='scatter',
                   x=x, y=y,
                   color=colors[i],
                   label = name)

# now we can use this function to plot the groupby data with categorical values
plot_grouped_df(df.groupby('label'),ax)


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答: What I don't understand is why your compiler doesn't complain.  You can't pass non-POD types like std::string or boost::filepath as varargs; my compiler says that this will abort at runtime, and any compiler will know here that you're passing class types to a vararg.  (Formally, it's undefined behavior, but unless the compiler defines it somehow as an extention, then there's no reason for it not to at least warn.)

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release