问:
Trying to generate a 2-column table using PHP from JSON data
This should be a fairly simple problem, however I cannot for the life of me get it to work right.

I have JSON data in the form of an array like so and I am trying to generate a 2-column table where every 2 elements in the array take up a row.

```<code>[
    {
        "type": "Ground",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Water",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Sewer",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Tap",
        "field_location": "",
        "field_user": "",
    }
]

</code>```

I have overly simplified the code, however the function currently looks as follows.

```<code>function generateHtml($jsonDoc){
    $html = "";
    $html .= "<table>";
    $count = 0;

    foreach ($jsonDoc as $key => $value) {
        $count ++;

        if ($count % 2 == 0)
            $html .= "<tr>";

        $html .= "<td>";
        foreach ($value as $key => $val) {
            if(!empty($val))
                $html .= $key.":".$val."<br />";
        }
        $html .= "</td>";

        if ($count % 2 == 0)
            $html .= "</tr>";
        // $count ++;
    }
    $html .= "</table>";

    print($html);
}
</code>```

The resulting HTML output always seems to come out as follows and I cannot seem to understand what is missing.

```<code><table>
    <tr>
        <td>Ground</td>
    </tr>
    <tr>
        <td>Water</td>
    </tr>
    <tr>
        <td>Sewer</td>
    </tr>
    <tr>
        <td>Tap</td>
    </tr>
</table>
</code>```

as opposed to

```<code><table>
    <tr>
        <td>Ground</td>
        <td>Water</td>
    </tr>
    <tr>
        <td>Sewer</td>
        <td>Tap</td>
    </tr>
</table>
```
which is what I am looking for.
```

答:
One simple(r) way to achieve this, would be to use array_chunk to split your original data into an array of arrays, and then just use two nested loops to generate the output.

In the outer loop, you create the table row (output
 before, and
 after), and in the inner loop, you create a table cell for each item.

```<code>function generateHtml($jsonDoc){
    $data = array_chunk($jsonDoc, 2); // split this into an array of arrays,
                                      // containing two of the items each
    $html = '<table>';

    foreach ($data as $row) { // loop over the first level
      $html .= '<tr>';
      foreach ($row as $cell) { // loop over the second level
        $html .= '<td>'.$cell->type.'</td>';
      }
      $html .= '</tr>';
    }
    $html .= '</table>';

    print($html);
}
</code>```

Body:
This should be a fairly simple problem, however I cannot for the life of me get it to work right.

I have JSON data in the form of an array like so and I am trying to generate a 2-column table where every 2 elements in the array take up a row.

[
    {
        "type": "Ground",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Water",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Sewer",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Tap",
        "field_location": "",
        "field_user": "",
    }
]

I have overly simplified the code, however the function currently looks as follows.

function generateHtml($jsonDoc){
    $html = "";
    $html .= "
";
    $count = 0;

    foreach ($jsonDoc as $key => $value) {
        $count ++;

        if ($count % 2 == 0)
            $html .= "
";

        $html .= "";
        foreach ($value as $key => $val) {
            if(!empty($val))
                $html .= $key.":".$val."
";
        }
        $html .= "	";

        if ($count % 2 == 0)
            $html .= "
";
        // $count ++;
    }
    $html .= "
";

    print($html);
}

The resulting HTML output always seems to come out as follows and I cannot seem to understand what is missing.

        Ground

        Water

        Sewer

        Tap

as opposed to

        Ground
        Water

        Sewer
        Tap

```
which is what I am looking for.

Body:
One simple(r) way to achieve this, would be to use array_chunk to split your original data into an array of arrays, and then just use two nested loops to generate the output.

In the outer loop, you create the table row (output <tr> before, and </tr> after), and in the inner loop, you create a table cell for each item.

function generateHtml($jsonDoc){
    $data = array_chunk($jsonDoc, 2); // split this into an array of arrays,
                                      // containing two of the items each
    $html = '<table>';

    foreach ($data as $row) { // loop over the first level
      $html .= '<tr>';
      foreach ($row as $cell) { // loop over the second level
        $html .= '<td>'.$cell->type.'</td>';
      }
      $html .= '</tr>';
    }
    $html .= '</table>';

    print($html);
}


来源: stackexchange

