问:
the form which remains null symfony
I set up a search form with a handmade Entity but the form does not transmit the info to the entity ... you have an idea to solve this problem?

Also it's symfony 4.4 and I've already checked the findWeeklyPlanningRs query in the repository and it works fine.

this is the entity:

```<code>
<?php

namespace App\Entity ;

class FilterWeek
{

  private $nbWeek ;

      public function getNbWeek(): ?int
      {
          return $this-> nbWeek;
      }

      public function setNbWeek(int $nbWeek): self
      {
          $this->$nbWeek = $nbWeek;

          return $this;
      }

}
</code>```

the Controller

```<code>  /**
        * @Route("/{id}/week" ,  name="week")
        */

        public function weeklyPlanning(Request $request ,  $id ) : Response
        {

          $em = $this->getDoctrine()->getManager();

          $week = new FilterWeek();

          $form = $this -> createForm(FilterWeekType::class , $week ) ;
          $form->handleRequest($request);

          $planning = $em -> getRepository(Chargement::class) -> findWeeklyPlanningRs($id , $week-> getNbWeek()  ) ;

          $responsableSecteur = $em ->getRepository(ResponsableSecteur::class)->find($id) ;

          return $this -> render('Planing/ResponsableSecteurWeek.html.twig' , [
            'responsable_secteur' => $responsableSecteur,
            'chargements' => $planning ,
            'form' => $form -> createView()
            ] );

        }

</code>```

the form :

```<code>
<?php

namespace App\Form;

use App\Entity\FilterWeek;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;

class FilterWeekType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nbWeek' , IntegerType::class , [

              'label' => 'numéro de la semaine' ,
              'required' => false
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => FilterWeek::class,
            'method' => 'get',
            'csrf_protection' => false,
        ]);
    }

    public function getBlockPrefix(){

      return '';
    }
}

</code>```

the view :

```<code>{% extends 'base.html.twig' %}

{% block body %}

  <div class="container">

    <h3>Planning des chargements par Semaine</h3>

    <br><br>

    <div class="form-row" >
      <div class="col-4">
        {{ form_start(form) }}
          {{ form_row(form.nbWeek) }}
            <button class="btn color-br"  style="top : 5em;" >Rechercher</button>

        {{ form_end(form) }}
      </div>
</code>```

答:
Your entity is currently incomplete. It is better to use php bin/console make:entity to generate entity because it generates $id and repository automatically. Also you need annotations to denote the type of nbWeek. So the entity should look like that:

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\FilterWeekRepository")
 */
