问:
Overlap between mask and fired beams in Pygame [AI car model vision]
I try to implement beam collision detection with a predefined track mask in Pygame. My final goal is to give an AI car model vision to see a track it's riding on:

This is my current code where I fire beams to mask and try to find an overlap:

import math
import sys

import pygame as pg

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

pg.init()
beam_surface = pg.Surface((500, 500), pg.SRCALPHA)

def draw_beam(surface, angle, pos):
    # compute beam final point
    x_dest = 250 + 500 * math.cos(math.radians(angle))
    y_dest = 250 + 500 * math.sin(math.radians(angle))

    beam_surface.fill((0, 0, 0, 0))

    # draw a single beam to the beam surface based on computed final point
    pg.draw.line(beam_surface, BLUE, (250, 250), (x_dest, y_dest))
    beam_mask = pg.mask.from_surface(beam_surface)

    # find overlap between "global mask" and current beam mask
    hit = mask.overlap(beam_mask, (pos[0] - 250, pos[1] - 250))
    if hit is not None:
        pg.draw.line(surface, BLUE, mouse_pos, hit)
        pg.draw.circle(surface, GREEN, hit, 3)

surface = pg.display.set_mode((500, 500))
mask_surface = pg.image.load("../assets/mask.png")
mask = pg.mask.from_surface(mask_surface)
clock = pg.time.Clock()

while True:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            pg.quit()
            sys.exit()

    mouse_pos = pg.mouse.get_pos()

    surface.fill((0, 0, 0))
    surface.blit(mask_surface, mask_surface.get_rect())

    for angle in range(0, 120, 30):
        draw_beam(surface, angle, mouse_pos)

    pg.display.update()
    clock.tick(30)

```

Let's describe what happens in the code snippet. One by one, I draw beams to beam_surface, make masks from them, and find overlap with background mask defined by one rectangle and a circle (black color in gifs). If there is a "hit point" (overlap point between both masks), I draw it with a line connecting hit point and mouse position.

It works fine for angles <0,90>:

But it's not working for angles in range <90,360>:

Pygame's overlap() documentation tells this:

Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1).

This means that this approach will work only if the beam hits the mask approximately from the top left corner. Do you have any advice on how to make it work for all of the situations? Is this generally a good approach to solve this problem?

答:
Your approach works fine, if the x and y component of the ray axis points in the positive direction, but it fails if it points in the negative direction. As you pointed out, that is caused by the way pygame.mask.Mask.overlap works:

Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1).

To make the algorithm work, you have to ensure that the rays point always in the positive direction. Hence if the ray points in the negative x direction, then flip the mask and the ray vertical and if the ray points in the negative y direction than flip the ray horizontal.

Use pygame.transform.flip() top create 4 masks. Not flipped, flipped horizontal, flipped vertical and flipped vertical and horizontal:

mask = pg.mask.from_surface(mask_surface)
mask_fx = pg.mask.from_surface(pg.transform.flip(mask_surface, True, False))
mask_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, False, True))
mask_fx_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, True, True))
flipped_masks = [[mask, mask_fy], [mask_fx, mask_fx_fy]]
```
<p>Determine if the direction of the ray:</p>
<pre class="lang-py prettyprint-override"><code>c = math.cos(math.radians(angle))
s = math.sin(math.radians(angle))
</code>```

Get the flipped mask dependent on the direction of the ray:

flip_x = c < 0
flip_y = s < 0
filpped_mask = flipped_masks[flip_x][flip_y]
```
<p>Compute the <em>flipped</em> target point:</p>
<pre class="lang-py prettyprint-override"><code>x_dest = 250 + 500 * abs(c)
y_dest = 250 + 500 * abs(s)
</code>```

Compute the flipped offset:

offset_x = 250 - pos[0] if flip_x else pos[0] - 250
offset_y = 250 - pos[1] if flip_y else pos[1] - 250
```
<p>Get the nearest intersection point of the <em>flipped</em> ray and mask and <em>unflip</em> the intersection point:</p>
<pre class="lang-py prettyprint-override"><code>hit = filpped_mask.overlap(beam_mask, (offset_x, offset_y))
if hit is not None and (hit[0] != pos[0] or hit[1] != pos[1]):
    hx = 500 - hit[0] if flip_x else hit[0]
    hy = 500 - hit[1] if flip_y else hit[1]
    hit_pos = (hx, hy)

    pg.draw.line(surface, BLUE, mouse_pos, hit_pos)
    pg.draw.circle(surface, GREEN, hit_pos, 3)
</code>```

See the example:  repl.it/@Rabbid76/PyGame-PyGame-SurfaceLineMaskIntersect-2

import math
import sys
import pygame as pg

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

pg.init()
beam_surface = pg.Surface((500, 500), pg.SRCALPHA)

def draw_beam(surface, angle, pos):
    c = math.cos(math.radians(angle))
    s = math.sin(math.radians(angle))

    flip_x = c < 0
    flip_y = s < 0
    filpped_mask = flipped_masks[flip_x][flip_y]

    # compute beam final point
    x_dest = 250 + 500 * abs(c)
    y_dest = 250 + 500 * abs(s)

    beam_surface.fill((0, 0, 0, 0))

    # draw a single beam to the beam surface based on computed final point
    pg.draw.line(beam_surface, BLUE, (250, 250), (x_dest, y_dest))
    beam_mask = pg.mask.from_surface(beam_surface)

    # find overlap between "global mask" and current beam mask
    offset_x = 250 - pos[0] if flip_x else pos[0] - 250
    offset_y = 250 - pos[1] if flip_y else pos[1] - 250
    hit = filpped_mask.overlap(beam_mask, (offset_x, offset_y))
    if hit is not None and (hit[0] != pos[0] or hit[1] != pos[1]):
        hx = 499 - hit[0] if flip_x else hit[0]
        hy = 499 - hit[1] if flip_y else hit[1]
        hit_pos = (hx, hy)

        pg.draw.line(surface, BLUE, pos, hit_pos)
        pg.draw.circle(surface, GREEN, hit_pos, 3)
        #pg.draw.circle(surface, (255, 255, 0), mouse_pos, 3)

surface = pg.display.set_mode((500, 500))
#mask_surface = pg.image.load("../assets/mask.png")
mask_surface = pg.Surface((500, 500), pg.SRCALPHA)
mask_surface.fill((255, 0, 0))
pg.draw.circle(mask_surface, (0, 0, 0, 0), (250, 250), 100)
pg.draw.rect(mask_surface, (0, 0, 0, 0), (170, 170, 160, 160))

mask = pg.mask.from_surface(mask_surface)
mask_fx = pg.mask.from_surface(pg.transform.flip(mask_surface, True, False))
mask_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, False, True))
mask_fx_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, True, True))
flipped_masks = [[mask, mask_fy], [mask_fx, mask_fx_fy]]

clock = pg.time.Clock()

while True:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            pg.quit()
            sys.exit()

    mouse_pos = pg.mouse.get_pos()

    surface.fill((0, 0, 0))
    surface.blit(mask_surface, mask_surface.get_rect())

    for angle in range(0, 359, 30):
        draw_beam(surface, angle, mouse_pos)

    pg.display.update()
    clock.tick(30)
```
<hr />
<p>Not,the algorithm can be further improved. The ray is always drawn on the bottom right quadrant of the <code>beam_surface</code>. Hence the other 3 quadrants are no longer needed and the size of <code>beam_surface</code> can be reduced to 250x250. The start of the ray is at (0, 0) rather than (250, 250) and the computation of the offsets hast to be slightly adapted:</p>
<pre class="lang-py prettyprint-override"><code>beam_surface = pg.Surface((250, 250), pg.SRCALPHA)

def draw_beam(surface, angle, pos):
    c = math.cos(math.radians(angle))
    s = math.sin(math.radians(angle))

    flip_x = c < 0
    flip_y = s < 0
    filpped_mask = flipped_masks[flip_x][flip_y]

    # compute beam final point
    x_dest = 500 * abs(c)
    y_dest = 500 * abs(s)

    beam_surface.fill((0, 0, 0, 0))

    # draw a single beam to the beam surface based on computed final point
    pg.draw.line(beam_surface, BLUE, (0, 0), (x_dest, y_dest))
    beam_mask = pg.mask.from_surface(beam_surface)

    # find overlap between "global mask" and current beam mask
    offset_x = 499-pos[0] if flip_x else pos[0]
    offset_y = 499-pos[1] if flip_y else pos[1]
    hit = filpped_mask.overlap(beam_mask, (offset_x, offset_y))
    if hit is not None and (hit[0] != pos[0] or hit[1] != pos[1]):
        hx = 499 - hit[0] if flip_x else hit[0]
        hy = 499 - hit[1] if flip_y else hit[1]
        hit_pos = (hx, hy)

        pg.draw.line(surface, BLUE, pos, hit_pos)
        pg.draw.circle(surface, GREEN, hit_pos, 3)
