问:
How can i set permissions for every single user?
I need to set permission for example: if i have two users in my website and both of them have the right to write a post and they can delete or edit their posts. so, how can i set delete or edit button without make it are accessible by all users on the website just make it accessible by the user who's made the post

question_view.html

```<code>{% extends 'base.html' %}
{% block title %} This Question Belong To User: {{ request.user }} {% endblock %}

{% block body %}
    <!-- Full Question View -->
    <div class="my_question">
        <div class="container">
            <div class="answer-question">
                <div class="row">
                    <div class="col-md-6 col-xs-12">
                        <div class="title">
                            <h3 class="text-primary">{{ my_question.title }}</h3>
                            <span class="clock">1 hour ago</span>
                        </div>
                        <div class="question">
                            <p class="">{{ my_question.question }}</p>
                        </div>
                        <div class="field">
                            <span>{{ my_question.field }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Options e.g 'Edit, Comment, Delete etc...' -->
    <div class="options">
        <div class="container">
            <div class="col-sm-12">
                {% if user.is_authenticated %}
                    <a data-showin=".my-form" class="showin">Comment</a>  |
                    <a href="">Edit</a>
                    <span>
                        <a href="">Like</a>  |
                        <a href="">Unlike</a>
                    </span>
                {% endif %}
            </div>
            <hr>
            <!-- Comment Text -->
            <div class="user-answer">
                <div class="row">
                    <div class="col-xs-12">
                        {% for comment in comments %}
                            <p>{{ comment }}</p>
                            <p>1 hour ago</p>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <!-- Comment Field -->
            {% include 'community/comment_form.html' %}
        </div>
    </div>
{% endblock %}
</code>```

community.models

```<code>from django.db import models
from account.models import UserProfile
from django.contrib.auth.models import User
from django.utils import timezone
import django

CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'),
          ('Lawyer', 'Lawyer'), ('Trading', 'Trading'),
          ('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy')
]

class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')

    def __str__(self):
        return self.title

class Comment(models.Model):
    userasking = models.ForeignKey(UserAsking, on_delete=models.CASCADE)
    comment = models.TextField(max_length=500, blank=True, null=True)

    def __str__(self):
        return self.comment
</code>```

account.models

```<code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

CHOICE = [('male', 'male'), ('female', 'female')]

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
    city = models.CharField(max_length=20, blank=False)
    phone = models.IntegerField(default=0, blank=True)
    sex = models.CharField(max_length=10, default='male', choices=CHOICE)
    skill = models.CharField(max_length=100, default='You have no skills yet')
    logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)

    def __str__(self):
        return self.user.username

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(receiver=create_profile, sender=User)
</code>```

if you don't mind I need to explain that here... I have no idea about the files can i attach but i think if you understand what i need you can get me to help

Thanks a lot

community.views.py

```<code>from django.shortcuts import render, redirect
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from account.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

@login_required
def user_asking(request):
    form = UserAskingForm
    if request.method == 'POST':
        form = UserAskingForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            asking = form.save(commit=False)
            asking.title = form.cleaned_data['title']
            asking.question = form.cleaned_data['question']
            asking.field = form.cleaned_data['field']
            asking = UserAsking.objects.create(userprofile=request.user.userprofile,
                                               title=asking.title,
                                               question=asking.question,
                                               field=asking.field)
            asking.save()
            return redirect('community:user_questions')
    else:
        form = UserAskingForm()
        return render(request, 'community/asking_question.html', {'form': form})

    return render(request, 'community/asking_question.html', {'form': form})

@login_required
def user_questions(request):
    all_objects = UserAsking.objects.all().order_by('-title')
    if not all_objects:
        return HttpResponse('<h1>This page Have no any question yet</h1>')
    return render(request, 'community/user_questions.html', {'all_objects': all_objects})

def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin'
    comment_form = CommentForm
    comments = Comment.objects.filter(userasking__title=my_question.title)
    context = {'my_question': my_question, 'comment_form': comment_form,
               'comments': comments}
    # Add comment
    if request.method == 'POST':
        comment_form = comment_form(request.POST)
        if comment_form.is_valid():
            comment_form.instance.userasking_id = user_id
            comment_form.save()
            return redirect('community:question_view', user_id)

    return render(request, 'community/question_view.html', context)

@login_required
def delete_post(request, post_id=None):
    post_to_delete = UserAsking.objects.get(id=post_id)
    all_objects = UserAsking.objects.all()
    try:
        post_to_delete.delete()
        return redirect('community:user_asking')
    except:
        HttpResponse('something wrong')

    return render(request, 'community/user_questions.html', {'all_objects': all_objects})
</code>```

答:
In your view you should pass the object(e.g. post here) and the user who is requesting then in template code in for the edit link use an if statement to check if the author of the post is the user who is requesting:</p>

```<code>{{ if user == userasking.userprofile.user }}
    <a href="">Edit</a>
</code>```

Body:
I need to set permission for example: if i have two users in my website and both of them have the right to write a post and they can delete or edit their posts. so, how can i set delete or edit button without make it are accessible by all users on the website just make it accessible by the user who's made the post

question_view.html

{% extends 'base.html' %}
{% block title %} This Question Belong To User: {{ request.user }} {% endblock %}

{% block body %}

{{ my_question.title }}

                            1 hour ago

{{ my_question.question }}

                            {{ my_question.field }}

                {% if user.is_authenticated %}
                    Comment  |
                    Edit

                        Like  |
                        Unlike

                {% endif %}

                        {% for comment in comments %}

{{ comment }}

1 hour ago

                        {% endfor %}

            {% include 'community/comment_form.html' %}

{% endblock %}

community.models

from django.db import models
from account.models import UserProfile
from django.contrib.auth.models import User
from django.utils import timezone
import django

CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'),
          ('Lawyer', 'Lawyer'), ('Trading', 'Trading'),
          ('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy')
]

class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')

    def __str__(self):
        return self.title

class Comment(models.Model):
    userasking = models.ForeignKey(UserAsking, on_delete=models.CASCADE)
    comment = models.TextField(max_length=500, blank=True, null=True)

    def __str__(self):
        return self.comment

account.models

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

CHOICE = [('male', 'male'), ('female', 'female')]

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
    city = models.CharField(max_length=20, blank=False)
    phone = models.IntegerField(default=0, blank=True)
    sex = models.CharField(max_length=10, default='male', choices=CHOICE)
    skill = models.CharField(max_length=100, default='You have no skills yet')
    logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)

    def __str__(self):
        return self.user.username

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(receiver=create_profile, sender=User)

if you don't mind I need to explain that here... I have no idea about the files can i attach but i think if you understand what i need you can get me to help

Thanks a lot

community.views.py

from django.shortcuts import render, redirect
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from account.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

@login_required
def user_asking(request):
    form = UserAskingForm
    if request.method == 'POST':
        form = UserAskingForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            asking = form.save(commit=False)
            asking.title = form.cleaned_data['title']
            asking.question = form.cleaned_data['question']
            asking.field = form.cleaned_data['field']
            asking = UserAsking.objects.create(userprofile=request.user.userprofile,
                                               title=asking.title,
                                               question=asking.question,
                                               field=asking.field)
            asking.save()
            return redirect('community:user_questions')
    else:
        form = UserAskingForm()
        return render(request, 'community/asking_question.html', {'form': form})

    return render(request, 'community/asking_question.html', {'form': form})