class FilterWeek
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $nbWeek;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNbWeek(): ?int
    {
        return $this->nbWeek;
    }

    public function setNbWeek(int $nbWeek): self
    {
        $this->nbWeek = $nbWeek;

        return $this;
    }
}
</code>```

The code of the controller which you post is currently incomplete. But I think you need to  add the following lines under $responsableSecteur = $em->getRepository(ResponsableSecteur::class)->find($id);:

```<code>$filterWeek = new FilterWeek();
$filterWeek->setNbWeek($request->get('nbWeek'));
$em->persist($filterWeek);
$em->flush();
</code>```

It creates the object of FilterWeek and pushes it into the database. Make sure that you have created the table in the database.

The form and template looks fine. At least, I didn't need to improve them before it started to work.

Title: the form which remains null symfony

Body:
I set up a search form with a handmade Entity but the form does not transmit the info to the entity ... you have an idea to solve this problem?

Also it's symfony 4.4 and I've already checked the findWeeklyPlanningRs query in the repository and it works fine.

this is the entity:

<?php

namespace App\Entity ;

class FilterWeek
{

  private $nbWeek ;

      public function getNbWeek(): ?int
      {
          return $this-> nbWeek;
      }

      public function setNbWeek(int $nbWeek): self
      {
          $this->$nbWeek = $nbWeek;

          return $this;
      }

}

the Controller

  /**
        * @Route("/{id}/week" ,  name="week")
        */

        public function weeklyPlanning(Request $request ,  $id ) : Response
        {

          $em = $this->getDoctrine()->getManager();

          $week = new FilterWeek();

          $form = $this -> createForm(FilterWeekType::class , $week ) ;
          $form->handleRequest($request);

          $planning = $em -> getRepository(Chargement::class) -> findWeeklyPlanningRs($id , $week-> getNbWeek()  ) ;

          $responsableSecteur = $em ->getRepository(ResponsableSecteur::class)->find($id) ;

          return $this -> render('Planing/ResponsableSecteurWeek.html.twig' , [
            'responsable_secteur' => $responsableSecteur,
            'chargements' => $planning ,
            'form' => $form -> createView()
            ] );

        }

the form :

<?php

namespace App\Form;

use App\Entity\FilterWeek;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;

class FilterWeekType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nbWeek' , IntegerType::class , [

              'label' => 'numéro de la semaine' ,
              'required' => false
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => FilterWeek::class,
            'method' => 'get',
            'csrf_protection' => false,
        ]);
    }

    public function getBlockPrefix(){

      return '';
    }
}

the view :

{% extends 'base.html.twig' %}

{% block body %}

Planning des chargements par Semaine

        {{ form_start(form) }}
          {{ form_row(form.nbWeek) }}
            <button class="btn color-br"  style="top : 5em;" >Rechercher</button>

        {{ form_end(form) }}

Body:
Your entity is currently incomplete. It is better to use php bin/console make:entity to generate entity because it generates $id and repository automatically. Also you need annotations to denote the type of nbWeek. So the entity should look like that:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\FilterWeekRepository")
 */
class FilterWeek
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $nbWeek;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNbWeek(): ?int
    {
        return $this->nbWeek;
    }

    public function setNbWeek(int $nbWeek): self
    {
        $this->nbWeek = $nbWeek;

        return $this;
    }
}

The code of the controller which you post is currently incomplete. But I think you need to  add the following lines under $responsableSecteur = $em->getRepository(ResponsableSecteur::class)->find($id);:

$filterWeek = new FilterWeek();
$filterWeek->setNbWeek($request->get('nbWeek'));
$em->persist($filterWeek);
$em->flush();

It creates the object of FilterWeek and pushes it into the database. Make sure that you have created the table in the database.

The form and template looks fine. At least, I didn't need to improve them before it started to work.


来源: stackexchange

问:
Character is out of Screen in 2D Unity Multiplayer Game
As you know positions are critical in multiplayer game and I want to define same position in different resolutions in my 2d multiplayer game.

My problem is like this: if my resolution is 1080p, it works nicely. However if resolution is set to 800x600, then the other character disappears because of the camera.

How can I make it right?

1080p:

800 x 600:

答: This is one solution that might work in your case : Controlling Aspect Ratio in Unity</p>

ContentLicense: CC BY-SA 4.0


问:
Flutter Web/Dart CORS Error with Firebase Hosting

Problem

I wrote an application in Flutter Web. When I run it in the Browser (debug), I get this error:

```<code>cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.googleapis.com/identityto...
</code>```

When I run it in release mode, I just get this:

```<code>Error while fetching an original source: NetworkError when attempting to fetch resource.
Source URL: org-dartlang-sdk:///sdk/lib/_internal/js_runtime/lib/js_helper.dart
</code>```

Other info

The App is hosted in Firebase Hosting but the error also occurs on localhost without Firebase

I think the Problem is cors in both cases but the release mode just has less logs

What I tried

According to this Documentation or this Question I have to add something using Expressjs like:

```<code>const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));
</code>```

Is there anything like Expressjs in Dart/Flutter? I saw this but I could not get it to work.

Or is there another way to set the headers?

答:
It seems that indeed, CORS is blocking you from using Firebase to store and access data. As per the documentation Configuring cross-origin resource sharing (CORS):

Cross Origin Resource Sharing (CORS) is a mechanism for allowing interactions between resources from different origins, something that is normally prohibited in order to prevent malicious behavior.

Considering that, you will need to configure yours to work and accept requests made via HTTP. I would recommend you to take a look at the above documentation and the following links, so you can get more information about it.

Enabling CORS in Cloud Functions for Firebase

Call functions via HTTP requests

Once you have them configured, you should not face both errors anymore, since the requests via HTTP will be authorized via CORS and the access to Firebase should be established.

Let me know if the information helped you!

Body:
Problem

I wrote an application in Flutter Web. When I run it in the Browser (debug), I get this error:

cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.googleapis.com/identityto...

When I run it in release mode, I just get this:

Error while fetching an original source: NetworkError when attempting to fetch resource.
Source URL: org-dartlang-sdk:///sdk/lib/_internal/js_runtime/lib/js_helper.dart

Other info

The App is hosted in Firebase Hosting but the error also occurs on localhost without Firebase

I think the Problem is cors in both cases but the release mode just has less logs

What I tried

According to this Documentation or this Question I have to add something using Expressjs like:

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));

Is there anything like Expressjs in Dart/Flutter? I saw this but I could not get it to work.

Or is there another way to set the headers?


问:
How to access value of child element in a object?
I want to access friends array of every user  (values of the array are user's id's) and return the value of the friend's array of the given user (friend)

```<code>const users = [
{
   "id": 1,
   "firstName": "Paul",
   "surname": "Crowe",
   "friends": [2]
 },
 {
   "id": 2,
   "firstName": "Rob",
   "surname": "Fitz",
   "friends": [1,3]
 },
 {
   "id": 3,
   "firstName": "Ben",
   "surname": "O'Carolan",
   "friends": [2]
 },
</code>```

This is what I have tried:

```<code>const fof = users.filter(user => {
      if (friend == user.id) {
        return true;
      }
    });
</code>```

答:
when you have a big array, find() is more effective. it'll return the first element matches the condition</p>

```<code>const findFOF = (id) => users.find(item => item.id === id).friends
</code>```

Body:
I want to access friends array of every user  (values of the array are user's id's) and return the value of the friend's array of the given user (friend)

const users = [
{
   "id": 1,
   "firstName": "Paul",
   "surname": "Crowe",
   "friends": [2]
 },
 {
   "id": 2,
   "firstName": "Rob",
   "surname": "Fitz",
   "friends": [1,3]
 },
 {
   "id": 3,
   "firstName": "Ben",
   "surname": "O'Carolan",
   "friends": [2]
 },

This is what I have tried:

const fof = users.filter(user => {
      if (friend == user.id) {
        return true;
      }
    });

Body:
when you have a big array, find() is more effective. it'll return the first element matches the condition

const findFOF = (id) => users.find(item => item.id === id).friends


问:
Getting random number from 6502 assembler
Trying to generate a series of random numbers on my Commodore 64 (C64) using JSR $E09A and retrieving the number from $63 and $64. (which according to all the documentation I've seen is the same routine when you use RND(0) from BASIC. But can't get it to iterate. The following will work and place a different number in $63 and $64 when executed by itself.

```<code>. C000  A5 00    LDA $00
. C002  20 9A E0 JSR $E09A
. C005  00       BRK
</code>```

Now when I try to iterate say 10 times with the following code, it never returns.

```<code>. C000  A0 0A    LDY #$0A
. C002  A9 00    LDA #$00
. C004  20 9A E0 JSR $E09A
. C007  88       DEY
. C008  D0 F8    BNE $C002
. C00A  00       BRK
</code>```

Am I missing something so obvious I can't see it. I'm not worried about how "random" it is. At this point I just want a series of random numbers.

答:
I found this thread searching for more general RND(start, end) routine in C64 assembly. Something implemented as this BASIC example:

```<code>INT(RND(1) * (end- start + 1)) + start
</code>```

While there are many helpful answers here, I was missing this kind of solution, so I had to find my own; and it might be helpful to another person coming to this thread, so here it goes:

```<code>            lda #<end
            sta $FD
            lda #>end
            sta $FE
            lda #<start
            sta $FB
            lda #>start
            sta $FC
rnd:
            //reseed, to avoid repeated sequence; RND(0)
            lda #00
            jsr $E09A
            //++end
            inc $FD
            bne skip1
            inc $FE
skip1:
            //- start
            lda $FD
            sec
            sbc $FB
            sta $FD
            lda $FE
            sbc $FC
            sta $FE

            //++end-start to FAC
            ldy $FD
            lda $FE
            jsr $B391 //A(h),Y(L) - FAC
            ldx #<flt
            ldy #>flt
            jsr $BBD4   //store FAC to flt
            //get actual RND(1)
            lda #$7f
            jsr $E09A
            //multiply by ++end - start
            lda #<flt
            ldy #>flt
            jsr $BA28
            //to integer
            jsr $BCCC
            //FAC to int;
            jsr $B1BF
            lda $65
            clc
            adc $FB
            sta $14
            lda $64
            adc $FC
            sta $15
            rts
flt:        .byte 0,0,0,0,0
</code>```

The routine works with 16 bit numbers in range 0 - 32767. Arguments start in 251,252; end in 253, 254.
16 bit result found in $14.

Body:
Trying to generate a series of random numbers on my Commodore 64 (C64) using JSR $E09A and retrieving the number from $63 and $64. (which according to all the documentation I've seen is the same routine when you use RND(0) from BASIC. But can't get it to iterate. The following will work and place a different number in $63 and $64 when executed by itself.

. C000  A5 00    LDA $00
. C002  20 9A E0 JSR $E09A
. C005  00       BRK

Now when I try to iterate say 10 times with the following code, it never returns.

. C000  A0 0A    LDY #$0A
. C002  A9 00    LDA #$00
. C004  20 9A E0 JSR $E09A
. C007  88       DEY
. C008  D0 F8    BNE $C002
. C00A  00       BRK

Am I missing something so obvious I can't see it. I'm not worried about how "random" it is. At this point I just want a series of random numbers.

Body:
I found this thread searching for more general RND(start, end) routine in C64 assembly. Something implemented as this BASIC example:

INT(RND(1) * (end- start + 1)) + start

While there are many helpful answers here, I was missing this kind of solution, so I had to find my own; and it might be helpful to another person coming to this thread, so here it goes:

            lda #<end
            sta $FD
            lda #>end
            sta $FE
            lda #<start
            sta $FB
            lda #>start
            sta $FC
rnd:
            //reseed, to avoid repeated sequence; RND(0)
            lda #00
            jsr $E09A
            //++end
            inc $FD
            bne skip1
            inc $FE
skip1:
            //- start
            lda $FD
            sec
            sbc $FB
            sta $FD
            lda $FE
            sbc $FC
            sta $FE

            //++end-start to FAC
            ldy $FD
            lda $FE
            jsr $B391 //A(h),Y(L) - FAC
            ldx #<flt
            ldy #>flt
            jsr $BBD4   //store FAC to flt
            //get actual RND(1)
            lda #$7f
            jsr $E09A
            //multiply by ++end - start
            lda #<flt
            ldy #>flt
            jsr $BA28
            //to integer
            jsr $BCCC
            //FAC to int;
            jsr $B1BF
            lda $65
            clc
            adc $FB
            sta $14
            lda $64
            adc $FC
            sta $15
            rts
flt:        .byte 0,0,0,0,0

The routine works with 16 bit numbers in range 0 - 32767. Arguments start in 251,252; end in 253, 254.
16 bit result found in $14.


问:
How can I append div on click?
Lets say I have this div

```<code>        <div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
</code>```

and this button

```<code><button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button" id="add_place">
    <i class="fa fa-plus"></i>
</button>
</code>```

How can I actually append this entire div after itself by clicking on this button?

Entire structure of my code looks like:

```<code>        <div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
        <button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button"
                id="add_place">
            <i class="fa fa-plus"></i>
        </button>
</code>```

答:
Step 1 : try to wrap this with a div of specific id.

```<code><div id="newrow">
    <div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
</div>
</code>```

Step 2 : Create a variable in jquery and assign the element what you want to append.
Example:

```<code>var element = "<div> New Div Appending</div>"
</code>```

Step3: Jquery to append to wrapped div.

```<code>$("#newrow").append(element)
</code>```

Title: How can I append div on click?

Body:
Lets say I have this div

                Region
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">

                District
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">

                Town
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">

and this button

<button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button" id="add_place">

</button>

How can I actually append this entire div after itself by clicking on this button?

Entire structure of my code looks like:

                Region
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">

                District
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">

                Town
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">

        <button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button"
                id="add_place">

        </button>

Body:
Step 1 : try to wrap this with a div of specific id.

<div id="newrow">
    <div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
</div>

Step 2 : Create a variable in jquery and assign the element what you want to append.
Example:

var element = "<div> New Div Appending</div>"

Step3: Jquery to append to wrapped div.

$("#newrow").append(element)


问:
How to correctly replace data in text files based on input
I have the following problem. Im trying to replace the name based on the input of gender. If anyone could help improve my code it would be really appreciated.

The text file(duedate.txt):

User: Tommy

Gender: Male

Date due: 2020-02-18

The code I have so far is:

```<code>with open f = ('duedate.txt).read()
    z = input("Please select gender to change)
    zz = input("Please select new name")
    if z == 'female'
       line.startswith('User'):
       field, value = line.split(:)
       value = zz
       print (zz)
</code>```

I know the code isn't 100% right but the output, if Jessica was chosen as the name, should be:

User: Jessica

Gender: Female

Date due: 2020-02-18

答:
This should work. Code explanation is given in the comments:</p>

```<code>
import pandas as pd
import numpy as np

# Read the text file into a dataframe
df = pd.read_csv('duedate.txt', sep = "\n",header=None)

# Do dataframe manipulations
df[['Variable','Value']] = df[0].str.split(':',expand=True)
del df[0]

# Collect inputs from user:
z = input("Please select gender to change")
zz = input("Please select new name")

# modify dataframe based on user inputs
df.loc[0,"Value"]=zz
df.loc[1,"Value"]=z

#Construct output column
df["Output"] = df["Variable"] + ": " + df["Value"] + "\n"

# Save the file back to disk
np.savetxt(r'duedate.txt', df["Output"].values,fmt='%s')
</code>```

Body:
I have the following problem. Im trying to replace the name based on the input of gender. If anyone could help improve my code it would be really appreciated.

The text file(duedate.txt):

User: Tommy

Gender: Male

Date due: 2020-02-18

The code I have so far is:

with open f = ('duedate.txt).read()
    z = input("Please select gender to change)
    zz = input("Please select new name")
    if z == 'female'
       line.startswith('User'):
       field, value = line.split(:)
       value = zz
       print (zz)

I know the code isn't 100% right but the output, if Jessica was chosen as the name, should be:

User: Jessica

Gender: Female

Date due: 2020-02-18

Body:
This should work. Code explanation is given in the comments:

import pandas as pd
import numpy as np

# Read the text file into a dataframe
df = pd.read_csv('duedate.txt', sep = "\n",header=None)

# Do dataframe manipulations
df[['Variable','Value']] = df[0].str.split(':',expand=True)
del df[0]

# Collect inputs from user:
z = input("Please select gender to change")
zz = input("Please select new name")

# modify dataframe based on user inputs
df.loc[0,"Value"]=zz
df.loc[1,"Value"]=z

#Construct output column
df["Output"] = df["Variable"] + ": " + df["Value"] + "\n"

# Save the file back to disk
np.savetxt(r'duedate.txt', df["Output"].values,fmt='%s')


问:
ASP.NET MVC - is it okay to have sideline presentation logic?
In most documentation you read about ASP.NET MVC, the entire 'Separation of Concerns' is very heavily pushed. Dependency Injection/Inversion of Control, Unit Testing, keeping 'logic' out of the Views, etc.

But how far is this intended to be pushed? Is it bad practice if a specific task requires extra logic beyond the 'three layer' approach of View/Model/Persistence?

For example, I have a solution set up with four individual projects.

```<code>Project.Web (ASP.NET MVC) [ References Data.dll, Models.dll ]
Project.Data (Fluent nHibernate Mapping) [ References Models.dll ]
Project.Models (POCO, Helpers, Factories, etc)
Project.Tests (Unit Testing)
</code>```

Up until now, this has served me pretty well. But I require some very abstract logic for some of my MVC Views, such that I need to take part of the Models and arrange a View Model that is persisted in the database.

This cannot happen in my Data section, as that would dispose the re-usability of it, and there is business logic included in the process. It cannot entirely happen in my Models section, because that would require it to have knowledge of the Data section, which it does not. And I do not want to put it in the Web section because I don't want data access code there.

Question

Is it in massive violation for me to add, say, a Project.Presentation project that references Data.dll and Models.dll to construct what I need to? Moreover project concerns aside, is this a bad approach in general or is this something a lot of you find yourselves having to do at times? Part of me feels that if I am having to resort to this, then I've just built my software wrong - but at the same time I am very confident I have done a fairly good job, it is just too abstract to make a raw HTML interpretation of without middle-man arrangement.

答:
"take part of the Models and arrange a View Model that is persisted in the database"

Then its not a viewmodel.

Does that simplify things?

ContentLicense: CC BY-SA 3.0

Body:
In most documentation you read about ASP.NET MVC, the entire 'Separation of Concerns' is very heavily pushed. Dependency Injection/Inversion of Control, Unit Testing, keeping 'logic' out of the Views, etc.

But how far is this intended to be pushed? Is it bad practice if a specific task requires extra logic beyond the 'three layer' approach of View/Model/Persistence?

For example, I have a solution set up with four individual projects.

Project.Web (ASP.NET MVC) [ References Data.dll, Models.dll ]
Project.Data (Fluent nHibernate Mapping) [ References Models.dll ]
Project.Models (POCO, Helpers, Factories, etc)
Project.Tests (Unit Testing)

Up until now, this has served me pretty well. But I require some very abstract logic for some of my MVC Views, such that I need to take part of the Models and arrange a View Model that is persisted in the database.

This cannot happen in my Data section, as that would dispose the re-usability of it, and there is business logic included in the process. It cannot entirely happen in my Models section, because that would require it to have knowledge of the Data section, which it does not. And I do not want to put it in the Web section because I don't want data access code there.

Question

Is it in massive violation for me to add, say, a Project.Presentation project that references Data.dll and Models.dll to construct what I need to? Moreover project concerns aside, is this a bad approach in general or is this something a lot of you find yourselves having to do at times? Part of me feels that if I am having to resort to this, then I've just built my software wrong - but at the same time I am very confident I have done a fairly good job, it is just too abstract to make a raw HTML interpretation of without middle-man arrangement.


问:
Interfacing with QEMU edu device via Userspace I/O (UIO) Linux driver
I'm looking at QEMU's edu device (source) which provides a basic "educational" PCI device within QEMU, that can be accessed as a PCI device from within a QEMU guest like Linux.

I have been trying to get this to work with the UIO driver (Userspace I/O) via the UIO PCI generic driver, as an exercise to better understand PCI devices in both QEMU and Linux.

My overall goal is to implement a Linux driver for an FPGA. The FPGA is connected to an ARM Cortex-A53 CPU as a PCI-E device, providing several distinct blocks of memory that will be treated as registers for device configuration. I'm using an x86_64 QEMU initially to become familiar with PCI drivers and hopefully UIO. Note: vfio has been suggested to me however I believe this relies on IOMMU support which I'm not sure exists on my target platform.

I'm having some trouble with the memory region mapping. The UIO PCI driver is (I think) meant to create entries in /sys/class/uio/uio0/map for each addressable region, however from what I can tell, there are no regions being automatically detected or set up when the UIO driver is bound to the edu device.

I'm starting my freshly compiled QEMU (./configure --target-list=x86_64-softmmu) with a yocto-generated "fairly standard" Linux 4.9 x86_64 distro:

```<code>$ ./x86_64-softmmu/qemu-system-x86_64 --device edu -m 512 -nographic -serial mon:stdio -append 'console=ttyS0 root=/dev/hda' -kernel bzImage -hda image-qemu.ext3
</code>```

Then within the guest, the edu PCI device is detected:

```<code># lspci
00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]
00:01.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 03)
00:02.0 VGA compatible controller: Device 1234:1111 (rev 02)
00:03.0 Ethernet controller: Intel Corporation 82540EM Gigabit Ethernet Controller (rev 03)
00:04.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
</code>```

Loading the uio_pci_generic module and binding it to the edu device:

```<code># modprobe uio_pci_generic
# echo "1234 11e8" > /sys/bus/pci/drivers/uio_pci_generic/new_id

# ls -l /sys/bus/pci/devices/0000\:00\:04.0/driver
lrwxrwxrwx 1 root root 0 Mar 15 01:50 /sys/bus/pci/devices/0000:00:04.0/driver -> ../../../bus/pci/drivers/uio_pci_generic
</code>```

Taking a closer look at the device, noting the memory address fea00000:

```<code># lspci -v -s 00:04.0
00:04.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
Subsystem: Red Hat, Inc Device 1100
Flags: fast devsel, IRQ 10
Memory at fea00000 (32-bit, non-prefetchable) [size=1M]
Capabilities: [40] MSI: Enable- Count=1/1 Maskable- 64bit+
Kernel driver in use: uio_pci_generic
</code>```

I built lsuio from source:

```<code># ./lsuio -m -v
uio0: name=uio_pci_generic, version=0.01.0, events=0
Device attributes:
vendor=0x1234
uevent=DRIVER=uio_pci_generic
subsystem_vendor=0x1af4
subsystem_device=0x1100
resource=0x00000000fea00000 0x00000000feafffff 0x0000000000040200
msi_bus=1
modalias=pci:v00001234d000011E8sv00001AF4sd00001100bc00scFFi00
local_cpus=1
local_cpulist=0
irq=10
enable=1
driver_override=(null)
dma_mask_bits=32
device=0x11e8
d3cold_allowed=0
consistent_dma_mask_bits=32
config=4è
class=0x00ff00
broken_parity_status=0

# ls /sys/class/uio/uio0/ -l
total 0
-r--r--r-- 1 root root 4096 Mar 15 01:53 dev
lrwxrwxrwx 1 root root    0 Mar 15 01:53 device -> ../../../0000:00:04.0
-r--r--r-- 1 root root 4096 Mar 15 01:53 event
-r--r--r-- 1 root root 4096 Mar 15 01:53 name
drwxr-xr-x 2 root root    0 Mar 15 01:53 power
lrwxrwxrwx 1 root root    0 Mar 15 01:53 subsystem -> ../../../../../class/uio
-rw-r--r-- 1 root root 4096 Mar 15 01:22 uevent
-r--r--r-- 1 root root 4096 Mar 15 01:53 version
</code>```

According to this, there should be a mappable region starting at 0xfea00000 I think, but no "map" directory appears and I haven't been able to work out why. Attempting to access /dev/uio0 (read or mmap) results in Error 22: "Invalid argument". Opening the file and scanning to the end shows that the block device has zero size.

Firstly, do I need to manually create these region mappings, or should the UIO driver be setting these up automatically? Does the edu device need to do something extra to make this happen?

Secondly, are there other QEMU PCI devices that are known to work with UIO? Ideally something with a working Linux driver so I can try to understand both the QEMU device side and the corresponding Linux driver side.

On that last note, is anyone aware of a working Linux driver for the edu device?

答:
To add to OP answer, it seems that /dev/uio0 is used for receiving and counting interrupts on uio_pci_generic module.

An example code of using uio_pci_generic shows this:

uiofd = open("/dev/uio0", O_RDONLY);
...
/* Wait for next interrupt. */
err = read(uiofd, &icount, 4);
```

<p><code>icount</code> is the number of interrupts received.</p>

<p>When using qemu's <code>edu</code> device, you can use <code>resource0</code> to access the mapped IO, and use <code>/dev/uio0</code> to wait for an interrupt.  </p>

<p>Here is a user-space example (extension of the example code above) of using <code>uio_pci_generic</code> to write and read the "card liveness check" of <code>edu</code> device that inverts the input, and to trigger <code>edu</code> interrupts by writing to "interrupt raise register":</p>

<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdint.h>
#include <sys/mman.h>

#define EDU_IO_SIZE 0x100
#define EDU_CARD_VERSION_ADDR  0x0
#define EDU_CARD_LIVENESS_ADDR 0x1
#define EDU_RAISE_INT_ADDR 0x18
#define EDU_CLEAR_INT_ADDR 0x19

int main()
{
    int uiofd;
    int configfd;
    int bar0fd;
    int resetfd;
    int err;
    int i;
    unsigned icount;
    unsigned char command_high;
    volatile uint32_t *bar0;

    uiofd = open("/dev/uio0", O_RDWR);
    if (uiofd < 0) {
        perror("uio open:");
        return errno;
    }

    configfd = open("/sys/class/uio/uio0/device/config", O_RDWR);
    if (configfd < 0) {
        perror("config open:");
        return errno;
    }

    /* Read and cache command value */
    err = pread(configfd, &command_high, 1, 5);
    if (err != 1) {
        perror("command config read:");
        return errno;
    }
    command_high &= ~0x4;

    /* Map edu's MMIO */
    bar0fd = open("/sys/class/uio/uio0/device/resource0", O_RDWR);
    if (bar0fd < 0) {
        perror("bar0fd open:");
        return errno;
    }

    /* mmap the device's BAR */
    bar0 = (volatile uint32_t *)mmap(NULL, EDU_IO_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, bar0fd, 0);
    if (bar0 == MAP_FAILED) {
        perror("Error mapping bar0!");
        return errno;
    }
    fprintf(stdout, "Version = %08X\n", bar0[EDU_CARD_VERSION_ADDR]);

    /* Test the invertor function */
    i = 0x12345678;
    bar0[EDU_CARD_LIVENESS_ADDR] = i;
    fprintf(stdout, "Inversion: %08X --> %08X\n", i, bar0[EDU_CARD_LIVENESS_ADDR]);

    /* Clear previous interrupt */
    bar0[EDU_CLEAR_INT_ADDR] = 0xABCDABCD;

    /* Raise an interrupt */
    bar0[EDU_RAISE_INT_ADDR] = 0xABCDABCD;

    for(i = 0;; ++i) {
        /* Print out a message, for debugging. */
        if (i == 0)
            fprintf(stderr, "Started uio test driver.\n");
        else
            fprintf(stderr, "Interrupts: %d\n", icount);

        /****************************************/
        /* Here we got an interrupt from the
           device. Do something to it. */
        /****************************************/

        /* Re-enable interrupts. */
        err = pwrite(configfd, &command_high, 1, 5);
        if (err != 1) {
            perror("config write:");
            break;
        }

        /* Clear previous interrupt */
        bar0[EDU_CLEAR_INT_ADDR] = 0xABCDABCD;

        /* Raise an interrupt */
        bar0[EDU_RAISE_INT_ADDR] = 0xABCDABCD;

        /* Wait for next interrupt. */
        err = read(uiofd, &icount, 4);
        if (err != 4) {
            perror("uio read:");
            break;
        }

    }
    return errno;
}

</code>```

The result looks something like this:

```<code>Version = 010000ED
Inversion: 12345678 --> EDCBA987
Started uio test driver.
Interrupts: 3793548
Interrupts: 3793549
Interrupts: 3793550
Interrupts: 3793551
Interrupts: 3793552
Interrupts: 3793553
Interrupts: 3793554
Interrupts: 3793555
Interrupts: 3793556
...
</code>```

Body:
I'm looking at QEMU's edu device (source) which provides a basic "educational" PCI device within QEMU, that can be accessed as a PCI device from within a QEMU guest like Linux.

I have been trying to get this to work with the UIO driver (Userspace I/O) via the UIO PCI generic driver, as an exercise to better understand PCI devices in both QEMU and Linux.

My overall goal is to implement a Linux driver for an FPGA. The FPGA is connected to an ARM Cortex-A53 CPU as a PCI-E device, providing several distinct blocks of memory that will be treated as registers for device configuration. I'm using an x86_64 QEMU initially to become familiar with PCI drivers and hopefully UIO. Note: vfio has been suggested to me however I believe this relies on IOMMU support which I'm not sure exists on my target platform.

I'm having some trouble with the memory region mapping. The UIO PCI driver is (I think) meant to create entries in /sys/class/uio/uio0/map for each addressable region, however from what I can tell, there are no regions being automatically detected or set up when the UIO driver is bound to the edu device.

I'm starting my freshly compiled QEMU (./configure --target-list=x86_64-softmmu) with a yocto-generated "fairly standard" Linux 4.9 x86_64 distro:

$ ./x86_64-softmmu/qemu-system-x86_64 --device edu -m 512 -nographic -serial mon:stdio -append 'console=ttyS0 root=/dev/hda' -kernel bzImage -hda image-qemu.ext3

Then within the guest, the edu PCI device is detected:

# lspci
00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]
00:01.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 03)
00:02.0 VGA compatible controller: Device 1234:1111 (rev 02)
00:03.0 Ethernet controller: Intel Corporation 82540EM Gigabit Ethernet Controller (rev 03)
00:04.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)

Loading the uio_pci_generic module and binding it to the edu device:

# modprobe uio_pci_generic
# echo "1234 11e8" > /sys/bus/pci/drivers/uio_pci_generic/new_id

# ls -l /sys/bus/pci/devices/0000\:00\:04.0/driver
lrwxrwxrwx 1 root root 0 Mar 15 01:50 /sys/bus/pci/devices/0000:00:04.0/driver -> ../../../bus/pci/drivers/uio_pci_generic

Taking a closer look at the device, noting the memory address fea00000:

# lspci -v -s 00:04.0
00:04.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
Subsystem: Red Hat, Inc Device 1100
Flags: fast devsel, IRQ 10
Memory at fea00000 (32-bit, non-prefetchable) [size=1M]
Capabilities: [40] MSI: Enable- Count=1/1 Maskable- 64bit+
Kernel driver in use: uio_pci_generic

I built lsuio from source:

# ./lsuio -m -v
uio0: name=uio_pci_generic, version=0.01.0, events=0
Device attributes:
vendor=0x1234
uevent=DRIVER=uio_pci_generic
subsystem_vendor=0x1af4
subsystem_device=0x1100
resource=0x00000000fea00000 0x00000000feafffff 0x0000000000040200
msi_bus=1
modalias=pci:v00001234d000011E8sv00001AF4sd00001100bc00scFFi00
local_cpus=1
local_cpulist=0
irq=10
enable=1
driver_override=(null)
dma_mask_bits=32
device=0x11e8
d3cold_allowed=0
consistent_dma_mask_bits=32
config=4è
class=0x00ff00
broken_parity_status=0

# ls /sys/class/uio/uio0/ -l
total 0
-r--r--r-- 1 root root 4096 Mar 15 01:53 dev
lrwxrwxrwx 1 root root    0 Mar 15 01:53 device -> ../../../0000:00:04.0
-r--r--r-- 1 root root 4096 Mar 15 01:53 event
-r--r--r-- 1 root root 4096 Mar 15 01:53 name
drwxr-xr-x 2 root root    0 Mar 15 01:53 power
lrwxrwxrwx 1 root root    0 Mar 15 01:53 subsystem -> ../../../../../class/uio
-rw-r--r-- 1 root root 4096 Mar 15 01:22 uevent
-r--r--r-- 1 root root 4096 Mar 15 01:53 version

According to this, there should be a mappable region starting at 0xfea00000 I think, but no "map" directory appears and I haven't been able to work out why. Attempting to access /dev/uio0 (read or mmap) results in Error 22: "Invalid argument". Opening the file and scanning to the end shows that the block device has zero size.

Firstly, do I need to manually create these region mappings, or should the UIO driver be setting these up automatically? Does the edu device need to do something extra to make this happen?

Secondly, are there other QEMU PCI devices that are known to work with UIO? Ideally something with a working Linux driver so I can try to understand both the QEMU device side and the corresponding Linux driver side.

On that last note, is anyone aware of a working Linux driver for the edu device?

Body:
To add to OP answer, it seems that /dev/uio0 is used for receiving and counting interrupts on uio_pci_generic module.

An example code of using uio_pci_generic shows this:

uiofd = open("/dev/uio0", O_RDONLY);
...
/* Wait for next interrupt. */
err = read(uiofd, &icount, 4);

icount is the number of interrupts received.

When using qemu's edu device, you can use resource0 to access the mapped IO, and use /dev/uio0 to wait for an interrupt.

Here is a user-space example (extension of the example code above) of using uio_pci_generic to write and read the "card liveness check" of edu device that inverts the input, and to trigger edu interrupts by writing to "interrupt raise register":

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdint.h>
#include <sys/mman.h>

#define EDU_IO_SIZE 0x100
#define EDU_CARD_VERSION_ADDR  0x0
#define EDU_CARD_LIVENESS_ADDR 0x1
#define EDU_RAISE_INT_ADDR 0x18
#define EDU_CLEAR_INT_ADDR 0x19

int main()
{
    int uiofd;
    int configfd;
    int bar0fd;
    int resetfd;
    int err;
    int i;
    unsigned icount;
    unsigned char command_high;
    volatile uint32_t *bar0;

    uiofd = open("/dev/uio0", O_RDWR);
    if (uiofd < 0) {
        perror("uio open:");
        return errno;
    }

    configfd = open("/sys/class/uio/uio0/device/config", O_RDWR);
    if (configfd < 0) {
        perror("config open:");
        return errno;
    }

    /* Read and cache command value */
    err = pread(configfd, &command_high, 1, 5);
    if (err != 1) {
        perror("command config read:");
        return errno;
    }
    command_high &= ~0x4;

    /* Map edu's MMIO */
    bar0fd = open("/sys/class/uio/uio0/device/resource0", O_RDWR);
    if (bar0fd < 0) {
        perror("bar0fd open:");
        return errno;
    }

    /* mmap the device's BAR */
    bar0 = (volatile uint32_t *)mmap(NULL, EDU_IO_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, bar0fd, 0);
    if (bar0 == MAP_FAILED) {
        perror("Error mapping bar0!");
        return errno;
    }
    fprintf(stdout, "Version = %08X\n", bar0[EDU_CARD_VERSION_ADDR]);

    /* Test the invertor function */
    i = 0x12345678;
    bar0[EDU_CARD_LIVENESS_ADDR] = i;
    fprintf(stdout, "Inversion: %08X --> %08X\n", i, bar0[EDU_CARD_LIVENESS_ADDR]);

    /* Clear previous interrupt */
    bar0[EDU_CLEAR_INT_ADDR] = 0xABCDABCD;

    /* Raise an interrupt */
    bar0[EDU_RAISE_INT_ADDR] = 0xABCDABCD;

    for(i = 0;; ++i) {
        /* Print out a message, for debugging. */
        if (i == 0)
            fprintf(stderr, "Started uio test driver.\n");
        else
            fprintf(stderr, "Interrupts: %d\n", icount);

        /****************************************/
        /* Here we got an interrupt from the
           device. Do something to it. */
        /****************************************/

        /* Re-enable interrupts. */
        err = pwrite(configfd, &command_high, 1, 5);
        if (err != 1) {
            perror("config write:");
            break;
        }

        /* Clear previous interrupt */
        bar0[EDU_CLEAR_INT_ADDR] = 0xABCDABCD;

        /* Raise an interrupt */
        bar0[EDU_RAISE_INT_ADDR] = 0xABCDABCD;

        /* Wait for next interrupt. */
        err = read(uiofd, &icount, 4);
        if (err != 4) {
            perror("uio read:");
            break;
        }

    }
    return errno;
}

The result looks something like this:

Version = 010000ED
Inversion: 12345678 --> EDCBA987
Started uio test driver.
Interrupts: 3793548
Interrupts: 3793549
Interrupts: 3793550
Interrupts: 3793551
Interrupts: 3793552
Interrupts: 3793553
Interrupts: 3793554
Interrupts: 3793555
Interrupts: 3793556
...


问:
How to create a X window to perform another program or Set one window alway on top
I get 2 independent programs (A & B) on Linux Redhat, developed by Motif toolkit based on X window.
These 2 programs all have there own human-machine-interface.
and there come the questions:
When displaying these 2 programs on the same desktop, how can i set one program's interface alway on the top-level? the current situation is when i run them on the same desktop, and i click on program A(fullscreen), the program B(one small window) will lower down behind the program A and cannot be seen unless using alt+Tab to change between them, which is unacceptable.

I want to display program B always on the top-level when click program A, it would not lower down.
Or can i set the program B display on one window insert into program A? if it is possible, how to realize it on Motif X window? using motif x window in one program to display another program's interface.

Looking forward to ur advice, even i know there are few people still using Motif as a toolkit to build an interface. but it is too hard to rebuild the whole program which is an industrial-grade product.

答:
You can programmatically make sure your window is on top by calling

```<code>XRaiseWindow(XtDisplay(toplevel), XtWindow(toplevel));
</code>```

(Assuming toplevel is your toplevel widget).

Whether this stays on top forever is most probably controlled by the window manager.  If that happens to be mwm, the you can try to call

```<code>XtVaSetValues(toplevel, XmNmwmInputMode, MWM_INPUT_SYSTEM_MODAL, NULL);
</code>```

Body:
You can programmatically make sure your window is on top by calling

XRaiseWindow(XtDisplay(toplevel), XtWindow(toplevel));

(Assuming toplevel is your toplevel widget).

Whether this stays on top forever is most probably controlled by the window manager.  If that happens to be mwm, the you can try to call

XtVaSetValues(toplevel, XmNmwmInputMode, MWM_INPUT_SYSTEM_MODAL, NULL);


问:
How can CoroutineScope(job+Dispatchers.Main) run on the main/UI thread?
If the operations inside CoroutineScope(job+Dispatchers.Main){...} run on the main thread then how come it does not violate Android's requirement that slow (blocking) operations (Networking etc.) are not allowed to run on the main/UI thread? I can run blocking operations with this scope and the UI does not freeze at all.

I would be grateful if someone could explain what is happening under the hood. My guess is that it is similar to how JavaScript manages blocking operations with the event loop, but I struggle to find any relevant materials.

答:
My guess is that it is similar to how JavaScript manages blocking operations with the event loop

Yes, this is correct, the event loop is essential to making coroutines work. Basically, when you write this:

```<code>uiScope.launch {
    delay(1000)
    println("A second has passed")
}
</code>```

it compiles into code that has the same effect as this:

```<code>Handler(Looper.mainLooper()).postDelayed(1000) { println("A second has passed") }
</code>```

The main concept is the continuation, an object  that implements a state machine that corresponds to the sequential code you wrote in a suspendable function. When you call delay or any other suspendable function, the continuation's entry-point method returns a special COROUTINE_SUSPENDED value. Later on, when some outside code comes up with the return value of the suspendable function, it must call continuation.resume(result). This call will be intercepted by the dispatcher in charge, which will post this call as an event on the GUI event loop. When the event handler is dequeued and executed, you are back inside the state machine which figures out where to resume the execution.

You can review this answer for a more fleshed-out example of using the Continuation API.

Body:
My guess is that it is similar to how JavaScript manages blocking operations with the event loop

Yes, this is correct, the event loop is essential to making coroutines work. Basically, when you write this:

uiScope.launch {
    delay(1000)
    println("A second has passed")
}

it compiles into code that has the same effect as this:

Handler(Looper.mainLooper()).postDelayed(1000) { println("A second has passed") }

The main concept is the continuation, an object  that implements a state machine that corresponds to the sequential code you wrote in a suspendable function. When you call delay or any other suspendable function, the continuation's entry-point method returns a special COROUTINE_SUSPENDED value. Later on, when some outside code comes up with the return value of the suspendable function, it must call continuation.resume(result). This call will be intercepted by the dispatcher in charge, which will post this call as an event on the GUI event loop. When the event handler is dequeued and executed, you are back inside the state machine which figures out where to resume the execution.

You can review this answer for a more fleshed-out example of using the Continuation API.


问:
How do I set permissions on dynamically linked files?
I have an InstallScript installer that utilizes dynamic file links for several components. These components contain configuration files that standard users should be able to edit. We recently discovered that when these files are installed on Windows Server 08, the permissions are set to full access for the Administrators group, but only read & execute access for the Users group.  The typical install location is C:\programName.

I've tried creating new files manually as an admin (right click - new text file) in the C:\programName directory, and they are generated with identical permissions. I'm assuming that this is just the standard permission setup for new files.

Is there any way, within InstallShield, to set the permissions for dynamically linked files or the directory containing them?

I've looked for permission settings in

Organization -> Components

Application Data -> Files and Folders

but I haven't found anything. The documentation on dynamic file links makes no mention of permissions.

We are using InstallShield 2010.

答:
Generally these permissions are a good thing; they're inherited from their parent folders. Non-administrator users (including the limited access admin before accepting a UAC prompt) should be unable to modify files under Program Files or C: so I would suggest addressing this concern in your application (for instance by using each user's Documents folder). Since you don't talk about why you need it, it's hard to say with certainty if this applies to your case.

If it turns out it does make sense to address this in the installation instead of the application, you can use the SetObjectPermissions API to set permissions programmatically.


问:
Set specific Maven dependency to latest release during local development
Given that I have the following dependency for my multi-module CI:

```<code><groupId>my_group</groupId>
<artifactId>artifact1</artifactId>
<version>2.0.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>my_group</groupId>
        <artifactId>artifact2</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>
</code>```

On my CI I want to compile artifact 2. However, on my dev I rarely touch it and since compilation of that artifact requires some external dependencies and significant time I would very much like to skip it and use whatever latest release exists.

Up until now I had a profile that overrode artifact2 version with RELEASE, e.g.:

        use-released-artifact2

                    my_group
                    artifact2
                    RELEASE

and locally I would run with -Puse-released-artifact2. Great.

Now maven3 deprecates RELEASE and LATEST pseudo-versions and I'm trying to find a solution that:

doesn't leave modified pom.xml files to be identified as "modified" by git. in the past that led to developer inadvertently committing the wrong file. for the same reason I can't just add ignore to this file.

doesn't require the developer to follow the release schedule and substitute parameters in their "mvn clean install..." line.

doesn't go through lengthy resolution as version ranges do.

doesn't force me to commit a version on every release (besides version plugin doesn't support advancing to version "next-1" afaik).

any ideas?

Clarification:

I don't want to run artifcat2 build at all. Moreover, artifact2 isn't available at 2.0.0-SNAPSHOT in the repository as it has not been released yet. I really want to take the latest release (e.g. 1.5.7) from the repository to compile artifact1 against that.

答:
My advice would be as follows.

Check out the whole multi-module project.

Build all the modules once.

Then, use a flag (as described here) to only build artifact1 for each subsequent build.

So the first build will take some time, but afterwards you only need to build artifact1 and the SNAPSHOT for artifact2 will be readily available in your local repository.

Of course, with this approach you use the latest version of artifact2, not the latest release version, but in practise, this should not matter to much.

Body:
Given that I have the following dependency for my multi-module CI:

<groupId>my_group</groupId>
<artifactId>artifact1</artifactId>
<version>2.0.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>my_group</groupId>
        <artifactId>artifact2</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

On my CI I want to compile artifact 2. However, on my dev I rarely touch it and since compilation of that artifact requires some external dependencies and significant time I would very much like to skip it and use whatever latest release exists.

Up until now I had a profile that overrode artifact2 version with RELEASE, e.g.:

        use-released-artifact2

                    my_group
                    artifact2
                    RELEASE

and locally I would run with -Puse-released-artifact2. Great.

Now maven3 deprecates RELEASE and LATEST pseudo-versions and I'm trying to find a solution that:

doesn't leave modified pom.xml files to be identified as "modified" by git. in the past that led to developer inadvertently committing the wrong file. for the same reason I can't just add ignore to this file.

doesn't require the developer to follow the release schedule and substitute parameters in their "mvn clean install..." line.

doesn't go through lengthy resolution as version ranges do.

doesn't force me to commit a version on every release (besides version plugin doesn't support advancing to version "next-1" afaik).

any ideas?

Clarification:

I don't want to run artifcat2 build at all. Moreover, artifact2 isn't available at 2.0.0-SNAPSHOT in the repository as it has not been released yet. I really want to take the latest release (e.g. 1.5.7) from the repository to compile artifact1 against that.


问:
Xcode 10 Error: Multiple commands produce

error: Multiple commands produce '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist':
1) Target 'OptimalLive' has copy command from '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Info.plist' to '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist'
2) Target 'OptimalLive' has copy command from '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Server/Masonry/Info.plist' to '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist'
3) Target 'OptimalLive' has process command with input '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Info.plist'

Running the code in Xcode 9 works, but there is an error in Xcode 10.

答:
In my case I had a modified watch project where the app and the extension all had a info.plist files (all named with the same name), to solve this I have renamed the files for the ios app I left it as info.plist for the watch I have named it watch_info.plistand so on
After that I have modified the 'project->target->build settings' under packaging info.pilst and modified the plist file name accordingly, that solved it for me

note that I saw in other places to changed the build system from new to legacy under project/workspace settings, Although it works - I do not recommend this as it causes other issues down the road.


问:
Is there a method to blur a background in SwiftUI?
I'm looking to blur a view's background but don't want to have to break out into UIKit to accomplish it (eg. a UIVisualEffectView) I'm digging through docs and got nowhere, seemingly there is no way to live-clip a background and apply effects to it. Am I wrong or looking into it the wrong way?

答:
The simplest way is here by Richard Mullinix:

```<code>struct Blur: UIViewRepresentable {
    var style: UIBlurEffect.Style = .systemMaterial

    func makeUIView(context: Context) -> UIVisualEffectView {
        return UIVisualEffectView(effect: UIBlurEffect(style: style))
    }

    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
        uiView.effect = UIBlurEffect(style: style)
    }
}
</code>```

Then just use it somewhere in your code like background:

```<code>    //...
    MyView()
        .background(Blur(style: .systemUltraThinMaterial))