</code>```

Body:
I try to implement beam collision detection with a predefined track mask in Pygame. My final goal is to give an AI car model vision to see a track it's riding on:

This is my current code where I fire beams to mask and try to find an overlap:

import math
import sys

import pygame as pg

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

pg.init()
beam_surface = pg.Surface((500, 500), pg.SRCALPHA)

def draw_beam(surface, angle, pos):
    # compute beam final point
    x_dest = 250 + 500 * math.cos(math.radians(angle))
    y_dest = 250 + 500 * math.sin(math.radians(angle))

    beam_surface.fill((0, 0, 0, 0))

    # draw a single beam to the beam surface based on computed final point
    pg.draw.line(beam_surface, BLUE, (250, 250), (x_dest, y_dest))
    beam_mask = pg.mask.from_surface(beam_surface)

    # find overlap between "global mask" and current beam mask
    hit = mask.overlap(beam_mask, (pos[0] - 250, pos[1] - 250))
    if hit is not None:
        pg.draw.line(surface, BLUE, mouse_pos, hit)
        pg.draw.circle(surface, GREEN, hit, 3)

surface = pg.display.set_mode((500, 500))
mask_surface = pg.image.load("../assets/mask.png")
mask = pg.mask.from_surface(mask_surface)
clock = pg.time.Clock()

while True:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            pg.quit()
            sys.exit()

    mouse_pos = pg.mouse.get_pos()

    surface.fill((0, 0, 0))
    surface.blit(mask_surface, mask_surface.get_rect())

    for angle in range(0, 120, 30):
        draw_beam(surface, angle, mouse_pos)

    pg.display.update()
    clock.tick(30)

Let's describe what happens in the code snippet. One by one, I draw beams to beam_surface, make masks from them, and find overlap with background mask defined by one rectangle and a circle (black color in gifs). If there is a "hit point" (overlap point between both masks), I draw it with a line connecting hit point and mouse position.

It works fine for angles <0,90>:

But it's not working for angles in range <90,360>:

Pygame's overlap() documentation tells this:

Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1).

This means that this approach will work only if the beam hits the mask approximately from the top left corner. Do you have any advice on how to make it work for all of the situations? Is this generally a good approach to solve this problem?

Body:
Your approach works fine, if the x and y component of the ray axis points in the positive direction, but it fails if it points in the negative direction. As you pointed out, that is caused by the way pygame.mask.Mask.overlap works:

Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1).

To make the algorithm work, you have to ensure that the rays point always in the positive direction. Hence if the ray points in the negative x direction, then flip the mask and the ray vertical and if the ray points in the negative y direction than flip the ray horizontal.

Use pygame.transform.flip() top create 4 masks. Not flipped, flipped horizontal, flipped vertical and flipped vertical and horizontal:

mask = pg.mask.from_surface(mask_surface)
mask_fx = pg.mask.from_surface(pg.transform.flip(mask_surface, True, False))
mask_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, False, True))
mask_fx_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, True, True))
flipped_masks = [[mask, mask_fy], [mask_fx, mask_fx_fy]]

Determine if the direction of the ray:

c = math.cos(math.radians(angle))
s = math.sin(math.radians(angle))

Get the flipped mask dependent on the direction of the ray:

flip_x = c < 0
flip_y = s < 0
filpped_mask = flipped_masks[flip_x][flip_y]

Compute the flipped target point:

x_dest = 250 + 500 * abs(c)
y_dest = 250 + 500 * abs(s)

Compute the flipped offset:

offset_x = 250 - pos[0] if flip_x else pos[0] - 250
offset_y = 250 - pos[1] if flip_y else pos[1] - 250

Get the nearest intersection point of the flipped ray and mask and unflip the intersection point:

hit = filpped_mask.overlap(beam_mask, (offset_x, offset_y))
if hit is not None and (hit[0] != pos[0] or hit[1] != pos[1]):
    hx = 500 - hit[0] if flip_x else hit[0]
    hy = 500 - hit[1] if flip_y else hit[1]
    hit_pos = (hx, hy)

    pg.draw.line(surface, BLUE, mouse_pos, hit_pos)
    pg.draw.circle(surface, GREEN, hit_pos, 3)

See the example:  repl.it/@Rabbid76/PyGame-PyGame-SurfaceLineMaskIntersect-2

import math
import sys
import pygame as pg

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

pg.init()
beam_surface = pg.Surface((500, 500), pg.SRCALPHA)

def draw_beam(surface, angle, pos):
    c = math.cos(math.radians(angle))
    s = math.sin(math.radians(angle))

    flip_x = c < 0
    flip_y = s < 0
    filpped_mask = flipped_masks[flip_x][flip_y]

    # compute beam final point
    x_dest = 250 + 500 * abs(c)
    y_dest = 250 + 500 * abs(s)

    beam_surface.fill((0, 0, 0, 0))

    # draw a single beam to the beam surface based on computed final point
    pg.draw.line(beam_surface, BLUE, (250, 250), (x_dest, y_dest))
    beam_mask = pg.mask.from_surface(beam_surface)

    # find overlap between "global mask" and current beam mask
    offset_x = 250 - pos[0] if flip_x else pos[0] - 250
    offset_y = 250 - pos[1] if flip_y else pos[1] - 250
    hit = filpped_mask.overlap(beam_mask, (offset_x, offset_y))
    if hit is not None and (hit[0] != pos[0] or hit[1] != pos[1]):
        hx = 499 - hit[0] if flip_x else hit[0]
        hy = 499 - hit[1] if flip_y else hit[1]
        hit_pos = (hx, hy)

        pg.draw.line(surface, BLUE, pos, hit_pos)
        pg.draw.circle(surface, GREEN, hit_pos, 3)
        #pg.draw.circle(surface, (255, 255, 0), mouse_pos, 3)

surface = pg.display.set_mode((500, 500))
#mask_surface = pg.image.load("../assets/mask.png")
mask_surface = pg.Surface((500, 500), pg.SRCALPHA)
mask_surface.fill((255, 0, 0))
pg.draw.circle(mask_surface, (0, 0, 0, 0), (250, 250), 100)
pg.draw.rect(mask_surface, (0, 0, 0, 0), (170, 170, 160, 160))

mask = pg.mask.from_surface(mask_surface)
mask_fx = pg.mask.from_surface(pg.transform.flip(mask_surface, True, False))
mask_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, False, True))
mask_fx_fy = pg.mask.from_surface(pg.transform.flip(mask_surface, True, True))
flipped_masks = [[mask, mask_fy], [mask_fx, mask_fx_fy]]

clock = pg.time.Clock()

while True:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            pg.quit()
            sys.exit()

    mouse_pos = pg.mouse.get_pos()

    surface.fill((0, 0, 0))
    surface.blit(mask_surface, mask_surface.get_rect())

    for angle in range(0, 359, 30):
        draw_beam(surface, angle, mouse_pos)

    pg.display.update()
    clock.tick(30)

Not,the algorithm can be further improved. The ray is always drawn on the bottom right quadrant of the beam_surface. Hence the other 3 quadrants are no longer needed and the size of beam_surface can be reduced to 250x250. The start of the ray is at (0, 0) rather than (250, 250) and the computation of the offsets hast to be slightly adapted:

beam_surface = pg.Surface((250, 250), pg.SRCALPHA)

def draw_beam(surface, angle, pos):
    c = math.cos(math.radians(angle))
    s = math.sin(math.radians(angle))

    flip_x = c < 0
    flip_y = s < 0
    filpped_mask = flipped_masks[flip_x][flip_y]

    # compute beam final point
    x_dest = 500 * abs(c)
    y_dest = 500 * abs(s)

    beam_surface.fill((0, 0, 0, 0))

    # draw a single beam to the beam surface based on computed final point
    pg.draw.line(beam_surface, BLUE, (0, 0), (x_dest, y_dest))
    beam_mask = pg.mask.from_surface(beam_surface)

    # find overlap between "global mask" and current beam mask
    offset_x = 499-pos[0] if flip_x else pos[0]
    offset_y = 499-pos[1] if flip_y else pos[1]
    hit = filpped_mask.overlap(beam_mask, (offset_x, offset_y))
    if hit is not None and (hit[0] != pos[0] or hit[1] != pos[1]):
        hx = 499 - hit[0] if flip_x else hit[0]
        hy = 499 - hit[1] if flip_y else hit[1]
        hit_pos = (hx, hy)

        pg.draw.line(surface, BLUE, pos, hit_pos)
        pg.draw.circle(surface, GREEN, hit_pos, 3)


来源: stackexchange

问:
How can I change the properties of an instantiated gameObject in game?
In my game I have a spawner which instantiates a gameObject multiple times (the game it's like a runner). Now this gameObject has a script which has void Start() and in the void start it has a function that makes the gameobject to take a random color. Every time I run the game and the first prefab takes a color (ex. green) and then the second one takes another color (ex. red) - but this first object takes the color of the second, like it has the void start multiple times. How to fix that?

答:
You could have a simple static counter like e.g.

```<code>private static Color[] colors = new []{
    Color.green,
    Color.red,
    Color.blue,
    Color.yellow,
    Color.black
};

private static int index = 0;

private void Start()
{
    if(index => colors.Length)
    {
        Debug.LogError("Not enough colors!", this);
        return;
    }

    GetComponent<Renderer>().material.color = colors[index];
    index++;
}
</code>```

Or if you want it random as you say you could do e.g.

```<code>private static Color[] colors = new []{
    Color.green,
    Color.red,
    Color.blue,
    Color.yellow,
    Color.black
};

private static int index = 0;

private void Start()
{
    if(index => colors.Length)
    {
        Debug.LogError("Not enough colors!", this);
        return;
    }

    if(index == 0)
    {
        // the first time shuffle up the array
        var rnd = new Random();
        colors = colors.OrderBy((c) => rnd.Next()).ToArray();
    }

    GetComponent<Renderer>().material.color = colors[index];
    index++;
}
</code>```

Or if you really want it completely random you could simply do (might have multiple "equal" or very similar results though)

```<code>private void Start()
{
    GetComponent<Renderer>().material.color = GetCompletelyRandomColor();
}