问:
Lazy load pages in UIScrollView
I have a UIScrollView that contains large images and am using paging to scroll between images. In order to save memory, I am loading only one image before and after the currently visible one and loading/releasing new images after a scroll has completed.

The problem occurs when one scrolls quickly and scrollViewDidEndDecelerating is not called.

How can I detect continuous scrolling?

I could check item location on every scrollViewDidScroll but this seems a bit heavy...

答:
As per my experience, @jd291 is correct; I am using following callbacks successfully for most places

```<code>-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
</code>```

but, the only case when a callback is not called is that you may not had set up the delegate properly.

ContentLicense: CC BY-SA 2.5

Title: Lazy load pages in UIScrollView

Body:
As per my experience, @jd291 is correct; I am using following callbacks successfully for most places

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate

but, the only case when a callback is not called is that you may not had set up the delegate properly.

ContentLicense: CC BY-SA 3.0


问:
Why do I need to do a "pip install" after "git clone.."?
I am following a (my company's internal) guide to installing some custom libraries from Bitbucket. I am instructed to do on the command line:

```<code># Install custom libraries.
git clone ssh://git@bitbucket.company.net:{number}/~js/company-libraries /tmp/company-libraries
</code>```

When I do

```<code>ls /tmp/company-libraries
</code>```

I see that there is a README.md file and a directory called CompanyLibraries

I am then instructed to do

```<code>sudo -H pip3 install /tmp/company-libraries/CompanyLibraries
</code>```

My question is that after doing "git clone.." why do we then need to do "pip3 install.."? What is pip doing in this case? The CompanyLibraries directory exists so I am unsure why we need to install again?

I have never used git and this guide doesn't assume any knowledge in git - it just wants me to copy and paste the commands.

答:
So basically, in Your case pip3 is simply installing some libraries most probably proprietary to Your company.

Your company has some git repository that is used for development of internal libraries for Python. But cloning the git repository doesn't mean that the Python is automatically able to use the libraries, You need to install them to proper folders, that's what pip3 is doing when You invoke the command plus also probably some dependencies are installed.

Python looks for libraries in some predefined folders, so If they are not there it simply assumes that they are not installed. The fact that You clone them somewhere doesn't mean that it is able to find them.

ContentLicense: CC BY-SA 4.0

Body:
I am following a (my company's internal) guide to installing some custom libraries from Bitbucket. I am instructed to do on the command line:

# Install custom libraries.
git clone ssh://git@bitbucket.company.net:{number}/~js/company-libraries /tmp/company-libraries

When I do

ls /tmp/company-libraries

I see that there is a README.md file and a directory called CompanyLibraries

I am then instructed to do

sudo -H pip3 install /tmp/company-libraries/CompanyLibraries

My question is that after doing "git clone.." why do we then need to do "pip3 install.."? What is pip doing in this case? The CompanyLibraries directory exists so I am unsure why we need to install again?

I have never used git and this guide doesn't assume any knowledge in git - it just wants me to copy and paste the commands.


问:
Do split one class hierarchy into several or not?
For now, we have a .NET application that leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

```<code>public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}
</code>```

And for example the input XML file will look like:

```<code><Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>
</code>```

But model classes contain a logic (Draw(), Clear() and Scale() methods) and it seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

```<code>public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape)
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}
</code>```

If that issue is known, please just redirect me to that resource.

Thank you in advance.

答:
Trying to separate model and business logic I get the following code. Is it acceptable? As for me, it looks not flexible: we should not forget to extend the if statement if we add a new shape drawer.</p>

```<code>public abstract class Drawer
{
    public abstract void Draw();
}

public class CircleDrawer : Drawer
{
    private readonly Circle _circle;

    public CircleDrawer(Circle circle)
    {
        _circle = circle;
    }

    public override void Draw() { }
}

public class RectangleDrawer : Drawer
{
    private readonly Rectangle _rectangle;

    public RectangleDrawer(Rectangle rectangle)
    {
        _rectangle = rectangle;
    }

    public override void Draw() { }
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        List<Drawer> drawers = new List<Drawer>();
        foreach (Shape shape in Shapes)
        {
            if (shape is Circle)
            {
                drawers.Add(new CircleDrawer(shape as Circle));
            }
            else if (shape is Rectangle)
            {
                drawers.Add(new RectangleDrawer(shape as Rectangle));
            }
            else
            {
            }
        }

        foreach (Drawer drawer in drawers)
        {
            drawer.Draw();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}
</code>```

Body:
For now, we have a .NET application that leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}

And for example the input XML file will look like:

<Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>

But model classes contain a logic (Draw(), Clear() and Scale() methods) and it seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape)
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}