@login_required
def user_questions(request):
    all_objects = UserAsking.objects.all().order_by('-title')
    if not all_objects:
        return HttpResponse('
This page Have no any question yet
')
    return render(request, 'community/user_questions.html', {'all_objects': all_objects})

def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin'
    comment_form = CommentForm
    comments = Comment.objects.filter(userasking__title=my_question.title)
    context = {'my_question': my_question, 'comment_form': comment_form,
               'comments': comments}
    # Add comment
    if request.method == 'POST':
        comment_form = comment_form(request.POST)
        if comment_form.is_valid():
            comment_form.instance.userasking_id = user_id
            comment_form.save()
            return redirect('community:question_view', user_id)

    return render(request, 'community/question_view.html', context)

@login_required
def delete_post(request, post_id=None):
    post_to_delete = UserAsking.objects.get(id=post_id)
    all_objects = UserAsking.objects.all()
    try:
        post_to_delete.delete()
        return redirect('community:user_asking')
    except:
        HttpResponse('something wrong')

    return render(request, 'community/user_questions.html', {'all_objects': all_objects})

Body:
In your view you should pass the object(e.g. post here) and the user who is requesting then in template code in for the edit link use an if statement to check if the author of the post is the user who is requesting:

{{ if user == userasking.userprofile.user }}
    <a href="">Edit</a>


来源: stackexchange

问:
Terminal in Intellij IDEA does not have JAVA_HOME and java command
I have my command prompt (cmd) and it does show everything even if I go to the same path i'm in Intellij, but in Intellij java command and JAVA_HOME environment variable isn't set.

I have set environment variables in system as well as in user settings (Win 10)

Here is output of terminal from intellij:

```<code>D:\IdeaProjects\(Project)>java -version
'java' is not recognized as an internal or external command,
operable program or batch file.

D:\IdeaProjects\AirbentPluginIF>gradlew dokka

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
</code>```

While output of cmd:

```<code>D:\IdeaProjects\AirbentPluginIF>java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

D:\IdeaProjects\AirbentPluginIF>gradlew dokka
Starting a Gradle Daemon, 1 stopped Daemon could not be reused, use --status for details

> Task :dokka
... (more stuffs)

</code>```

What could be the reason for this?

答:
In Environment Variables under Preferences/Tools/Terminal, try setting the value as:

JAVA_HOME=path to your java home

ContentLicense: CC BY-SA 4.0

Body:
I have my command prompt (cmd) and it does show everything even if I go to the same path i'm in Intellij, but in Intellij java command and JAVA_HOME environment variable isn't set.

I have set environment variables in system as well as in user settings (Win 10)

Here is output of terminal from intellij:

D:\IdeaProjects\(Project)>java -version
'java' is not recognized as an internal or external command,
operable program or batch file.

D:\IdeaProjects\AirbentPluginIF>gradlew dokka

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

While output of cmd:

D:\IdeaProjects\AirbentPluginIF>java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

D:\IdeaProjects\AirbentPluginIF>gradlew dokka
Starting a Gradle Daemon, 1 stopped Daemon could not be reused, use --status for details

> Task :dokka
... (more stuffs)

What could be the reason for this?


问:
How to update output with continuous user inputs until terminated with "."?
New to Java and trying to figure out how to keep a running evaluated expression given by a user continuously until they type in "." to terminate it and then print the output. I need to use methods outside of the main that I have already placed.I don't have to worry about order of operation but I'm confused on how to take on a continuous amount of operations/numbers while keeping track of their outputs and then how to finally print the result when they put ".".

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

public class Evaluator {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int num1;
        char expression;
        int num2;
        String numlist = "";

        System.out.println("Enter the expression: ");
        num1 = scan.nextInt();
        expression = scan.next().charAt(0);
        num2 = scan.nextInt();
        scan.close();

        if (expression == '+') {
            add(num1, num2);
        } else if (expression == '-') {
            subtract(num1, num2);
        } else if (expression == '*') {
            multiply(num1, num2);
        } else if (expression == '/') {
            divide(num1, num2);
        } else if (expression == '%') {
            modulus(num1, num2);
        } else if (expression == '.'){

        }
    }

    static int add(int num1, int num2) {
        return (num1 + num2);
    }

    static int subtract(int num1, int num2) {
        return (num1 - num2);
    }

    static int divide(int num1, int num2) {
        return (num1/num2);
    }

    static int multiply(int num1, int num2) {
        return (num1*num2);
    }

    static int modulus(int num1, int num2) {
        return (num1%num2);
    }
}
</code>```

OUTPUT:

Enter the expression:

```<code>1
+
26
*
2
%
19
/
5
.
</code>```

The result is 3

答:
Something like:

```<code>while(expression!='.'){
 if (expression == '+') {
        add(num1, num2);
    } else if (expression == '-') {
        subtract(num1, num2);
    } else if (expression == '*') {
        multiply(num1, num2);
    }else if (expression == '/') {
        divide(num1, num2);
    } else if (expression == '%') {
        modulus(num1, num2);
    }
}
</code>```

Is this what you're asking ?

Body:
New to Java and trying to figure out how to keep a running evaluated expression given by a user continuously until they type in "." to terminate it and then print the output. I need to use methods outside of the main that I have already placed.I don't have to worry about order of operation but I'm confused on how to take on a continuous amount of operations/numbers while keeping track of their outputs and then how to finally print the result when they put ".".

import java.util.Scanner;

public class Evaluator {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int num1;
        char expression;
        int num2;
        String numlist = "";

        System.out.println("Enter the expression: ");
        num1 = scan.nextInt();
        expression = scan.next().charAt(0);
        num2 = scan.nextInt();
        scan.close();

        if (expression == '+') {
            add(num1, num2);
        } else if (expression == '-') {
            subtract(num1, num2);
        } else if (expression == '*') {
            multiply(num1, num2);
        } else if (expression == '/') {
            divide(num1, num2);
        } else if (expression == '%') {
            modulus(num1, num2);
        } else if (expression == '.'){

        }
    }

    static int add(int num1, int num2) {
        return (num1 + num2);
    }

    static int subtract(int num1, int num2) {
        return (num1 - num2);
    }

    static int divide(int num1, int num2) {
        return (num1/num2);
    }

    static int multiply(int num1, int num2) {
        return (num1*num2);
    }

    static int modulus(int num1, int num2) {
        return (num1%num2);
    }
}

OUTPUT:

Enter the expression:

1
+
26
*
2
%
19
/
5
.

The result is 3

Body:
Something like:

while(expression!='.'){
 if (expression == '+') {
        add(num1, num2);
    } else if (expression == '-') {
        subtract(num1, num2);
    } else if (expression == '*') {
        multiply(num1, num2);
    }else if (expression == '/') {
        divide(num1, num2);
    } else if (expression == '%') {
        modulus(num1, num2);
    }
}

Is this what you're asking ?


问:
Parsing from json call to map in flutter
Hi the following dart code in flutter, make a rest call to a node.js server returning a map of values in a map. When I run the code, however, the exception below is raised. How can I go about solving this?
Below is an example of json values returning from the rest server in node.js.

Dart Code:

```<code>  static Future<Map> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }
</code>```

Exception:

```<code>[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
#0      CantiereController.Ricerca (package:MyApp/Controller/Cantiere.dart:28:5)
<asynchronous suspension>
#1      Cantiere.ricerca (package:MyApp/Model/Cantiere.dart:18:142)
#2      inizializzaValori (package:MyApp/View/Cantieri/training_screen.dart:25:38)
<asynchronous suspension>
#3      _TrainingScreenState.initState (package:MyApp/View/Cantieri/training_screen.dart:47:5)
#4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#7      MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5551:32)
#8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#9      Element.updateChild (package:flutter/src/widgets/framework.dart:2988<…>MyApp
</code>```

ApiRest.dart Code:

```<code>Future<String> apiRequest(String urlpassed, Map jsonMap) async {
  //Give server and port
  String server = await Storage.leggi("Server");
  String porta = await Storage.leggi("Porta");

  var url=""+server+":"+porta;

  url=url+urlpassed;
  HttpClient httpClient = new HttpClient();

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();

  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}
</code>```

JSON Example:

```<code>[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "dsdso",
        "NomeCantiere": "sala sdsd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "sddsdsd"
    },
    {
        "IdCantiere": 5,
        "IdCliente": 204,
        "Filiale": "SEDE",
        "RagioneSociale": "sdsds",
        "NomeCantiere": "manutenzione allarme",
        "DataCreazioneCantiere": "2017-08-04T18:27:42.017Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "manutenzione impianto allarme AVS"
    },
    {
        "IdCantiere": 6,
        "IdCliente": 140,
        "Filiale": "SEDE",
        "RagioneSociale": "Psdsddo",
        "NomeCantiere": "Ristrutturazione terremoto",
        "DataCreazioneCantiere": "2017-08-07T17:45:15.347Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "        stampato 10/01/19"
    }
]
</code>```

答:
Your JSON is returning a List not a Map.  Keep it a List:

```<code>List<dynamic> ret = json.decode(value);
</code>```

Then you can change the list type:

```<code>List<Map<String, dynamic>> data = ret.map((value) => value as Map<String, dynamic>).toList();
</code>```

Body:
Hi the following dart code in flutter, make a rest call to a node.js server returning a map of values in a map. When I run the code, however, the exception below is raised. How can I go about solving this?
Below is an example of json values returning from the rest server in node.js.

Dart Code:

  static Future<Map> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }

Exception:

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
#0      CantiereController.Ricerca (package:MyApp/Controller/Cantiere.dart:28:5)
<asynchronous suspension>
#1      Cantiere.ricerca (package:MyApp/Model/Cantiere.dart:18:142)
#2      inizializzaValori (package:MyApp/View/Cantieri/training_screen.dart:25:38)
<asynchronous suspension>
#3      _TrainingScreenState.initState (package:MyApp/View/Cantieri/training_screen.dart:47:5)
#4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#7      MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5551:32)
#8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#9      Element.updateChild (package:flutter/src/widgets/framework.dart:2988<…>MyApp

ApiRest.dart Code:

Future<String> apiRequest(String urlpassed, Map jsonMap) async {
  //Give server and port
  String server = await Storage.leggi("Server");
  String porta = await Storage.leggi("Porta");

  var url=""+server+":"+porta;

  url=url+urlpassed;
  HttpClient httpClient = new HttpClient();

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();

  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

JSON Example:

[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "dsdso",
        "NomeCantiere": "sala sdsd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "sddsdsd"
    },
    {
        "IdCantiere": 5,
        "IdCliente": 204,
        "Filiale": "SEDE",
        "RagioneSociale": "sdsds",
        "NomeCantiere": "manutenzione allarme",
        "DataCreazioneCantiere": "2017-08-04T18:27:42.017Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "manutenzione impianto allarme AVS"
    },
    {
        "IdCantiere": 6,
        "IdCliente": 140,
        "Filiale": "SEDE",
        "RagioneSociale": "Psdsddo",
        "NomeCantiere": "Ristrutturazione terremoto",
        "DataCreazioneCantiere": "2017-08-07T17:45:15.347Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "        stampato 10/01/19"
    }
]

Body:
Your JSON is returning a List not a Map.  Keep it a List:

List<dynamic> ret = json.decode(value);

Then you can change the list type:

List<Map<String, dynamic>> data = ret.map((value) => value as Map<String, dynamic>).toList();


问:
Add a query to Retrofit only if value exist
I'm trying to make an endpoint which can call to:

```<code>...retailer/home
</code>```

or

```<code>...retailer/home?uid=123123123
</code>```

I use the next source code to generate de call:

```<code>@GET("retailer/home")
fun retrieveHomeContent(@Query("uid") uid: String? = null): Single<HomeContentEntity>
</code>```

But when I test this, the result is:

```<code>retailer/home?uid=
</code>```

So, I don't know how to makes retrofit to ignores the Query when the value is null. Any advice?

答: I would use @QueryMap instead of @Query and pass it empty if you don't want to have any query key/parameters

Body:
I'm trying to make an endpoint which can call to:

...retailer/home

or

...retailer/home?uid=123123123

I use the next source code to generate de call:

@GET("retailer/home")
fun retrieveHomeContent(@Query("uid") uid: String? = null): Single<HomeContentEntity>

But when I test this, the result is:

retailer/home?uid=

So, I don't know how to makes retrofit to ignores the Query when the value is null. Any advice?


问:
Get the Sum of Lowest Values In 3 Columns Each added dynamically
i am having a trouble having the sum of 3 lowest values entered in columns added dynamically. it shows no value in the Total Cost Field, although if i changed the type from number to text of Total Cost Field. It gives NaN into it. I have tried a lot but did not get on the final step. Please look into, i really can use some help in this regard

//JS To Add Rows Dynamically
$(document).ready(function() {
  var i = 1;
  $("#Add_BDSP").click(function() {
    $('#BDSP' + i).html("<select class='form-control show-tick form-group form-float' name='RequiredServices[" + i + "]' id='Services'><optgroup label=' financial services'><option id='AccountingSoftware' value='ERP Systems'>ERP Systems</option> <option id='AccountingSystems' value='Accounting Book Keeping Systems'>Accounting / Book Keeping Systems</option><option id='ProductCosting' value='Product Costing'>Product Costing</option><option id='FinancialManagement' value='Financial Management Systems'>Financial Management Systems</option></optgroup><optgroup label='HR Services'><option id='HRPolicies' value='HR Policies and Procedures'>HR Policies and Procedures</option><option id='HR_System' value='HR_System'>HR Systems</option><option id='Appraisal' value='Appraisal'>Employee Internal Trainings Manuals</option><option id='SalesManagement' value='SalesManagement'>sEmployee Orientation Manuals.</option> </optgroup><optgroup label='General Management'><option id='Project' value='ProjectManagement'>Project Management System</option><option id='Inventory' value='Inventory Management Systems'>Inventory Management Systems</option><option id='Warehouse' value='Warehouse'>Procurement System</option><option id='SupplyChain' value='SupplyChain'>Supply Chain Systems</option><option id='FleetManagement' value='Fleet Management Systems'>Fleet Management Systems</option></optgroup><optgroup label='Regulatory Services'><option id='Sales_Income_Tax' value='Sales_Income_Tax'>sales / Income Tax Services</option><option id='TradeMark' value='TradeMark'>Intellectual Property Rights</option><option id='BusinessRegistration' value='BusinessRegistration'>Business Registration Services</option><option id='B2B' value='B2B'>B2B, B2C Contracting Services</option><option id='BusinessLicensing' value='BusinessLicensing'>Business Licensing Services</option></optgroup><optgroup label='Production Management'><option id='ProductionPlanning' value='ProductionPlanning'>Production Planning & Control Systems</option><option id='ProductionManagement' value='ProductionManagement'>Warehouse Management Information Systems (WMIS)</option> </optgroup></select>

<input type='text' name='Description[" + i + "]' >

	<input type='text' name='BDSPName1[" + i + "]' placeholder='BDSP Name'class='form-control' required /><input type='text' name='BDSPName2[" + i + "]' placeholder='BDSP Name'class='form-control'  /><input type='text' name='BDSPName3[" + i + "]' placeholder='BDSP Name'class='form-control'  />	 <input type='text' name='BDSP_NTN1[" + i + "]'placeholder='BDSP NTN Number' class='form-control'/><input type='text' name='BDSP_NTN2[" + i + "]'placeholder='BDSP NTN Number' class='form-control' /><input type='text' name='BDSP_NTN3[" + i + "]'placeholder='BDSP NTN Number' class='form-control' />	<input type='text' name='QuotedAmount1[" + i + "]' placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount2[" + i + "]'placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount3[" + i + "]' placeholder='Quoted Amount' class='form-control'/> 	<select class='form-group form-control' name='ExpectedDeliveryTime1[" + i + "]' id='ExpectedDeliveryTime1[0]'><option selected disabled>Select Days</option><option value='30' class='form-control input-md'>30</option><option value='60' class='form-control input-md'>60</option><option value='90' class='form-control input-md'>90</option><option value='120' class='form-control input-md'>120</option><option value='150' class='form-control input-md'>150</option><option value='180' class='form-control input-md'>180</option><option value='more180' class='form-control input-md'>More Than 180</option></select><select class='form-group form-control' name='ExpectedDeliveryTime2[" + i + "]' id='ExpectedDeliveryTime2[0]'><option selected disabled>Select Days</option><option value='30' class='form-control input-md'>30</option><option value='60' class='form-control input-md'>60</option><option value='90' class='form-control input-md'>90</option><option value='120' class='form-control input-md'>120</option><option value='150' class='form-control input-md'>150</option><option value='180' class='form-control input-md'>180</option><option value='more180' class='form-control input-md'>More Than 180</option></select><select class='form-group form-control' name='ExpectedDeliveryTime3[" + i + "]' id='ExpectedDeliveryTime3[0]'><option selected disabled>Select Days</option><option value='30' class='form-control input-md'>30</option><option value='60' class='form-control input-md'>60</option><option value='90' class='form-control input-md'>90</option><option value='120' class='form-control input-md'>120</option><option value='150' class='form-control input-md'>150</option><option value='180' class='form-control input-md'>180</option><option value='more180' class='form-control input-md'>More Than 180</option></select>	<input type='file' name='Quotation1[" + i + "]' class='form-control' /><input type='file' name='Quotation2[" + i + "]' class='form-control' /><input type='file' name='Quotation3[" + i + "]' class='form-control' />	");

    $('#Tab_BDSP').append('

');
    i++;
  });
  $("#Delete_BDSP").click(function() {
    if (i > 1) {
      $("#BDSP" + (i - 1)).html('');
      i--;
    }
  });

});

//JS To Add Lowest Value

$(document).on('change', '#Tab_BDSP tbody tr td input[type="text"]', function() {
  let result = 0;
  var MulRes = $('input#ServiceTotalCost');

  var QuotedAmount1 = $(this).parent().find('input[type="text"]').eq(0),
    QuotedAmount2 = $(this).parent().find('input[type="text"]').eq(1),
    QuotedAmount3 = $(this).parent().find('input[type="text"]').eq(2);

  var Qoute1 = (isNaN(parseInt(QuotedAmount1.val()))) ? 0 : parseInt(QuotedAmount1.val()),
    Qoute2 = (isNaN(parseInt(QuotedAmount2.val()))) ? 0 : parseInt(QuotedAmount2.val()),
    Qoute3 = (isNaN(parseInt(QuotedAmount3.val()))) ? 0 : parseInt(QuotedAmount3.val());

  var min = Math.min(Qoute1, Qoute2, Qoute3);
  $(this).parent().attr('data-lowest', min)

  $('#Tab_BDSP tbody tr td').each(function() {
    result += +$(this).attr('data-lowest')
  });

  MulRes.val(result)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
  <p>
    <b>Please Provide At Least 3 BDSPs Quotations Against Each Service</b> <span style="color: red">*</span>
  </p>
  <div class="form-group form-float">
    <table class="table table-bordered table-hover" id="Tab_BDSP">
      <thead>
        <tr>
          <td>Services Required</td>
          <td>Description</td>
          <td>BDSP Name</td>
          <td>NTN No.</td>
          <td>Amount</td>
          <td>Expected Delivery Time</td>
          <td>Attach Quotation</td>
        </tr>
      </thead>
      <tbody>
        <tr id='BDSP0'>
          <td>
            <select class="form-control show-tick form-group form-float" name="RequiredServices[0]" id="Services" required>
              <optgroup label="Financial Services">
                <option id="AccountingSoftware" value="ERP Systems">ERP Systems</option>
                <option id="AccountingSystems" value="Accounting Book Keeping Systems">Accounting / Book Keeping Systems</option>
                <option id="ProductCosting" value="Product Costing">Product Costing</option>
                <option id="FinancialManagement" value="Financial Management Systems">Financial Management Systems</option>

              </optgroup>

              <optgroup label="HR Services">
                <option id="HRPolicies" value="HR Policies and Procedures">HR Policies and Procedures</option>
                <option id="HR_System" value="HR_System">HR Systems</option>
                <option id="Appraisal" value="Appraisal">Employee Internal Trainings Manuals</option>
                <option id="SalesManagement" value="SalesManagement">sEmployee Orientation Manuals.</option>

              </optgroup>

              <optgroup label="General Management">
                <option id="Project" value="ProjectManagement">Project Management System</option>
                <option id="Inventory" value="Inventory Management Systems">Inventory Management Systems</option>
                <option id="Warehouse" value="Warehouse">Procurement System</option>
                <option id="SupplyChain" value="SupplyChain">Supply Chain Systems</option>
                <option id="FleetManagement" value="Fleet Management Systems">Fleet Management Systems</option>

              </optgroup>

              <optgroup label="Regulatory Services">
                <option id="Sales_Income_Tax" value="Sales_Income_Tax">sales / Income Tax Services</option>
                <option id="TradeMark" value="TradeMark">Intellectual Property Rights</option>
                <option id="BusinessRegistration" value="BusinessRegistration">Business Registration Services</option>
                <option id="B2B" value="B2B">B2B, B2C Contracting Services</option>
                <option id="BusinessLicensing" value="BusinessLicensing">Business Licensing Services</option>

              </optgroup>

              <optgroup label="Production Management">
                <option id="ProductionPlanning" value="ProductionPlanning">Production Planning & Control Systems</option>
                <option id="ProductionManagement" value="ProductionManagement">Warehouse Management Information Systems (WMIS)</option>

              </optgroup>
              <optgroup label="Other Services">
                <option id="Other" value="OtherServices">Mention Other Services</option>

              </optgroup>

            </select>
          </td>
          <td>
            <div class="input-group form-group">

              <div class="form-line">
                <input type="text" class="form-control" name="Description[0]" id="Description" required>
              </div>
            </div>

          </td>
          <td>
            <input type="text" name='BDSPName1[0]' placeholder='BDSP Name' class="form-control" required />
            <input type="text" name='BDSPName2[0]' placeholder='BDSP Name' class="form-control" required />
            <input type="text" name='BDSPName3[0]' placeholder='BDSP Name' class="form-control" required />
          </td>

          <td>
            <input type="text" name='BDSP_NTN1[0]' placeholder='BDSP NTN Number' class="form-control" required />
            <input type="text" name='BDSP_NTN2[0]' placeholder='BDSP NTN Number' class="form-control" required />
            <input type="text" name='BDSP_NTN3[0]' placeholder='BDSP NTN Number' class="form-control" required />
          </td>

          <td>
            <input type="text" name='QuotedAmount1[0]' placeholder='Quoted Amount' class="form-control" required />
            <input type="text" name='QuotedAmount2[0]' placeholder='Quoted Amount' class="form-control" required />
            <input type="text" name='QuotedAmount3[0]' placeholder='Quoted Amount' class="form-control" required />
          </td>
          <td>
            <select class="form-group form-control" name="ExpectedDeliveryTime1[0]" id="ExpectedDeliveryTime1[0]" required>
              <option selected disabled>Select Days</option>
              <option value="AJK" class='form-control input-md'>30</option>
              <option value="Balochistan" class='form-control input-md'>60</option>
              <option value="GB" class='form-control input-md'>90</option>
              <option value="ICT" class='form-control input-md'>120</option>
              <option value="KPK" class='form-control input-md'>150</option>
              <option value="Punjab" class='form-control input-md'>180</option>
              <option value="Sindh" class='form-control input-md'>More Than 180</option>
            </select>
            <select class="form-group form-control" name="ExpectedDeliveryTime2[0]" id="ExpectedDeliveryTime2[0]" required>
              <option selected disabled>Select Days</option>
              <option value="AJK" class='form-control input-md'>30</option>
              <option value="Balochistan" class='form-control input-md'>60</option>
              <option value="GB" class='form-control input-md'>90</option>
              <option value="ICT" class='form-control input-md'>120</option>
              <option value="KPK" class='form-control input-md'>150</option>
              <option value="Punjab" class='form-control input-md'>180</option>
              <option value="Sindh" class='form-control input-md'>More Than 180</option>
            </select>
            <select class="form-group form-control" name="ExpectedDeliveryTime3[0]" id="ExpectedDeliveryTime3[0]" required>
              <option selected disabled>Select Days</option>
              <option value="AJK" class='form-control input-md'>30</option>
              <option value="Balochistan" class='form-control input-md'>60</option>
              <option value="GB" class='form-control input-md'>90</option>
              <option value="ICT" class='form-control input-md'>120</option>
              <option value="KPK" class='form-control input-md'>150</option>
              <option value="Punjab" class='form-control input-md'>180</option>
              <option value="Sindh" class='form-control input-md'>More Than 180</option>
            </select>
          </td>
          <td>
            <input type="file" name="Quotation1[0]" class="form-control" required />
            <input type="file" name="Quotation2[0]" class="form-control" required />
            <input type="file" name="Quotation3[0]" class="form-control" required />
          </td>
        </tr>

        <tr id='BDSP1'></tr>
      </tbody>
    </table>
  </div>
  Add RowDelete Row
</div>
<div class="col-md-4">
  <p>
    <b>Total Cost Of The Service</b> <span style="color: red">*</span>
  </p>
  <div class="input-group form-group">
    <span class="input-group-addon">
 <i class="material-icons">business_center</i></span>
    <div class="form-line">
      <input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>
    </div>
  </div>
</div></code>```