private static Color GetCompletelyRandomColor()
{
    var r = Random.Range(0f, 1f);
    var g = Random.Range(0f, 1f);
    var b = Random.Range(0f, 1f);

    return new Color(r, g, b);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You could have a simple static counter like e.g.

private static Color[] colors = new []{
    Color.green,
    Color.red,
    Color.blue,
    Color.yellow,
    Color.black
};

private static int index = 0;

private void Start()
{
    if(index => colors.Length)
    {
        Debug.LogError("Not enough colors!", this);
        return;
    }

    GetComponent<Renderer>().material.color = colors[index];
    index++;
}

Or if you want it random as you say you could do e.g.

private static Color[] colors = new []{
    Color.green,
    Color.red,
    Color.blue,
    Color.yellow,
    Color.black
};

private static int index = 0;

private void Start()
{
    if(index => colors.Length)
    {
        Debug.LogError("Not enough colors!", this);
        return;
    }

    if(index == 0)
    {
        // the first time shuffle up the array
        var rnd = new Random();
        colors = colors.OrderBy((c) => rnd.Next()).ToArray();
    }

    GetComponent<Renderer>().material.color = colors[index];
    index++;
}

Or if you really want it completely random you could simply do (might have multiple "equal" or very similar results though)

private void Start()
{
    GetComponent<Renderer>().material.color = GetCompletelyRandomColor();
}

private static Color GetCompletelyRandomColor()
{
    var r = Random.Range(0f, 1f);
    var g = Random.Range(0f, 1f);
    var b = Random.Range(0f, 1f);

    return new Color(r, g, b);
}


问:
how to show RGB images in python
I have a RGB dataset like that:

```<code>   [[ 255 165 0]
    [255 255 0]
    [0  255 0]]
</code>```

I want to show each row's color,separate 3 PNG images, each 64x64 pixels
Is there some method existed in matplotlib or opencv?

答:
In OpenCV (and most other Python imaging libraries) an image is represented by a Numpy array. So, if you want to make a 3-channel (i.e. colour) image full of [255, 165, 0] you just need:

```<code>import cv2
import numpy as np

# Make 64x64 pixel colour image
im = np.full((64,64,3), [255,165,0], dtype=np.uint8)

# Save to disk
cv2.imwrite('result.png', im)
</code>```

Note that OpenCV uses BGR ordering, so if your 3 values are in fact RGB, you need:

```<code>im = np.full((64,64,3), [0,165,255], dtype=np.uint8)
</code>```

Title: how to show RGB images in python

Body:
I have a RGB dataset like that:

   [[ 255 165 0]
    [255 255 0]
    [0  255 0]]

I want to show each row's color,separate 3 PNG images, each 64x64 pixels
Is there some method existed in matplotlib or opencv?

Body:
In OpenCV (and most other Python imaging libraries) an image is represented by a Numpy array. So, if you want to make a 3-channel (i.e. colour) image full of [255, 165, 0] you just need:

import cv2
import numpy as np

# Make 64x64 pixel colour image
im = np.full((64,64,3), [255,165,0], dtype=np.uint8)

# Save to disk
cv2.imwrite('result.png', im)

Note that OpenCV uses BGR ordering, so if your 3 values are in fact RGB, you need:

im = np.full((64,64,3), [0,165,255], dtype=np.uint8)


问:
ScrollView moved AdMob ads
Well before my ads were working fine and were always at the bottom of the screen, but now I added a scrollview and the ads move up a little bit to be right under my scrollbar.

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/pattern_carbon_fiber_dark">

<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_height="339px">

<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">

<TextView android:text="Silent Mode" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/silent_textview"></TextView>
<ToggleButton android:layout_height="wrap_content" android:text="Silent Mode" android:id="@+id/silentbutton" android:layout_width="wrap_content" android:textOff="OFF" android:textOn="ON"></ToggleButton>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Wifi " android:id="@+id/wifi_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:layout_height="wrap_content" android:id="@+id/wifibutton"></ToggleButton>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/gps" android:id="@+id/gps_textview"></TextView>
<Button android:text="@string/gpsbutton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/gps"></Button>
<TextView android:layout_width="wrap_content" android:text="@string/bluetooth" android:layout_height="wrap_content" android:id="@+id/bluetooth_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:id="@+id/bluetooth" android:layout_height="wrap_content"></ToggleButton>
<TextView android:text="@string/brightness" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/screenbrightness_textview"></TextView>
<SeekBar android:layout_height="wrap_content" android:id="@+id/SbBar" android:layout_width="fill_parent" android:max="255"></SeekBar>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="wrap_content">

<com.google.ads.AdView
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/adView"
android:layout_width="fill_parent"
ads:adSize="BANNER"
ads:adUnitId="a14ddb1a61b9fb4"
ads:loadAdOnCreate="true"
android:visibility="visible"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
</com.google.ads.AdView>

 </RelativeLayout>
 </LinearLayout>
 </ScrollView>
 </LinearLayout>
</code>```

Please help, thanks!

EDIT: Picture

UI pic http://img52.imageshack.us/img52/9397/unledyv.png

答:
1) You will probably leave the ads outside the scollview so they are always visible (as opposed to scroll out of the screen)

2) What is the purpose of the relativelayout surrounding the adview? That is the only view inside it: just remove it and you will get the same layout, but better performance.

Based on the update, I suggest you to try this layout (you will need to fill many blanks):

```<code><RelativeLayout
...
>
<AdView
android:id="@+id/adView"
android:layout_alignParentBottom="true"
...
/>
<ScrollView
android:layout_alignParentTop="true"
android:layout_above="@id/adView"
...
>
<LinearLayout
...
>
...
...
</LinearLayout>
</ScrollView>
</RelativeLayout>
</code>```

The basic idea is to put the AdView ad the bottom of the screen using a RelativeLayout, and then setting the ScollView to be placed above the ads (so it does not block them) and aligned to the top of the screen.

ContentLicense: CC BY-SA 3.0

Title: ScrollView moved AdMob ads

Body:
Well before my ads were working fine and were always at the bottom of the screen, but now I added a scrollview and the ads move up a little bit to be right under my scrollbar.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/pattern_carbon_fiber_dark">

<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_height="339px">

<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">

<TextView android:text="Silent Mode" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/silent_textview"></TextView>
<ToggleButton android:layout_height="wrap_content" android:text="Silent Mode" android:id="@+id/silentbutton" android:layout_width="wrap_content" android:textOff="OFF" android:textOn="ON"></ToggleButton>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Wifi " android:id="@+id/wifi_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:layout_height="wrap_content" android:id="@+id/wifibutton"></ToggleButton>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/gps" android:id="@+id/gps_textview"></TextView>
<Button android:text="@string/gpsbutton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/gps"></Button>
<TextView android:layout_width="wrap_content" android:text="@string/bluetooth" android:layout_height="wrap_content" android:id="@+id/bluetooth_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:id="@+id/bluetooth" android:layout_height="wrap_content"></ToggleButton>
<TextView android:text="@string/brightness" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/screenbrightness_textview"></TextView>
<SeekBar android:layout_height="wrap_content" android:id="@+id/SbBar" android:layout_width="fill_parent" android:max="255"></SeekBar>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="wrap_content">

<com.google.ads.AdView
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/adView"
android:layout_width="fill_parent"
ads:adSize="BANNER"
ads:adUnitId="a14ddb1a61b9fb4"
ads:loadAdOnCreate="true"
android:visibility="visible"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
</com.google.ads.AdView>

 </RelativeLayout>
 </LinearLayout>
 </ScrollView>
 </LinearLayout>

Please help, thanks!

EDIT: Picture

UI pic http://img52.imageshack.us/img52/9397/unledyv.png

Body:
1) You will probably leave the ads outside the scollview so they are always visible (as opposed to scroll out of the screen)

2) What is the purpose of the relativelayout surrounding the adview? That is the only view inside it: just remove it and you will get the same layout, but better performance.

Based on the update, I suggest you to try this layout (you will need to fill many blanks):

<RelativeLayout
...
>
<AdView
android:id="@+id/adView"
android:layout_alignParentBottom="true"
...
/>
<ScrollView
android:layout_alignParentTop="true"
android:layout_above="@id/adView"
...
>
<LinearLayout
...
>
...
...
</LinearLayout>
</ScrollView>
</RelativeLayout>

The basic idea is to put the AdView ad the bottom of the screen using a RelativeLayout, and then setting the ScollView to be placed above the ads (so it does not block them) and aligned to the top of the screen.


问:
Getting undefined from puppeeter evaluate function
When I run this -->

```<code>let uiElement = await page.evaluate(() => document.querySelector('div[class=unf-emptystate-img]').innerHTML)
    console.log(uiElement)
</code>```

I get the correct value

```<code><img alt="Waduh, tujuanmu nggak ada!" src="https://ecs7.tokopedia.net/assets-unify/img/il-error-not-found.png">
</code>```

But when I try to use

```<code>    let uiElement = await page.evaluate(() => document.querySelector('div[class=unf-emptystate-img]'))
console.log(uiElement.innerHTML)
</code>```

I get

```<code>TypeError: Cannot read property 'innerHTML' of undefined
</code>```

How do I get uiElement.innerHTML without calling the innerHTML function inside the evaluate function?

答:
if you use page.$(), you can access the innerHTML, see this example:

```<code>const date = await page.$('div[class=unf-emptystate-img]');

console.log(await (await date.getProperty('innerHTML')).jsonValue());
</code>```

or see this complete example:

```<code>const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        slowMo: 250 // slow down by 250ms
    });
    const page = await browser.newPage();

    await page.goto('https://v4-alpha.getbootstrap.com/components/forms/');

    const date = await page.$('.lead');

    console.log(await (await date.getProperty('innerHTML')).jsonValue());

})();
</code>```

Body:
When I run this -->

let uiElement = await page.evaluate(() => document.querySelector('div[class=unf-emptystate-img]').innerHTML)
    console.log(uiElement)

I get the correct value

But when I try to use

    let uiElement = await page.evaluate(() => document.querySelector('div[class=unf-emptystate-img]'))
console.log(uiElement.innerHTML)

I get

TypeError: Cannot read property 'innerHTML' of undefined

How do I get uiElement.innerHTML without calling the innerHTML function inside the evaluate function?

Body:
if you use page.$(), you can access the innerHTML, see this example:

const date = await page.$('div[class=unf-emptystate-img]');

console.log(await (await date.getProperty('innerHTML')).jsonValue());

or see this complete example:

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        slowMo: 250 // slow down by 250ms
    });
    const page = await browser.newPage();

    await page.goto('https://v4-alpha.getbootstrap.com/components/forms/');

    const date = await page.$('.lead');

    console.log(await (await date.getProperty('innerHTML')).jsonValue());

})();


问:
Android Gradle - Failed to resolve error when implementing Apache POI in gradle
I am trying to use the following library (https://github.com/SUPERCILEX/poi-android) so that my app can read the contents of a Word document. I have tried to follow the instructions in the accepted answer to this similar question: How to add POI Android in Android Studio? but to no avail. My question is different, as I have already defined the poiVersion variable in my project-level build.gradle file.

Below is the error:

ERROR: Failed to resolve: com.github.SUPERCILEX.poi-android:poi:3.17

Below is my code (project-level build.gradle):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
    ext {
        poiVersion = '3.17'
    }
    dependencies {
        classpath 'com.android.tools:r8:1.4.93'
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Below is my code (app-level build.gradle):

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "com.github.SUPERCILEX.poi-android:poi:$poiVersion"
}
</code>```

答:
Try implementing this to your build.gradle.kts</p>