If that issue is known, please just redirect me to that resource.

Thank you in advance.

Body:
Trying to separate model and business logic I get the following code. Is it acceptable? As for me, it looks not flexible: we should not forget to extend the if statement if we add a new shape drawer.

public abstract class Drawer
{
    public abstract void Draw();
}

public class CircleDrawer : Drawer
{
    private readonly Circle _circle;

    public CircleDrawer(Circle circle)
    {
        _circle = circle;
    }

    public override void Draw() { }
}

public class RectangleDrawer : Drawer
{
    private readonly Rectangle _rectangle;

    public RectangleDrawer(Rectangle rectangle)
    {
        _rectangle = rectangle;
    }

    public override void Draw() { }
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        List<Drawer> drawers = new List<Drawer>();
        foreach (Shape shape in Shapes)
        {
            if (shape is Circle)
            {
                drawers.Add(new CircleDrawer(shape as Circle));
            }
            else if (shape is Rectangle)
            {
                drawers.Add(new RectangleDrawer(shape as Rectangle));
            }
            else
            {
            }
        }

        foreach (Drawer drawer in drawers)
        {
            drawer.Draw();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}


问:
Adding Labels to Xamarin map
I would like to add labels to my map.
I have a bunch of polygons on a map mapping out orchards (using Xamarin forms with Android and iOS custom renders) and would like to add a few labels to each with details. I have tried the below method where you make a custom pin with text used as the marker but this is not ideal as I would like a few lines of text in each and do not need it clickable. I also need this to work in iOS and Android.

Any help would be appreciated.

```<code>    public Marker AddText(Context context, GoogleMap map, LatLng location, string text, int fontSize, Polygon polygon)
    {
        try
        {
            if (text == null)
                throw new ArgumentNullException(nameof(text));
            if (location == null)
                throw new ArgumentNullException(nameof(location));
            if (map == null)
                throw new ArgumentNullException(nameof(map));
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            if (fontSize <= 0)
                throw new ArgumentOutOfRangeException(nameof(fontSize));

            var textView = new TextView(context);
            textView.Text = text;
            textView.TextSize = fontSize;
            var paintText = textView.Paint;
            var boundsText = new Rect();
            paintText.GetTextBounds(text, 0, textView.Length(), boundsText);
            paintText.TextAlign = Paint.Align.Center;
            paintText.Color = Android.Graphics.Color.White;
            paintText.FakeBoldText = true;
            var bmpText = Bitmap.CreateBitmap(boundsText.Width() + 10, boundsText.Height(), Bitmap.Config.Argb8888);
            var canvasText = new Canvas(bmpText);
            canvasText.DrawText(text, canvasText.Width / 2, canvasText.Height - boundsText.Bottom, paintText);
            var markerOptions = new MarkerOptions();
            markerOptions.SetPosition(location);
            markerOptions.SetIcon(BitmapDescriptorFactory.FromBitmap(bmpText));
            markerOptions.Anchor(0.5f, 0.5f);

            //markerOptions.SetTitle(text);

            Marker marker = map.AddMarker(markerOptions);

            Constants.markerPolygons.Add(markerOptions.Position.ToString(), polygon);
            lstText.Add(marker);

            return marker;
        }
</code>```

答:
I think what you are looking for is SkiaSharp.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/

I would also recommend that you consider Xamarin.Forms.GoogleMaps for multiple polygons
https://github.com/amay077/Xamarin.Forms.GoogleMaps

Title: Adding Labels to Xamarin map

Body:
I would like to add labels to my map.
I have a bunch of polygons on a map mapping out orchards (using Xamarin forms with Android and iOS custom renders) and would like to add a few labels to each with details. I have tried the below method where you make a custom pin with text used as the marker but this is not ideal as I would like a few lines of text in each and do not need it clickable. I also need this to work in iOS and Android.

Any help would be appreciated.