答:
I would recommend you to give clear explanation of the code but i have tried to understand your code and tried to debug your code.

You are getting NaN, because some of the values inside forEach are undefined. And when you add undefined to a number, it results in NaN.

Please use below logic and replace in your code.

$('#Tab_BDSP tbody tr td').each(function() {
  result += $(this).attr('data-lowest') ? +$(this).attr('data-lowest') : 0;
});```

Body:
i am having a trouble having the sum of 3 lowest values entered in columns added dynamically. it shows no value in the Total Cost Field, although if i changed the type from number to text of Total Cost Field. It gives NaN into it. I have tried a lot but did not get on the final step. Please look into, i really can use some help in this regard

//JS To Add Rows Dynamically
$(document).ready(function() {
  var i = 1;
  $("#Add_BDSP").click(function() {
    $('#BDSP' + i).html("<select class='form-control show-tick form-group form-float' name='RequiredServices[" + i + "]' id='Services'><optgroup label=' financial services'><option id='AccountingSoftware' value='ERP Systems'>ERP Systems</option> <option id='AccountingSystems' value='Accounting Book Keeping Systems'>Accounting / Book Keeping Systems</option><option id='ProductCosting' value='Product Costing'>Product Costing</option><option id='FinancialManagement' value='Financial Management Systems'>Financial Management Systems</option></optgroup><optgroup label='HR Services'><option id='HRPolicies' value='HR Policies and Procedures'>HR Policies and Procedures</option><option id='HR_System' value='HR_System'>HR Systems</option><option id='Appraisal' value='Appraisal'>Employee Internal Trainings Manuals</option><option id='SalesManagement' value='SalesManagement'>sEmployee Orientation Manuals.</option> </optgroup><optgroup label='General Management'><option id='Project' value='ProjectManagement'>Project Management System</option><option id='Inventory' value='Inventory Management Systems'>Inventory Management Systems</option><option id='Warehouse' value='Warehouse'>Procurement System</option><option id='SupplyChain' value='SupplyChain'>Supply Chain Systems</option><option id='FleetManagement' value='Fleet Management Systems'>Fleet Management Systems</option></optgroup><optgroup label='Regulatory Services'><option id='Sales_Income_Tax' value='Sales_Income_Tax'>sales / Income Tax Services</option><option id='TradeMark' value='TradeMark'>Intellectual Property Rights</option><option id='BusinessRegistration' value='BusinessRegistration'>Business Registration Services</option><option id='B2B' value='B2B'>B2B, B2C Contracting Services</option><option id='BusinessLicensing' value='BusinessLicensing'>Business Licensing Services</option></optgroup><optgroup label='Production Management'><option id='ProductionPlanning' value='ProductionPlanning'>Production Planning & Control Systems</option><option id='ProductionManagement' value='ProductionManagement'>Warehouse Management Information Systems (WMIS)</option> </optgroup></select>

<input type='text' name='Description[" + i + "]' >

	<input type='text' name='BDSPName1[" + i + "]' placeholder='BDSP Name'class='form-control' required /><input type='text' name='BDSPName2[" + i + "]' placeholder='BDSP Name'class='form-control'  /><input type='text' name='BDSPName3[" + i + "]' placeholder='BDSP Name'class='form-control'  />	 <input type='text' name='BDSP_NTN1[" + i + "]'placeholder='BDSP NTN Number' class='form-control'/><input type='text' name='BDSP_NTN2[" + i + "]'placeholder='BDSP NTN Number' class='form-control' /><input type='text' name='BDSP_NTN3[" + i + "]'placeholder='BDSP NTN Number' class='form-control' />	<input type='text' name='QuotedAmount1[" + i + "]' placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount2[" + i + "]'placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount3[" + i + "]' placeholder='Quoted Amount' class='form-control'/> 	<select class='form-group form-control' name='ExpectedDeliveryTime1[" + i + "]' id='ExpectedDeliveryTime1[0]'><option selected disabled>Select Days</option><option value='30' class='form-control input-md'>30</option><option value='60' class='form-control input-md'>60</option><option value='90' class='form-control input-md'>90</option><option value='120' class='form-control input-md'>120</option><option value='150' class='form-control input-md'>150</option><option value='180' class='form-control input-md'>180</option><option value='more180' class='form-control input-md'>More Than 180</option></select><select class='form-group form-control' name='ExpectedDeliveryTime2[" + i + "]' id='ExpectedDeliveryTime2[0]'><option selected disabled>Select Days</option><option value='30' class='form-control input-md'>30</option><option value='60' class='form-control input-md'>60</option><option value='90' class='form-control input-md'>90</option><option value='120' class='form-control input-md'>120</option><option value='150' class='form-control input-md'>150</option><option value='180' class='form-control input-md'>180</option><option value='more180' class='form-control input-md'>More Than 180</option></select><select class='form-group form-control' name='ExpectedDeliveryTime3[" + i + "]' id='ExpectedDeliveryTime3[0]'><option selected disabled>Select Days</option><option value='30' class='form-control input-md'>30</option><option value='60' class='form-control input-md'>60</option><option value='90' class='form-control input-md'>90</option><option value='120' class='form-control input-md'>120</option><option value='150' class='form-control input-md'>150</option><option value='180' class='form-control input-md'>180</option><option value='more180' class='form-control input-md'>More Than 180</option></select>	<input type='file' name='Quotation1[" + i + "]' class='form-control' /><input type='file' name='Quotation2[" + i + "]' class='form-control' /><input type='file' name='Quotation3[" + i + "]' class='form-control' />	");

    $('#Tab_BDSP').append('

');
    i++;
  });
  $("#Delete_BDSP").click(function() {
    if (i > 1) {
      $("#BDSP" + (i - 1)).html('');
      i--;
    }
  });

});

//JS To Add Lowest Value

$(document).on('change', '#Tab_BDSP tbody tr td input[type="text"]', function() {
  let result = 0;
  var MulRes = $('input#ServiceTotalCost');

  var QuotedAmount1 = $(this).parent().find('input[type="text"]').eq(0),
    QuotedAmount2 = $(this).parent().find('input[type="text"]').eq(1),
    QuotedAmount3 = $(this).parent().find('input[type="text"]').eq(2);

  var Qoute1 = (isNaN(parseInt(QuotedAmount1.val()))) ? 0 : parseInt(QuotedAmount1.val()),
    Qoute2 = (isNaN(parseInt(QuotedAmount2.val()))) ? 0 : parseInt(QuotedAmount2.val()),
    Qoute3 = (isNaN(parseInt(QuotedAmount3.val()))) ? 0 : parseInt(QuotedAmount3.val());

  var min = Math.min(Qoute1, Qoute2, Qoute3);
  $(this).parent().attr('data-lowest', min)

  $('#Tab_BDSP tbody tr td').each(function() {
    result += +$(this).attr('data-lowest')
  });

  MulRes.val(result)
});

    Please Provide At Least 3 BDSPs Quotations Against Each Service *

          Services Required
          Description
          BDSP Name
          NTN No.
          Amount
          Expected Delivery Time
          Attach Quotation

            <select class="form-control show-tick form-group form-float" name="RequiredServices[0]" id="Services" required>
              <optgroup label="Financial Services">
                <option id="AccountingSoftware" value="ERP Systems">ERP Systems</option>
                <option id="AccountingSystems" value="Accounting Book Keeping Systems">Accounting / Book Keeping Systems</option>
                <option id="ProductCosting" value="Product Costing">Product Costing</option>
                <option id="FinancialManagement" value="Financial Management Systems">Financial Management Systems</option>

              </optgroup>

              <optgroup label="HR Services">
                <option id="HRPolicies" value="HR Policies and Procedures">HR Policies and Procedures</option>
                <option id="HR_System" value="HR_System">HR Systems</option>
                <option id="Appraisal" value="Appraisal">Employee Internal Trainings Manuals</option>
                <option id="SalesManagement" value="SalesManagement">sEmployee Orientation Manuals.</option>

              </optgroup>

              <optgroup label="General Management">
                <option id="Project" value="ProjectManagement">Project Management System</option>
                <option id="Inventory" value="Inventory Management Systems">Inventory Management Systems</option>
                <option id="Warehouse" value="Warehouse">Procurement System</option>
                <option id="SupplyChain" value="SupplyChain">Supply Chain Systems</option>
                <option id="FleetManagement" value="Fleet Management Systems">Fleet Management Systems</option>

              </optgroup>

              <optgroup label="Regulatory Services">
                <option id="Sales_Income_Tax" value="Sales_Income_Tax">sales / Income Tax Services</option>
                <option id="TradeMark" value="TradeMark">Intellectual Property Rights</option>
                <option id="BusinessRegistration" value="BusinessRegistration">Business Registration Services</option>
                <option id="B2B" value="B2B">B2B, B2C Contracting Services</option>
                <option id="BusinessLicensing" value="BusinessLicensing">Business Licensing Services</option>

              </optgroup>

              <optgroup label="Production Management">
                <option id="ProductionPlanning" value="ProductionPlanning">Production Planning & Control Systems</option>
                <option id="ProductionManagement" value="ProductionManagement">Warehouse Management Information Systems (WMIS)</option>

              </optgroup>
              <optgroup label="Other Services">
                <option id="Other" value="OtherServices">Mention Other Services</option>

              </optgroup>

            </select>

                <input type="text" class="form-control" name="Description[0]" id="Description" required>

            <input type="text" name='BDSPName1[0]' placeholder='BDSP Name' class="form-control" required />
            <input type="text" name='BDSPName2[0]' placeholder='BDSP Name' class="form-control" required />
            <input type="text" name='BDSPName3[0]' placeholder='BDSP Name' class="form-control" required />

            <input type="text" name='BDSP_NTN1[0]' placeholder='BDSP NTN Number' class="form-control" required />
            <input type="text" name='BDSP_NTN2[0]' placeholder='BDSP NTN Number' class="form-control" required />
            <input type="text" name='BDSP_NTN3[0]' placeholder='BDSP NTN Number' class="form-control" required />

            <input type="text" name='QuotedAmount1[0]' placeholder='Quoted Amount' class="form-control" required />
            <input type="text" name='QuotedAmount2[0]' placeholder='Quoted Amount' class="form-control" required />
            <input type="text" name='QuotedAmount3[0]' placeholder='Quoted Amount' class="form-control" required />

            <select class="form-group form-control" name="ExpectedDeliveryTime1[0]" id="ExpectedDeliveryTime1[0]" required>
              <option selected disabled>Select Days</option>
              <option value="AJK" class='form-control input-md'>30</option>
              <option value="Balochistan" class='form-control input-md'>60</option>
              <option value="GB" class='form-control input-md'>90</option>
              <option value="ICT" class='form-control input-md'>120</option>
              <option value="KPK" class='form-control input-md'>150</option>
              <option value="Punjab" class='form-control input-md'>180</option>
              <option value="Sindh" class='form-control input-md'>More Than 180</option>
            </select>
            <select class="form-group form-control" name="ExpectedDeliveryTime2[0]" id="ExpectedDeliveryTime2[0]" required>
              <option selected disabled>Select Days</option>
              <option value="AJK" class='form-control input-md'>30</option>
              <option value="Balochistan" class='form-control input-md'>60</option>
              <option value="GB" class='form-control input-md'>90</option>
              <option value="ICT" class='form-control input-md'>120</option>
              <option value="KPK" class='form-control input-md'>150</option>
              <option value="Punjab" class='form-control input-md'>180</option>
              <option value="Sindh" class='form-control input-md'>More Than 180</option>
            </select>
            <select class="form-group form-control" name="ExpectedDeliveryTime3[0]" id="ExpectedDeliveryTime3[0]" required>
              <option selected disabled>Select Days</option>
              <option value="AJK" class='form-control input-md'>30</option>
              <option value="Balochistan" class='form-control input-md'>60</option>
              <option value="GB" class='form-control input-md'>90</option>
              <option value="ICT" class='form-control input-md'>120</option>
              <option value="KPK" class='form-control input-md'>150</option>
              <option value="Punjab" class='form-control input-md'>180</option>
              <option value="Sindh" class='form-control input-md'>More Than 180</option>
            </select>

            <input type="file" name="Quotation1[0]" class="form-control" required />
            <input type="file" name="Quotation2[0]" class="form-control" required />
            <input type="file" name="Quotation3[0]" class="form-control" required />

  Add RowDelete Row

    Total Cost Of The Service *

 business_center

      <input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>


问:
Visual Studio.NET 2008 doesn't give me english exception-messages
In previous versions of VS.NET or the .NET framework, you got english exception messages by default.
If you installed a 'language pack', you received exception messages in the language of that language pack.

Now, I'm working with an English VS.NET 2008 (no language packs have been installed) on a dutch Windows Vista.

When I'm developing, and I write some code that triggers an exception, the exception message that I receive, is in dutch (the language of my OS).
I don't want it to be in dutch; I want it to be in English.  (Reasons are obvious: easier to Google, and those translated error-messages are crap).

In VS.NET, my international settings are set to 'English', in Windows Vista, my regional settings are set to 'Dutch/Belgium'.
How can I get English exception messages, without having to change anything to my regional settings in Windows?

答:
Thread.CurrentThread.CurrentUICulture is based on the language of your installed OS. So installing an English version of your OS is your only option.

Or like you stated setting Thread.CurrentThread.CurrentUICulture to "en-Us" within each application you code whitch seems to my quite 'quite awkward'.

OwnerDisplayName: Frederik Gheysels

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha

OwnerDisplayName: Mez


问:
Updates to chrome extension popup disappear
So I'm trying to make an extension that takes the contents put in the search bar in popup.html and adds it as a div with a checkbox and button similar to the one that already exists. The issue is that every time I use the search the div will add properly then immediately disappear. For example if I were to type hello into the search bar and hit submit on popup.html the hello div will create and show up for a single frame then disappear and the popup.html is reset to where it was before anything was searched for. How can I make it so that the content stays on the popup and doesn't just reset to the original immediately after?

manifest.json

```<code>{
  "manifest_version": 2,
  "name": "test 2.0",
  "version": "2.0",
  "description": "test extension",
  "browser_action": {
    "default_icon": "images/16.png",
    "default_popup": "popup.html"
  },
  "author": "Cormac",
  "commands": {},
  "incognito": "split",
  "permissions": [
    "activeTab",
    "declarativeContent",
    "storage",
    "tabs"
  ],
  "short_name": "test"
}
</code>```

popup.html

```<code><!DOCTYPE html>
<!-- popup when icon is clicked for extension-->
<html>
  <head>
    <style>
    </style>
  </head>
  <body>
    <div class="search-container">
      <form>
        <input id="search" type="text" placeholder="Search.." name="search">
        <button id="searchbut" class="submit" type="submit"></button>
      </form>
    </div>
    <div id="movies">
      <div id="mov">
        <p id = "p">Movie 1</p>
        <label class="switch">
          <input type="checkbox" checked>
          <span class="slider round"></span>
        </label>
        <button type="submit"></button>
      </div>
    </div>
  </body>
  <script src="popup.js"></script>