</code>```

Body:
The simplest way is here by Richard Mullinix:

struct Blur: UIViewRepresentable {
    var style: UIBlurEffect.Style = .systemMaterial

    func makeUIView(context: Context) -> UIVisualEffectView {
        return UIVisualEffectView(effect: UIBlurEffect(style: style))
    }

    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
        uiView.effect = UIBlurEffect(style: style)
    }
}

Then just use it somewhere in your code like background:

    //...
    MyView()
        .background(Blur(style: .systemUltraThinMaterial))


问:
How to embed or recreate a Google Analytics Graph in a custom CMS
I would like to know how to create a graph with Google Analytics (maybe using the api), but I'm unsure if there is already a plugin or tutorial on how to do this. The Javascript API reference at Google.com sucks.

Also any reference to how to create a line graph (canvas element?) would be great too.

Thanks!

答:
Here is step-by-step guide how to embed Google Analytics chart into a webpage as interactive widget: http://explainum.blogspot.com/2011/04/how-to-add-google-analytics-chart-to.html

EDIT (5/15/2012): The link above goes to a blog post on Explainum -- 3rd party web-service which allows creating embeddable charts from various data sources including (and most popular) Google Analytics.

Connection to GA is made using OAuth. You will need to know your GA profile ID in order to connect. Data is updated every 2-24 hours. The service is free.

DISCLAIMER: I'm one of Explainum's creators.

ContentLicense: CC BY-SA 2.5


问:
C# nettcpbinding disable ntlm
How to disable NTLM when connecting to WCF service?
I want to be sure that Im using Kerberos, but there is no option on ChannelFactory in .netstandard20:

```<code>channelFactory.Credentials.Windows.AllowNtlm = false;
</code>```

So currently Im unable to disable "fallback" to NTLM to check whether Kerberos even working.

答:
This is a deprecated attribute. Kerberos authentication will be used first as long as the server and client environments support Windows Kerberos authentication. If the machine environment on both sides is not supported, whether to downgrade to NTLM certification will be determined by the computer policy.

https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.security.windowsclientcredential.allowntlm?view=netframework-4.8

As the description said.

This property is deprecated and is maintained for backward
  compatibility only. The local machine policy will be used to determine
  if NTLM should be used.

Here are some related links.

https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-restrict-ntlm-ntlm-authentication-in-this-domain

https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-allow-local-system-to-use-computer-identity-for-ntlm

https://developers.de/blogs/damir_dobric/archive/2009/08/16/enabling-of-ntlm-on-windows-7-and-windows-server-2008-r2.aspx

Title: C# nettcpbinding disable ntlm

Body:
How to disable NTLM when connecting to WCF service?
I want to be sure that Im using Kerberos, but there is no option on ChannelFactory in .netstandard20:

channelFactory.Credentials.Windows.AllowNtlm = false;

So currently Im unable to disable "fallback" to NTLM to check whether Kerberos even working.


问:
Imagick Text is Overwriting Each Frames
I've created this imagick php code to create my own images in gif format.
All the code is perfect except one thing. The last text (date) is overwriting the title text. Can someone figure this out?

The result for what i've build is like this

[![enter image description here][1]][1]

This is the code from that

```<code>        ob_clean();
        $text=ucfirst('Title Name');
        $image = new Imagick('1.gif');

        $draw = new ImagickDraw();
        $frameCount = 0;
        foreach($image as $frame){
        $image->setImageDelay((($frameCount % 40) * 40));

        $draw->setGravity (Imagick::GRAVITY_NORTHWEST);
        $draw->setTextAlignment(Imagick::ALIGN_CENTER);

        $imgSize   = $image->getImageGeometry();
        $imgHeight = $imgSize['height'];
        $imgWidth = $imgSize['width'];
        // Calculate size
        $textProperties = array( 'textWidth' => 0 );
        $textDesiredWidth = intval( $imgWidth * 0.9 );

        $defaultFontSize = 25;
        $fontSize = 0;
        $draw->setFillColor('white');
        /* Font properties */
        $draw->setFont('assets/fonts/EX.ttf');
        while ( $textProperties['textWidth'] <= $textDesiredWidth ) {
            $draw->setFontSize( $fontSize );
            $textProperties = $image->queryFontMetrics( $draw, $text );
            $fontSize++;
        }

        if($fontSize>$defaultFontSize){
            $draw->setFontSize( $defaultFontSize );
            $centerY = floor( ($imgHeight) / 3.3 );
        }else{
            $centerY = floor( ($imgHeight) / 3.6 );
        }
        $centerX = intval( ($imgWidth) / 2 );
        $image->annotateImage( $draw, $centerX, $centerY, 0, $text );
</code>```

As you can see that the date ('58 days ago') is overwriting the text "PAYING" from the gif image

anyone can help me figure this out?
thanks

答:
Found the fix.!!

First we need to know the height of images then reverse the Y position

```<code>$imgHeight/1
</code>```

and put in the correct position.

Title: Imagick Text is Overwriting Each Frames

Body:
I've created this imagick php code to create my own images in gif format.
All the code is perfect except one thing. The last text (date) is overwriting the title text. Can someone figure this out?

The result for what i've build is like this

[![enter image description here][1]][1]

This is the code from that

        ob_clean();
        $text=ucfirst('Title Name');
        $image = new Imagick('1.gif');

        $draw = new ImagickDraw();
        $frameCount = 0;
        foreach($image as $frame){
        $image->setImageDelay((($frameCount % 40) * 40));

        $draw->setGravity (Imagick::GRAVITY_NORTHWEST);
        $draw->setTextAlignment(Imagick::ALIGN_CENTER);

        $imgSize   = $image->getImageGeometry();
        $imgHeight = $imgSize['height'];
        $imgWidth = $imgSize['width'];
        // Calculate size
        $textProperties = array( 'textWidth' => 0 );
        $textDesiredWidth = intval( $imgWidth * 0.9 );

        $defaultFontSize = 25;
        $fontSize = 0;
        $draw->setFillColor('white');
        /* Font properties */
        $draw->setFont('assets/fonts/EX.ttf');
        while ( $textProperties['textWidth'] <= $textDesiredWidth ) {
            $draw->setFontSize( $fontSize );
            $textProperties = $image->queryFontMetrics( $draw, $text );
            $fontSize++;
        }

        if($fontSize>$defaultFontSize){
            $draw->setFontSize( $defaultFontSize );
            $centerY = floor( ($imgHeight) / 3.3 );
        }else{
            $centerY = floor( ($imgHeight) / 3.6 );
        }
        $centerX = intval( ($imgWidth) / 2 );
        $image->annotateImage( $draw, $centerX, $centerY, 0, $text );

As you can see that the date ('58 days ago') is overwriting the text "PAYING" from the gif image

anyone can help me figure this out?
thanks

Body:
Found the fix.!!

First we need to know the height of images then reverse the Y position

$imgHeight/1

and put in the correct position.


问:
Count dicts which has same value
I did count dicts which has same value and tried to add result into dict. But the problem is I couldn't remove the duplicated dicts.

```<code>from collections import defaultdict

[
  {"project_name": "apollo"},
  {"project_name": "apollo"}
]
</code>```

for example there are two apollo projects in the list. So I am trying to merge the dicts that has same value. And add the counted result as new key value pair.

expected output be like.

```<code>[
  {
    "project_name": "apollo",
    "count": "2"
  }
]
</code>```

I tried something like below.

```<code>d = defaultdict(int)
for item in conversions:
    key = item['project_name']
    d[key] += 1
    dic["count"] = d[key]
</code>```

But the result is (of course) came out like below.

```<code>[
  {"project_name": "apollo", "count": "1"},
  {"project_name": "apollo", "count": "2"}
]
</code>```

How to manage to count the quantity dicts and merge.

答:
Slightly changed your code and restructured the result:

```<code>from collections import defaultdict

conversions = [
  {"project_name": "apollo"},
  {"project_name": "apollo"},
  {"project_name": "foo"},
  {"project_name": "apollo"}
]

d = defaultdict(int)

for item in conversions:
    key = item['project_name']
    d[key] += 1

res = [{"project_name": k, "count": v} for (k, v) in d.items()]
print(res)
</code>```

Output:

```<code>[{'count': 3, 'project_name': 'apollo'}, {'count': 1, 'project_name': 'foo'}]
</code>```

Title: Count dicts which has same value

Body:
I did count dicts which has same value and tried to add result into dict. But the problem is I couldn't remove the duplicated dicts.

from collections import defaultdict

[
  {"project_name": "apollo"},
  {"project_name": "apollo"}
]

for example there are two apollo projects in the list. So I am trying to merge the dicts that has same value. And add the counted result as new key value pair.

expected output be like.

[
  {
    "project_name": "apollo",
    "count": "2"
  }
]

I tried something like below.

d = defaultdict(int)
for item in conversions:
    key = item['project_name']
    d[key] += 1
    dic["count"] = d[key]

But the result is (of course) came out like below.

[
  {"project_name": "apollo", "count": "1"},
  {"project_name": "apollo", "count": "2"}
]

How to manage to count the quantity dicts and merge.

Body:
Slightly changed your code and restructured the result:

from collections import defaultdict

conversions = [
  {"project_name": "apollo"},
  {"project_name": "apollo"},
  {"project_name": "foo"},
  {"project_name": "apollo"}
]

d = defaultdict(int)

for item in conversions:
    key = item['project_name']
    d[key] += 1

res = [{"project_name": k, "count": v} for (k, v) in d.items()]
print(res)

Output:

[{'count': 3, 'project_name': 'apollo'}, {'count': 1, 'project_name': 'foo'}]


问:
How to do conditional rendering in react with combining components
I am trying to do concatenation just like we do in string in js in react components and want to deliver them like below

```<code><Fragment>

              {score_array.map((ScoreArray, idx) => {
                let _re;
                   if(!ScoreArray.score_childs)
                   {

                    _re+=
                      <Colxx key={idx} sm={6}>

                       <Input
                         type="number"
                         pattern="[0-9]*"
                         inputMode="numeric"
                         className="number_type"
                         placeholder={ScoreArray.score_name}
                         name="score_value"
                         value={ScoreArray.score_value}
                         onChange={this.handleScoreArrayValueChange(idx)}
                       />
                     </Colxx>

                   }

                   else{

                    ScoreArray.score_childs.map((_scorechild,id)=>{
                      _re+=
                        <Colxx key={idx} sm={6}>

                         <Input
                           type="number"
                           pattern="[0-9]*"
                           inputMode="numeric"
                           className="number_type"
                           placeholder={_scorechild.score_name}
                           name="score_value"
                           value={ScoreArray.score_value}
                           onChange={this.handleScoreArrayValueChange(idx)}
                         />
                       </Colxx>

                    })

                   }

               return _re;

              })}
            </Fragment>
</code>```

The array is something like which I am trying to iterate

```<code>let score_array= [
     {
      "score_name": "GMAT",
        "ps_score_id": 200,
        "score_childs":null
      },
      {
        "score_name": "GRE",
        "ps_score_id": 2,
        "score_childs": [
          {
            "score_name": "GRE READ",
            "ps_score_id": 9
          },
          {
            "score_name": "GRE WRITE",
            "ps_score_id": 10
          },
          {
            "score_name": "GRE SPEAK",
            "ps_score_id": 11
          },
          {
            "score_name": "GRE LISTEN",
            "ps_score_id": 12
          }
        ]
      }
    ]
</code>```

I want a structure like

```<code><h1>GMAT</h1>
<input  name="GMAT ">

<h1>GRE</h1>
<input  name="GRE READ ">
<input  name="GRE WRITE ">
<input  name="GRE SPEAK ">
</code>```

Currently its displaying [object] [object] in the dom ,I want a structure as mentioned above ,Any help will be appreciated.Thanks

答:
You don't need to concat components like string, you can just render the array using map directly like this:

```<code><Fragment>
    // for each item
    {score_array.map((ScoreArray, idx) => {
      // if it doesn't have children render it directly
      if (!ScoreArray.score_childs) {
        return <Colxx key={idx} sm={6}>
          <Input
            type="number"
            pattern="[0-9]*"
            inputMode="numeric"
            className="number_type"
            placeholder={ScoreArray.score_name}
            name="score_value"
            value={ScoreArray.score_value}
            onChange={this.handleScoreArrayValueChange(idx)}
          />
        </Colxx>;
      } else {
        // if it has children render all of them one by one
        return ScoreArray.score_childs.map((_scorechild, id) => (
          <Colxx key={id} sm={6}>
            <Input
              type="number"
              pattern="[0-9]*"
              inputMode="numeric"
              className="number_type"
              placeholder={_scorechild.score_name}
              name="score_value"
              value={ScoreArray.score_value}
              onChange={this.handleScoreArrayValueChange(idx)}
            />
          </Colxx>
        ));
      }
    })}
</Fragment>
</code>```

Here's a shorter way which also adds an h1 tag and replaces the if statement with a ternary operator:

```<code>    <Fragment>
      {score_array.map((ScoreArray, idx) => (
        <Fragment>
          <h1>{ScoreArray.score_name}</h1>
          {!ScoreArray.score_childs ? (
            <Colxx key={idx} sm={6}>
              <Input
                type="number"
                pattern="[0-9]*"
                inputMode="numeric"
                className="number_type"
                placeholder={ScoreArray.score_name}
                name="score_value"
                value={ScoreArray.score_value}
                onChange={this.handleScoreArrayValueChange(idx)}
              />
            </Colxx>
          ) : ScoreArray.score_childs.map((_scorechild, id) => (
            <Colxx key={id} sm={6}>
              <Input
                type="number"
                pattern="[0-9]*"
                inputMode="numeric"
                className="number_type"
                placeholder={_scorechild.score_name}
                name="score_value"
                value={ScoreArray.score_value}
                onChange={this.handleScoreArrayValueChange(idx)}
              />
            </Colxx>
          ))}
        </Fragment>
      ))}
    </Fragment>
</code>```

Body:
I am trying to do concatenation just like we do in string in js in react components and want to deliver them like below

<Fragment>

              {score_array.map((ScoreArray, idx) => {
                let _re;
                   if(!ScoreArray.score_childs)
                   {

                    _re+=
                      <Colxx key={idx} sm={6}>

                       <Input
                         type="number"
                         pattern="[0-9]*"
                         inputMode="numeric"
                         className="number_type"
                         placeholder={ScoreArray.score_name}
                         name="score_value"
                         value={ScoreArray.score_value}
                         onChange={this.handleScoreArrayValueChange(idx)}
                       />
                     </Colxx>

                   }

                   else{

                    ScoreArray.score_childs.map((_scorechild,id)=>{
                      _re+=
                        <Colxx key={idx} sm={6}>

                         <Input
                           type="number"
                           pattern="[0-9]*"
                           inputMode="numeric"
                           className="number_type"
                           placeholder={_scorechild.score_name}
                           name="score_value"
                           value={ScoreArray.score_value}
                           onChange={this.handleScoreArrayValueChange(idx)}
                         />
                       </Colxx>

                    })

                   }

               return _re;

              })}
            </Fragment>

The array is something like which I am trying to iterate

let score_array= [
     {
      "score_name": "GMAT",
        "ps_score_id": 200,
        "score_childs":null
      },
      {
        "score_name": "GRE",
        "ps_score_id": 2,
        "score_childs": [
          {
            "score_name": "GRE READ",
            "ps_score_id": 9
          },
          {
            "score_name": "GRE WRITE",
            "ps_score_id": 10
          },
          {
            "score_name": "GRE SPEAK",
            "ps_score_id": 11
          },
          {
            "score_name": "GRE LISTEN",
            "ps_score_id": 12
          }
        ]
      }
    ]

I want a structure like

GMAT

<input  name="GMAT ">

GRE

<input  name="GRE READ ">
<input  name="GRE WRITE ">
<input  name="GRE SPEAK ">

Currently its displaying [object] [object] in the dom ,I want a structure as mentioned above ,Any help will be appreciated.Thanks

Body:
You don't need to concat components like string, you can just render the array using map directly like this:

<Fragment>
    // for each item
    {score_array.map((ScoreArray, idx) => {
      // if it doesn't have children render it directly
      if (!ScoreArray.score_childs) {
        return <Colxx key={idx} sm={6}>
          <Input
            type="number"
            pattern="[0-9]*"
            inputMode="numeric"
            className="number_type"
            placeholder={ScoreArray.score_name}
            name="score_value"
            value={ScoreArray.score_value}
            onChange={this.handleScoreArrayValueChange(idx)}
          />
        </Colxx>;
      } else {
        // if it has children render all of them one by one
        return ScoreArray.score_childs.map((_scorechild, id) => (
          <Colxx key={id} sm={6}>
            <Input
              type="number"
              pattern="[0-9]*"
              inputMode="numeric"
              className="number_type"
              placeholder={_scorechild.score_name}
              name="score_value"
              value={ScoreArray.score_value}
              onChange={this.handleScoreArrayValueChange(idx)}
            />
          </Colxx>
        ));
      }
    })}
</Fragment>

Here's a shorter way which also adds an h1 tag and replaces the if statement with a ternary operator:

    <Fragment>
      {score_array.map((ScoreArray, idx) => (
        <Fragment>
          <h1>{ScoreArray.score_name}</h1>
          {!ScoreArray.score_childs ? (
            <Colxx key={idx} sm={6}>
              <Input
                type="number"
                pattern="[0-9]*"
                inputMode="numeric"
                className="number_type"
                placeholder={ScoreArray.score_name}
                name="score_value"
                value={ScoreArray.score_value}
                onChange={this.handleScoreArrayValueChange(idx)}
              />
            </Colxx>
          ) : ScoreArray.score_childs.map((_scorechild, id) => (
            <Colxx key={id} sm={6}>
              <Input
                type="number"
                pattern="[0-9]*"
                inputMode="numeric"
                className="number_type"
                placeholder={_scorechild.score_name}
                name="score_value"
                value={ScoreArray.score_value}
                onChange={this.handleScoreArrayValueChange(idx)}
              />
            </Colxx>
          ))}
        </Fragment>
      ))}
    </Fragment>


问:
how to set datasource in jsp?
I have datasource.the code is as below:

```<code>public class DataSource {
    Connection connection = null;
    BasicDataSource bdsource = new BasicDataSource();

    public DataSource() {
        bdsource.setDriverClassName("com.mysql.jdbc.Driver");
        bdsource.setUrl("jdbc:mysql://localhost:3306/databaseName");
        bdsource.setUsername("UserName");
        bdsource.setPassword("PassWord");

    }

    public Connection createConnection() {

        Connection con = null;

        try {

            if (connection != null) {
                System.out.println("Can't create a new connection");
            } else {
                con = bdsource.getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return con;
    }
}
</code>```

I need to display some data from database on jsp. So how can i set the the datasource in jsp without letting the world know the username, password and database name in jsp?

答:
Connection class

```<code>    public class ConnectBean {
    private Connection con;
    private static ConnectBean instance;
    private ConnectBean() throws Exception {
        try {
            String driver = "oracle.jdbc.OracleDriver";
            Class.forName(driver).newInstance();
            String url = "jdbc:oracle:thin:@10.0.1.1:1521:base";
            String user = "user";
            String password = "pass";
            con = DriverManager.getConnection(url,user,password);

        }
        catch (ClassNotFoundException e) {
            throw new Exception(e);
        }
        catch (SQLException e) {
            throw new Exception(e);
        }
    }
    public static synchronized  ConnectBean getInstance () throws Exception {
        if (instance == null) {
            instance = new ConnectBean();
        }
        return instance;
    }
    public Connection getConnection() {
        return con;
    }
}
</code>```

JSP page

```<code><%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>

<h2 align="center"><font color="#FF00FF"><strong>Select query in JSP</strong></font></h2>
<table align="center" cellpadding="4" cellspacing="4">
<tr>

</tr>
<tr bgcolor="#008000">
<td><b>Id</b></td>
<td><b>Name</b></td>
</tr>
<%
    Statement stmt = evg.oracle_jta.connection.ConnectBean.getInstance().getConnection().createStatement();
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM your_table");
    out.println("<html><body><h2>The Select query has following results : </h2>");

    while (resultSet.next()) {
        out.println("<tr bgcolor='#8FBC8F'>");
        out.println("<td>"+resultSet.getString("id") + "</td>");
        out.println("<td>"+resultSet.getString("name") + "</td>");
        out.println("</tr>");
    }
%>
</table>
</code>```

Title: how to set datasource in jsp?

Body:
I have datasource.the code is as below:

public class DataSource {
    Connection connection = null;
    BasicDataSource bdsource = new BasicDataSource();

    public DataSource() {
        bdsource.setDriverClassName("com.mysql.jdbc.Driver");
        bdsource.setUrl("jdbc:mysql://localhost:3306/databaseName");
        bdsource.setUsername("UserName");
        bdsource.setPassword("PassWord");

    }

    public Connection createConnection() {

        Connection con = null;

        try {

            if (connection != null) {
                System.out.println("Can't create a new connection");
            } else {
                con = bdsource.getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return con;
    }
}

I need to display some data from database on jsp. So how can i set the the datasource in jsp without letting the world know the username, password and database name in jsp?

Body:
Connection class

    public class ConnectBean {
    private Connection con;
    private static ConnectBean instance;
    private ConnectBean() throws Exception {
        try {
            String driver = "oracle.jdbc.OracleDriver";
            Class.forName(driver).newInstance();
            String url = "jdbc:oracle:thin:@10.0.1.1:1521:base";
            String user = "user";
            String password = "pass";
            con = DriverManager.getConnection(url,user,password);

        }
        catch (ClassNotFoundException e) {
            throw new Exception(e);
        }
        catch (SQLException e) {
            throw new Exception(e);
        }
    }
    public static synchronized  ConnectBean getInstance () throws Exception {
        if (instance == null) {
            instance = new ConnectBean();
        }
        return instance;
    }
    public Connection getConnection() {
        return con;
    }
}

JSP page

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>

<h2 align="center"><font color="#FF00FF"><strong>Select query in JSP</strong></font></h2>
<table align="center" cellpadding="4" cellspacing="4">
<tr>

</tr>
<tr bgcolor="#008000">
<td><b>Id</b></td>
<td><b>Name</b></td>
</tr>
<%
    Statement stmt = evg.oracle_jta.connection.ConnectBean.getInstance().getConnection().createStatement();
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM your_table");
    out.println("<html><body><h2>The Select query has following results : </h2>");

    while (resultSet.next()) {
        out.println("<tr bgcolor='#8FBC8F'>");
        out.println("<td>"+resultSet.getString("id") + "</td>");
        out.println("<td>"+resultSet.getString("name") + "</td>");
        out.println("</tr>");
    }
%>
</table>


问:
Setting navigation between different screens on my app
Hello stackoverflow i develop app in react-native and I completely implement login system. Now my problem is I don't understand how I route between different screens like i have flows e.g signup flow :
1)user enter phone number (verifyPhone screen)
2)user enter confirmation code and enter his data e.g username email etc(verify code screen)
3)user enter login credentials (loginScreen)
4)then user navigate to home screen

i have 4 different flows like signup,signin,signout,forgotpassword

I don't know how I achieve the functionality i try to do it through stacknavigator and switchnavigator but nothing works

my app.js look like :

//app.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform } from 'react-native';
import {createAppContainer,createStackNavigator,createSwitchNavigator} from 'react-navigation';
import MobileCheck from './screens/MobileCheck';
import VerifyCode from './screens/VerifyCode';
import SignUp from './screens/SignUp';
import HomeScreen from './screens/HomeScreen';
import LoginScreen from './screens/LoginScreen';
import ForgotPassword from './screens/ForgotPassword';
//import helper from './helper';

// const authSwitch = createSwitchNavigator ({
//   Home: HomeScreen,
//   stack :  createStackNavigator({
//     MobileCheck : MobileCheck,
//     VerifyCode : VerifyCode,
//     SignUp : SignUp,
//   })

// })
const authSwitch = createStackNavigator({
//   MobileCheck : {
//     screen : MobileCheck
//   },
//   VerifyCode : {
//     screen : VerifyCode
//   },
//  SignUp : {
//     screen : SignUp
//   },
  Login : {
    screen : LoginScreen
  },
  Home : {
    screen : HomeScreen
  },
//   SignUp : {
//     screen : SignUp
//   },
//   MobileCheck : {
//     screen : MobileCheck
//   },
//   VerifyCode : {
//     screen : VerifyCode
//   },
//   ForgotPassword : {
//     screen : ForgotPassword
//   },
    // Help : {
    //     screen : helper
    // },
})
const App = createAppContainer(authSwitch);

// const SignUpStack = createStackNavigator({

// })
// const LoginStack = createStackNavigator({

// })
// const ForgotPasswordStack = createStackNavigator({

// })
// const App = createSwitchNavigator({

// })
export default App;```

答:
Hey Haseeb Javaid

It seems you are using latest react-navigation version 5+
So as per their documentation, you have to create your StackNavigator something like this

```<code>import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;
</code>```

For more information, you can follow this react-navigation documentation

Hope it will help you :)

Thanks!

Body:
Hey Haseeb Javaid

It seems you are using latest react-navigation version 5+
So as per their documentation, you have to create your StackNavigator something like this

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

For more information, you can follow this react-navigation documentation

Hope it will help you :)

Thanks!


问:
android location with pin on map
I'm working on an Android application which basically shows the real time location of user on map with a pin.

When the user moves the pin should also move. I want to show multiple user's with image and moving pin as location changes on map.

答:
```<code>    myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);
    myLocationOverlay.enableMyLocation();
    myLocationOverlay.runOnFirstFix(addfirststandort);
</code>```

Title: android location with pin on map