    public Marker AddText(Context context, GoogleMap map, LatLng location, string text, int fontSize, Polygon polygon)
    {
        try
        {
            if (text == null)
                throw new ArgumentNullException(nameof(text));
            if (location == null)
                throw new ArgumentNullException(nameof(location));
            if (map == null)
                throw new ArgumentNullException(nameof(map));
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            if (fontSize <= 0)
                throw new ArgumentOutOfRangeException(nameof(fontSize));

            var textView = new TextView(context);
            textView.Text = text;
            textView.TextSize = fontSize;
            var paintText = textView.Paint;
            var boundsText = new Rect();
            paintText.GetTextBounds(text, 0, textView.Length(), boundsText);
            paintText.TextAlign = Paint.Align.Center;
            paintText.Color = Android.Graphics.Color.White;
            paintText.FakeBoldText = true;
            var bmpText = Bitmap.CreateBitmap(boundsText.Width() + 10, boundsText.Height(), Bitmap.Config.Argb8888);
            var canvasText = new Canvas(bmpText);
            canvasText.DrawText(text, canvasText.Width / 2, canvasText.Height - boundsText.Bottom, paintText);
            var markerOptions = new MarkerOptions();
            markerOptions.SetPosition(location);
            markerOptions.SetIcon(BitmapDescriptorFactory.FromBitmap(bmpText));
            markerOptions.Anchor(0.5f, 0.5f);

            //markerOptions.SetTitle(text);

            Marker marker = map.AddMarker(markerOptions);

            Constants.markerPolygons.Add(markerOptions.Position.ToString(), polygon);
            lstText.Add(marker);

            return marker;
        }


问:
How to make Pairs using Stream for two lists
I have two lists:

```<code>List<Flight> flightsToCity = findFlightToCity(airport);
List<Flight> flightsFromCity = findFlightFromCity(airport);
</code>```

Elements of lists are flights. I must connect every flights from list flightsToCity, with every element of second list and this must be pairs. I must do this with stream and result it must be List<Pair<Flight, Flight>>
For example:

```<code>flightsToCity:

London -> Warsow,
Berlin -> Warsow

flightFromCity:

Warsow -> Barcelona,
Warsow -> Zakopane

Result:

London -> Warsow, Warsow -> Barcelona
London -> Warsow, Warsow -> Zakopane
Berlin -> Warsow, Warsow -> Barcelona
Berlin -> Warsow, Warsow -> Zakopane

</code>```

答:
Assuming that the lists have the same size and the elements are in the right order you could use an IntStream to solve your problem.</p>

```<code>        List<Pair<Flight, Flight>> flightsOfAirport = IntStream
            .range(0, flightsFromCity.size())
            .mapToObj(index -> Pair.of(flightsToCity.get(index), flightsFromCity.get(index)))
            .collect(Collectors.toList());
</code>```

Body:
I have two lists:

List<Flight> flightsToCity = findFlightToCity(airport);
List<Flight> flightsFromCity = findFlightFromCity(airport);

Elements of lists are flights. I must connect every flights from list flightsToCity, with every element of second list and this must be pairs. I must do this with stream and result it must be List<Pair<Flight, Flight>>
For example:

flightsToCity:

London -> Warsow,
Berlin -> Warsow

flightFromCity:

Warsow -> Barcelona,
Warsow -> Zakopane

Result:

London -> Warsow, Warsow -> Barcelona
London -> Warsow, Warsow -> Zakopane
Berlin -> Warsow, Warsow -> Barcelona
Berlin -> Warsow, Warsow -> Zakopane

Body:
Assuming that the lists have the same size and the elements are in the right order you could use an IntStream to solve your problem.

        List<Pair<Flight, Flight>> flightsOfAirport = IntStream
            .range(0, flightsFromCity.size())
            .mapToObj(index -> Pair.of(flightsToCity.get(index), flightsFromCity.get(index)))
            .collect(Collectors.toList());


问:
Mediaquery makes navbar unresponsive
I've been working on a MVC web application. So far everything has worked out fine, expect that one single thing. Basically, my problem is, that while attempting and succeeding in making the toggle button of my navbar disappear when the site has a certain size, my navbar is no longer responsive, as it no longer adapts its size to the screen.

Here is my entire button and navbar code:

Here is my environment:

```<code>     <environment names="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

    </environment>
    <environment names="Staging,Production">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
until here

            <div class="navbar-header navbarnone">
                <button type="button" class="navbar-toggler-icon navbarbutton" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" asp-controller="X" asp-action="Index">X</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" asp-controller="x" asp-action="Index">x</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" asp-controller="X" asp-action="Privacy">x</a>
                    </li>
                    <partial name="_LoginPartial" />
                </ul>
            </div>
</code>```

And here the CSS code for the mediaquery:

```<code>@media screen and (min-width: 768px) {
    .navbarnone {
        display: none;
    }
}
</code>```

答:
Because others might have the same problem, I'll post the answer I found for myself:

There's a line that's missing in the code. A meta line.

```<code><meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
</code>```

For some reason this meta tag prevents Google Chrome from screwing their dev tools up.

Title: Mediaquery makes navbar unresponsive

Body:
I've been working on a MVC web application. So far everything has worked out fine, expect that one single thing. Basically, my problem is, that while attempting and succeeding in making the toggle button of my navbar disappear when the site has a certain size, my navbar is no longer responsive, as it no longer adapts its size to the screen.

Here is my entire button and navbar code:

Here is my environment:

     <environment names="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    </environment>
    <environment names="Staging,Production">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
until here

                <button type="button" class="navbar-toggler-icon navbarbutton" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

                        Home (current)

                        X

                        x

                        x

                    <partial name="_LoginPartial" />

And here the CSS code for the mediaquery:

@media screen and (min-width: 768px) {
    .navbarnone {
        display: none;
    }
}

Body:
Because others might have the same problem, I'll post the answer I found for myself:

There's a line that's missing in the code. A meta line.

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

For some reason this meta tag prevents Google Chrome from screwing their dev tools up.


问:
How to format DayTime as Day of week Medium Time on Access
I was trying some SQL out on Access, but when I am trying to format the Date/Time data type so that I can input the day of the week and the medium time for my variables.

For example, I want to be able to input something like: Mon 1:00 PM.

I have tried formatting the data type as ddd h:nn AM/PM, but when I am trying to input the value, the system gives me an error stating that the input does not match my format.

I have also tried to auto-fill the input by clicking on the calendar next to the input box and selecting a date, but this way I cannot format the time.

Any help would be appreciated.

I did not add any pictures or code because I do not think that is needed to answer the question. If anything extra is needed, I am more than willing to provide them.

Thank You

答:
You can't enter the date/time in the formatted layout/text.

Although the date/time value is displayed according to your 'Format' property, it changes as soon as you move the cursor into the field or click into it.

Then you have to enter it in the conventional way, i.e. date and if desired the time behind it.

With the calendar you can only enter the date, unfortunately no the time. You would have to enter the time in the field yourself after you have selected the date.

The only way I see to enter date/time formatted is to write a VBA routine that interprets your input and puts the correctly formatted conventional text into your textbox.


问:
Export xlsx file through executing scripts in SQL developer
I know that we can use SPOOL command to export query result in CSV format from sql developer. However, I would like to export the query result as xlsx format instead of CSV format. Is there any command that I can use ??</p>

答:
No.

The best you can do is CSV via spool.

Or, if you're going to be exporting tables/views, you can use the sdcli to batch xlsx exports. I show this in detail here


问:
net core Validation: diffrent type of result
I am developing some Rest API using c# in net Core 3 that will be used by a REACT app.

For validation, I saw that three different types of objects are returned:

1) For rules defined in model (e.g. confirm password)

```<code>[Compare("Password")]
public string ConfirmPassword { get; set; }
</code>```

I got this object:

```<code>
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|ff4cda9e-4dd30d18a2a38002.",
    "errors": {
        "ConfirmPassword": [
            "La password e la password di conferma non coincidono"
        ]
    }
}
</code>```

2) For the password rules managed by IdentityProvider, I got this:

```<code>[
    {
        "code": "PasswordTooShort",
        "description": "La password deve essere almeno di 6 caratteri."
    },
    {
        "code": "PasswordRequiresNonAlphanumeric",
        "description": "La password deve contenere almeno un carattere speciale."
    },
    {
        "code": "PasswordRequiresDigit",
        "description": "La password deve contenere almeno un numero ('0'-'9')."
    },
    {
        "code": "PasswordRequiresUpper",
        "description": "La password deve contenere almeno un carattere minuscolo ('A'-'Z')."
    }
]
</code>```

3) Finally, for custom errors added with ModelStat.AddModelError I got this object:

```<code>{
    "Key 1": [
        "error messagge 1-1",
        "error messagge 2-1"
    ],
    "Key 2": [
        "error messagge 2-1"
    ]
}
</code>```

How can I handle all errors evenly?

答:
If you want the 1st format to be everywhere, you can use the ValidationProblem() method in your controllers, like in this example:

var result = await _userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
    foreach(var error in result.Errors)
    {
        ModelState.AddModelError("userCreation", error.Description);
    }
    return ValidationProblem();
}
```

<p>Have a look at the multiple overloads of the <code>ValidationProblem</code> method for more customization.</p>

<p>On the other hand, if you don't like the 1st format, you can redefine it as explained in the official documentation:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            // format the response as you wish
            var result = new BadRequestObjectResult(context.ModelState);
            result.ContentTypes.Add(MediaTypeNames.Application.Json);
            result.ContentTypes.Add(MediaTypeNames.Application.Xml);

            return result;
        };
    });
</code>```