</html>

</code>```

If someone were to search for "Movie 2", then movie 2 should be put in a duplicate of the mov div and placed after the first mov div. Thus there would be a mov div with Movie 1 and a mov div with Movie 2.

popup.js

```<code>'use strict';

let page = document.getElementById('movies');

document.addEventListener('DOMContentLoaded', function () {
  var button = document.getElementById('searchbut');
  button.addEventListener('click', function() {
        addMovie();
    });
});

function addMovie(){
    var x = document.getElementById("search");
    var movies = document.getElementById("movies");
    movies.innerHTML += "<p id = \"p\">" + x.value + "</p><label class=\"switch\"><input type=\"checkbox\" checked><span class=\"slider round\"></span></label><button type=\"submit\"></button></div>";
}
</code>```

Additionally in trying to find a solution for this phantom content update I've seen that a common issue is that once the popup is closed it will also reset. This is another issue I expect to encounter after this current one is resolved. If someone could explain that as well that would be amazing.

答:
Remove the form tags:</p>

```<code><div class="search-container">
    <input id="search" type="text" placeholder="Search.." name="search">
    <button id="searchbut" class="submit" type="submit"></button>
</div>
</code>```

Body:
So I'm trying to make an extension that takes the contents put in the search bar in popup.html and adds it as a div with a checkbox and button similar to the one that already exists. The issue is that every time I use the search the div will add properly then immediately disappear. For example if I were to type hello into the search bar and hit submit on popup.html the hello div will create and show up for a single frame then disappear and the popup.html is reset to where it was before anything was searched for. How can I make it so that the content stays on the popup and doesn't just reset to the original immediately after?

manifest.json

{
  "manifest_version": 2,
  "name": "test 2.0",
  "version": "2.0",
  "description": "test extension",
  "browser_action": {
    "default_icon": "images/16.png",
    "default_popup": "popup.html"
  },
  "author": "Cormac",
  "commands": {},
  "incognito": "split",
  "permissions": [
    "activeTab",
    "declarativeContent",
    "storage",
    "tabs"
  ],
  "short_name": "test"
}

popup.html

<!DOCTYPE html>

      <form>
        <input id="search" type="text" placeholder="Search.." name="search">
        <button id="searchbut" class="submit" type="submit"></button>
      </form>

Movie 1

          <input type="checkbox" checked>

        <button type="submit"></button>

If someone were to search for "Movie 2", then movie 2 should be put in a duplicate of the mov div and placed after the first mov div. Thus there would be a mov div with Movie 1 and a mov div with Movie 2.

popup.js

'use strict';

let page = document.getElementById('movies');

document.addEventListener('DOMContentLoaded', function () {
  var button = document.getElementById('searchbut');
  button.addEventListener('click', function() {
        addMovie();
    });
});

function addMovie(){
    var x = document.getElementById("search");
    var movies = document.getElementById("movies");
    movies.innerHTML += "
" + x.value + "
<input type=\"checkbox\" checked><button type=\"submit\"></button>
";
}

Additionally in trying to find a solution for this phantom content update I've seen that a common issue is that once the popup is closed it will also reset. This is another issue I expect to encounter after this current one is resolved. If someone could explain that as well that would be amazing.

Body:
Remove the form tags:

<div class="search-container">
    <input id="search" type="text" placeholder="Search.." name="search">
    <button id="searchbut" class="submit" type="submit"></button>
</div>


问:
Login gmail open message check for sucess or fail in message

Java Selenium program  Login to Gmail account in search box check for
    text this is working fine.  How to check if the message is a success or fail If I write a separate class im getting session ID null
    exception.

//

```<code>    WebElement searchbox = driver.findElement(By.xpath("//input[@placeholder='Search mail']"));
    Thread.sleep(100);
    searchbox.click();
    searchbox.sendKeys("SAP to Magento stock sync");
    Thread.sleep(100);
    searchbox.sendKeys(Keys.ENTER);
    Thread.sleep(1000);
    new WebDriverWait(driver, 30).until(ExpectedConditions
        .visibilityOfElementLocated(By.className("xY a4W")));
