问:
Flutter bottom overflowed by infinity pixels
I'm facing this issue where I keep getting "bottom overflowed by infinity pixels" when I add a certain widget into a column's children. Now this is how it looks like before adding the new widget called countdown:

The following is what happens after I add countdown:

Here is the code for the bottom half of the screen, where I add countdown:

    final countdown = Countdown();

    final quizBottomContent = SingleChildScrollView(
      child: Container(
      width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[quizBottomContentText, quizOptions, countdown],
        ),
      )
    );

```

<p>Here is the countdown widget:</p>

<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
import 'dart:math' as math;

class Countdown extends StatefulWidget {
  @override
  CountdownState createState() => CountdownState();
}

class CountdownState extends State<Countdown> with TickerProviderStateMixin {
  AnimationController controller;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 10),
    );
  }

  @override
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: Align(
                alignment: FractionalOffset.center,
                child: AspectRatio(
                  aspectRatio: 1.0,
                  child: Stack(
                    children: <Widget>[
                      Positioned.fill(
                        child: AnimatedBuilder(
                          animation: controller,
                          builder: (BuildContext context, Widget child) {
                            return CustomPaint(
                                painter: TimerPainter(
                              animation: controller,
                              backgroundColor: Colors.white,
                              color: themeData.indicatorColor,
                            ));
                          },
                        ),
                      ),
                      Align(
                        alignment: FractionalOffset.center,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              "Count Down",
                              style: themeData.textTheme.subhead,
                            ),
                            AnimatedBuilder(
                                animation: controller,
                                builder: (BuildContext context, Widget child) {
                                  return Text(
                                    timerString,
                                    style: themeData.textTheme.display4,
                                  );
                                }),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  FloatingActionButton(
                    child: AnimatedBuilder(
                      animation: controller,
                      builder: (BuildContext context, Widget child) {
                        return Icon(controller.isAnimating
                            ? Icons.pause
                            : Icons.play_arrow);
                      },
                    ),
                    onPressed: () {
                      if (controller.isAnimating)
                        controller.stop();
                      else {
                        controller.reverse(
                            from: controller.value == 0.0
                                ? 1.0
                                : controller.value);
                      }
                    },
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class TimerPainter extends CustomPainter {
  TimerPainter({
    this.animation,
    this.backgroundColor,
    this.color,
  }) : super(repaint: animation);

  final Animation<double> animation;
  final Color backgroundColor, color;

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = backgroundColor
      ..strokeWidth = 5.0
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke;

    canvas.drawCircle(size.center(Offset.zero), size.width / 2.0, paint);
    paint.color = color;
    double progress = (1.0 - animation.value) * 2 * math.pi;
    canvas.drawArc(Offset.zero & size, math.pi * 1.5, -progress, false, paint);
  }

  @override
  bool shouldRepaint(TimerPainter old) {
    return animation.value != old.animation.value ||
        color != old.color ||
        backgroundColor != old.backgroundColor;
  }
}

</code>```

Some context:
Countdown is basically a timer with animation while counting down I extracted from this link. So the timer would be just below the buttons.

答:
try to set mainaxissize of the column
mainAxisSize: MainAxisSize.min,

update

ok so if you are trying to Countdown widget as a widget in a column you can remove the scaffold from build method of count down widget and wrap it in a container and define a height

```<code> return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Column(
</code>```

to

```<code> return Container(
         height: 100,
         child: Padding(
              padding: EdgeInsets.all(8.0),
              child: Column(
</code>```

Body:
I'm facing this issue where I keep getting "bottom overflowed by infinity pixels" when I add a certain widget into a column's children. Now this is how it looks like before adding the new widget called countdown:

The following is what happens after I add countdown:

Here is the code for the bottom half of the screen, where I add countdown:

    final countdown = Countdown();

    final quizBottomContent = SingleChildScrollView(
      child: Container(
      width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[quizBottomContentText, quizOptions, countdown],
        ),
      )
    );

Here is the countdown widget:

import 'package:flutter/material.dart';
import 'dart:math' as math;

class Countdown extends StatefulWidget {
  @override
  CountdownState createState() => CountdownState();
}