Body:
I am developing some Rest API using c# in net Core 3 that will be used by a REACT app.

For validation, I saw that three different types of objects are returned:

1) For rules defined in model (e.g. confirm password)

[Compare("Password")]
public string ConfirmPassword { get; set; }

I got this object:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|ff4cda9e-4dd30d18a2a38002.",
    "errors": {
        "ConfirmPassword": [
            "La password e la password di conferma non coincidono"
        ]
    }
}

2) For the password rules managed by IdentityProvider, I got this:

[
    {
        "code": "PasswordTooShort",
        "description": "La password deve essere almeno di 6 caratteri."
    },
    {
        "code": "PasswordRequiresNonAlphanumeric",
        "description": "La password deve contenere almeno un carattere speciale."
    },
    {
        "code": "PasswordRequiresDigit",
        "description": "La password deve contenere almeno un numero ('0'-'9')."
    },
    {
        "code": "PasswordRequiresUpper",
        "description": "La password deve contenere almeno un carattere minuscolo ('A'-'Z')."
    }
]

3) Finally, for custom errors added with ModelStat.AddModelError I got this object:

{
    "Key 1": [
        "error messagge 1-1",
        "error messagge 2-1"
    ],
    "Key 2": [
        "error messagge 2-1"
    ]
}

How can I handle all errors evenly?

Body:
If you want the 1st format to be everywhere, you can use the ValidationProblem() method in your controllers, like in this example:

var result = await _userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
    foreach(var error in result.Errors)
    {
        ModelState.AddModelError("userCreation", error.Description);
    }
    return ValidationProblem();
}

Have a look at the multiple overloads of the ValidationProblem method for more customization.

On the other hand, if you don't like the 1st format, you can redefine it as explained in the official documentation:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            // format the response as you wish
            var result = new BadRequestObjectResult(context.ModelState);
            result.ContentTypes.Add(MediaTypeNames.Application.Json);
            result.ContentTypes.Add(MediaTypeNames.Application.Xml);

            return result;
        };
    });


问:
Find which element of list is a key in a dictionary and what is it's value
I have a dictionary:

```<code>classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
</code>```

and a list:

```<code>labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']
</code>```

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

```<code>class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])
</code>```

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

答:
Currently your labels_list consists of one string. It seems it should be a list of 5 strings. You do not need self. in front of classes_dictionary:</p>

```<code>class_str = list()
for k in labels_list:
  print(k)
  if k in classes_dictionary:
    class_str.append(classes_dictionary[k])
</code>```

Body:
I have a dictionary:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}

and a list:

labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

Body:
Currently your labels_list consists of one string. It seems it should be a list of 5 strings. You do not need self. in front of classes_dictionary:

class_str = list()
for k in labels_list:
  print(k)
  if k in classes_dictionary:
    class_str.append(classes_dictionary[k])


问:
How can I ship my app with a pre-populated Core Data database?
My app uses Core Data and I want some default entries to be inside.
What's best practices of how to do that?</p>