WebElement NumberofRecord = driver.findElement(By.className("xY a4W"));
System.out.println(NumberofRecord.getText());
</code>```

error:

```<code>TimeoutException: Expected condition failed: waiting for visibility of element located by By.className: xY a4W (tried for 30 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:81)

</code>```

答:
```<code>// extract notification subjects
ArrayList<WebElement> notificationsSubjects = ...// code to locate displayed subjects
// resolve subjects
for (WebElement element: notificationsSubjects) {
 if (element.getText().split(": SAP")[0] == "SUCCESS") {
// do something
}
else if (element.getText().split(": SAP")[0] == "ERROR") {
// do something else
}
else {
System.out.print("Unexpected subject.");
}
</code>```

Body:
Java Selenium program  Login to Gmail account in search box check for
    text this is working fine.  How to check if the message is a success or fail If I write a separate class im getting session ID null
    exception.

//

    WebElement searchbox = driver.findElement(By.xpath("//input[@placeholder='Search mail']"));
    Thread.sleep(100);
    searchbox.click();
    searchbox.sendKeys("SAP to Magento stock sync");
    Thread.sleep(100);
    searchbox.sendKeys(Keys.ENTER);
    Thread.sleep(1000);
    new WebDriverWait(driver, 30).until(ExpectedConditions
        .visibilityOfElementLocated(By.className("xY a4W")));
WebElement NumberofRecord = driver.findElement(By.className("xY a4W"));
System.out.println(NumberofRecord.getText());

error:

TimeoutException: Expected condition failed: waiting for visibility of element located by By.className: xY a4W (tried for 30 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:81)


问:
How to make the button immovable when rendering a side nav in angular?
I have a side navigation panel and it is being rendered correctly from the side. But my issue is that when it is rendering from the side, the toggle button (MoreDetails) is moving along.
I want it to remain stationary and just do the toggling.
The code is as follows in navigation.component.html:</p>

```<code><mat-sidenav-container class="example-container" >

  <mat-sidenav #sidenav mode="side" [(opened)]="opened" (opened)="events.push('open!')"
               (closed)="events.push('close!')">
   <mat-list>
        <mat-list-item> Pepper </mat-list-item>
        <mat-list-item> Oil </mat-list-item>
        <mat-list-item> Salt </mat-list-item>
        <mat-list-item> Paprika </mat-list-item>
       </mat-list>
  </mat-sidenav>

  <mat-sidenav-content>

    <p><button mat-button (click)="sidenav.toggle()">More Details</button></p>

  </mat-sidenav-content>
</mat-sidenav-container>
</code>```

答:
You need to use mode='"over"' to render the sidenav "over" the primary content. mode="side" put the primary content side by side with the sidenav and shrink the content.

Material DOcs - Sidenav

Body:
I have a side navigation panel and it is being rendered correctly from the side. But my issue is that when it is rendering from the side, the toggle button (MoreDetails) is moving along.
I want it to remain stationary and just do the toggling.
The code is as follows in navigation.component.html:

<mat-sidenav-container class="example-container" >

  <mat-sidenav #sidenav mode="side" [(opened)]="opened" (opened)="events.push('open!')"
               (closed)="events.push('close!')">
   <mat-list>
        <mat-list-item> Pepper </mat-list-item>
        <mat-list-item> Oil </mat-list-item>
        <mat-list-item> Salt </mat-list-item>
        <mat-list-item> Paprika </mat-list-item>
       </mat-list>
  </mat-sidenav>

  <mat-sidenav-content>

<button mat-button (click)="sidenav.toggle()">More Details</button>

  </mat-sidenav-content>
</mat-sidenav-container>


问:
JSX component doesn't render map of state
i'm trying to make a list when users selects their fav links onClick ...

Any idea why this doesn't work? it will push values to state.array in console.log but JSX will not render in ul.li

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

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      link: {
        name: "",
        type: "",
        size: "",
        tests: []
      },
      tests: ["1", "2", "3", "4"]
    };
  }

  componentDidMount() {
    console.log(this.state);
  }

  onClick = e => {
    const linktests = this.state.link.tests;
    console.log("clicked");

    linktests.push(e.target.innerText);
    console.log("link tests : " + linktests);
  };
  render() {
    const { link, tests } = this.state;
    const linktests = this.state.link.tests;
    return (
      <div>
        <div id="link">
          {linktests.map(stuff => (
            <ul>
              <li> {stuff} </li>
            </ul>
          ))}
        </div>
        <br></br>
        {tests.map(stuff => (
          <ul>
            <li onClick={this.onClick} value={stuff}>
              {stuff}
            </li>
          </ul>
        ))}
      </div>
    );
  }
}

</code>```

hope someone can help :D <3 thanks

答:
You need to set the new links to the state. Also use concat or slice on the original state array to avoid mutating it directly.

```<code> onClick = e => {
    const linktests = this.state.link.tests.concat();
    console.log("clicked");

    linktests.push(e.target.innerText);
    this.setState({link: { ...this.state.link, tests: linktests});
  };
</code>```

Body:
i'm trying to make a list when users selects their fav links onClick ...

Any idea why this doesn't work? it will push values to state.array in console.log but JSX will not render in ul.li

import React, { Component } from "react";

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      link: {
        name: "",
        type: "",
        size: "",
        tests: []
      },
      tests: ["1", "2", "3", "4"]
    };
  }

  componentDidMount() {
    console.log(this.state);
  }

  onClick = e => {
    const linktests = this.state.link.tests;
    console.log("clicked");

    linktests.push(e.target.innerText);
    console.log("link tests : " + linktests);
  };
  render() {
    const { link, tests } = this.state;
    const linktests = this.state.link.tests;
    return (

          {linktests.map(stuff => (

 {stuff}

          ))}

        {tests.map(stuff => (

              {stuff}

        ))}

    );
  }
}