class CountdownState extends State<Countdown> with TickerProviderStateMixin {
  AnimationController controller;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 10),
    );
  }

  @override
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: Align(
                alignment: FractionalOffset.center,
                child: AspectRatio(
                  aspectRatio: 1.0,
                  child: Stack(
                    children: <Widget>[
                      Positioned.fill(
                        child: AnimatedBuilder(
                          animation: controller,
                          builder: (BuildContext context, Widget child) {
                            return CustomPaint(
                                painter: TimerPainter(
                              animation: controller,
                              backgroundColor: Colors.white,
                              color: themeData.indicatorColor,
                            ));
                          },
                        ),
                      ),
                      Align(
                        alignment: FractionalOffset.center,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              "Count Down",
                              style: themeData.textTheme.subhead,
                            ),
                            AnimatedBuilder(
                                animation: controller,
                                builder: (BuildContext context, Widget child) {
                                  return Text(
                                    timerString,
                                    style: themeData.textTheme.display4,
                                  );
                                }),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  FloatingActionButton(
                    child: AnimatedBuilder(
                      animation: controller,
                      builder: (BuildContext context, Widget child) {
                        return Icon(controller.isAnimating
                            ? Icons.pause
                            : Icons.play_arrow);
                      },
                    ),
                    onPressed: () {
                      if (controller.isAnimating)
                        controller.stop();
                      else {
                        controller.reverse(
                            from: controller.value == 0.0
                                ? 1.0
                                : controller.value);
                      }
                    },
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class TimerPainter extends CustomPainter {
  TimerPainter({
    this.animation,
    this.backgroundColor,
    this.color,
  }) : super(repaint: animation);

  final Animation<double> animation;
  final Color backgroundColor, color;

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = backgroundColor
      ..strokeWidth = 5.0
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke;

    canvas.drawCircle(size.center(Offset.zero), size.width / 2.0, paint);
    paint.color = color;
    double progress = (1.0 - animation.value) * 2 * math.pi;
    canvas.drawArc(Offset.zero & size, math.pi * 1.5, -progress, false, paint);
  }

  @override
  bool shouldRepaint(TimerPainter old) {
    return animation.value != old.animation.value ||
        color != old.color ||
        backgroundColor != old.backgroundColor;
  }
}

Some context:
Countdown is basically a timer with animation while counting down I extracted from this link. So the timer would be just below the buttons.

Body:
try to set mainaxissize of the column
mainAxisSize: MainAxisSize.min,

update

ok so if you are trying to Countdown widget as a widget in a column you can remove the scaffold from build method of count down widget and wrap it in a container and define a height

 return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Column(

to

 return Container(
         height: 100,
         child: Padding(
              padding: EdgeInsets.all(8.0),
              child: Column(


来源: stackexchange

问:
How to set proxy settings (http_proxy variables) for kubernetes (v1.11.2) cluster?
I have setup a Kubernetes cluster which somehow cannot have internet connectivity because of organizaion policies. Now there are some services which I need to communicate via internet. To resolve this I have setup a forward proxy (Squid) which is outside of K8s cluster. All the nodes of my K8s cluster can access "google.com" using forward proxy. But I am not able to make my pods communicate through that proxy.

I have setup following variable on all the master and worker nodes:

```<code>export http_proxy="http://10.x.x.x:3128"
export https_proxy="https://10.x.x.x:3128"
</code>```

I am able to curl google.com from master and worker nodes. But when I attach into my container I notice that there are no variable http_proxy and https_proxy. and it cannot perform successful curl.

My pods and service network is different than my VM network

```<code>pod-network-cidr=192.167.0.0/16
service-cidr 192.168.0.0/16
</code>```

and my VM network is like:

```<code>Master  -> 10.2.2.40
Worker1 -> 10.2.2.41
Worker2 -> 10.2.2.42
Worker3 -> 10.2.2.43
</code>```

And my forward proxy is running at

```<code>Forward Proxy: 10.5.2.30
</code>```

I am using kubernetes version v1.11.2. Any help here like where should I put my http_proxy setting for kubernetes cluster to make it effective for all pods and services?

答:
For the docker service, use the systemd settings files:

Create a file:

```<code>/etc/systemd/system/docker.service.d/http-proxy.conf
</code>```

With the content:

```<code>[Service]
Environment="HTTP_PROXY=http://10.x.x.x:3128"
Environment="HTTPS_PROXY=http://10.x.x.x:3128"
</code>```

(you could also include NO_PROXY variables)

You'll need to reload systemctl and restart the docker service:

```<code>systemctl daemon-reload
systemctl restart docker
</code>```

For the containers to be able to connect to the proxy use /etc/default/docker or /etc/sysconfig/docker as mk_sta said.

ContentLicense: CC BY-SA 4.0

Body:
I have setup a Kubernetes cluster which somehow cannot have internet connectivity because of organizaion policies. Now there are some services which I need to communicate via internet. To resolve this I have setup a forward proxy (Squid) which is outside of K8s cluster. All the nodes of my K8s cluster can access "google.com" using forward proxy. But I am not able to make my pods communicate through that proxy.

I have setup following variable on all the master and worker nodes:

export http_proxy="http://10.x.x.x:3128"
export https_proxy="https://10.x.x.x:3128"

I am able to curl google.com from master and worker nodes. But when I attach into my container I notice that there are no variable http_proxy and https_proxy. and it cannot perform successful curl.

My pods and service network is different than my VM network

pod-network-cidr=192.167.0.0/16
service-cidr 192.168.0.0/16

and my VM network is like:

Master  -> 10.2.2.40
Worker1 -> 10.2.2.41
Worker2 -> 10.2.2.42
Worker3 -> 10.2.2.43

And my forward proxy is running at

Forward Proxy: 10.5.2.30

I am using kubernetes version v1.11.2. Any help here like where should I put my http_proxy setting for kubernetes cluster to make it effective for all pods and services?

Body:
For the docker service, use the systemd settings files:

Create a file:

/etc/systemd/system/docker.service.d/http-proxy.conf

With the content:

[Service]
Environment="HTTP_PROXY=http://10.x.x.x:3128"
Environment="HTTPS_PROXY=http://10.x.x.x:3128"

(you could also include NO_PROXY variables)

You'll need to reload systemctl and restart the docker service:

systemctl daemon-reload
systemctl restart docker

For the containers to be able to connect to the proxy use /etc/default/docker or /etc/sysconfig/docker as mk_sta said.


问:
I am facing an error when using the @login_required decorator, it shows TemplateDoesNotExist at /accounts/login/
I am trying to use login decorator in my project but when I use it it shows me the error

```<code>TemplateDoesNotExist at /accounts/login/

registration/login.html
</code>```

urls.py

```<code>path('', login.login_view , name='login'),
path('fileupload/', FileUpload.fileup, name='fileupload'),
</code>```

view.py->FileUpload.py->fileup

```<code>@login_required(login_url='login')
def fileup(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            form = form.save(commit=False)
            form.user = request.user
            form.save()
            print(form.image)
            print(form.user_id)
            send_message(str(form.image), form.user_id)

            text_filename = 'media/' + str(form.image).rstrip('.jpg') + '.txt'
            form.text_file = text_filename
            print(str(form.text_file))
            form.save()
            with open(text_filename, 'r+') as file:
                new_text = file.read()

            return render(request, "pd/NewText.html", {
                'form': form,
                'new_text': new_text,
            })
    else:
        form = DocumentForm()
    return render(request, 'pd/FileUpload.html', {'form': form})
</code>```

I want if user has not signed in and try to access the url fileupload\ then it not allow until he/she has not signed in.

答:
This is what you want.

# Create your views here.
def post_create(request):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "Succefully Created")
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "form": form,
    }
    return render(request, "post_form.html", context)
```

Here is the official doc so you can explore your options

You don't need a decorator, just put in your view an if statement to check if the user is member or something else, if it's not then raise error.

Also here is the Mozila Django Tutorial about creating login functionality

Also make sure you have your templates in the right path.

Body:
I am trying to use login decorator in my project but when I use it it shows me the error

TemplateDoesNotExist at /accounts/login/

registration/login.html

urls.py

path('', login.login_view , name='login'),
path('fileupload/', FileUpload.fileup, name='fileupload'),

view.py->FileUpload.py->fileup

@login_required(login_url='login')
def fileup(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            form = form.save(commit=False)
            form.user = request.user
            form.save()
            print(form.image)
            print(form.user_id)
            send_message(str(form.image), form.user_id)

            text_filename = 'media/' + str(form.image).rstrip('.jpg') + '.txt'
            form.text_file = text_filename
            print(str(form.text_file))
            form.save()
            with open(text_filename, 'r+') as file:
                new_text = file.read()

            return render(request, "pd/NewText.html", {
                'form': form,
                'new_text': new_text,
            })
    else:
        form = DocumentForm()
    return render(request, 'pd/FileUpload.html', {'form': form})

I want if user has not signed in and try to access the url fileupload\ then it not allow until he/she has not signed in.

Body:
This is what you want.

# Create your views here.
def post_create(request):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "Succefully Created")
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "form": form,
    }
    return render(request, "post_form.html", context)

Here is the official doc so you can explore your options

You don't need a decorator, just put in your view an if statement to check if the user is member or something else, if it's not then raise error.

Also here is the Mozila Django Tutorial about creating login functionality

Also make sure you have your templates in the right path.


问:
Powershell winforms save default background state
Experimenting with Winforms in Powershell.

I'm generating a Winform on which I draw with System.Drawing. After finishing the drawing, I need to save its state to revert to it later.

In the example below I want to return to the state with a single line drawn (=before drawing the rectangle). Where is the error?

```<code>Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
cd $PSScriptRoot
$Form = new-Object system.Windows.Forms.Form
$size = 150
$Form.ClientSize = "$size,$size"
$graphics = $Form.CreateGraphics()
$pen = New-Object System.Drawing.pen Black, 25
$brush = New-Object System.Drawing.SolidBrush Green
$form.Add_Paint(
{
    $graphics.DrawLine($pen, 0,0,100,100)
    # Save graphics state.
    $state = $graphics.Save()
    $graphics.FillRectangle($brush, 0, 0, 100, 100)
    # Restore graphics state.
    $graphics = $graphics.Restore($state)
}
)
$Form.ShowDialog()
</code>```

答:
Managed to solve it. Not ideal, but mostly working.</p>

```<code>Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
cd $PSScriptRoot
$size = 150
$Form = new-Object system.Windows.Forms.Form
$Form.ClientSize = "$size,$size"
$picbox = New-Object System.Windows.Forms.PictureBox
$picbox.Width = $size
$picbox.Height = $size
$Form.Controls.Add($picbox)
$bitmap = New-Object system.drawing.bitmap $size, $size
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$pen = New-Object System.Drawing.pen Orange, 25
$brush = New-Object System.Drawing.SolidBrush Blue
$backgroundBrush = New-Object System.Drawing.SolidBrush White
$form.Add_Shown(
{
    $graphics.DrawLine($pen, 0,0,100,100)
    # Save graphics state.
    $bitmap.Save("C:\tmp.jpeg") #problems with closing access to files
    $graphics.FillRectangle($brush, 0, 0, 100, 100)
    $bitmap.Save("C:\tmpChanged.jpeg")#just to see it really changed.
    # Restore graphics state.
    $bitmap = [System.Drawing.Bitmap]::FromFile("C:\tmp.jpeg")
    $picbox.Image = $bitmap
    $Form.Update()
}
)
$Form.ShowDialog()
</code>```

Body:
Experimenting with Winforms in Powershell.

I'm generating a Winform on which I draw with System.Drawing. After finishing the drawing, I need to save its state to revert to it later.

In the example below I want to return to the state with a single line drawn (=before drawing the rectangle). Where is the error?

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
cd $PSScriptRoot
$Form = new-Object system.Windows.Forms.Form
$size = 150
$Form.ClientSize = "$size,$size"
$graphics = $Form.CreateGraphics()
$pen = New-Object System.Drawing.pen Black, 25
$brush = New-Object System.Drawing.SolidBrush Green
$form.Add_Paint(
{
    $graphics.DrawLine($pen, 0,0,100,100)
    # Save graphics state.
    $state = $graphics.Save()
    $graphics.FillRectangle($brush, 0, 0, 100, 100)
    # Restore graphics state.
    $graphics = $graphics.Restore($state)
}
)
$Form.ShowDialog()

Body:
Managed to solve it. Not ideal, but mostly working.

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
cd $PSScriptRoot
$size = 150
$Form = new-Object system.Windows.Forms.Form
$Form.ClientSize = "$size,$size"
$picbox = New-Object System.Windows.Forms.PictureBox
$picbox.Width = $size
$picbox.Height = $size
$Form.Controls.Add($picbox)
$bitmap = New-Object system.drawing.bitmap $size, $size
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$pen = New-Object System.Drawing.pen Orange, 25
$brush = New-Object System.Drawing.SolidBrush Blue
$backgroundBrush = New-Object System.Drawing.SolidBrush White
$form.Add_Shown(
{
    $graphics.DrawLine($pen, 0,0,100,100)
    # Save graphics state.
    $bitmap.Save("C:\tmp.jpeg") #problems with closing access to files
    $graphics.FillRectangle($brush, 0, 0, 100, 100)
    $bitmap.Save("C:\tmpChanged.jpeg")#just to see it really changed.
    # Restore graphics state.
    $bitmap = [System.Drawing.Bitmap]::FromFile("C:\tmp.jpeg")
    $picbox.Image = $bitmap
    $Form.Update()
}
)
$Form.ShowDialog()


问:
using the charindex to match a field to a search
I have a query where one of the columns value are coming a json formatted value as:

```<code>column1 {"type":"a","main":"/documents/500/a.pdf","id":500}
</code>```

i want to use the id in the where clause to search like

where column1 = 500

i want to use the 500 on the left hand side for matching to a search

答:
You can try this:</p>

```<code>Declare @t table ( EMpid int , Groups nvarchar(500))

Insert into @t values (500,'{"type":"a","main":"/documents/500/a.pdf","id":500}')

select * from @t where replace(RIGHT(groups, CHARINDEX(':', REVERSE(groups)) -1),'}','') = 500
</code>```

Body:
I have a query where one of the columns value are coming a json formatted value as:

column1 {"type":"a","main":"/documents/500/a.pdf","id":500}

i want to use the id in the where clause to search like

where column1 = 500

i want to use the 500 on the left hand side for matching to a search

Body:
You can try this:

Declare @t table ( EMpid int , Groups nvarchar(500))

Insert into @t values (500,'{"type":"a","main":"/documents/500/a.pdf","id":500}')

select * from @t where replace(RIGHT(groups, CHARINDEX(':', REVERSE(groups)) -1),'}','') = 500


问:
PSQL select either a or b in order but not both a and b if both a and b exists
I have a PSQL table

```<code>+--------+------+------+------+
|  Col1  | Col2 | Col3 | Col4 |
+--------+------+------+------+
|    001 | 00A  | 00B  | 001  |
| 001001 | 00A  | 00B  | 001  |
|    002 | 00X  | 00Y  | 002  |
| 002002 | 00X  | 00Y  | 002  |
+--------+------+------+------+
</code>```

I have the following PSQL query:

```<code>select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
order by Col3 asc;
</code>```

I get the first two rows.

Here what happens is that it matches both conditions for OR condition. I need to match only one of the or conditions. That is if first condition (Col1='001001') is true then do not evaluate the next condition.
I need to select only the 2nd row (| 001001 | 00A  | 00B  | 001  |)

I have build another query using EXCEPT

```<code>select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
    except (select *
            from my_table
            where Col1 != '001'
              and Col2 = '00A')
order by Col3 asc
limit 1;
</code>```

I would like to know if there is any other elegant queries for this job?

答:
Your explanation is confusing as you say col1 = '001001' in one place and use 001 in the query. But I presume you want to use a hierarchy of comparison and return the one with the highest per each group ( col2,col3,col4) . Use DISTINCT ON. Change the condition in whichever way you like to return the appropriate row.

```<code>SELECT DISTINCT ON (col2, col3, col4) *
  FROM     my_table WHERE  col2 = '00A'
ORDER  BY col2,
          col3,
          col4,
          CASE
            WHEN col1 = '001001' THEN 1
            WHEN col4 = '001'    THEN 2
          END;
</code>```

DEMO

Body:
I have a PSQL table

+--------+------+------+------+
|  Col1  | Col2 | Col3 | Col4 |
+--------+------+------+------+
|    001 | 00A  | 00B  | 001  |
| 001001 | 00A  | 00B  | 001  |
|    002 | 00X  | 00Y  | 002  |
| 002002 | 00X  | 00Y  | 002  |
+--------+------+------+------+

I have the following PSQL query:

select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
order by Col3 asc;

I get the first two rows.

Here what happens is that it matches both conditions for OR condition. I need to match only one of the or conditions. That is if first condition (Col1='001001') is true then do not evaluate the next condition.
I need to select only the 2nd row (| 001001 | 00A  | 00B  | 001  |)

I have build another query using EXCEPT

select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
    except (select *
            from my_table
            where Col1 != '001'
              and Col2 = '00A')
order by Col3 asc
limit 1;

I would like to know if there is any other elegant queries for this job?

Body:
Your explanation is confusing as you say col1 = '001001' in one place and use 001 in the query. But I presume you want to use a hierarchy of comparison and return the one with the highest per each group ( col2,col3,col4) . Use DISTINCT ON. Change the condition in whichever way you like to return the appropriate row.

SELECT DISTINCT ON (col2, col3, col4) *
  FROM     my_table WHERE  col2 = '00A'
ORDER  BY col2,
          col3,
          col4,
          CASE
            WHEN col1 = '001001' THEN 1
            WHEN col4 = '001'    THEN 2
          END;

DEMO


问:
Same Object is getting added into list of object
I have 5 records in db , and i want to show them on UI , but with the below code while iterating it shows different object but in list it shows same object 5 times
Help me with this and tell if i can have better coding practice

I have used For loop to iterate and get the record into list of friend

```<code>  public ViewResult Contact()
    {
        Friends friend = new Friends();
        List<Friends> friends = new List<Friends>();
        string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("select * from Friends", con);
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        da.SelectCommand = cmd;
        da.Fill(dt);

        for (var i = 0; i < dt.Rows.Count; i++)
        {
            friend.friendId = Convert.ToInt32(dt.Rows[i]["FriendId"]);
            friend.firstName = dt.Rows[i]["FirstName"].ToString();
            friend.lastName = dt.Rows[i]["LastName"].ToString();
            friend.currentAmountGiven = Convert.ToInt32(dt.Rows[i]["CurrentAmountGiven"]);
            friend.totalAmount = Convert.ToInt32(dt.Rows[i]["TotalAmount"]);
            friends.Add(friend);
        }
        return View(friends);

    }
</code>```

In Friends i am getting same row 5 times from db

need output as i told above

答:
You need to instantiate Friends object inside for loop.

In your case you are creating instance of Friends object outside for loop and changing values of its property in every iteration, that is why every time your code ending up with same instance in the list.

You need to create new instance of Friends everytime, assigning values to its property everytime and adding it to list in every iteration

```<code>    for (var i = 0; i < dt.Rows.Count; i++)
    {
        Friends friend = new Friends();  // Change scope of friends from function level to for loop level.
        friend.friendId = Convert.ToInt32(dt.Rows[i]["FriendId"]);
        friend.firstName = dt.Rows[i]["FirstName"].ToString();
        friend.lastName = dt.Rows[i]["LastName"].ToString();
        friend.currentAmountGiven = Convert.ToInt32(dt.Rows[i]["CurrentAmountGiven"]);
        friend.totalAmount = Convert.ToInt32(dt.Rows[i]["TotalAmount"]);
        friends.Add(friend);
    }
</code>```

Body:
I have 5 records in db , and i want to show them on UI , but with the below code while iterating it shows different object but in list it shows same object 5 times
Help me with this and tell if i can have better coding practice

I have used For loop to iterate and get the record into list of friend

  public ViewResult Contact()
    {
        Friends friend = new Friends();
        List<Friends> friends = new List<Friends>();
        string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("select * from Friends", con);
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        da.SelectCommand = cmd;
        da.Fill(dt);

        for (var i = 0; i < dt.Rows.Count; i++)
        {
            friend.friendId = Convert.ToInt32(dt.Rows[i]["FriendId"]);
            friend.firstName = dt.Rows[i]["FirstName"].ToString();
            friend.lastName = dt.Rows[i]["LastName"].ToString();
            friend.currentAmountGiven = Convert.ToInt32(dt.Rows[i]["CurrentAmountGiven"]);
            friend.totalAmount = Convert.ToInt32(dt.Rows[i]["TotalAmount"]);
            friends.Add(friend);
        }
        return View(friends);

    }

In Friends i am getting same row 5 times from db

need output as i told above

Body:
You need to instantiate Friends object inside for loop.

In your case you are creating instance of Friends object outside for loop and changing values of its property in every iteration, that is why every time your code ending up with same instance in the list.

You need to create new instance of Friends everytime, assigning values to its property everytime and adding it to list in every iteration

    for (var i = 0; i < dt.Rows.Count; i++)
    {
        Friends friend = new Friends();  // Change scope of friends from function level to for loop level.
        friend.friendId = Convert.ToInt32(dt.Rows[i]["FriendId"]);
        friend.firstName = dt.Rows[i]["FirstName"].ToString();
        friend.lastName = dt.Rows[i]["LastName"].ToString();
        friend.currentAmountGiven = Convert.ToInt32(dt.Rows[i]["CurrentAmountGiven"]);
        friend.totalAmount = Convert.ToInt32(dt.Rows[i]["TotalAmount"]);
        friends.Add(friend);
    }


问:
Getting user input with function
Here is my code:

```<code>def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

btc = input("Input your Bitcoins amount: ")

bitcoin_to_usd(btc)
</code>```

I want to get Bitcoin number from user then I want to calculate how much USD is it.

That code gives me repetition of the input. Such as if you input 2 it returns 222222222222222222222222.... doesn't calculate it.

My Python version is 3.4.1 and I am using PyCharm.

Any ideas?

答:
You could use</p>

```<code>btc = input("Input your Bitcoins amount: ")

def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

bitcoin_to_usd(btc)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting user input with function

Body:
Here is my code:

def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

btc = input("Input your Bitcoins amount: ")

bitcoin_to_usd(btc)

I want to get Bitcoin number from user then I want to calculate how much USD is it.

That code gives me repetition of the input. Such as if you input 2 it returns 222222222222222222222222.... doesn't calculate it.

My Python version is 3.4.1 and I am using PyCharm.

Any ideas?

Body:
You could use

btc = input("Input your Bitcoins amount: ")

def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

bitcoin_to_usd(btc)


问:
Cannot connect to Access Database using C++
My subject is somewhat stupid and complex for me. I'm trying to make a very simple connection with an Access 2007 db, but the connection never happens. I'm trying to see what happens with SQLGetDiagRec(), but the program crashes when SQLGetDiagRec() is executed. I'm not that much into C++, so I'm stuck for the past few days in this. Any help will be highly appreciated. I'm using Visual C++ 2008.

EDIT: After changing the character set from Unicode to Multibyte, I was able to execute the SQLGetDiagRec. I, then, changed my two pointers from int and char to SQLSMALLINT and SQLCHAR and, bam, it worked. Thanx a lot for the heads up guys.

```<code>#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#include <iostream>
#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
    char szDSN[256] = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DSN='Hospital_mdb';DBQ=C:\\Hospital.mdb;";
    SQLHANDLE EnvHandlePtr;
    SQLHANDLE ConHandle;
    SQLHANDLE StmtHandle;
    SQLRETURN rc;

    SQLSMALLINT iConnStrLength2Ptr; // Changing from int     iConnStrLength2Ptr;
    SQLCHAR szConnStrOut[256]; //changing from char    szConnStrOut[256];
    SQLCHAR SQLState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
    SQLINTEGER NativeError;
    SQLSMALLINT MsgLen;

    if ( (rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandlePtr)) == SQL_SUCCESS){
        printf("Environment Set!");
        if( (rc = SQLSetEnvAttr(EnvHandlePtr, SQL_ATTR_ODBC_VERSION,
            (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER))==SQL_SUCCESS ){
                printf("Driver Set!");
                if ( (rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandlePtr, &ConHandle))==SQL_SUCCESS ){
                    printf("Allocation Done!");//**so far, so good, but then the connection doesn't happen**
                    rc = SQLDriverConnect(ConHandle, NULL, (SQLWCHAR*)szDSN,
                        SQL_NTS, (SQLWCHAR*) szConnStrOut, 0, (SQLSMALLINT*) iConnStrLength2Ptr, SQL_DRIVER_NOPROMPT);
                    if ( rc == SQL_SUCCESS ){
                    //if ( (rc = SQLConnect(ConHandle, (SQLWCHAR*)szDSN, SQL_NTS, (SQLWCHAR*)"", SQL_NTS, (SQLWCHAR*)"", SQL_NTS))== SQL_SUCCESS ){
                        printf("Connection Done");
                    }//end of Connection clause
                    else{
                        SQLGetDiagRec(SQL_HANDLE_DBC, ConHandle, 1, (SQLWCHAR*)SQLState, &NativeError, (SQLWCHAR*)Msg, sizeof(Msg), &MsgLen);
                            printf("Connection Failed\n%s", Msg);
                    }
                    SQLDisconnect(ConHandle);
                }//end of Connection Allocation clause
                SQLFreeHandle(SQL_HANDLE_DBC, ConHandle);
        }//end of Driver clause
        SQLFreeHandle(SQL_HANDLE_ENV, EnvHandlePtr);
    }//end of Enviroment clause

    _getch();

}//end of main
</code>```

答:
You are casting the diagnostics that the compiler generates for your bad code away.  At least SQLState is bad, you are passing a 6 byte buffer when 12 bytes are written.  That corrupts the stack frame.  The SQLDriverConnect call cannot work for the same reason.

Remove all casts by declaring your local variables properly.

And use Unicode in your code.  You could disable it in your project settings but that's never not a mistake when you work with a dbase.

Body:
My subject is somewhat stupid and complex for me. I'm trying to make a very simple connection with an Access 2007 db, but the connection never happens. I'm trying to see what happens with SQLGetDiagRec(), but the program crashes when SQLGetDiagRec() is executed. I'm not that much into C++, so I'm stuck for the past few days in this. Any help will be highly appreciated. I'm using Visual C++ 2008.

EDIT: After changing the character set from Unicode to Multibyte, I was able to execute the SQLGetDiagRec. I, then, changed my two pointers from int and char to SQLSMALLINT and SQLCHAR and, bam, it worked. Thanx a lot for the heads up guys.

#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#include <iostream>
#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
    char szDSN[256] = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DSN='Hospital_mdb';DBQ=C:\\Hospital.mdb;";
    SQLHANDLE EnvHandlePtr;
    SQLHANDLE ConHandle;
    SQLHANDLE StmtHandle;
    SQLRETURN rc;

    SQLSMALLINT iConnStrLength2Ptr; // Changing from int     iConnStrLength2Ptr;
    SQLCHAR szConnStrOut[256]; //changing from char    szConnStrOut[256];
    SQLCHAR SQLState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
    SQLINTEGER NativeError;
    SQLSMALLINT MsgLen;

    if ( (rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandlePtr)) == SQL_SUCCESS){
        printf("Environment Set!");
        if( (rc = SQLSetEnvAttr(EnvHandlePtr, SQL_ATTR_ODBC_VERSION,
            (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER))==SQL_SUCCESS ){
                printf("Driver Set!");
                if ( (rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandlePtr, &ConHandle))==SQL_SUCCESS ){
                    printf("Allocation Done!");//**so far, so good, but then the connection doesn't happen**
                    rc = SQLDriverConnect(ConHandle, NULL, (SQLWCHAR*)szDSN,
                        SQL_NTS, (SQLWCHAR*) szConnStrOut, 0, (SQLSMALLINT*) iConnStrLength2Ptr, SQL_DRIVER_NOPROMPT);
                    if ( rc == SQL_SUCCESS ){
                    //if ( (rc = SQLConnect(ConHandle, (SQLWCHAR*)szDSN, SQL_NTS, (SQLWCHAR*)"", SQL_NTS, (SQLWCHAR*)"", SQL_NTS))== SQL_SUCCESS ){
                        printf("Connection Done");
                    }//end of Connection clause
                    else{
                        SQLGetDiagRec(SQL_HANDLE_DBC, ConHandle, 1, (SQLWCHAR*)SQLState, &NativeError, (SQLWCHAR*)Msg, sizeof(Msg), &MsgLen);
                            printf("Connection Failed\n%s", Msg);
                    }
                    SQLDisconnect(ConHandle);
                }//end of Connection Allocation clause
                SQLFreeHandle(SQL_HANDLE_DBC, ConHandle);
        }//end of Driver clause
        SQLFreeHandle(SQL_HANDLE_ENV, EnvHandlePtr);
    }//end of Enviroment clause

    _getch();

}//end of main


问:
how to read csv file and extract specific coulmn?
This is my csv file :

```<code>CommitId                                RefactoringType      RefactoringDetail
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Pla
</code>```

I need to extract this:

```<code>RefactoringDetail
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
</code>```

I tried this code:

```<code>import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep='delimiter', header=None)
df.iloc[:,-1]
</code>```

it return all the data

Any help please!

答:
If you wanted to just use the inbuilt csv module:

```<code>import csv
import re
third_column = []
with open("result_refactorings.csv") as csvfile:
    fixed_spaces = [re.sub(" {2,}","\t",x) for x in csvfile]
    reader = csv.DictReader(fixed_spaces, delimiter="\t")
    for row in reader:
        print(row["RefactoringDetail"])
        third_column.append(row["RefactoringDetail"])
</code>```

This code both prints out the third column and adds each item in the third column to a list third_column.. take out one or the other depending on what you wanna do.

EDIT: On closer inspection it seems your csv input is delimited with an uneven number of spaces.. and not actually tabs, which is what it looks like.. Added a little regex to replace 2 or more concurrent spaces with an actual tab.. since in its current state it isn't a valid csv.

Body:
This is my csv file :

CommitId                                RefactoringType      RefactoringDetail
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Pla

I need to extract this:

RefactoringDetail
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"

I tried this code:

import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep='delimiter', header=None)
df.iloc[:,-1]

it return all the data

Any help please!

Body:
If you wanted to just use the inbuilt csv module:

import csv
import re
third_column = []
with open("result_refactorings.csv") as csvfile:
    fixed_spaces = [re.sub(" {2,}","\t",x) for x in csvfile]
    reader = csv.DictReader(fixed_spaces, delimiter="\t")
    for row in reader:
        print(row["RefactoringDetail"])
        third_column.append(row["RefactoringDetail"])

This code both prints out the third column and adds each item in the third column to a list third_column.. take out one or the other depending on what you wanna do.

EDIT: On closer inspection it seems your csv input is delimited with an uneven number of spaces.. and not actually tabs, which is what it looks like.. Added a little regex to replace 2 or more concurrent spaces with an actual tab.. since in its current state it isn't a valid csv.


问:
Identify affected tables during application Run - SQL Server 2012
I have scenario to Identify the tables and columns affected during various transactions happening through an application. I need a way to capture details of Table, column affected in database during application run. The application is a desktop application where bussiness layer is Java and backend is in SQL Server 2012.

I have already tried by creating triggers on all tables. These triggers would insert the details of Table, column affected into a common table. so at the end of the day this table would give me the information I need.
But this can be messy when there are too many tables with large number of columns.

```<code> Table name|column Name|old value|new value|action (insert/update/delete)|transaction type
</code>```

答: Triggers are very expensive and not scale properly. So, you should avoid them in most cases including your scenario. However, in order to know what is going on your databases the best solution IMO is to use Adam Machanic sp_whoisactive. This is the stored procedure which can run periodically and captured the system state at the moment of the execution. </p>

Body:
I have scenario to Identify the tables and columns affected during various transactions happening through an application. I need a way to capture details of Table, column affected in database during application run. The application is a desktop application where bussiness layer is Java and backend is in SQL Server 2012.

I have already tried by creating triggers on all tables. These triggers would insert the details of Table, column affected into a common table. so at the end of the day this table would give me the information I need.
But this can be messy when there are too many tables with large number of columns.

 Table name|column Name|old value|new value|action (insert/update/delete)|transaction type


问:
making column vector from the rows of a data frame
I have a data frame with 12 columns and Five Rows. I need to convert this into a column vector with each row being successively pasted one below other.

For example
1 2 3 A a b c B d e f C g h i I need the final output as A1 a b c d e f g h i

答:
If you want the rownames to be which column it comes from try, </p>

```<code>data.frame(all = unlist(mtcars))
#                   all
# mpg1           21.000
# mpg2           21.000
# mpg3           22.800
# mpg4           21.400
# mpg5           18.700
# mpg6           18.100
</code>```

Body:
If you want the rownames to be which column it comes from try,

data.frame(all = unlist(mtcars))
#                   all
# mpg1           21.000
# mpg2           21.000
# mpg3           22.800
# mpg4           21.400
# mpg5           18.700
# mpg6           18.100


问:
URL routing in Django
I am prrety new in URLs and Django and got some questions.

For now I have 2 HTML templates which are routing correctly: home.html and ladder.html .

What do I have to do to go from my ladder.html(ladder/) back to my home.html("") if I click to home again nothing is happening.
And as second when I am on ladder and click ladder again it adds another ladder/ to the URL and Im getting a router error , how can I resolve this ?

Thanks for the help.

I will show the code of my navbar wher my href attributes are so u can understand what I mean and my urls.py

My hrefs:

```<code><div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="">Home<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="ladder/">Ladders</a>
</code>```

My urls.py:

```<code>from django.contrib import admin
from django.urls import path
from pages.views import home_view,ladder_view
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', home_view),
    path('admin/', admin.site.urls),
    path('ladder/',ladder_view),

]
</code>```

答:
you can use the tag to call any route . for this you must :

```<code><li class="nav-item active">
    <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
    <a class="nav-link" href="{% url 'ladder' %}">Ladders</a>
</li>
</code>```

in this step. when you set name to route you can call it with :

```<code>{% url 'home' %}
</code>```

Title: URL routing in Django

Body:
I am prrety new in URLs and Django and got some questions.

For now I have 2 HTML templates which are routing correctly: home.html and ladder.html .

What do I have to do to go from my ladder.html(ladder/) back to my home.html("") if I click to home again nothing is happening.
And as second when I am on ladder and click ladder again it adds another ladder/ to the URL and Im getting a router error , how can I resolve this ?

Thanks for the help.

I will show the code of my navbar wher my href attributes are so u can understand what I mean and my urls.py

My hrefs:

        Home(current)

        Ladders

My urls.py:

from django.contrib import admin
from django.urls import path
from pages.views import home_view,ladder_view
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', home_view),
    path('admin/', admin.site.urls),
    path('ladder/',ladder_view),

]

Body:
you can use the tag to call any route . for this you must :

<li class="nav-item active">
    <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
    <a class="nav-link" href="{% url 'ladder' %}">Ladders</a>
</li>

in this step. when you set name to route you can call it with :

{% url 'home' %}


问:
Possible to move the tmp directory of Eclipse?
I'm trying to speed up Eclipse by having my projects on a RAM disk (stuck with a slow laptop and a heavy kind of eclipse project at the moment). Worked great for loading the project and such, but when I'm building it seems to read and write a lot to a directory in %APPDATA% (seems to have a generated name from the name of the project). This makes it actually go slower than usual...

So... is there a way I can move the tmp directory of eclipse? Preferably without moving the tmp directory of other applications in the process.

答:
It can be done by Djava.io.tmpdir property

->On root directory of your project right click as select run or debug as then in:

In Run/Debug Configuration of your project

->Run configuration

->Arguments-->

In VM Arguments

write the complete path of your temp directory

example: if you want to select a folder JAVAtmp in F drive  then pass the VM arguments as :

-Djava.io.tmpdir=F:\JAVATmp


问:
Is there any way to inject a variable into a web.xml?
I have web app by using Java EE. I want to run my app for different URL. My app consist of many project and in main project I have web.xml file that decides about URL path. I want to inject form other file like config.xml, a variable to web.xml. Is any way to do that?</p>

答: You can use entities, XML's and SGML's mechanism for text variable substitution. The general technique is explained in eg XML configuration inheritance, avoid duplications , though you must check if entity expansion is actually supported in your servlet container. This old JIRA bug would imply it's supported by tomcat, but OTOH maven prominently disables it.


问:
react native firebase check if user already exisits in real time database
i need to check if username already exists in real time database then prompt user to select another username. it keep saying not found. I think it because of how my data is nested.

signup.js

```<code>const { email, username, password } = this.state;

    await firebase
                .auth()
                .createUserWithEmailAndPassword(email, password)
                .then(async user => {
                    console.log('Data created', user);
                    let rootRef = firebase.database().ref()

                rootRef.child("users")
                        .orderByChild("username")
                        .equalTo(username)
                        .once("value")
                        .then(snapshot => {
                            if (snapshot.exists()) {
                                    let userData = snapshot.val()
                                console.log(userData)
                              Alert.alert('username is taken')
                                return userData;
                            }else {
                                console.log('not found')

                            }
                    })
</code>```

答:
You are creating a user, then check if that user exists. Check if the user exists before creating the user.</p>

```<code>const { email, username, password } = this.state;

let rootRef = firebase.database().ref();

rootRef
  .child('users')
  .orderByChild('username')
  .equalTo(username)
  .once('value')
  .then(snapshot => {
    if (snapshot.exists()) {
      let userData = snapshot.val();
      console.log(userData);
      Alert.alert('username is taken');
      return userData;
    } else {
      console.log('not found');
      firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(async user => {
          console.log('Data created', user);
        });
    }
});
</code>```

Body:
i need to check if username already exists in real time database then prompt user to select another username. it keep saying not found. I think it because of how my data is nested.

signup.js

const { email, username, password } = this.state;

    await firebase
                .auth()
                .createUserWithEmailAndPassword(email, password)
                .then(async user => {
                    console.log('Data created', user);
                    let rootRef = firebase.database().ref()

                rootRef.child("users")
                        .orderByChild("username")
                        .equalTo(username)
                        .once("value")
                        .then(snapshot => {
                            if (snapshot.exists()) {
                                    let userData = snapshot.val()
                                console.log(userData)
                              Alert.alert('username is taken')
                                return userData;
                            }else {
                                console.log('not found')

                            }
                    })

Body:
You are creating a user, then check if that user exists. Check if the user exists before creating the user.

const { email, username, password } = this.state;

let rootRef = firebase.database().ref();

rootRef
  .child('users')
  .orderByChild('username')
  .equalTo(username)
  .once('value')
  .then(snapshot => {
    if (snapshot.exists()) {
      let userData = snapshot.val();
      console.log(userData);
      Alert.alert('username is taken');
      return userData;
    } else {
      console.log('not found');
      firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(async user => {
          console.log('Data created', user);
        });
    }
});


问:
How to compare two circuits based on their utilization
I have some hardware IPs that I need to synthesize. And the IP contains several generic parameters I can play with. Each combination of parameters gives me a different utilization report after synthesis and implementation.

So for example for two different configurations Design_1 and Design_2, I get the following in Vivado 2018.1. The 3rd line is the ratio of the values of Design_2 devided by values of Design_1.

So as you can see in this simple example, Design_2 has less Slice LUTs but slightly more F7 Muxes.

My question is how to conclude about the cost of each one? Should I privilege Slice LUTs or Registers ...etc?

```<code>+----------+-------------------+-----------------+------------------+----------+-------------------+-------------------+---------------+---------------------+----------------+------+------------+--------------+-------------+------------+----------+---------+------------+---------+---------------------------+-------------------------+-----------------------------+--------+--------+----------+---------+------------+-----------+---------+--------+---------+---------+-----------+----------+-----------+-------------+---------+----------+-----------+---------+
|   Name   |    Slice LUTs     | Slice Registers |     F7 Muxes     | F8 Muxes |       Slice       |   LUT as Logic    | LUT as Memory | LUT Flip Flop Pairs | Block RAM Tile | DSPs | Bonded IOB | Bonded IPADs | PHY_CONTROL | PHASER_REF | OUT_FIFO | IN_FIFO | IDELAYCTRL | IBUFDS  | PHASER_OUT/PHASER_OUT_PHY | PHASER_IN/PHASER_IN_PHY | IDELAYE2/IDELAYE2_FINEDELAY | ILOGIC | OLOGIC | BUFGCTRL |  BUFIO  | MMCME2_ADV | PLLE2_ADV | BUFMRCE | BUFHCE |  BUFR   | BSCANE2 | CAPTUREE2 | DNA_PORT | EFUSE_USR | FRAME_ECCE2 | ICAPE2  | PCIE_2_1 | STARTUPE2 |  XADC   |
+----------+-------------------+-----------------+------------------+----------+-------------------+-------------------+---------------+---------------------+----------------+------+------------+--------------+-------------+------------+----------+---------+------------+---------+---------------------------+-------------------------+-----------------------------+--------+--------+----------+---------+------------+-----------+---------+--------+---------+---------+-----------+----------+-----------+-------------+---------+----------+-----------+---------+
| Design_1 |             34124 |           16913 |             1453 |       91 |             10272 |             31538 |          2586 |                9020 |             37 |   11 |        125 | 0            |           1 |          1 |        4 |       2 |          1 | 0       |                         4 |                       2 |                          16 |     16 |     46 |       10 | 0       |          2 |         2 | 0       |      2 | 0       |       4 | 0         | 0        | 0         | 0           | 0       | 0        | 0         | 0       |
| Design_2 |             34097 |           16913 |             1550 |       91 |             10189 |             31511 |          2586 |                9021 |             37 |   11 |        125 | 0            |           1 |          1 |        4 |       2 |          1 | 0       |                         4 |                       2 |                          16 |     16 |     46 |       10 | 0       |          2 |         2 | 0       |      2 | 0       |       4 | 0         | 0        | 0         | 0           | 0       | 0        | 0         | 0       |
| -------- |                   |                 |                  |          |                   |                   |               |                     |                |      |            |              |             |            |          |         |            |         |                           |                         |                             |        |        |          |         |            |           |         |        |         |         |           |          |           |             |         |          |           |         |
| (2)/(1)  | 0.999208768022506 |               1 | 1.06675843083276 |        1 | 0.991919781931464 | 0.999143889910584 |             1 |    1.00011086474501 |              1 |    1 |          1 | #DIV/0!      |           1 |          1 |        1 |       1 |          1 | #DIV/0! |                         1 |                       1 |                           1 |      1 |      1 |        1 | #DIV/0! |          1 |         1 | #DIV/0! |      1 | #DIV/0! |       1 | #DIV/0!   | #DIV/0!  | #DIV/0!   | #DIV/0!     | #DIV/0! | #DIV/0!  | #DIV/0!   | #DIV/0! |
+----------+-------------------+-----------------+------------------+----------+-------------------+-------------------+---------------+---------------------+----------------+------+------------+--------------+-------------+------------+----------+---------+------------+---------+---------------------------+-------------------------+-----------------------------+--------+--------+----------+---------+------------+-----------+---------+--------+---------+---------+-----------+----------+-----------+-------------+---------+----------+-----------+---------+
</code>```

答:
It's depending on your needs, LUTs and F7 Muxes are differents physical cells in your FPGA. So even if you don't use its, its will be there.

If you have one ressource more critical than the other, you should try to minimize the utilisation of the critical ressource to simplify the place and route.

If you have nothing critical, I think the better is to use F7 Muxes first because Slice LUTs are more flexible for the rest of your design.

Body:
I have some hardware IPs that I need to synthesize. And the IP contains several generic parameters I can play with. Each combination of parameters gives me a different utilization report after synthesis and implementation.

So for example for two different configurations Design_1 and Design_2, I get the following in Vivado 2018.1. The 3rd line is the ratio of the values of Design_2 devided by values of Design_1.

So as you can see in this simple example, Design_2 has less Slice LUTs but slightly more F7 Muxes.

My question is how to conclude about the cost of each one? Should I privilege Slice LUTs or Registers ...etc?

+----------+-------------------+-----------------+------------------+----------+-------------------+-------------------+---------------+---------------------+----------------+------+------------+--------------+-------------+------------+----------+---------+------------+---------+---------------------------+-------------------------+-----------------------------+--------+--------+----------+---------+------------+-----------+---------+--------+---------+---------+-----------+----------+-----------+-------------+---------+----------+-----------+---------+
|   Name   |    Slice LUTs     | Slice Registers |     F7 Muxes     | F8 Muxes |       Slice       |   LUT as Logic    | LUT as Memory | LUT Flip Flop Pairs | Block RAM Tile | DSPs | Bonded IOB | Bonded IPADs | PHY_CONTROL | PHASER_REF | OUT_FIFO | IN_FIFO | IDELAYCTRL | IBUFDS  | PHASER_OUT/PHASER_OUT_PHY | PHASER_IN/PHASER_IN_PHY | IDELAYE2/IDELAYE2_FINEDELAY | ILOGIC | OLOGIC | BUFGCTRL |  BUFIO  | MMCME2_ADV | PLLE2_ADV | BUFMRCE | BUFHCE |  BUFR   | BSCANE2 | CAPTUREE2 | DNA_PORT | EFUSE_USR | FRAME_ECCE2 | ICAPE2  | PCIE_2_1 | STARTUPE2 |  XADC   |
+----------+-------------------+-----------------+------------------+----------+-------------------+-------------------+---------------+---------------------+----------------+------+------------+--------------+-------------+------------+----------+---------+------------+---------+---------------------------+-------------------------+-----------------------------+--------+--------+----------+---------+------------+-----------+---------+--------+---------+---------+-----------+----------+-----------+-------------+---------+----------+-----------+---------+
| Design_1 |             34124 |           16913 |             1453 |       91 |             10272 |             31538 |          2586 |                9020 |             37 |   11 |        125 | 0            |           1 |          1 |        4 |       2 |          1 | 0       |                         4 |                       2 |                          16 |     16 |     46 |       10 | 0       |          2 |         2 | 0       |      2 | 0       |       4 | 0         | 0        | 0         | 0           | 0       | 0        | 0         | 0       |
| Design_2 |             34097 |           16913 |             1550 |       91 |             10189 |             31511 |          2586 |                9021 |             37 |   11 |        125 | 0            |           1 |          1 |        4 |       2 |          1 | 0       |                         4 |                       2 |                          16 |     16 |     46 |       10 | 0       |          2 |         2 | 0       |      2 | 0       |       4 | 0         | 0        | 0         | 0           | 0       | 0        | 0         | 0       |
| -------- |                   |                 |                  |          |                   |                   |               |                     |                |      |            |              |             |            |          |         |            |         |                           |                         |                             |        |        |          |         |            |           |         |        |         |         |           |          |           |             |         |          |           |         |
| (2)/(1)  | 0.999208768022506 |               1 | 1.06675843083276 |        1 | 0.991919781931464 | 0.999143889910584 |             1 |    1.00011086474501 |              1 |    1 |          1 | #DIV/0!      |           1 |          1 |        1 |       1 |          1 | #DIV/0! |                         1 |                       1 |                           1 |      1 |      1 |        1 | #DIV/0! |          1 |         1 | #DIV/0! |      1 | #DIV/0! |       1 | #DIV/0!   | #DIV/0!  | #DIV/0!   | #DIV/0!     | #DIV/0! | #DIV/0!  | #DIV/0!   | #DIV/0! |
+----------+-------------------+-----------------+------------------+----------+-------------------+-------------------+---------------+---------------------+----------------+------+------------+--------------+-------------+------------+----------+---------+------------+---------+---------------------------+-------------------------+-----------------------------+--------+--------+----------+---------+------------+-----------+---------+--------+---------+---------+-----------+----------+-----------+-------------+---------+----------+-----------+---------+


问:
is there any other use of & other than bitwise AND
I am going through SCJP 6 book by Kathy and Bret and came across some text from this book, chapter 4 (operators)

Because you know by
  now that Java is not C++, you won't be surprised that Java operators aren't typically
  overloaded. There are, however, a few exceptional operators that come overloaded:

The + operator can be used to add two numeric primitives together, or to
perform a concatenation operation if either operand is a String.

The &, |, and ^ operators can all be used in two different ways, although as
of this version of the exam, their bit-twiddling capabilities won't be tested.

I am failing to understand the second use of &, | and ^ operators in java other than bitwise AND, OR and XOR respectively. What are the two different ways of using & operator in java?

答:
& can be applied on two boolean operands as a non short circuiting version of binary AND operator (unlike the short circuiting && operator).

| can be applied on two boolean operands as a non short circuiting version of binary OR operator (unlike the short circuiting || operator).

^ (XOR) can also be applied on two boolean operands.

To summarize, all 3 operators can serve as boolean operators (when applied to boolean operands) or bit-wise operators (when applies to integer operands).

These operators are described in JLS 15.22.2.:

15.22.2. Boolean Logical Operators &, ^, and |

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.


问:
Resolve Type from Class Name in a Different Assembly
I have a method where I need to resolve the Type of a class. This class exists in another assembly with the namespace similar to:

```<code>MyProject.Domain.Model
</code>```

I am attempting to perform the following:

```<code>Type.GetType("MyProject.Domain.Model." + myClassName);
</code>```

This works great if the code that is performing this action is in the same assembly as the class whose type I am trying to resolve, however, if my class is in a different assembly, this code fails.

I am sure there is a far better way to accomplish this task, but I have not had a lot of experience with resolving assemblies and traversing namespaces within to resolve the type of the class I am looking for. Any advice or tips to accomplish this task more gracefully?

答:
Similar to the OP, I needed to load a limited subset of types by name (in my case all of the classes were in a single assembly and implemented the same interface). I had a lot of weird issues when trying to use Type.GetType(string) against a different assembly (even adding the AssemblyQualifiedName as mentioned in other posts). Here is how I solved the issue:

Usage:

```<code>var mytype = TypeConverter<ICommand>.FromString("CreateCustomer");
</code>```

Code:

    public class TypeConverter<BaseType>
        {
            private static Dictionary<string, Type> _types;
            private static object _lock = new object();

            public static Type FromString(string typeName)
            {
                if (_types == null) CacheTypes();

                if (_types.ContainsKey(typeName))
                {
                    return _types[typeName];
                }
                else
                {
                    return null;
                }
            }

            private static void CacheTypes()
            {
                lock (_lock)
                {
                    if (_types == null)
                    {
                        // Initialize the myTypes list.
                        var baseType = typeof(BaseType);
                        var typeAssembly = baseType.Assembly;
                        var types = typeAssembly.GetTypes().Where(t =>
                            t.IsClass &&
                            !t.IsAbstract &&
                            baseType.IsAssignableFrom(t));

                        _types = types.ToDictionary(t => t.Name);
                    }
                }
            }
        }
```

Obviously you could tweak the CacheTypes method to inspect all assemblies in the AppDomain, or other logic that better fits your use-case.  If your use-case allows for types to be loaded from multiple namespaces, you might want to change the dictionary key to use the type's FullName instead.  Or if your types don't inherit from a common interface or base class, you could remove the <BaseType> and change the CacheTypes method to use something like .GetTypes().Where(t => t.Namespace.StartsWith("MyProject.Domain.Model.")

ContentLicense: CC BY-SA 2.5

Body:
I have a method where I need to resolve the Type of a class. This class exists in another assembly with the namespace similar to:

MyProject.Domain.Model

I am attempting to perform the following:

Type.GetType("MyProject.Domain.Model." + myClassName);

This works great if the code that is performing this action is in the same assembly as the class whose type I am trying to resolve, however, if my class is in a different assembly, this code fails.

I am sure there is a far better way to accomplish this task, but I have not had a lot of experience with resolving assemblies and traversing namespaces within to resolve the type of the class I am looking for. Any advice or tips to accomplish this task more gracefully?

Body:
Similar to the OP, I needed to load a limited subset of types by name (in my case all of the classes were in a single assembly and implemented the same interface). I had a lot of weird issues when trying to use Type.GetType(string) against a different assembly (even adding the AssemblyQualifiedName as mentioned in other posts). Here is how I solved the issue:

Usage:

var mytype = TypeConverter<ICommand>.FromString("CreateCustomer");

Code:

    public class TypeConverter<BaseType>
        {
            private static Dictionary<string, Type> _types;
            private static object _lock = new object();

            public static Type FromString(string typeName)
            {
                if (_types == null) CacheTypes();

                if (_types.ContainsKey(typeName))
                {
                    return _types[typeName];
                }
                else
                {
                    return null;
                }
            }

            private static void CacheTypes()
            {
                lock (_lock)
                {
                    if (_types == null)
                    {
                        // Initialize the myTypes list.
                        var baseType = typeof(BaseType);
                        var typeAssembly = baseType.Assembly;
                        var types = typeAssembly.GetTypes().Where(t =>
                            t.IsClass &&
                            !t.IsAbstract &&
                            baseType.IsAssignableFrom(t));

                        _types = types.ToDictionary(t => t.Name);
                    }
                }
            }
        }

Obviously you could tweak the CacheTypes method to inspect all assemblies in the AppDomain, or other logic that better fits your use-case.  If your use-case allows for types to be loaded from multiple namespaces, you might want to change the dictionary key to use the type's FullName instead.  Or if your types don't inherit from a common interface or base class, you could remove the <BaseType> and change the CacheTypes method to use something like .GetTypes().Where(t => t.Namespace.StartsWith("MyProject.Domain.Model.")