答: There is Core Data Editor at the app store. Alternatively you could build your own simple mac app just for this particular DB and manage it from there. If the amount of default entries is small, then you're better off storing it in a plist or something and loading it into DB after the first launch.</p>


问:
Skip RLS checks temporarily
I have tables with enabled row-level-security and the relevant policies in place - working really well.

My problem is that sometimes, based on some conditions, I want to bypass a policy for a specific statement during a function execution.

something like:

```<code>...
statement 1
statement 2
if (some cond) then
   disable rls temporarily
   statement 3 -- mostly delete rows the user can't normally see
   enable rls
else
   statement 3
end if
</code>```

The way I've implemented it is by creating a function check_cond which returns a boolean evaluating some cond and created an additional select policy which calls this check_cond.

It works - but the actual problem is that the query select * from tab now looks like this:
select * from tab where <original policy condition> or check_cond()

This or check_cond() causes postges to always do a full table scan since it cannot evaluate the result pre-planning.

If I were able to write "dynamic" code in the policy I would have been able to add/remove conditions based on the value of check_cond() but as far as I know it's not possible.

Any smart way which would allow me to temporarily disable rls or dynamically add conditions  without sacrificing performance?

Thanks.

答:
The easiest way would be to have a SECURITY DEFINER function owned by a superuser which runs:

```<code>ALTER ROLE someuser BYPASSRLS;
</code>```

where someuser is the user that runs the SQL statements.

Afterwards, you can re-enable it in the same way.

But that's pretty insecure, because nothing keeps the user from calling theses functions at other times.

A better way would be to define a security definer function owned by a user with BYPASSRLS that does the deletes for you.

Note: for security reasons, always SET search_path when you define a SECURITY DEFINER function.

Title: Skip RLS checks temporarily

Body:
I have tables with enabled row-level-security and the relevant policies in place - working really well.

My problem is that sometimes, based on some conditions, I want to bypass a policy for a specific statement during a function execution.

something like:

...
statement 1
statement 2
if (some cond) then
   disable rls temporarily
   statement 3 -- mostly delete rows the user can't normally see
   enable rls
else
   statement 3
end if

The way I've implemented it is by creating a function check_cond which returns a boolean evaluating some cond and created an additional select policy which calls this check_cond.

It works - but the actual problem is that the query select * from tab now looks like this:
select * from tab where <original policy condition> or check_cond()

This or check_cond() causes postges to always do a full table scan since it cannot evaluate the result pre-planning.

If I were able to write "dynamic" code in the policy I would have been able to add/remove conditions based on the value of check_cond() but as far as I know it's not possible.

Any smart way which would allow me to temporarily disable rls or dynamically add conditions  without sacrificing performance?

Thanks.

Body:
The easiest way would be to have a SECURITY DEFINER function owned by a superuser which runs:

ALTER ROLE someuser BYPASSRLS;

where someuser is the user that runs the SQL statements.

Afterwards, you can re-enable it in the same way.

But that's pretty insecure, because nothing keeps the user from calling theses functions at other times.

A better way would be to define a security definer function owned by a user with BYPASSRLS that does the deletes for you.

Note: for security reasons, always SET search_path when you define a SECURITY DEFINER function.


问:
compileSdkVersion is not specified error in React Native Android
I get the build error when I try to build an Android app in my React Native project.

When I run react-native run-android, it says:

```<code>> Configure project :react-native-os
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-os'.
> compileSdkVersion is not specified.
</code>```

In Android Studio, I can see that it says the same thing:
Cause: compileSdkVersion is not specified.

So I edited build.gradle(Module: app) file in Android Studio, but the problem persists and the error message doesn't change.

```<code>android {
//    compileSdkVersion rootProject.ext.compileSdkVersion
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
</code>```

I tried solutions in other threads like this one but nothing worked. Does anyone know what the problem is here?

答:
I also faced the same issue solved by :

1- run npm i @react-native-firebase/app in terminal

2- follow these steps to add firebase to the android platform.

Body:
I get the build error when I try to build an Android app in my React Native project.

When I run react-native run-android, it says:

> Configure project :react-native-os
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-os'.
> compileSdkVersion is not specified.