hope someone can help :D <3 thanks

Body:
You need to set the new links to the state. Also use concat or slice on the original state array to avoid mutating it directly.

 onClick = e => {
    const linktests = this.state.link.tests.concat();
    console.log("clicked");

    linktests.push(e.target.innerText);
    this.setState({link: { ...this.state.link, tests: linktests});
  };


问:
Unable to export Rest API output to CSV via Azure Powershell RunBook
I am trying to export VMs list from Azure Update management using Azure Rest API. Below is my code.
$url = "https://management.azure.com/subscriptions/$($SubscriptionId)/resourceGroups/$($resourceGroup)/providers/Microsoft.Automation/automationAccounts/$($automationAccount)/softwareUpdateConfigurations/$($UpdateScheduleName)?api-version=" + $apiversion
$RestMethod = (Invoke-RestMethod -Uri $url -Headers $headerParams -Method Get)
$NonAzComputerList  = ($RestMethod).Properties.updateConfiguration.nonAzureComputerNames
$NonAzComputerList.GetType().FullName
Write-Output $NonAzComputerList
$NonAzComputerList | Export-Csv "VMList.csv" -NoTypeInformation

On Console, I do get the output correctly with VM names, but in CSV file, I get some random numbers instead of VM names.

I tried convertfrom-json as well but it shows error as "convertfrom-json : Invalid JSON primitive".

The GetType shows System.Object[]

In Console, I am getting correct VM names.
OurVM01
OurVM022
OurVM0113
OurVM034

In CSV file, I am getting numbers (equal to number of characters in VM names).
List
07
08
09
08

答: Ok figured it out. Used out-file instead of export-csv</p>


问:
Is there a way to set implicit timeouts beyond the driver.manage().timeouts() method?
I continue to get an "element not interactable" error which I think is due to the link not being loaded fast enough after an action on the page. Implicit driver wait doesn't seem to be working, looks like it's not even setting?

I'm setting implicit wait for the driver like this: (Pageload doesn't seem to help)