```<code>dependencies {
       implementation("org.apache.poi","poi","4.1.2")
 }
</code>```

Body:
I am trying to use the following library (https://github.com/SUPERCILEX/poi-android) so that my app can read the contents of a Word document. I have tried to follow the instructions in the accepted answer to this similar question: How to add POI Android in Android Studio? but to no avail. My question is different, as I have already defined the poiVersion variable in my project-level build.gradle file.

Below is the error:

ERROR: Failed to resolve: com.github.SUPERCILEX.poi-android:poi:3.17

Below is my code (project-level build.gradle):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
    ext {
        poiVersion = '3.17'
    }
    dependencies {
        classpath 'com.android.tools:r8:1.4.93'
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Below is my code (app-level build.gradle):

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "com.github.SUPERCILEX.poi-android:poi:$poiVersion"
}

Body:
Try implementing this to your build.gradle.kts

dependencies {
       implementation("org.apache.poi","poi","4.1.2")
 }


问:
how to package kivy and python to executable file?
I have two files in a folder:

‘main.py`

calculator.kv

I tried packaging in command prompt with

```<code>pyinstaller main.py
</code>```

I am not getting any errors during the process, but when i try to open the EXE file I am not getting the desired window.

答:
make sure you have followed these steps from here.You didn't mention your exact spec file and the error you get. But i guess you are missing this important part in spec file :

```<code>from kivy_deps import sdl2, glew
coll = COLLECT(exe, Tree('examples-path\\demo\\touchtracer\\'),
               a.binaries,
               a.zipfiles,
               a.datas,
               *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
               strip=False,
               upx=True,
               name='touchtracer')
</code>```

Body:
I have two files in a folder:

‘main.py`

calculator.kv

I tried packaging in command prompt with

pyinstaller main.py

I am not getting any errors during the process, but when i try to open the EXE file I am not getting the desired window.

Body:
make sure you have followed these steps from here.You didn't mention your exact spec file and the error you get. But i guess you are missing this important part in spec file :

from kivy_deps import sdl2, glew
coll = COLLECT(exe, Tree('examples-path\\demo\\touchtracer\\'),
               a.binaries,
               a.zipfiles,
               a.datas,
               *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
               strip=False,
               upx=True,
               name='touchtracer')


问:
Proper way to structure a program formed by 3 sub-programs
I'm building a system formed by 3 programs, lets call them A, B and C. Right now I think that my file structure is a disaster.

Inside my root folder I have some shortcuts to .bat files that run the programs and a folder called programs_data. Inside that folder I have 4 separate folders, one for each program plus a common folder.
The issue is that I need each program and the sub-scripts in those programs to be able to import from the common folder and I need program C and B to be able to call program A API.

As it is right now, I have a mess of appending to sys.path in the sub files to import functions from upper levels.

What's the correct way to structure something like this?

Current structure:

```<code>root
├── Configuration.lnk
├── Documentation.lnk
├── Program A.lnk
├── Program B.lnk
├── Program C.lnk
├── programs_data
│   ├── Program A
│   │   ├── Program A API.py
│   │   ├── Program A.bat
│   │   ├── Program A.py
│   │   ├── src
│   │   │   ├── server.py
│   │   │   ├── test_functions.py
│   │   │   └── validation.py
│   │   └── targets
│   │       ├── sql_querys
│   │       │   ├── query1.sql
│   │       │   ├── query2.sql
│   │       │   └── queryn.sql
│   │       ├── target1.py
│   │       ├── target2.py
│   │       ├── target3.py
│   │       └── targetn.py
│   ├── Program B
│   │   ├── Program B.bat
│   │   ├── Program B.py
│   │   ├── classifiers
│   │   │   ├── classifier1.py
│   │   │   ├── classifier2.py
│   │   │   └── classifiern.py
│   │   ├── events.log
│   │   ├── o365_token.txt
│   │   └── src
│   │       ├── batchECImport.py
│   │       ├── classifier.py
│   │       └── logger.py
│   ├── Program C
│   │   ├── Program C.bat
│   │   ├── Program C.py
│   │   ├── Reports
│   │   │   ├── report 1
│   │   │   │   └── report.py
│   │   │   └── report 2
│   │   │       └── report.py
│   │   ├── o365_token.txt
│   │   ├── schedule.xlsx
│   │   └── src
│   │       └── report.py
│   └── common
│       ├── APIMailboxManager.py
│       ├── Documentation
│       │   └── Documentation.pdf
│       ├── FlexibleProcess.py
│       ├── config.py
│       ├── misc.py
│       ├── print_functions.py
│       ├── production_support_passwords.py
│       ├── reports_log.db
│       └── reports_log.py
└── schedule spreadsheet.Ink
</code>```

Thanks!

答:
You could use __init__.py files to configure the import path of your modules in each directory. Documentation here.
In these files, you should only add the relative path to the common folder.
I don't think there is an other way to have a common folder if you want to avoid duplicated code...

Body:
I'm building a system formed by 3 programs, lets call them A, B and C. Right now I think that my file structure is a disaster.

Inside my root folder I have some shortcuts to .bat files that run the programs and a folder called programs_data. Inside that folder I have 4 separate folders, one for each program plus a common folder.
The issue is that I need each program and the sub-scripts in those programs to be able to import from the common folder and I need program C and B to be able to call program A API.

As it is right now, I have a mess of appending to sys.path in the sub files to import functions from upper levels.

What's the correct way to structure something like this?

Current structure:

root
├── Configuration.lnk
├── Documentation.lnk
├── Program A.lnk
├── Program B.lnk
├── Program C.lnk
├── programs_data
│   ├── Program A
│   │   ├── Program A API.py
│   │   ├── Program A.bat
│   │   ├── Program A.py
│   │   ├── src
│   │   │   ├── server.py
│   │   │   ├── test_functions.py
│   │   │   └── validation.py
│   │   └── targets
│   │       ├── sql_querys
│   │       │   ├── query1.sql
│   │       │   ├── query2.sql
│   │       │   └── queryn.sql
│   │       ├── target1.py
│   │       ├── target2.py
│   │       ├── target3.py
│   │       └── targetn.py
│   ├── Program B
│   │   ├── Program B.bat
│   │   ├── Program B.py
│   │   ├── classifiers
│   │   │   ├── classifier1.py
│   │   │   ├── classifier2.py
│   │   │   └── classifiern.py
│   │   ├── events.log
│   │   ├── o365_token.txt
│   │   └── src
│   │       ├── batchECImport.py
│   │       ├── classifier.py
│   │       └── logger.py
│   ├── Program C
│   │   ├── Program C.bat
│   │   ├── Program C.py
│   │   ├── Reports
│   │   │   ├── report 1
│   │   │   │   └── report.py
│   │   │   └── report 2
│   │   │       └── report.py
│   │   ├── o365_token.txt
│   │   ├── schedule.xlsx
│   │   └── src
│   │       └── report.py
│   └── common
│       ├── APIMailboxManager.py
│       ├── Documentation
│       │   └── Documentation.pdf
│       ├── FlexibleProcess.py
│       ├── config.py
│       ├── misc.py
│       ├── print_functions.py
│       ├── production_support_passwords.py
│       ├── reports_log.db
│       └── reports_log.py
└── schedule spreadsheet.Ink

Thanks!


问:
How to set a variable and check it for null both in the "case when" conditions SQL
I have problem with this piece of code.

I need to do something like this:

```<code>DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END
</code>```

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

答:
like this?</p>

```<code>IF EXISTS (SELECT UserPk FROM Users WHERE Name= 'JoeDoe')
    SET @UserID = 0;
ELSE
    SET @UserID = 1;
</code>```

Body:
I have problem with this piece of code.

I need to do something like this:

DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

Body:
like this?

IF EXISTS (SELECT UserPk FROM Users WHERE Name= 'JoeDoe')
    SET @UserID = 0;
ELSE
    SET @UserID = 1;


问:
creating volume point on candle
I want to point out the highest volume on a candlestick with a vertical line. Now I only see this point inside the body of the candlestick (without seeing this point in the wick). I would include the wicks in this. Could someone help?

```<code>//@version=4
study("Name", overlay=true)
i = input(1, title="Volume Periods")
Name = barssince(volume == max(highest(volume, i), 0))
plot(close[Name], color=color.black, title="Name", style=plot.style_circles)
</code>```

enter image description here

The length of the horizontal line should be shorter.

答:
highestbars() returns the offset to the highest value:

```<code>//@version=4
study("Name", overlay=true)
i = input(10, title="Volume Periods")
ofst = - highestbars(volume, i)
line.new(bar_index[ofst], low[ofst], bar_index[ofst], high[ofst], color = color.new(color.silver, 0), width = 3)
</code>```

Title: creating volume point on candle

Body:
I want to point out the highest volume on a candlestick with a vertical line. Now I only see this point inside the body of the candlestick (without seeing this point in the wick). I would include the wicks in this. Could someone help?

//@version=4
study("Name", overlay=true)
i = input(1, title="Volume Periods")
Name = barssince(volume == max(highest(volume, i), 0))
plot(close[Name], color=color.black, title="Name", style=plot.style_circles)

enter image description here

The length of the horizontal line should be shorter.

Body:
highestbars() returns the offset to the highest value:

//@version=4
study("Name", overlay=true)
i = input(10, title="Volume Periods")
ofst = - highestbars(volume, i)
line.new(bar_index[ofst], low[ofst], bar_index[ofst], high[ofst], color = color.new(color.silver, 0), width = 3)


问:
Incorrect syntax near 'S' when passing string parameter
In c# I have the following lines of code:

```<code> string mySqlStmt = "SELECT CASE WHEN (SELECT COUNT(*)  FROM tlGenericName WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' ) ) > 0 THEN"
   + " ( SELECT top(1) isnull(genericNameCode_str, '') FROM tlGenericName "
       + " WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' )  ) ELSE '' END";
</code>```

Then I use an SqlCommand (in c#) for executeScalar.
However, I get the following error:

```<code>Incorrect syntax near 'S'
</code>```

I have noticed that this occurs for some records (a break in the parameter  value); for example:

'BANDAGE P.O.P.ROLL TYPE 1;200MMX2.7M 12's'

How can I safely pass the string parameter in Sql in the designer (c#) ?

答:
Escape the single quotes something like below:

```<code>this.cmbGenericName.Text.Trim().ToUpper().Replace("'", "''")
</code>```

Also as a suggestion as mentioned by Peter in the comment avoid using inline SQL statements to avoid the SQL injection attacks by using the SqlCommand and its parameters!

Body:
In c# I have the following lines of code:

 string mySqlStmt = "SELECT CASE WHEN (SELECT COUNT(*)  FROM tlGenericName WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' ) ) > 0 THEN"
   + " ( SELECT top(1) isnull(genericNameCode_str, '') FROM tlGenericName "
       + " WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' )  ) ELSE '' END";

Then I use an SqlCommand (in c#) for executeScalar.
However, I get the following error:

Incorrect syntax near 'S'

I have noticed that this occurs for some records (a break in the parameter  value); for example:

'BANDAGE P.O.P.ROLL TYPE 1;200MMX2.7M 12's'

How can I safely pass the string parameter in Sql in the designer (c#) ?

Body:
Escape the single quotes something like below:

this.cmbGenericName.Text.Trim().ToUpper().Replace("'", "''")

Also as a suggestion as mentioned by Peter in the comment avoid using inline SQL statements to avoid the SQL injection attacks by using the SqlCommand and its parameters!


问:
Filtering QuerySets by OR instead of AND
If I do:

```<code>People.filter(name = 'Oscar', lastName = 'Mederos)
</code>```

it will be translated to something like:

```<code>SELECT ______ WHERE Name = 'Oscar' AND LastName = 'Mederos
</code>```

Does Django allow to do the same but using OR instead of AND?

答:
Q objects.

```<code>People.objects.filter(Q(name='Oscar') | Q(lastName='Mederos'))
</code>```

Body:
If I do:

People.filter(name = 'Oscar', lastName = 'Mederos)

it will be translated to something like:

SELECT ______ WHERE Name = 'Oscar' AND LastName = 'Mederos

Does Django allow to do the same but using OR instead of AND?

Body:
Q objects.

People.objects.filter(Q(name='Oscar') | Q(lastName='Mederos'))


问:
PL/SQL UTL_HTTP send multiple raws
I'm trying to send with webservice POST method a dozens of records to other side but problem is that other side get only one raw of data.
I put cursor and in begin section open cursor and make loop.
I think the problem is somewhere in part UTL_HTTP.read_raw. I have to add something additional or modify function.
Where is the catch, where I'm wrong?

create or replace FUNCTION "TST" return clob is

```<code>l_http_request   UTL_HTTP.req;
l_http_response  UTL_HTTP.resp;
l_buffer_size    NUMBER(10) := 20000;
l_line_size      NUMBER(10) := 50;
l_lines_count    NUMBER(10) := 20;
l_string_request VARCHAR2(32767);
l_line           VARCHAR2(128);
l_substring_msg  VARCHAR2(20000);
l_raw_data       RAW(20000);
l_clob_response  CLOB ;
v_clob clob;
url varchar2(200) := 'http://tst';

cursor c_get_prihod is
select     IDORIG   ,    IDSUSTAVA  ,    DATUM  ,    SIFAGENCIJE    ,    SIFDRZAVE  ,
SIFOSUSL    ,    IZNOSNETO  ,    IZNOSBRUTO ,    IZNOSPOREZA    ,    SIFHOTELA
from HRS_LASERLINE_PRIHOD
where datum = pms_p.business_date
and sifhotela = pms_p.resort
;

begin

for a in c_get_prihod loop

l_string_request:=
'{
IdOrig:"'||a.IDORIG||'",
IdSustava:"'||a.IDSUSTAVA||'",
Datum:"'||a.DATUM||'",
SifAgencije:"'||a.SIFAGENCIJE||'",
SifDrzave:"'||a.SIFDRZAVE||'",
SifOsUsl:"'||a.SIFOSUSL||'",
IznosNeto:"'||a.IZNOSNETO||'",
IznosBruto:"'||a.IZNOSBRUTO||'",
IznosPoreza:"'||a.IZNOSPOREZA||'",
SifHotela:"'||a.SIFHOTELA||'",
}}'
;

end loop;

l_http_request := UTL_HTTP.begin_request(url , method => 'POST', http_version => 'HTTP/1.1');
utl_http.set_header(l_http_request, 'user-agent', 'mozilla/4.0');
utl_http.set_header(l_http_request, 'content-type', 'application/json');
utl_http.set_header(l_http_request, 'Content-Length', length(l_string_request));

BEGIN

<<request_loop>>

FOR i IN 0..CEIL(LENGTH(l_string_request) / l_buffer_size) - 1 LOOP
    l_substring_msg := SUBSTR(l_string_request, i * l_buffer_size + 1, l_buffer_size);

BEGIN
    l_raw_data := utl_raw.cast_to_raw(l_substring_msg);
    UTL_HTTP.write_raw(r => l_http_request, data => l_raw_data);

EXCEPTION

WHEN NO_DATA_FOUND THEN
EXIT request_loop;

END;
END LOOP request_loop;

l_http_response := UTL_HTTP.get_response(l_http_request);

BEGIN

LOOP
    UTL_HTTP.read_raw(l_http_response, l_raw_data, l_buffer_size);
    l_clob_response := l_clob_response || UTL_RAW.cast_to_varchar2(l_raw_data);
END LOOP response_loop;

EXCEPTION

WHEN UTL_HTTP.end_of_body THEN
    UTL_HTTP.end_response(l_http_response);
END;

<<print_response>>

FOR i IN 0..CEIL(LENGTH(l_clob_response) / l_line_size) - 1
LOOP
    l_line := SUBSTR(l_clob_response, i * l_line_size + 1, l_line_size);
EXIT WHEN i > l_lines_count - 1;
END LOOP print_response;

v_clob:= l_clob_response;

return v_clob ;

exception
  when utl_http.end_of_body then
  utl_http.end_response(l_http_response);
end;
end TST;
</code>```

答:
Your cursor query might find dozens of rows, but you're doing this:

```<code>for a in c_get_prihod loop

l_string_request:= ... ;

end loop;
</code>```

Each time around that loop you're replacing the entire contents of l_string_request, so however many rows you get and how many times you go around the loop, you'll always end up with that containing only the last row returned by that query. So you only send that single, final, record to the web service.

Assuming the receiving service is expecting an array of records, you might want something like:

```<code>begin

  l_string_request := '[ ';

  for a in c_get_prihod loop
    if a.FLAG > 1 then
      l_string_request := l_string_request || ', ';
    end if;
    l_string_request := l_string_request || '{ ';
    l_string_request := l_string_request || '"IdOrig": "' || a.IDORIG || '", ';
    l_string_request := l_string_request || '"IdSustava": "' || a.IDSUSTAVA ||' ", ';
    l_string_request := l_string_request || '"Datum": "' || a.DATUM || '", ';
    l_string_request := l_string_request || '"SifAgencije": "' || a.SIFAGENCIJE || '", ';
    l_string_request := l_string_request || '"SifDrzave": "' || a.SIFDRZAVE || '", ';
    l_string_request := l_string_request || '"SifOsUsl": "' || a.SIFOSUSL || '", ';
    l_string_request := l_string_request || '"IznosNeto": "' || a.IZNOSNETO || '", ';
    l_string_request := l_string_request || '"IznosBruto": "' || a.IZNOSBRUTO || '", ';
    l_string_request := l_string_request || '"IznosPoreza": "' || a.IZNOSPOREZA || '", ';
    l_string_request := l_string_request || '"SifHotela": "' || a.SIFHOTELA || '"';
    l_string_request := l_string_request || ' }';
  end loop;

  l_string_request := l_string_request || ' ]';

  dbms_output.put_line(l_string_request);

  ...
</code>```

where flag is an extra column added to the cursor result as e.g. , ROWNUM AS FLAG - just as a mechanism to know if you are on the first row or a subsequent row (and so need as comma between array elements).

The dbms_output lets you see the entire generated value, which you can manually inspect and/or pass through a JSON validator to check it is what you (and more importantly the receiving service) expect to see. You can still add newlines during the JSON construction for readability, though the service won't care about those.

Depending on how many rows you could have you might need l_string_request to be a CLOB instead of a varchar2. I'd also suggest you explicitly format date/timestamp values, and handle numbers properly if you have any of those.

After modification according to your advice I'm getting this error:

ORA-06502: PL/SQL: numeric or value error ORA-06512: at "OPERA_MARRIOTT.HRS_LASERLINE_BI_PRIHOD", line 87

You would get this if l_clob_response is empty, so perhaps your read loop isn't getting what you expect now. (Which may well be because the request is now invalid JSON, or doesn't match what the service expects). After the UTL_HTTP.get_response() call, see what l_http_response.status_code and l_http_response.reason_phrase show. The status codes are in the documentation.

Title: PL/SQL UTL_HTTP send multiple raws

Body:
I'm trying to send with webservice POST method a dozens of records to other side but problem is that other side get only one raw of data.
I put cursor and in begin section open cursor and make loop.
I think the problem is somewhere in part UTL_HTTP.read_raw. I have to add something additional or modify function.
Where is the catch, where I'm wrong?

create or replace FUNCTION "TST" return clob is

l_http_request   UTL_HTTP.req;
l_http_response  UTL_HTTP.resp;
l_buffer_size    NUMBER(10) := 20000;
l_line_size      NUMBER(10) := 50;
l_lines_count    NUMBER(10) := 20;
l_string_request VARCHAR2(32767);
l_line           VARCHAR2(128);
l_substring_msg  VARCHAR2(20000);
l_raw_data       RAW(20000);
l_clob_response  CLOB ;
v_clob clob;
url varchar2(200) := 'http://tst';

cursor c_get_prihod is
select     IDORIG   ,    IDSUSTAVA  ,    DATUM  ,    SIFAGENCIJE    ,    SIFDRZAVE  ,
SIFOSUSL    ,    IZNOSNETO  ,    IZNOSBRUTO ,    IZNOSPOREZA    ,    SIFHOTELA
from HRS_LASERLINE_PRIHOD
where datum = pms_p.business_date
and sifhotela = pms_p.resort
;

begin

for a in c_get_prihod loop

l_string_request:=
'{
IdOrig:"'||a.IDORIG||'",
IdSustava:"'||a.IDSUSTAVA||'",
Datum:"'||a.DATUM||'",
SifAgencije:"'||a.SIFAGENCIJE||'",
SifDrzave:"'||a.SIFDRZAVE||'",
SifOsUsl:"'||a.SIFOSUSL||'",
IznosNeto:"'||a.IZNOSNETO||'",
IznosBruto:"'||a.IZNOSBRUTO||'",
IznosPoreza:"'||a.IZNOSPOREZA||'",
SifHotela:"'||a.SIFHOTELA||'",
}}'
;

end loop;

l_http_request := UTL_HTTP.begin_request(url , method => 'POST', http_version => 'HTTP/1.1');
utl_http.set_header(l_http_request, 'user-agent', 'mozilla/4.0');
utl_http.set_header(l_http_request, 'content-type', 'application/json');
utl_http.set_header(l_http_request, 'Content-Length', length(l_string_request));

BEGIN

<<request_loop>>

FOR i IN 0..CEIL(LENGTH(l_string_request) / l_buffer_size) - 1 LOOP
    l_substring_msg := SUBSTR(l_string_request, i * l_buffer_size + 1, l_buffer_size);

BEGIN
    l_raw_data := utl_raw.cast_to_raw(l_substring_msg);
    UTL_HTTP.write_raw(r => l_http_request, data => l_raw_data);

EXCEPTION

WHEN NO_DATA_FOUND THEN
EXIT request_loop;

END;
END LOOP request_loop;

l_http_response := UTL_HTTP.get_response(l_http_request);

BEGIN

LOOP
    UTL_HTTP.read_raw(l_http_response, l_raw_data, l_buffer_size);
    l_clob_response := l_clob_response || UTL_RAW.cast_to_varchar2(l_raw_data);
END LOOP response_loop;

EXCEPTION

WHEN UTL_HTTP.end_of_body THEN
    UTL_HTTP.end_response(l_http_response);
END;

<<print_response>>

FOR i IN 0..CEIL(LENGTH(l_clob_response) / l_line_size) - 1
LOOP
    l_line := SUBSTR(l_clob_response, i * l_line_size + 1, l_line_size);
EXIT WHEN i > l_lines_count - 1;
END LOOP print_response;

v_clob:= l_clob_response;

return v_clob ;

exception
  when utl_http.end_of_body then
  utl_http.end_response(l_http_response);
end;
end TST;

Body:
Your cursor query might find dozens of rows, but you're doing this:

for a in c_get_prihod loop

l_string_request:= ... ;

end loop;

Each time around that loop you're replacing the entire contents of l_string_request, so however many rows you get and how many times you go around the loop, you'll always end up with that containing only the last row returned by that query. So you only send that single, final, record to the web service.

Assuming the receiving service is expecting an array of records, you might want something like:

begin

  l_string_request := '[ ';

  for a in c_get_prihod loop
    if a.FLAG > 1 then
      l_string_request := l_string_request || ', ';
    end if;
    l_string_request := l_string_request || '{ ';
    l_string_request := l_string_request || '"IdOrig": "' || a.IDORIG || '", ';
    l_string_request := l_string_request || '"IdSustava": "' || a.IDSUSTAVA ||' ", ';
    l_string_request := l_string_request || '"Datum": "' || a.DATUM || '", ';
    l_string_request := l_string_request || '"SifAgencije": "' || a.SIFAGENCIJE || '", ';
    l_string_request := l_string_request || '"SifDrzave": "' || a.SIFDRZAVE || '", ';
    l_string_request := l_string_request || '"SifOsUsl": "' || a.SIFOSUSL || '", ';
    l_string_request := l_string_request || '"IznosNeto": "' || a.IZNOSNETO || '", ';
    l_string_request := l_string_request || '"IznosBruto": "' || a.IZNOSBRUTO || '", ';
    l_string_request := l_string_request || '"IznosPoreza": "' || a.IZNOSPOREZA || '", ';
    l_string_request := l_string_request || '"SifHotela": "' || a.SIFHOTELA || '"';
    l_string_request := l_string_request || ' }';
  end loop;

  l_string_request := l_string_request || ' ]';

  dbms_output.put_line(l_string_request);

  ...

where flag is an extra column added to the cursor result as e.g. , ROWNUM AS FLAG - just as a mechanism to know if you are on the first row or a subsequent row (and so need as comma between array elements).

The dbms_output lets you see the entire generated value, which you can manually inspect and/or pass through a JSON validator to check it is what you (and more importantly the receiving service) expect to see. You can still add newlines during the JSON construction for readability, though the service won't care about those.

Depending on how many rows you could have you might need l_string_request to be a CLOB instead of a varchar2. I'd also suggest you explicitly format date/timestamp values, and handle numbers properly if you have any of those.

After modification according to your advice I'm getting this error:

ORA-06502: PL/SQL: numeric or value error ORA-06512: at "OPERA_MARRIOTT.HRS_LASERLINE_BI_PRIHOD", line 87

You would get this if l_clob_response is empty, so perhaps your read loop isn't getting what you expect now. (Which may well be because the request is now invalid JSON, or doesn't match what the service expects). After the UTL_HTTP.get_response() call, see what l_http_response.status_code and l_http_response.reason_phrase show. The status codes are in the documentation.


问:
Asp.net unable to get focus loss
I am currently working on a form in asp.net and it is my first web page so I am trying to get OnBlur event to work but I am unable to.

This is my code:-

Contact.aspx

```<code><%@ Page Language="C#" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="contact.aspx.cs" Inherits="contact" Title="Contact Us" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<title>Sugarsnooper | Contact Us</title>
<meta name="keyword" content=""/>
<meta name="Description" content=""/>
<meta name="key-phrases" content=""/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<section class="content-page"><div class="container"><div class="row">
<div class="col-md-12"><h1>Contact Us</h1></div>
<div class="col-md-8">
<h4>Enquiry Form</h4>
<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
        <ContentTemplate>
<div class="col-lg-12 form-group">

        <div class="row">
        <input name="name" runat="server" type="text" id="name2" class="form-control" placeholder="Enter Your Name">
        <asp:Label ID="invalidname" runat="server" Text=""/>
        </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
        <input name="website" runat="server" type="text" id="cont2" class="form-control" placeholder="Enter Mobile Number">
<asp:Label ID="invalidmobile" runat="server" Text=""/>
    </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
       <input onblur="validate()" name="email" runat="server" type="text" id="email3" class="form-control" placeholder="Enter Your Email ID">
    <asp:Label ID="invalidemail" runat="server" Text=""/>
        </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
        <textarea name="message" runat="server" id="msg2" class="form-control" placeholder="Enter Your Message.." rows="6"></textarea>
        <asp:Label ID="invalidmessage" runat="server" Text=""/>
        </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
          <input type="submit" class="btn btn-primary" id="enquiry_post" value="Send"
       runat="server" onserverclick="enquiry_post_click"/>
     <asp:Label style="margin: 60" ID="message" runat="server" Text=""/>

        </div>

      </div>

       </ContentTemplate>
    </asp:UpdatePanel>

      </form>
</div>
<div class="col-md-4"><h4>Contact Info</h4>
<table class="table">
<tr>
<td>Email</td>
<td><a href="mailto:support@SugarSnooper.com">support@SugarSnooper.com</a></td>
</tr>
<tr style="display:none;">
<td>Helpline No.</td>
<td>xxx xxx xxxx</td>
</tr>
</table>
</div>
</div></div></section>
</asp:Content>

</code>```

Contact.aspx.cs

```<code>using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Drawing;

public partial class contact : System.Web.UI.Page
{

    //private Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

    int i = 0;

    private static Regex EmailValidation()
    {
    const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
    const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

    // Set explicit regex match timeout, sufficient enough for email parsing
    // Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
    TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

    try
    {
        if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
        {
            return new Regex(pattern, options, matchTimeout);
        }
    }
    catch
    {
        // Fallback on error
    }

    // Legacy fallback (without explicit match timeout)
    return new Regex(pattern, options);
    }

    private bool IsValidPhoneNumber(string num)
    {
        var phoneNumber = num.Trim()
            .Replace(" ", "")
            .Replace("-", "")
            .Replace("(", "")
            .Replace(")", "");
        return Regex.Match(phoneNumber, @"^\+\d{5,15}$").Success || Regex.Match(phoneNumber, @"^\d{5,15}$").Success;
    }

    private bool validateemailandupdate(){
    string emailid = email3.Value;
    if(emailid.Length > 0){
    Match match = EmailValidation().Match(emailid);
    if(!match.Success){
    invalidemail.ForeColor = Color.Red;
    invalidemail.Font.Bold = true;
    invalidemail.Text = "Email is Invalid";
    return false;
    }
    invalidemail.Text = "";
    return true;
    }
    else{
    invalidemail.ForeColor = Color.Red;
    invalidemail.Font.Bold = true;
    invalidemail.Text = "This Field is Required";
    return false;
    }
    }

    private bool validatemobileandupdate(){

    string mobile = cont2.Value;
    if(mobile.Length > 0){
    bool isalldigits = IsValidPhoneNumber(mobile);
    bool islengthenough = mobile.Length > 5;
    bool islengthless = mobile.Length < 16;
    bool isnumbervalid = isalldigits && islengthenough && islengthless;
    if(isnumbervalid){
    invalidmobile.Text = "";
    return true;
    }
    invalidmobile.ForeColor = Color.Red;
    invalidmobile.Font.Bold = true;
    invalidmobile.Text = "Please enter a Valid Phone Number";
    return false;
    }
    else{
    invalidmobile.ForeColor = Color.Red;
    invalidmobile.Font.Bold = true;
    invalidmobile.Text = "This Field is Required";
    return false;
    }

    }

    private bool validatenameandupdate(){
    string name = name2.Value;
    if(name.Length > 50){
    invalidname.ForeColor = Color.Red;
    invalidname.Font.Bold = true;
        invalidname.Text = "Name Too Long";
        return false;
    }
    if(name.Length < 1){
    invalidname.ForeColor = Color.Red;
    invalidname.Font.Bold = true;
        invalidname.Text = "This Field is Requred";
        return false;
    }
    invalidname.Text = "";
    return true;
    }

    private bool validatemsgandupdate(){
    string msg = msg2.Value;
    if(msg.Length > 0){
        invalidmessage.Text = "";
        return true;
    }
    else{
    invalidmessage.ForeColor = Color.Red;
    invalidmessage.Font.Bold = true;
        invalidmessage.Text = "This Field is Requred";
        return false;
    }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //msg2.Attributes.Add("OnBlur", "return validate()");
    }

public void validate(){
    i++;
    //bool isemailvalid = validateemailandupdate();
    //bool ismobilevalid = validatemobileandupdate();
    //bool isnamevalid = validatenameandupdate();
    //bool ismsgvalid = validatemsgandupdate();
//UpdatePanel1.Update();
}

    protected void enquiry_post_click(object sender, EventArgs e){

    bool isemailvalid = validateemailandupdate();
    bool ismobilevalid = validatemobileandupdate();
    bool isnamevalid = validatenameandupdate();
    bool ismsgvalid = validatemsgandupdate();
    bool result = isemailvalid && ismobilevalid && isnamevalid && ismsgvalid;

        message.Text = i.ToString();
        if (result){
       cont2.Value = "";
       email3.Value = "";
       name2.Value = "";
       msg2.Value = "";
    }
    }

}

</code>```

I tried using onfocusout but that didn't work either. I also tried using onblur="validate();", and onblur="return validate();" and 2 or 3 more variations but none worked
Pls help
Thanks in Advance.

答:
First you use a control like a asp:TextBox instead of the input-control.

```<code><asp:TextBox ID="email3" CssClass="form-control" AutoPostBack="true" runat="server"/>

</code>```

If you want to react on changes on the server side, you add the AutoPostBack and use the changed event - so in your code behind:

```<code>protected void Page_Init(object sender, EventArgs e)
{
    email3.TextChanged += Email3_TextChanged;
}

private void Email3_TextChanged(object sender, EventArgs e)
{
    validate();
}
</code>```

If you want to add some validation, you can add a validator to the page, as shown here

```<code><asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="email3" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
</code>```

Title: Asp.net unable to get focus loss

Body:
I am currently working on a form in asp.net and it is my first web page so I am trying to get OnBlur event to work but I am unable to.

This is my code:-

Contact.aspx

<%@ Page Language="C#" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="contact.aspx.cs" Inherits="contact" Title="Contact Us" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<title>Sugarsnooper | Contact Us</title>
<meta name="keyword" content=""/>
<meta name="Description" content=""/>
<meta name="key-phrases" content=""/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

Contact Us

Enquiry Form

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
        <ContentTemplate>

        <input name="name" runat="server" type="text" id="name2" class="form-control" placeholder="Enter Your Name">
        <asp:Label ID="invalidname" runat="server" Text=""/>

        <input name="website" runat="server" type="text" id="cont2" class="form-control" placeholder="Enter Mobile Number">
<asp:Label ID="invalidmobile" runat="server" Text=""/>

       <input onblur="validate()" name="email" runat="server" type="text" id="email3" class="form-control" placeholder="Enter Your Email ID">
    <asp:Label ID="invalidemail" runat="server" Text=""/>

        <textarea name="message" runat="server" id="msg2" class="form-control" placeholder="Enter Your Message.." rows="6"></textarea>
        <asp:Label ID="invalidmessage" runat="server" Text=""/>

          <input type="submit" class="btn btn-primary" id="enquiry_post" value="Send"
       runat="server" onserverclick="enquiry_post_click"/>
     <asp:Label style="margin: 60" ID="message" runat="server" Text=""/>

       </ContentTemplate>
    </asp:UpdatePanel>

      </form>

Contact Info

Email
support@SugarSnooper.com

Helpline No.
xxx xxx xxxx

</asp:Content>

Contact.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Drawing;

public partial class contact : System.Web.UI.Page
{

    //private Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

    int i = 0;

    private static Regex EmailValidation()
    {
    const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
    const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

    // Set explicit regex match timeout, sufficient enough for email parsing
    // Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
    TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

    try
    {
        if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
        {
            return new Regex(pattern, options, matchTimeout);
        }
    }
    catch
    {
        // Fallback on error
    }

    // Legacy fallback (without explicit match timeout)
    return new Regex(pattern, options);
    }

    private bool IsValidPhoneNumber(string num)
    {
        var phoneNumber = num.Trim()
            .Replace(" ", "")
            .Replace("-", "")
            .Replace("(", "")
            .Replace(")", "");
        return Regex.Match(phoneNumber, @"^\+\d{5,15}$").Success || Regex.Match(phoneNumber, @"^\d{5,15}$").Success;
    }

    private bool validateemailandupdate(){
    string emailid = email3.Value;
    if(emailid.Length > 0){
    Match match = EmailValidation().Match(emailid);
    if(!match.Success){
    invalidemail.ForeColor = Color.Red;
    invalidemail.Font.Bold = true;
    invalidemail.Text = "Email is Invalid";
    return false;
    }
    invalidemail.Text = "";
    return true;
    }
    else{
    invalidemail.ForeColor = Color.Red;
    invalidemail.Font.Bold = true;
    invalidemail.Text = "This Field is Required";
    return false;
    }
    }

    private bool validatemobileandupdate(){

    string mobile = cont2.Value;
    if(mobile.Length > 0){
    bool isalldigits = IsValidPhoneNumber(mobile);
    bool islengthenough = mobile.Length > 5;
    bool islengthless = mobile.Length < 16;
    bool isnumbervalid = isalldigits && islengthenough && islengthless;
    if(isnumbervalid){
    invalidmobile.Text = "";
    return true;
    }
    invalidmobile.ForeColor = Color.Red;
    invalidmobile.Font.Bold = true;
    invalidmobile.Text = "Please enter a Valid Phone Number";
    return false;
    }
    else{
    invalidmobile.ForeColor = Color.Red;
    invalidmobile.Font.Bold = true;
    invalidmobile.Text = "This Field is Required";
    return false;
    }

    }

    private bool validatenameandupdate(){
    string name = name2.Value;
    if(name.Length > 50){
    invalidname.ForeColor = Color.Red;
    invalidname.Font.Bold = true;
        invalidname.Text = "Name Too Long";
        return false;
    }
    if(name.Length < 1){
    invalidname.ForeColor = Color.Red;
    invalidname.Font.Bold = true;
        invalidname.Text = "This Field is Requred";
        return false;
    }
    invalidname.Text = "";
    return true;
    }

    private bool validatemsgandupdate(){
    string msg = msg2.Value;
    if(msg.Length > 0){
        invalidmessage.Text = "";
        return true;
    }
    else{
    invalidmessage.ForeColor = Color.Red;
    invalidmessage.Font.Bold = true;
        invalidmessage.Text = "This Field is Requred";
        return false;
    }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //msg2.Attributes.Add("OnBlur", "return validate()");
    }

public void validate(){
    i++;
    //bool isemailvalid = validateemailandupdate();
    //bool ismobilevalid = validatemobileandupdate();
    //bool isnamevalid = validatenameandupdate();
    //bool ismsgvalid = validatemsgandupdate();
//UpdatePanel1.Update();
}

    protected void enquiry_post_click(object sender, EventArgs e){

    bool isemailvalid = validateemailandupdate();
    bool ismobilevalid = validatemobileandupdate();
    bool isnamevalid = validatenameandupdate();
    bool ismsgvalid = validatemsgandupdate();
    bool result = isemailvalid && ismobilevalid && isnamevalid && ismsgvalid;

        message.Text = i.ToString();
        if (result){
       cont2.Value = "";
       email3.Value = "";
       name2.Value = "";
       msg2.Value = "";
    }
    }

}

I tried using onfocusout but that didn't work either. I also tried using onblur="validate();", and onblur="return validate();" and 2 or 3 more variations but none worked
Pls help
Thanks in Advance.

Body:
First you use a control like a asp:TextBox instead of the input-control.

<asp:TextBox ID="email3" CssClass="form-control" AutoPostBack="true" runat="server"/>

If you want to react on changes on the server side, you add the AutoPostBack and use the changed event - so in your code behind:

protected void Page_Init(object sender, EventArgs e)
{
    email3.TextChanged += Email3_TextChanged;
}

private void Email3_TextChanged(object sender, EventArgs e)
{
    validate();
}

If you want to add some validation, you can add a validator to the page, as shown here

<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="email3" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>


问:
How to return biggest x coordinate and biggest y coordinate from a list of segments?
So, I have a bunch of segments as inputs, that are made of x coordinates and y coordinates. Horizontal segments have left and right x coordinates, and a unique y coordinate, while vertical segments have up and down y coordinates and a unique x coordinate.
I figured out they are gonna look like this:

Horizontal segment = ((2,8), 4)

Vertical segment = (3, (2,5))

All segments = [((2,8), 1), (3, (2,5)), (5, (3,4)), (4, (6,7))]

I want to return the biggest x coordinate and the biggest y coordinate. How can I do that?

答:
This is how you can solve it:

```<code>data = [((2,8), 1), (3, (2,5)), (5, (3,4)), (4, (6,7))]
x = []
y = []
for elem in data:
    if type(elem[0])==tuple:
        x.append(max(elem[0]))
    else:
        x.append(elem[0])
    if type(elem[1])==tuple:
        y.append(max(elem[1]))
    else:
        y.append(elem[1])

print("Max(x) =",max(x))
print("Max(y) =",max(y))
</code>```

Output:

```<code>Max(x) = 8
Max(y) = 7
</code>```

Body:
This is how you can solve it:

data = [((2,8), 1), (3, (2,5)), (5, (3,4)), (4, (6,7))]
x = []
y = []
for elem in data:
    if type(elem[0])==tuple:
        x.append(max(elem[0]))
    else:
        x.append(elem[0])
    if type(elem[1])==tuple:
        y.append(max(elem[1]))
    else:
        y.append(elem[1])

print("Max(x) =",max(x))
print("Max(y) =",max(y))

Output:

Max(x) = 8
Max(y) = 7


问:
SQL query counts returns the same number
The following query:

Select t1.name
       , t1.email
       , t1.activated
       , count(t2.id) as 'reporter'
       , count(t3.id) as 'comments'
       , count(t4.id) as 'reported'
from users t1
     inner join tickets as t2 on t1.id = t2.reporter_id
     inner join comments as t3 on t1.id = t3.user_id
     inner join tickets as t4 on t1.id = t4.reported_id
group by name
```

The counts return all 3 the same number

答:
It would be great to see sample data, current results and expect results.

But I'm guessing it's because your group by clause doesn't include the t1.email and t1.activated columns.

```<code>Select t1.name
       , t1.email
       , t1.activated
       , count(t2.id) as 'reporter'
       , count(t3.id) as 'comments'
       , count(t4.id) as 'reported'
from users t1
     inner join tickets as t2 on t1.id = t2.reporter_id
     inner join comments as t3 on t1.id = t3.user_id
     inner join tickets as t4 on t1.id = t4.reported_id
group by name
       , t1.email
       , t1.activated
</code>```

Without sample data, it's hard to be sure, but I don't think your joins do what you want them to do. You will only get results for users who have are both "reported" and "reporter", and those tickets include at least 1 comment from the user who reported it.

Body:
The following query:

Select t1.name
       , t1.email
       , t1.activated
       , count(t2.id) as 'reporter'
       , count(t3.id) as 'comments'
       , count(t4.id) as 'reported'
from users t1
     inner join tickets as t2 on t1.id = t2.reporter_id
     inner join comments as t3 on t1.id = t3.user_id
     inner join tickets as t4 on t1.id = t4.reported_id
group by name

The counts return all 3 the same number

Body:
It would be great to see sample data, current results and expect results.

But I'm guessing it's because your group by clause doesn't include the t1.email and t1.activated columns.

Select t1.name
       , t1.email
       , t1.activated
       , count(t2.id) as 'reporter'
       , count(t3.id) as 'comments'
       , count(t4.id) as 'reported'
from users t1
     inner join tickets as t2 on t1.id = t2.reporter_id
     inner join comments as t3 on t1.id = t3.user_id
     inner join tickets as t4 on t1.id = t4.reported_id
group by name
       , t1.email
       , t1.activated

Without sample data, it's hard to be sure, but I don't think your joins do what you want them to do. You will only get results for users who have are both "reported" and "reporter", and those tickets include at least 1 comment from the user who reported it.


问:
Use inner join with C# SQL Server (Retrieving data from multiple table using SQL query and inner join in C# ADO.NET)
Am trying to retrieve data from two different tables into a datatable and to assign into textboxes in C# WinForms. Though I succeeded with this query when I tried it in SQL Server but implementing it on WinForms is what I don't know.
This is what have tried in my code:

```<code> string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString();
                    SqlDataAdapter cmd = new SqlDataAdapter("select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.'" + supplier_id + "' = Purchase_Entry.'" + supplier_id + "' ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();

</code>```

Tried this also:

```<code> string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString(); MessageBox.Show(supplier_id);
                    SqlDataAdapter cmd = new SqlDataAdapter($"select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.{supplier_id} = Purchase_Entry.{supplier_id} ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();
</code>```

But am having error concatenating the query when fetching data
Tried this in SQL Server and it works

```<code>select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.supplier_id = Purchase_Entry.supplier_id
</code>```

and it returned me back what I want:

答:
I think you should write like this

```<code>SqlDataAdapter cmd =new SqlDataAdapter(
                    "select
                    New_Supplier.Supplier_Name,
                    New_Supplier.Address,
                    New_Supplier.City,
                    New_Supplier.Contact_No,
                    Purchase_Entry.Balance
                    from New_Supplier,Purchase_Entry
                    where New_Supplier.supplier_id = Purchase_Entry.supplier_id
                    and New_Supplier.supplier_id='"+supplier_id +"'
                 ", con);
</code>```

or

```<code>SqlDataAdapter cmd =new SqlDataAdapter(
                    "select
                    New_Supplier.Supplier_Name,
                    New_Supplier.Address,
                    New_Supplier.City,
                    New_Supplier.Contact_No,
                    Purchase_Entry.Balance
                    from New_Supplier
                    inner join Purchase_Entry on New_Supplier.supplier_id =
                    Purchase_Entry.supplier_id
                    where New_Supplier.supplier_id='"+supplier_id +"'
                 ", con);
</code>```

but it's better to use SQL parameter instead of concate string because of SQL injection as shown below:

```<code>    SqlCommand cmd = new SqlCommand(
     @"select
            New_Supplier.Supplier_Name,
            New_Supplier.Address,
            New_Supplier.City,
            New_Supplier.Contact_No,
            Purchase_Entry.Balance
            from New_Supplier
            inner join Purchase_Entry on New_Supplier.supplier_id =
            Purchase_Entry.supplier_id
            where New_Supplier.supplier_id= @supplier_id", con);

    cmd.Parameters.Add("@supplier_id",SqlDbType.Int).Value = supplier_id;
    cmd.CommandType = System.Data.CommandType.Text;
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
</code>```

Body:
Am trying to retrieve data from two different tables into a datatable and to assign into textboxes in C# WinForms. Though I succeeded with this query when I tried it in SQL Server but implementing it on WinForms is what I don't know.
This is what have tried in my code:

 string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString();
                    SqlDataAdapter cmd = new SqlDataAdapter("select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.'" + supplier_id + "' = Purchase_Entry.'" + supplier_id + "' ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();

Tried this also:

 string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString(); MessageBox.Show(supplier_id);
                    SqlDataAdapter cmd = new SqlDataAdapter($"select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.{supplier_id} = Purchase_Entry.{supplier_id} ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();

But am having error concatenating the query when fetching data
Tried this in SQL Server and it works

select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.supplier_id = Purchase_Entry.supplier_id

and it returned me back what I want:

Body:
I think you should write like this

SqlDataAdapter cmd =new SqlDataAdapter(
                    "select
                    New_Supplier.Supplier_Name,
                    New_Supplier.Address,
                    New_Supplier.City,
                    New_Supplier.Contact_No,
                    Purchase_Entry.Balance
                    from New_Supplier,Purchase_Entry
                    where New_Supplier.supplier_id = Purchase_Entry.supplier_id
                    and New_Supplier.supplier_id='"+supplier_id +"'
                 ", con);

or

SqlDataAdapter cmd =new SqlDataAdapter(
                    "select
                    New_Supplier.Supplier_Name,
                    New_Supplier.Address,
                    New_Supplier.City,
                    New_Supplier.Contact_No,
                    Purchase_Entry.Balance
                    from New_Supplier
                    inner join Purchase_Entry on New_Supplier.supplier_id =
                    Purchase_Entry.supplier_id
                    where New_Supplier.supplier_id='"+supplier_id +"'
                 ", con);

but it's better to use SQL parameter instead of concate string because of SQL injection as shown below:

    SqlCommand cmd = new SqlCommand(
     @"select
            New_Supplier.Supplier_Name,
            New_Supplier.Address,
            New_Supplier.City,
            New_Supplier.Contact_No,
            Purchase_Entry.Balance
            from New_Supplier
            inner join Purchase_Entry on New_Supplier.supplier_id =
            Purchase_Entry.supplier_id
            where New_Supplier.supplier_id= @supplier_id", con);

    cmd.Parameters.Add("@supplier_id",SqlDbType.Int).Value = supplier_id;
    cmd.CommandType = System.Data.CommandType.Text;
    SqlDataAdapter sda = new SqlDataAdapter(cmd);


问:
Input File onchange event not firing
I am trying to fire onchange event everytime a file is selected. It does fire if the file I select is different, however, I wanted to fire even if  the same file is selected twice.

html

```<code>  <input name="file" type="file"  (change)="onChange($event)" style="width:80%" />
</code>```

component

```<code>onChange(event: any) {
   let files = event.srcElement.files;
   this.files = files;
   event= null;
}
</code>```

答:
You need to clear the value of file input. As if you select the file it matches with the value and if value is same then no change event.

You need to use native onclick of JS

```<code><input name="file" type="file" onclick="value = null" (change)="onChange($event)" style="width:80%"/>
</code>```

if you use Angular's (click) then it will set the ts variable value which can cause error as it will be not declared in your ts file.

If you want to use angualr's (click) event then use template variable like this

```<code><input name="file" type="file" (click)="myInputFile.value = null" (change)="onChange($event)" style="width:80%" #myInputFile/>
</code>```

Title: Input File onchange event not firing

Body:
I am trying to fire onchange event everytime a file is selected. It does fire if the file I select is different, however, I wanted to fire even if  the same file is selected twice.

html

  <input name="file" type="file"  (change)="onChange($event)" style="width:80%" />

component

onChange(event: any) {
   let files = event.srcElement.files;
   this.files = files;
   event= null;
}

Body:
You need to clear the value of file input. As if you select the file it matches with the value and if value is same then no change event.

You need to use native onclick of JS

<input name="file" type="file" onclick="value = null" (change)="onChange($event)" style="width:80%"/>

if you use Angular's (click) then it will set the ts variable value which can cause error as it will be not declared in your ts file.

If you want to use angualr's (click) event then use template variable like this

<input name="file" type="file" (click)="myInputFile.value = null" (change)="onChange($event)" style="width:80%" #myInputFile/>


问:
Debugger compile handler overriden, will not be active in this request
I have Zend Debugger setup on the server and trying to remote debug from Zend Studio client. It doesn't work and I get this in the server error log:

[Zend Debugger] Debugger compile handler overriden, will not be active in this request

What's the issue?

答: The debugger is very finicky about any PHP extensions enabled. I was receiving the same [Zend Debugger] Debugger compile handler overriden, will not be active in this request error on the Apache error log on Mac OS X with MAMP and PHP 5.2.x. Disabling the Zend Optimizer and XCache from the MAMP control panel resolved this error.


问:
Python function to return concatenated string from a list, where the length of the string is more than 2 characters
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

```<code>def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))
</code>```

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

答:
You have initialized start with strings[0]
Just initialize start ="" as an empty string.</p>

```<code>def concatenate(strings):
start = ""
for string in strings:
    if len(string) > 2:
        start += string
return start
</code>```

Body:
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

Body:
You have initialized start with strings[0]
Just initialize start ="" as an empty string.

def concatenate(strings):
start = ""
for string in strings:
    if len(string) > 2:
        start += string
return start