In Android Studio, I can see that it says the same thing:
Cause: compileSdkVersion is not specified.

So I edited build.gradle(Module: app) file in Android Studio, but the problem persists and the error message doesn't change.

android {
//    compileSdkVersion rootProject.ext.compileSdkVersion
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

I tried solutions in other threads like this one but nothing worked. Does anyone know what the problem is here?


问:
How to render React Component into itself, in a recursive way
I have a component say, List Component. List component can render items
through component ListItem. Which can be easily achieved with something like below

```<code>import React from 'react';
import ListItem from '../list-item/list-item';

class List extends React.Component {

  renderListItems() {
    return this.props.items.map(item => <ListItem item={item} />)
  }

  render(){
    return (
      <div className="list">{this.renderListItems()}</div>
    )
  }

}
</code>```

and

```<code>import React from 'react';
class ListItem extends React.Component {

  render(){
    return (
      <div className="list-item">Name: {this.props.item.name}</div>
    )
  }

}
</code>```

Now, in this scenario if list items can have parent children within them i.e. one list item can further render more list items how can I render ListItem component from within itself. Following is the rendering tree I am looking for and also the state of my data

```<code>List
 - ListItem
  - ListItem
  - ListItem
 - ListItem
 - ListItem
</code>```

Edit

I think right structure will be something like this

```<code>List
 - ListItem
  - List
    - ListItem
    - ListItem
 - ListItem
 - ListItem
</code>```

But it will ofcourse create a circular dependency between List and ListItem components, will that be a problem?

答:
Tested.
Did call it recursively inside component's render.</p>

```<code>import React from "react";
import { isItemComponent } from "../utils/utils";

const SubMenuModified = ({
      SubMenuComponent,
      ItemComponent,
      data,
      ...others
    }) => {
      return (
        <SubMenuComponent
          key={`SubMenuComponent${data.id}`}
          title={<span>{data.name}</span>}
          {...others}
        >
          {data.list.map(info => {
            if (isItemComponent(info)) {
              return <ItemComponent key={info.id}>{info.name}</ItemComponent>;
            } else {
              return (
                <SubMenuModified
                  SubMenuComponent={SubMenuComponent}
                  ItemComponent={ItemComponent}
                  key={`SubMenuComponent${info.id}`}
                  data={info}
                  {...others}
                />
              );
            }
          })}
        </SubMenuComponent>
      );
    };

    export default SubMenuModified;
</code>```

Body:
I have a component say, List Component. List component can render items
through component ListItem. Which can be easily achieved with something like below

import React from 'react';
import ListItem from '../list-item/list-item';

class List extends React.Component {

  renderListItems() {
    return this.props.items.map(item => <ListItem item={item} />)
  }

  render(){
    return (

{this.renderListItems()}

    )
  }

}

and

import React from 'react';
class ListItem extends React.Component {

  render(){
    return (

Name: {this.props.item.name}

    )
  }

}

Now, in this scenario if list items can have parent children within them i.e. one list item can further render more list items how can I render ListItem component from within itself. Following is the rendering tree I am looking for and also the state of my data

List
 - ListItem
  - ListItem
  - ListItem
 - ListItem
 - ListItem

Edit

I think right structure will be something like this

List
 - ListItem
  - List
    - ListItem
    - ListItem
 - ListItem
 - ListItem

But it will ofcourse create a circular dependency between List and ListItem components, will that be a problem?

Body:
Tested.
Did call it recursively inside component's render.

import React from "react";
import { isItemComponent } from "../utils/utils";

const SubMenuModified = ({
      SubMenuComponent,
      ItemComponent,
      data,
      ...others
    }) => {
      return (
        <SubMenuComponent
          key={`SubMenuComponent${data.id}`}
          title={<span>{data.name}</span>}
          {...others}
        >
          {data.list.map(info => {
            if (isItemComponent(info)) {
              return <ItemComponent key={info.id}>{info.name}</ItemComponent>;
            } else {
              return (
                <SubMenuModified
                  SubMenuComponent={SubMenuComponent}
                  ItemComponent={ItemComponent}
                  key={`SubMenuComponent${info.id}`}
                  data={info}
                  {...others}
                />
              );
            }
          })}
        </SubMenuComponent>
      );
    };

    export default SubMenuModified;