```<code>driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
</code>```

Capabilities [{mobileEmulationEnabled=false, timeouts={implicit=0, pageLoad=300000, script=30000}, hasTouchScreen=false, platform=XP, acceptSslCerts=false, goog:chromeOptions={debuggerAddress=localhost:63891}, acceptInsecureCerts=false, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=ignore, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387), userDataDir=C:\Users\jxg262\AppData\Local\Temp\scoped_dir2012_6758}, takesHeapSnapshot=true, unhandledPromptBehavior=ignore, pageLoadStrategy=normal, strictFileInteractability=false, databaseEnabled=false, handlesAlerts=true, version=71.0.3578.98, browserConnectionEnabled=false, proxy=Proxy(), nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]

This seems to show that implicits are not being set.  Am I doing something wrong?  Is there a way to set this elsewhere?

答:
Implicit timeout is chrome server timeout so try setting it before starting Chrome, like this</p>

```<code>ChromeOptions chromeOptions = new ChromeOptions();

Map<String, Integer> timeouts = new HashMap<>();
timeouts.put("implicit", 3000);
chromeOptions.setCapability("timeouts", timeouts);

webDriver = new ChromeDriver(chromeOptions);
</code>```

Body:
I continue to get an "element not interactable" error which I think is due to the link not being loaded fast enough after an action on the page. Implicit driver wait doesn't seem to be working, looks like it's not even setting?

I'm setting implicit wait for the driver like this: (Pageload doesn't seem to help)

driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Capabilities [{mobileEmulationEnabled=false, timeouts={implicit=0, pageLoad=300000, script=30000}, hasTouchScreen=false, platform=XP, acceptSslCerts=false, goog:chromeOptions={debuggerAddress=localhost:63891}, acceptInsecureCerts=false, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=ignore, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387), userDataDir=C:\Users\jxg262\AppData\Local\Temp\scoped_dir2012_6758}, takesHeapSnapshot=true, unhandledPromptBehavior=ignore, pageLoadStrategy=normal, strictFileInteractability=false, databaseEnabled=false, handlesAlerts=true, version=71.0.3578.98, browserConnectionEnabled=false, proxy=Proxy(), nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]

This seems to show that implicits are not being set.  Am I doing something wrong?  Is there a way to set this elsewhere?

Body:
Implicit timeout is chrome server timeout so try setting it before starting Chrome, like this

ChromeOptions chromeOptions = new ChromeOptions();

Map<String, Integer> timeouts = new HashMap<>();
timeouts.put("implicit", 3000);
chromeOptions.setCapability("timeouts", timeouts);

webDriver = new ChromeDriver(chromeOptions);


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答: The difference between include/include_once and require/require_once is that when a file is not found, the former triggers a warning whereas the latter triggers an error. Opinions may vary but IMO, if a needed file is not present or readable for some reason, this represents a very broken situation and I would rather see an error and halt execution, than have a warning and proceed execution in a clearly broken context. So I believe it to be best practice to use require/require_once exclusively and avoid include/include_once altogether.

ContentLicense: CC BY-SA 3.0


问:
Kotlin SupervisorJob unexpected behaviour
I have the next code:

```<code>import kotlin.coroutines.*;
import kotlinx.coroutines.*;

val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
    println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler

fun main() {
    val job1 = GlobalScope.launch(coroutineContext) {
        // supervisorScope {
        launch {
            println("Test0")
            for (i in 0..5) {
                println("Working! Iteration: $i")
                delay(1000)
            }
            println("Test0 end")
        }

        launch {
            println("Test1")
            delay(2000)
            throw IllegalAccessException()
        }

        launch {
            println("Test2")
            delay(3000)
            println("Test2 end")
        }

    }
    //}
    runBlocking { job1.join() }
    println("Test3")
}
</code>```

As You can see, I'm using SupervisorJob by passing it in coroutineContext into GlobalScope.launch to avoid canceling of any children on error if it happened anywhere and error must be handled in handler. The documetation says next about SupervisorJob:

```<code>Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.
</code>```

Based on this, I'm expecting something like that:

```<code>Test0
Working! Iteration: 0
Test1
Test2
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Working! Iteration: 2
Working! Iteration: 3
Test2 end
Working! Iteration: 4
Working! Iteration: 5
Test0 end
Test3
</code>```

But I get:

```<code>Test2
Test0
Working! Iteration: 0
Test1
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Test3
</code>```

The only that helps is uncomment supervisorScope in code above.

What I'm doing wrong? How I can set expected behaviour globaly in ViewModel, for example, to avoid wrapping every launch in supervisorScope?

Thanks in advance.

答:
Thanks to @MarkoTopolnik, solution that worked for me:

```<code>val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
    println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler
val coroutineScope: CoroutineScope = CoroutineScope(coroutineContext)

fun main() {
    val job1 = coroutineScope.launch {
        println("Test0 start")
        for (i in 0..5) {
            println("Test0 iteration: $i")
            delay(1000)
        }
        println("Test0 end")
    }

    val job2 = coroutineScope.launch {
        println("Test4 start")
        for (i in 0..5) {
            println("Test4 iteration: $i")
            delay(1000)
        }
        println("Test4 end")
    }

    val job3 = coroutineScope.launch {
        println("Test1")
        delay(2000)
        throw IllegalAccessException()
    }

    val job4 = coroutineScope.launch {
        println("Test2 start")
        delay(4000)
        println("Test2 end")
    }

    val jobs = mutableListOf(job1, job2, job3, job4)
    runBlocking {
        jobs.forEach { it.join() }
    }

    println("end")
}
</code>```

Result:

```<code>Test0 start
Test0 iteration: 0
Test1
Test4 start
Test4 iteration: 0
Test2 start
Test0 iteration: 1
Test4 iteration: 1
Test0 iteration: 2
Test4 iteration: 2
Catch: java.lang.IllegalAccessException
Test4 iteration: 3
Test0 iteration: 3
Test2 end
Test4 iteration: 4
Test0 iteration: 4
Test4 iteration: 5
Test0 iteration: 5
Test4 end
Test0 end
end
</code>```

Body:
I have the next code:

import kotlin.coroutines.*;
import kotlinx.coroutines.*;

val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
    println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler

fun main() {
    val job1 = GlobalScope.launch(coroutineContext) {
        // supervisorScope {
        launch {
            println("Test0")
            for (i in 0..5) {
                println("Working! Iteration: $i")
                delay(1000)
            }
            println("Test0 end")
        }

        launch {
            println("Test1")
            delay(2000)
            throw IllegalAccessException()
        }

        launch {
            println("Test2")
            delay(3000)
            println("Test2 end")
        }

    }
    //}
    runBlocking { job1.join() }
    println("Test3")
}

As You can see, I'm using SupervisorJob by passing it in coroutineContext into GlobalScope.launch to avoid canceling of any children on error if it happened anywhere and error must be handled in handler. The documetation says next about SupervisorJob:

Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.

Based on this, I'm expecting something like that:

Test0
Working! Iteration: 0
Test1
Test2
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Working! Iteration: 2
Working! Iteration: 3
Test2 end
Working! Iteration: 4
Working! Iteration: 5
Test0 end
Test3

But I get:

Test2
Test0
Working! Iteration: 0
Test1
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Test3

The only that helps is uncomment supervisorScope in code above.

What I'm doing wrong? How I can set expected behaviour globaly in ViewModel, for example, to avoid wrapping every launch in supervisorScope?

Thanks in advance.

Body:
Thanks to @MarkoTopolnik, solution that worked for me:

val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
    println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler
val coroutineScope: CoroutineScope = CoroutineScope(coroutineContext)

fun main() {
    val job1 = coroutineScope.launch {
        println("Test0 start")
        for (i in 0..5) {
            println("Test0 iteration: $i")
            delay(1000)
        }
        println("Test0 end")
    }

    val job2 = coroutineScope.launch {
        println("Test4 start")
        for (i in 0..5) {
            println("Test4 iteration: $i")
            delay(1000)
        }
        println("Test4 end")
    }

    val job3 = coroutineScope.launch {
        println("Test1")
        delay(2000)
        throw IllegalAccessException()
    }

    val job4 = coroutineScope.launch {
        println("Test2 start")
        delay(4000)
        println("Test2 end")
    }

    val jobs = mutableListOf(job1, job2, job3, job4)
    runBlocking {
        jobs.forEach { it.join() }
    }

    println("end")
}

Result:

Test0 start
Test0 iteration: 0
Test1
Test4 start
Test4 iteration: 0
Test2 start
Test0 iteration: 1
Test4 iteration: 1
Test0 iteration: 2
Test4 iteration: 2
Catch: java.lang.IllegalAccessException
Test4 iteration: 3
Test0 iteration: 3
Test2 end
Test4 iteration: 4
Test0 iteration: 4
Test4 iteration: 5
Test0 iteration: 5
Test4 end
Test0 end
end


问:
org.gradle.kotlin.kotlin-dsl was not found
I am getting the following error while running the build

```<code>FAILURE: Build failed with an exception.

* Where:
Build file '/home/charming/mainframer/bigovlog_android/buildSrc/build.gradle.kts' line: 4

* What went wrong:
Plugin [id: 'org.gradle.kotlin.kotlin-dsl', version: '1.2.6'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:1.2.6')
  Searched in the following repositories:
    Gradle Central Plugin Repository
</code>```

my buildSrc/build.gradle.kts

```<code>repositories {
    jcenter()
}
plugins {
    `kotlin-dsl`
    id("groovy")
}
dependencies{
    gradleApi()
    localGroovy()
}
</code>```

I tried everything but still not working

答: Did you check that Android Studio wasn't running in Offline Mode? Take a look at Preferences/Build, Execution, Deployment/Gradle/Global Gradle settings and see if Offline Work is checked.

Body:
I am getting the following error while running the build

FAILURE: Build failed with an exception.

* Where:
Build file '/home/charming/mainframer/bigovlog_android/buildSrc/build.gradle.kts' line: 4

* What went wrong:
Plugin [id: 'org.gradle.kotlin.kotlin-dsl', version: '1.2.6'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:1.2.6')
  Searched in the following repositories:
    Gradle Central Plugin Repository

my buildSrc/build.gradle.kts

repositories {
    jcenter()
}
plugins {
    `kotlin-dsl`
    id("groovy")
}
dependencies{
    gradleApi()
    localGroovy()
}

I tried everything but still not working


问:
How to run the program while it is away from the database file?
I'm trying to run my program it is away from the SQLite database file BUT there is an exception raised that says

Data Source cannot be empty.  Use :memory: to open an in-memory database

Here is my code

static string path;
static SQLiteConnection cnn = new SQLiteConnection($"Data Source={path};Pooling=true;FailIfMissing=false;Version=3");

private void Form_Load(object sender, EventArgs e) {
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK) path = ofd.FileName;
    OpenDB();
}
```

答: I had to create a shortcut from the folder of my project.</p>


答:
include - this attempts to load a file but does not halt execution if it fails

include_once - does the same as 'include' but runs an additional check to make sure the file hasn't already been included in the current script

require - this attempts to load a file and throws a fatal error on failure

require_once - same as 'require' but runs an additional check to make sure it's loaded only once

If you don't need to use include_once or require_once try to avoid them since the extra check adds a little overhead.

EDIT: I should add that they key difference is that require fails at the compiler level, while include throws an error at run-time.

Title: Why include when you can require in PHP?

Body: What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?


问:
How to take Multiple values input(with different types and separated with comma) from user in java
I want to accept multiple values from user like productName,Price,gstAmount like this:

```<code>sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10
</code>```

After this calculate the item with minimum price

```<code>sample output:watch
</code>```

答:
Follow these steps:

Use a scanner to read in the 3 values from the user, after each ask if they wish to enter another item, if yes then loop else close scanner

for each entry store in an object with 3 fields for name, price, gst, then add to array

sort array in order of price and pick lowest

Body:
I want to accept multiple values from user like productName,Price,gstAmount like this:

sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10

After this calculate the item with minimum price

sample output:watch


问:
How to make a function find the address of the function pointer it's been called by?
I want to implement the toString() method for a pure C struct. That can, of course, be done using a function pointer, but the catch is that I don't wan't to pass the object's location to the function and I want the function to figure it out by itself based on the function pointer in said struct. So, if we have a struct like this:

```<code>typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;
</code>```

after instantiating it, I want its contents printed the same way you do it in Java, like this:

```<code>Node a;
a.toString();
</code>```

Except our toString() will print the stringized object itself and won't actually return a string.

I took my time and this is what I came up with:

```<code>#include <stdio.h>
#include <stdint.h>

typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;

void f()
{
  Node *beginnning = __builtin_frame_address(1) - sizeof(Node);
  const char ** temp = (const char *) beginnning + 8;
  printf("{%d, %s}\n", *((int*)beginnning), *temp);
}

int main()
{
    Node a, b;
    a.a = 67, a.str = "alpine", a.toString = f;
    a.toString();
    b.a = 25, b.str = "hello world", b.toString = f;
    b.toString();
}
</code>```

The fundamental idea is to use this __builtin_frame_address() function, which in my case conveniently returns the last byte of my object. After getting it, obtaining the variables is relatively straight forward using pointer arithmetic and the fact that we actually know how our variables are placed inside the struct.

The problem with this solution is that it only works with only one object. First one is being printed correctly, but for the second one, we don't get the right address. So, the expected output is:

```<code>{67, alpine}
{25, hello world}
</code>```

but the real output is actually:

```<code>{67, alpine}
{67, alpine}
</code>```

Is there a way to forcefully "end" the frame, or reset in some way so that a next function call returns what we need? I believe if there were a way to do that, this problem can be solved. However, I couldn't really find anything like that in __builtin_frame_address() documentation.

The function I used from what I gathered is a part of the gcc compiler on linux. I wouldn't exactly look for it on Windows. Therefore, to save time, you might want to test it here.

答:
You can't do this.

What you have found is a way to print the contents of the Node object at the top of the previous call frame. That has nothing to do with the expression a.toString, you could just call f in that place to the same effect.

I don't wan't to pass the object's location to the function

Why not? It's what Java does (implicitly).

Body:
I want to implement the toString() method for a pure C struct. That can, of course, be done using a function pointer, but the catch is that I don't wan't to pass the object's location to the function and I want the function to figure it out by itself based on the function pointer in said struct. So, if we have a struct like this:

typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;

after instantiating it, I want its contents printed the same way you do it in Java, like this:

Node a;
a.toString();

Except our toString() will print the stringized object itself and won't actually return a string.

I took my time and this is what I came up with:

#include <stdio.h>
#include <stdint.h>

typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;

void f()
{
  Node *beginnning = __builtin_frame_address(1) - sizeof(Node);
  const char ** temp = (const char *) beginnning + 8;
  printf("{%d, %s}\n", *((int*)beginnning), *temp);
}

int main()
{
    Node a, b;
    a.a = 67, a.str = "alpine", a.toString = f;
    a.toString();
    b.a = 25, b.str = "hello world", b.toString = f;
    b.toString();
}

The fundamental idea is to use this __builtin_frame_address() function, which in my case conveniently returns the last byte of my object. After getting it, obtaining the variables is relatively straight forward using pointer arithmetic and the fact that we actually know how our variables are placed inside the struct.

The problem with this solution is that it only works with only one object. First one is being printed correctly, but for the second one, we don't get the right address. So, the expected output is:

{67, alpine}
{25, hello world}

but the real output is actually:

{67, alpine}
{67, alpine}

Is there a way to forcefully "end" the frame, or reset in some way so that a next function call returns what we need? I believe if there were a way to do that, this problem can be solved. However, I couldn't really find anything like that in __builtin_frame_address() documentation.

The function I used from what I gathered is a part of the gcc compiler on linux. I wouldn't exactly look for it on Windows. Therefore, to save time, you might want to test it here.


问:
Running batch file which runs 2 other batch files from SQL Server job
I have this step in sql server job

AAA.bat content is this

```<code>call BBB.bat
call CCC.bat
</code>```

BBB.bat and CCC.bat each run ETL packages.
When I run above step it throws error

BBB.bat is not recognized as an internal or external command, operable
  program or batch file... CCC.bat is not recognized as an internal or
  external command, operable program or batch file

However, when I replace AAA.bat with either BBB.bat or CCC.bat it works as intended.

答:
Are BBB.bat and CCC.bat in the same directory as AAA.bat? You need to set the working directory first. In AAA.bat add the following at the top of the file:

```<code>cd /d D:\Path\Client1
</code>```

Or, call BBB.bat and CCC.bat using their full path.

A possibly better solution, depending on your environment and needs, would be to have your job contain two steps, each one calling the appropriate batch file (BBB or CCC) separately. That way, if you have a failure, its very obvious which batch file had a problem.

Body:
I have this step in sql server job

AAA.bat content is this

call BBB.bat
call CCC.bat

BBB.bat and CCC.bat each run ETL packages.
When I run above step it throws error

BBB.bat is not recognized as an internal or external command, operable
  program or batch file... CCC.bat is not recognized as an internal or
  external command, operable program or batch file

However, when I replace AAA.bat with either BBB.bat or CCC.bat it works as intended.

Body:
Are BBB.bat and CCC.bat in the same directory as AAA.bat? You need to set the working directory first. In AAA.bat add the following at the top of the file:

cd /d D:\Path\Client1

Or, call BBB.bat and CCC.bat using their full path.

A possibly better solution, depending on your environment and needs, would be to have your job contain two steps, each one calling the appropriate batch file (BBB or CCC) separately. That way, if you have a failure, its very obvious which batch file had a problem.


问:
Rails routes redirection for subdomains
We can't change the server configuration files, so we need to do our redirections at the rails level.

I have no problem with path redirections to external sites, like:

match "/meow" => redirect("http://meow.com/")

The issue is with the subdomains. I need to redirect for example:

http://my.example.com => http://example.com

How can this be done using routes.rb?

答:
If you don't want to hard-code the URL (so, for example, you can test/use this locally), you could do:

```<code>  constraints subdomain: 'subdomain_from' do
    get '/' => redirect(subdomain: :new_subdomain, path: '')
  end
</code>```

So now subdomain_from.google.com will redirect to new_subdomain.google.com.

Title: Rails routes redirection for subdomains

Body:
If you don't want to hard-code the URL (so, for example, you can test/use this locally), you could do:

  constraints subdomain: 'subdomain_from' do
    get '/' => redirect(subdomain: :new_subdomain, path: '')
  end

So now subdomain_from.google.com will redirect to new_subdomain.google.com.