问:
How can I access <Image Name="AddImg"/> from Code in WPF?
I have created an Image in XAML and I would like to access it from code to modify the Source dynamically. I could not access so far. Is there any solution?

```<code><Window x:Class="DDSV2.MasterMain"
    Name="MainWw"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DDSV2"
    mc:Ignorable="d"
    Title="MasterMain" Height="1123.439" Width="1822.363" Loaded="Window_Loaded">
<Grid Name="MainGrid">
    <ListView x:Name="MainMasterLv" Height="333" Margin="10,10,1494,0" VerticalAlignment="Top" SelectionChanged="MainMasterLv_SelectionChanged">
        <ListView.View>
            <GridView x:Name="GridVw">
                <GridViewColumn x:Name="DataGridCn"  Header="">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate x:Name="DataTmp">
                            <StackPanel Orientation="Horizontal">
                                <Image x:Name="AddImg" Source="pack://application:,,,/Resources        /gears.png" MaxWidth="80" MaxHeight="80" Margin="3,3,3,3"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</code>```

答:
```<code> public T FindChild<T>(DependencyObject parent, string childName)
   where T : DependencyObject
        {
            // Confirm parent and childName are valid.
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindChild<T>(child, childName);

                    // If the child is found, break so we do not overwrite the found child.
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // If the child's name is set for search
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        // if the child's name is of the request name
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }
</code>```

And use it like :

```<code>Image item =FindChild<Image>(DataGridCn.CellTemplate.LoadContent(), "AddImg");
string source = item.Source.ToString();
</code>```

Body:
I have created an Image in XAML and I would like to access it from code to modify the Source dynamically. I could not access so far. Is there any solution?

<Window x:Class="DDSV2.MasterMain"
    Name="MainWw"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DDSV2"
    mc:Ignorable="d"
    Title="MasterMain" Height="1123.439" Width="1822.363" Loaded="Window_Loaded">
<Grid Name="MainGrid">
    <ListView x:Name="MainMasterLv" Height="333" Margin="10,10,1494,0" VerticalAlignment="Top" SelectionChanged="MainMasterLv_SelectionChanged">
        <ListView.View>
            <GridView x:Name="GridVw">
                <GridViewColumn x:Name="DataGridCn"  Header="">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate x:Name="DataTmp">
                            <StackPanel Orientation="Horizontal">
                                <Image x:Name="AddImg" Source="pack://application:,,,/Resources        /gears.png" MaxWidth="80" MaxHeight="80" Margin="3,3,3,3"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

</Grid>

Body:
 public T FindChild<T>(DependencyObject parent, string childName)
   where T : DependencyObject
        {
            // Confirm parent and childName are valid.
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindChild<T>(child, childName);

                    // If the child is found, break so we do not overwrite the found child.
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // If the child's name is set for search
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        // if the child's name is of the request name
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }

And use it like :

Image item =FindChild<Image>(DataGridCn.CellTemplate.LoadContent(), "AddImg");
string source = item.Source.ToString();


来源: stackexchange

问:
How can I preserve both matching and non-matching parts using immutable collection in O(n) time
I have to operate on tmp list based on some condition.
false does a bulk db insert and true does an update

```<code>val tmp = List(1,2,3, 15)
val bool = List(true, true, true, false)
</code>```

I am using the below approach to create 2 lists , one matching and one non-matching.

```<code>val result = tmp.zip(bool).partition {
case tuple if tuple._2 => true
case tuple if !tuple._2 => false
}
</code>```

I get 2 lists , so I can run insertAll(result._2) and updateAll(result._1)

Since partition uses scala.collection.mutable.Builder, I was trying to find an approach that solves the problem using immutable collections.

答:
I came up with two solutions. I don't find either fully satisfactory but hopefully they can help you achieve your goal.

The first one is tail recursive but reverses the original input. It may be enough for your use case if you don't care about the order, but if you do you have to reverse the resulting lists before returning them, which involves a second pass through the list (O(n)):

```<code>def zipAndPartition[A, B](as: List[A], bs: List[B])(p: ((A, B)) => Boolean): (List[(A, B)], List[(A, B)]) = {
  @annotation.tailrec
  def loop(left: List[A], right: List[B], acc: (List[(A, B)], List[(A, B)])): (List[(A, B)], List[(A, B)]) =
    (left, right) match {
      case (Nil, _) | (_, Nil) => acc
      case (lhead :: ltail, rhead :: rtail) if p((lhead, rhead)) => loop(ltail, rtail, ((lhead, rhead) :: acc._1, acc._2))
      case (lhead :: ltail, rhead :: rtail) => loop(ltail, rtail, (acc._1, (lhead, rhead) :: acc._2))
    }

  val (left, right) = loop(as, bs, (Nil, Nil))
  (left.reverse, right.reverse)
}
</code>```

The second doesn't require reversing the outputs before returning them but relies on mutually recursive functions and thus cannot be annotated with @annotation.tailrec:

```<code>def zap[A, B](as: List[A], bs: List[B])(p: ((A, B)) => Boolean): (List[(A, B)], List[(A, B)]) = {
  def loop(left: List[A], right: List[B], acc: (List[(A, B)], List[(A, B)])): (List[(A, B)], List[(A, B)]) =
    (left, right) match {
      case (Nil, _) | (_, Nil) => acc
      case (lhead :: ltail, rhead :: rtail) if p((lhead, rhead)) =>
        val tail = zap(ltail, rtail)(p)
        ((lhead, rhead) :: tail._1, tail._2)
      case (lhead :: ltail, rhead :: rtail) =>
        val tail = zap(ltail, rtail)(p)
        (tail._1, (lhead, rhead) :: tail._2)
    }

  loop(as, bs, (Nil, Nil))
}
</code>```

You can play around with this code here on Scastie.

Edit

A third solution, which retains the shortcomings of the first but is probably more readable, splits the problem in two and uses function composition:

```<code>val tmp = List(1, 2, 3, 15)
val bool = List(true, true, true, false)

def zip[A, B](as: List[A], bs: List[B]): List[(A, B)] = {
  @annotation.tailrec
  def loop(left: List[A], right: List[B], acc: List[(A, B)]): List[(A, B)] =
    (left, right) match {
      case (Nil, _) | (_, Nil) => acc
      case (lhead :: ltail, rhead :: rtail) => loop(ltail, rtail, (lhead, rhead) :: acc)
    }
  loop(as, bs, Nil)
}

def partition[A](as: List[A])(p: A => Boolean): (List[A], List[A]) = {
  @annotation.tailrec
  def loop(list: List[A], acc: (List[A], List[A])): (List[A], List[A]) =
    list match {
      case Nil => acc
      case head :: tail if p(head) => loop(tail, (head :: acc._1, acc._2))
      case head :: tail => loop(tail, (acc._1, head:: acc._2))
    }
  loop(as, (Nil, Nil))
}

def zap[A, B] = (zip[A, B] _).tupled.andThen(partition[(A, B)] _)

zap(tmp, bool)(_._2)
</code>```

This solution is available on Scastie as well.

ContentLicense: CC BY-SA 4.0

Body:
I have to operate on tmp list based on some condition.
false does a bulk db insert and true does an update

val tmp = List(1,2,3, 15)
val bool = List(true, true, true, false)

I am using the below approach to create 2 lists , one matching and one non-matching.

val result = tmp.zip(bool).partition {
case tuple if tuple._2 => true
case tuple if !tuple._2 => false
}

I get 2 lists , so I can run insertAll(result._2) and updateAll(result._1)

Since partition uses scala.collection.mutable.Builder, I was trying to find an approach that solves the problem using immutable collections.

Body:
I came up with two solutions. I don't find either fully satisfactory but hopefully they can help you achieve your goal.

The first one is tail recursive but reverses the original input. It may be enough for your use case if you don't care about the order, but if you do you have to reverse the resulting lists before returning them, which involves a second pass through the list (O(n)):

def zipAndPartition[A, B](as: List[A], bs: List[B])(p: ((A, B)) => Boolean): (List[(A, B)], List[(A, B)]) = {
  @annotation.tailrec
  def loop(left: List[A], right: List[B], acc: (List[(A, B)], List[(A, B)])): (List[(A, B)], List[(A, B)]) =
    (left, right) match {
      case (Nil, _) | (_, Nil) => acc
      case (lhead :: ltail, rhead :: rtail) if p((lhead, rhead)) => loop(ltail, rtail, ((lhead, rhead) :: acc._1, acc._2))
      case (lhead :: ltail, rhead :: rtail) => loop(ltail, rtail, (acc._1, (lhead, rhead) :: acc._2))
    }

  val (left, right) = loop(as, bs, (Nil, Nil))
  (left.reverse, right.reverse)
}

The second doesn't require reversing the outputs before returning them but relies on mutually recursive functions and thus cannot be annotated with @annotation.tailrec:

def zap[A, B](as: List[A], bs: List[B])(p: ((A, B)) => Boolean): (List[(A, B)], List[(A, B)]) = {
  def loop(left: List[A], right: List[B], acc: (List[(A, B)], List[(A, B)])): (List[(A, B)], List[(A, B)]) =
    (left, right) match {
      case (Nil, _) | (_, Nil) => acc
      case (lhead :: ltail, rhead :: rtail) if p((lhead, rhead)) =>
        val tail = zap(ltail, rtail)(p)
        ((lhead, rhead) :: tail._1, tail._2)
      case (lhead :: ltail, rhead :: rtail) =>
        val tail = zap(ltail, rtail)(p)
        (tail._1, (lhead, rhead) :: tail._2)
    }

  loop(as, bs, (Nil, Nil))
}

You can play around with this code here on Scastie.

Edit

A third solution, which retains the shortcomings of the first but is probably more readable, splits the problem in two and uses function composition:

val tmp = List(1, 2, 3, 15)
val bool = List(true, true, true, false)

def zip[A, B](as: List[A], bs: List[B]): List[(A, B)] = {
  @annotation.tailrec
  def loop(left: List[A], right: List[B], acc: List[(A, B)]): List[(A, B)] =
    (left, right) match {
      case (Nil, _) | (_, Nil) => acc
      case (lhead :: ltail, rhead :: rtail) => loop(ltail, rtail, (lhead, rhead) :: acc)
    }
  loop(as, bs, Nil)
}

def partition[A](as: List[A])(p: A => Boolean): (List[A], List[A]) = {
  @annotation.tailrec
  def loop(list: List[A], acc: (List[A], List[A])): (List[A], List[A]) =
    list match {
      case Nil => acc
      case head :: tail if p(head) => loop(tail, (head :: acc._1, acc._2))
      case head :: tail => loop(tail, (acc._1, head:: acc._2))
    }
  loop(as, (Nil, Nil))
}

def zap[A, B] = (zip[A, B] _).tupled.andThen(partition[(A, B)] _)

zap(tmp, bool)(_._2)

This solution is available on Scastie as well.


问:
Keep only those rows in a Pandas DataFrame equal to a certain value (paired multiple columns)
A part of the answer can be found here (How to select rows from a DataFrame based on column values?), however it's only for one column. I'm wondering how to apply it for paired values in multiple columns (two in this case).

I have a data frame df where the filtering columns are B and C (NaN represents empty cells):

```<code>    A     B      C  D
0   1  Blue  Green  4
1   2  Blue  Green  6
2   3  Blue  Green  2
3   4  Blue    NaN  6
4   5  Blue    NaN  9
5   6   NaN  Green  8
6   7  Blue  Green  8
7   8   NaN    NaN  9
8   9   NaN  Green  1
9  10   NaN  Green  2
</code>```

I would only like to keep the rows with respect to B and C for which B='Blue' and C='Green', all the other rows can be dropped, ideally producing:

```<code>    A     B      C  D
0   1  Blue  Green  4
1   2  Blue  Green  6
2   3  Blue  Green  2
6   7  Blue  Green  8
</code>```

Any ideas?

Code for the dataframe:

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

df = pd.DataFrame({"A": [1,2,3,4,5,6,7,8,9,10], "B": ['Blue', 'Blue', 'Blue', 'Blue','Blue', np.nan,
'Blue', np.nan, np.nan, np.nan], "C": ['Green', 'Green', 'Green', np.nan, np.nan, 'Green', 'Green',
np.nan, 'Green', 'Green'], "D": [4,6,2,6,9,8,8,9,1,2]})
print(df)
</code>```

答:
I think what you need is the & operator:

```<code>df[(df['B']=='Blue') & (df['C']=='Green')]
</code>```

Body:
A part of the answer can be found here (How to select rows from a DataFrame based on column values?), however it's only for one column. I'm wondering how to apply it for paired values in multiple columns (two in this case).

I have a data frame df where the filtering columns are B and C (NaN represents empty cells):

    A     B      C  D
0   1  Blue  Green  4
1   2  Blue  Green  6
2   3  Blue  Green  2
3   4  Blue    NaN  6
4   5  Blue    NaN  9
5   6   NaN  Green  8
6   7  Blue  Green  8
7   8   NaN    NaN  9
8   9   NaN  Green  1
9  10   NaN  Green  2

I would only like to keep the rows with respect to B and C for which B='Blue' and C='Green', all the other rows can be dropped, ideally producing:

    A     B      C  D
0   1  Blue  Green  4
1   2  Blue  Green  6
2   3  Blue  Green  2
6   7  Blue  Green  8

Any ideas?

Code for the dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": [1,2,3,4,5,6,7,8,9,10], "B": ['Blue', 'Blue', 'Blue', 'Blue','Blue', np.nan,
'Blue', np.nan, np.nan, np.nan], "C": ['Green', 'Green', 'Green', np.nan, np.nan, 'Green', 'Green',
np.nan, 'Green', 'Green'], "D": [4,6,2,6,9,8,8,9,1,2]})
print(df)

Body:
I think what you need is the & operator:

df[(df['B']=='Blue') & (df['C']=='Green')]


问:
javascript not compiling in rails 6
I recently updated to rails 6.0.2 everything works fine but as i was creating a new project i fined that the javascript folder has been moved from assest pipeline to the app folder. Am using a theme to create a simple one page site everything works fine except the javascript. I have placed all my javascripts file app/javascripts/packs and here is how am calling it on my homepage.

```<code><script type="text/javascript" src="/javascript/jquery.min.js"></script>
        <script type="text/javascript" src="/javascript/jquery-migrate.min.js"></script>
        <script type="text/javascript" src="/javascript/bootstrap.min.js"></script>
        <script type="text/javascript" src="/javascript/jquery.themepunch.tools.min.js"></script>
        <script type="text/javascript" src="/javascript/jquery.themepunch.revolution.min.js"></script>
        <script type="text/javascript" src="/javascript/snap.min.js"></script>
        <script type="text/javascript" src="/javascript/owl.carousel.min.js"></script>
        <script type="text/javascript" src="/javascript/jquery.prettyPhoto.js"></script>
        <script type="text/javascript" src="/javascript/jquery.prettyPhoto.init.min.js"></script>
        <script type="text/javascript" src="/javascript/jQuery.headroom.min.js"></script>
        <script type="text/javascript" src="/javascript/headroom.min.js"></script>
        <script type="text/javascript" src="/javascript/script.js"></script>

        <script type="text/javascript" src="/javascript/revolution.extension.video.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.slideanims.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.actions.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.layeranimation.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.kenburn.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.navigation.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.migration.min.js"></script>
        <script type="text/javascript" src="/javascript/revolution.extension.parallax.min.js"></script>
</code>```

here is my application.js

```<code>console.log('Hello World from Webpacker')
require("packs/bootstrap")
require("packs/headroom")
require("packs/jquery-migrate")
require("packs/jQuery.headroom")
require("packs/jquery")
require("packs/jquery.prettyPhoto.init")
require("packs/jquery.prettyPhoto")
require("packs/jquery.themepunch.revolution")
require("packs/jquery.themepunch.tools")
require("packs/owl.carousel")
require("packs/revolution.extension.actions")
require("packs/revolution.extension.kenburn")
require("packs/revolution.extension.layeranimation")
require("packs/revolution.extension.migration")
require("packs/revolution.extension.navigation")
require("packs/revolution.extension.parallax")
require("packs/revolution.extension.slideanims")
require("packs/revolution.extension.video")
</code>```

but i still get

```<code>ActionController::RoutingError (No route matches [GET] "/javascript/revolution.extension.parallax.min.js"):
</code>```

答:
if you have loaded all your js in application.js . Shouldn't it be sufficient to call

```<code> <%= yield :javascript %>
</code>```

in application.html.erb.
Another way you can place your js files in public/js/packs directory and access those file like

```<code><script src="/js/packs/jquery.prettyPhoto.init"></script>
</code>```

Title: javascript not compiling in rails 6

Body:
I recently updated to rails 6.0.2 everything works fine but as i was creating a new project i fined that the javascript folder has been moved from assest pipeline to the app folder. Am using a theme to create a simple one page site everything works fine except the javascript. I have placed all my javascripts file app/javascripts/packs and here is how am calling it on my homepage.

here is my application.js

console.log('Hello World from Webpacker')
require("packs/bootstrap")
require("packs/headroom")
require("packs/jquery-migrate")
require("packs/jQuery.headroom")
require("packs/jquery")
require("packs/jquery.prettyPhoto.init")
require("packs/jquery.prettyPhoto")
require("packs/jquery.themepunch.revolution")
require("packs/jquery.themepunch.tools")
require("packs/owl.carousel")
require("packs/revolution.extension.actions")
require("packs/revolution.extension.kenburn")
require("packs/revolution.extension.layeranimation")
require("packs/revolution.extension.migration")
require("packs/revolution.extension.navigation")
require("packs/revolution.extension.parallax")
require("packs/revolution.extension.slideanims")
require("packs/revolution.extension.video")

but i still get

ActionController::RoutingError (No route matches [GET] "/javascript/revolution.extension.parallax.min.js"):

Body:
if you have loaded all your js in application.js . Shouldn't it be sufficient to call

 <%= yield :javascript %>

in application.html.erb.
Another way you can place your js files in public/js/packs directory and access those file like

<script src="/js/packs/jquery.prettyPhoto.init"></script>


问:
Generating smooth normals for terrains in OpenGL
I'm implementing a system to generate terrains using perlin noise. This is how I generate the vertices:

```<code>int arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {
            float height0 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height1 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height2 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH),
            height3 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            mapVertices[arrayIdx + 0] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height0, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 1] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 2] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 3] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height3, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 4] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 5] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);

            mapUVs[arrayIdx + 0] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 1] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 2] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 3] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 4] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 5] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            glm::vec3 normal0 = -1.0f * glm::triangleNormal(mapVertices[arrayIdx + 0], mapVertices[arrayIdx + 1], mapVertices[arrayIdx + 2]),
            normal1 = +1.0f * glm::triangleNormal(mapVertices[arrayIdx + 3], mapVertices[arrayIdx + 4], mapVertices[arrayIdx + 5]);

            mapNormals[arrayIdx + 0] = normal0;
            mapNormals[arrayIdx + 1] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 2] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 3] = normal1;
            mapNormals[arrayIdx + 4] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 5] = (normal0 + normal1) / 2.0f;

            arrayIdx += 6;
        }
    }
</code>```

Not using lighting produces these quite smooth results,

The only thing left to do is to generate normals for the triangles, that will make the terrain look smooth.
Just using glm::triangleNormal yields this result,

As you can see, lighting really destroys the illusion of a smooth surface.

I tried using an average value of normals on the colliding vertices of the triangles like this:

```<code>arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {

            if((x == offset.x - CHUNK_WIDTH / 2.0f && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == offset.x - CHUNK_WIDTH / 2.0f && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH)) {
                //Special case
            }
            else if(x ==  float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH ||
                    y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) {
                 //Special case
            }
            else {
                glm::vec3 averageNormals = (mapNormals[arrayIdx + 3 + 0] + //This triangle
                                            mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] + //Triangle after and this one
                                            mapNormals[arrayIdx + 2 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 5 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] + //Triangle after this one
                                            mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6])  //Triangle after this one
                                            / 6.0f;

                mapNormals[arrayIdx + 3 + 0] = averageNormals;
                mapNormals[arrayIdx + 2 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 5 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] = mapNormals[arrayIdx + 3 + 0];
            }

            arrayIdx += 6;
        }
    }
</code>```

which yielded this result,

but this doesn't look much better.

Using the normals as fragment color give this result:

Rendering the normals as lines yields this, this is before the optimization and with larger triangles, to reduce the number of lines:

This is with my optimization:

Somehow, two normals dont get set.

The blue lines here are the average normals, the green lines are the individual normals before optimizing, they look good:

This is with wireframe:

Maybe some normals aren't set to the average value?

How can I generate normals that are smooth?

答:
I can see the images I requested...

Now look below the terrain if there are not some normals pointing downwords. If yes it means wrong order of multiplication in cross or not the same winding in the terrain geometry.

Then check if your normals are normalized (the same size) but from a quick look it look OK to me.

If you render your averaged normal (with different color) it should be enclosed by the other normals (in the middle of them)

Anyway this does not look right to me:

looks like one of the normal is going in reflected direction. Are you sure you are computing the normal from correct vertexes ?

Your geometry looks like triangulated QUAD grid so you just may be use wrong diagonal ...

Body:
I'm implementing a system to generate terrains using perlin noise. This is how I generate the vertices:

int arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {
            float height0 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height1 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height2 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH),
            height3 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            mapVertices[arrayIdx + 0] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height0, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 1] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 2] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 3] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height3, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 4] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 5] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);

            mapUVs[arrayIdx + 0] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 1] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 2] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 3] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 4] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 5] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            glm::vec3 normal0 = -1.0f * glm::triangleNormal(mapVertices[arrayIdx + 0], mapVertices[arrayIdx + 1], mapVertices[arrayIdx + 2]),
            normal1 = +1.0f * glm::triangleNormal(mapVertices[arrayIdx + 3], mapVertices[arrayIdx + 4], mapVertices[arrayIdx + 5]);

            mapNormals[arrayIdx + 0] = normal0;
            mapNormals[arrayIdx + 1] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 2] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 3] = normal1;
            mapNormals[arrayIdx + 4] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 5] = (normal0 + normal1) / 2.0f;

            arrayIdx += 6;
        }
    }

Not using lighting produces these quite smooth results,

The only thing left to do is to generate normals for the triangles, that will make the terrain look smooth.
Just using glm::triangleNormal yields this result,

As you can see, lighting really destroys the illusion of a smooth surface.

I tried using an average value of normals on the colliding vertices of the triangles like this:

arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {

            if((x == offset.x - CHUNK_WIDTH / 2.0f && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == offset.x - CHUNK_WIDTH / 2.0f && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH)) {
                //Special case
            }
            else if(x ==  float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH ||
                    y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) {
                 //Special case
            }
            else {
                glm::vec3 averageNormals = (mapNormals[arrayIdx + 3 + 0] + //This triangle
                                            mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] + //Triangle after and this one
                                            mapNormals[arrayIdx + 2 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 5 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] + //Triangle after this one
                                            mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6])  //Triangle after this one
                                            / 6.0f;

                mapNormals[arrayIdx + 3 + 0] = averageNormals;
                mapNormals[arrayIdx + 2 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 5 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] = mapNormals[arrayIdx + 3 + 0];
            }

            arrayIdx += 6;
        }
    }

which yielded this result,

but this doesn't look much better.

Using the normals as fragment color give this result:

Rendering the normals as lines yields this, this is before the optimization and with larger triangles, to reduce the number of lines:

This is with my optimization:

Somehow, two normals dont get set.

The blue lines here are the average normals, the green lines are the individual normals before optimizing, they look good:

This is with wireframe:

Maybe some normals aren't set to the average value?

How can I generate normals that are smooth?


问:
How to convert in Date format the columns of a particular excel file?
I have an excel file with 77 columns (with 43 NA columns) of different length, 12 of which are Date. Ideally, I want to import it in R the dataset with the columns that refer to Date in date format, while the other columns in numeric format. There is lot of material in stackoverflow and I tried all the options but it is not working.

The first option would be to do it directly from excel:

```<code>dataset <- read_xlsx("Data.xlsx", col_types = "numeric") #it gives everything numeric but column date always in this format "36164"

#I also tried something like this:

dataset <- read_xlsx("Data.xlsx", col_types = c("date", rep("numeric", n))) #where "n" stands for all the columns with numbers I have but it did not work

</code>```

I can import the data with the incorret date columns. After some cleaning (removing NA columns) I get a tbl with different column length. I tried the following codes to transform the incorrect column dates into date format:

```<code>dataset <- janitor::remove_empty(dataset, which = "cols") #remove NA columns
dataset <- dataset[-c(1),] #remove the first row of all columns

# Now using this command I could transform each incorrect date column into a date format:

  date <- as.Date(as.numeric(dataset$column1), origin = "1899-12-30")

# I would like to do it for all the date columns in one shot but when I try to do it in this way

  as.Date(as.numeric(dataset[,c(1,3,5,7,14,16,18,20,21,23,25,32)]), origin = "1899-12-30")

# I get an error, probably because the columns have different length
# the error is: Error in as.Date(as.numeric(var_dataset[, c(1, 3, 5, 7, 14, 16, 18, 20,  :
  'list' object cannot be coerced to type 'double'
# unlisting the object doesn't solve the problem

</code>```

I am aware it is missing data to reproduce my problem but in the first scenario I don't know how to approximate my quite big excel file while in the second case I don't know how to create a tbl with many columns of different length without wasting lot of time. Sorry.

Do you have any solution? Either for importing directly from Excel or playing with the dataframe

Thanks so much

I attach here the structure of my dataset:

```<code>Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   5500 obs. of  77 variables:
 $ Name...1                                                     : chr  "Code" "36164" "36165" "36166" ...
 $ VSTOXX VOLATILITY INDEX - PRICE INDEX                        : chr  "VSTOXXI(PI)" "18.2" "29.69" "25.17" ...
 $ ...3                                                         : logi  NA NA NA NA NA NA ...
 $ ...4                                                         : logi  NA NA NA NA NA NA ...
 $ ...5                                                         : logi  NA NA NA NA NA NA ...
 $ ...6                                                         : logi  NA NA NA NA NA NA ...
 $ Name...7                                                     : chr  "Code" "36799" "36830" "36860" ...
 $ EM COMPOSITE INDICATOR OF SOVEREIGN STRESS: GDP WEIGHTS NADJ : chr  "EMEBSCGWR" "7.8255999999999992E-2" "8.9886999999999995E-2" "8.0714999999999995E-2" ...
 $ ...9                                                         : logi  NA NA NA NA NA NA ...
 $ Name...10                                                    : chr  "Code" "36168" "36175" "36182" ...
 $ CISS BOND MKT: GOV & NFC VOLATILITY - ECONOMIC SERIES        : chr  "EMCIBMG" "4.4651999999999997E-2" "6.6535999999999998E-2" "4.9789E-2" ...
 $ ...12                                                        : logi  NA NA NA NA NA NA ...
 $ Name...13                                                    : chr  "Code" "36168" "36175" "36182" ...
 $ CISS MONEY MKT: 3M RATE+ VOLATILITY - ECONOMIC SERIES        : chr  "EMECM3E" "5.7435999999999994E-2" "7.463199999999999E-2" "7.2263999999999995E-2" ...
 $ CISS FX MKT: EUR VOLATILITY - ECONOMIC SERIES                : chr  "EMECFEM" "7.2139999999999996E-2" "8.6049E-2" "4.5948999999999997E-2" ...
 $ CISS FIN INTERM: BANK+ VOLATILITY - ECONOMIC SERIES          : chr  "EMCIFIN" "4.5384999999999995E-2" "0.11820399999999999" "0.11516499999999999" ...
 $ CISS NF EQUITY: VOLATILITY - ECONOMIC SERIES                 : chr  "EMCIEMN" "7.7453999999999995E-2" "0.12733" "0.11918899999999999" ...
 $ CISS: CROSS SUBINDEXCORRELATION - ECONOMIC SERIES            : chr  "EMCICRO" "-0.21210999999999999" "-0.29791000000000001" "-0.2369" ...
 $ SYSTEMIC STRESS COMPINDICATOR - ECONOMIC SERIES              : chr  "EMCISSI" "8.4954000000000002E-2" "0.174844" "0.16546" ...
 $ ...20                                                        : logi  NA NA NA NA NA NA ...
 $ ...21                                                        : logi  NA NA NA NA NA NA ...
 $ ...22                                                        : logi  NA NA NA NA NA NA ...
 $ ...23                                                        : logi  NA NA NA NA NA NA ...
 $ ...24                                                        : logi  NA NA NA NA NA NA ...
 $ ...25                                                        : logi  NA NA NA NA NA NA ...
 $ Name...26                                                    : chr  "Code" "33253" "33284" "33312" ...
 $ Z8 IPI: MFG., VOLUME INDEX OF PRODUCTION, 2015=100 (WDA) VOLA: chr  "Z8ES493KG" "81" "79.7" "79.400000000000006" ...
 $ ...28                                                        : logi  NA NA NA NA NA NA ...
 $ ...29                                                        : logi  NA NA NA NA NA NA ...
 $ ...30                                                        : logi  NA NA NA NA NA NA ...
 $ ...31                                                        : logi  NA NA NA NA NA NA ...
 $ ...32                                                        : logi  NA NA NA NA NA NA ...
 $ ...33                                                        : logi  NA NA NA NA NA NA ...
 $ ...34                                                        : logi  NA NA NA NA NA NA ...
 $ Name...35                                                    : chr  "Code" "35779" "35810" "35841" ...
 $ EH HICP: ALL-ITEMS NADJ                                      : chr  "EHES795WR" "1.7" "1.6" "1.6" ...
 $ ...37                                                        : logi  NA NA NA NA NA NA ...
 $ ...38                                                        : logi  NA NA NA NA NA NA ...
 $ Name...39                                                    : chr  "Code" "35110" "35139" "35170" ...
 $ EH HICP: ALL-ITEMS (%MOM) NADJ                               : chr  "EHESPQ93R" "0.4" "0.4" "0.3" ...
 $ ...41                                                        : logi  NA NA NA NA NA NA ...
 $ ...42                                                        : logi  NA NA NA NA NA NA ...
 $ ...43                                                        : logi  NA NA NA NA NA NA ...
 $ Name...44                                                    : chr  "Code" "35445" "35476" "35504" ...
 $ EH HICP: ALL-ITEMS HICP (%YOY) NADJ                          : chr  "EHESAKZER" "2.2000000000000002" "2" "1.7" ...
 $ ...46                                                        : logi  NA NA NA NA NA NA ...
 $ ...47                                                        : logi  NA NA NA NA NA NA ...
 $ ...48                                                        : logi  NA NA NA NA NA NA ...
 $ ...49                                                        : logi  NA NA NA NA NA NA ...
 $ Name...50                                                    : chr  "Code" "36206" "36234" "36265" ...
 $ EM EUROSYSTEM: BASE MONEY CURN                               : chr  "EMEBSMYBA" "426.64374199999997" "430.51499999999999" "432.34064499999999" ...
 $ ...52                                                        : logi  NA NA NA NA NA NA ...
 $ ...53                                                        : logi  NA NA NA NA NA NA ...
 $ ...54                                                        : logi  NA NA NA NA NA NA ...
 $ ...55                                                        : logi  NA NA NA NA NA NA ...
 $ Name...56                                                    : chr  "Code" "35703" "35734" "35762" ...
 $ EM EUROSYSTEM: TOTAL ASSETS/LIABILITIES (EP) CURN            : chr  "EMECBSALA" "710257.53500000003" "711193.47100000002" "714957.58900000004" ...
 $ ...58                                                        : logi  NA NA NA NA NA NA ...
 $ ...59                                                        : logi  NA NA NA NA NA NA ...
 $ ...60                                                        : logi  NA NA NA NA NA NA ...
 $ ...61                                                        : logi  NA NA NA NA NA NA ...
 $ ...62                                                        : logi  NA NA NA NA NA NA ...
 $ ...63                                                        : logi  NA NA NA NA NA NA ...
 $ Name...64                                                    : chr  "Code" "41548" "41579" "41609" ...
 $ TR EU FWD INFL-LKD SWAP 10YF20Y - MIDDLE RATE                : chr  "TREFSTT" NA NA NA ...
 $ TR EU FWD INFL-LKD SWAP 10YF10Y - MIDDLE RATE                : chr  "TREFS1T" NA NA NA ...
 $ TR EU FWD INFL-LKD SWAP 2YF2Y - MIDDLE RATE                  : chr  "TREFS22" "1.5158" "1.4669000000000001" "1.4715" ...
 $ TR EU FWD INFL-LKD SWAP 1YF1Y - MIDDLE RATE                  : chr  "TREFS11" "1.4509000000000001" "1.2338" "1.1225000000000001" ...
 $ TR EU FWD INFL-LKD SWAP 2YF3Y - MIDDLE RATE                  : chr  "TREFS23" "1.5906000000000002" "1.5453000000000001" "1.5283000000000002" ...
 $ TR EU FWD INFL-LKD SWAP 5YF10Y - MIDDLE RATE                 : chr  "TREFS5T" "2.3516000000000004" "2.3323" "2.3070000000000004" ...
 $ ...71                                                        : logi  NA NA NA NA NA NA ...
 $ ...72                                                        : logi  NA NA NA NA NA NA ...
 $ ...73                                                        : logi  NA NA NA NA NA NA ...
 $ ...74                                                        : logi  NA NA NA NA NA NA ...
 $ ...75                                                        : logi  NA NA NA NA NA NA ...
 $ Name...76                                                    : chr  "Code" "41255" "41286" "41317" ...
 $ TR EU FWD INFL-LKD SWAP 5YF5Y - MIDDLE RATE                  : chr  "TREFS55" "2.2027000000000001" "2.2637" "2.383" ...
</code>```

答:
You have to specify the col_types correctly in the read_excel (or read_xlsx) command. For example:

```<code>dataset <- read_xlsx("Data.xlsx",
     col_types=c("numeric","date","numeric","date","numeric", "date", ...))
</code>```

Edit: Finally after much interrogation, the problem is that your data starts in row 3, not 2. So skip the first row (skip=1) and try again.

```<code>dataset <- read_xlsx("Data.xlsx", skip=1)
</code>```

Body:
I have an excel file with 77 columns (with 43 NA columns) of different length, 12 of which are Date. Ideally, I want to import it in R the dataset with the columns that refer to Date in date format, while the other columns in numeric format. There is lot of material in stackoverflow and I tried all the options but it is not working.

The first option would be to do it directly from excel:

dataset <- read_xlsx("Data.xlsx", col_types = "numeric") #it gives everything numeric but column date always in this format "36164"

#I also tried something like this:

dataset <- read_xlsx("Data.xlsx", col_types = c("date", rep("numeric", n))) #where "n" stands for all the columns with numbers I have but it did not work

I can import the data with the incorret date columns. After some cleaning (removing NA columns) I get a tbl with different column length. I tried the following codes to transform the incorrect column dates into date format:

dataset <- janitor::remove_empty(dataset, which = "cols") #remove NA columns
dataset <- dataset[-c(1),] #remove the first row of all columns

# Now using this command I could transform each incorrect date column into a date format:

  date <- as.Date(as.numeric(dataset$column1), origin = "1899-12-30")

# I would like to do it for all the date columns in one shot but when I try to do it in this way

  as.Date(as.numeric(dataset[,c(1,3,5,7,14,16,18,20,21,23,25,32)]), origin = "1899-12-30")

# I get an error, probably because the columns have different length
# the error is: Error in as.Date(as.numeric(var_dataset[, c(1, 3, 5, 7, 14, 16, 18, 20,  :
  'list' object cannot be coerced to type 'double'
# unlisting the object doesn't solve the problem

I am aware it is missing data to reproduce my problem but in the first scenario I don't know how to approximate my quite big excel file while in the second case I don't know how to create a tbl with many columns of different length without wasting lot of time. Sorry.

Do you have any solution? Either for importing directly from Excel or playing with the dataframe

Thanks so much

I attach here the structure of my dataset:

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   5500 obs. of  77 variables:
 $ Name...1                                                     : chr  "Code" "36164" "36165" "36166" ...
 $ VSTOXX VOLATILITY INDEX - PRICE INDEX                        : chr  "VSTOXXI(PI)" "18.2" "29.69" "25.17" ...
 $ ...3                                                         : logi  NA NA NA NA NA NA ...
 $ ...4                                                         : logi  NA NA NA NA NA NA ...
 $ ...5                                                         : logi  NA NA NA NA NA NA ...
 $ ...6                                                         : logi  NA NA NA NA NA NA ...
 $ Name...7                                                     : chr  "Code" "36799" "36830" "36860" ...
 $ EM COMPOSITE INDICATOR OF SOVEREIGN STRESS: GDP WEIGHTS NADJ : chr  "EMEBSCGWR" "7.8255999999999992E-2" "8.9886999999999995E-2" "8.0714999999999995E-2" ...
 $ ...9                                                         : logi  NA NA NA NA NA NA ...
 $ Name...10                                                    : chr  "Code" "36168" "36175" "36182" ...
 $ CISS BOND MKT: GOV & NFC VOLATILITY - ECONOMIC SERIES        : chr  "EMCIBMG" "4.4651999999999997E-2" "6.6535999999999998E-2" "4.9789E-2" ...
 $ ...12                                                        : logi  NA NA NA NA NA NA ...
 $ Name...13                                                    : chr  "Code" "36168" "36175" "36182" ...
 $ CISS MONEY MKT: 3M RATE+ VOLATILITY - ECONOMIC SERIES        : chr  "EMECM3E" "5.7435999999999994E-2" "7.463199999999999E-2" "7.2263999999999995E-2" ...
 $ CISS FX MKT: EUR VOLATILITY - ECONOMIC SERIES                : chr  "EMECFEM" "7.2139999999999996E-2" "8.6049E-2" "4.5948999999999997E-2" ...
 $ CISS FIN INTERM: BANK+ VOLATILITY - ECONOMIC SERIES          : chr  "EMCIFIN" "4.5384999999999995E-2" "0.11820399999999999" "0.11516499999999999" ...
 $ CISS NF EQUITY: VOLATILITY - ECONOMIC SERIES                 : chr  "EMCIEMN" "7.7453999999999995E-2" "0.12733" "0.11918899999999999" ...
 $ CISS: CROSS SUBINDEXCORRELATION - ECONOMIC SERIES            : chr  "EMCICRO" "-0.21210999999999999" "-0.29791000000000001" "-0.2369" ...
 $ SYSTEMIC STRESS COMPINDICATOR - ECONOMIC SERIES              : chr  "EMCISSI" "8.4954000000000002E-2" "0.174844" "0.16546" ...
 $ ...20                                                        : logi  NA NA NA NA NA NA ...
 $ ...21                                                        : logi  NA NA NA NA NA NA ...
 $ ...22                                                        : logi  NA NA NA NA NA NA ...
 $ ...23                                                        : logi  NA NA NA NA NA NA ...
 $ ...24                                                        : logi  NA NA NA NA NA NA ...
 $ ...25                                                        : logi  NA NA NA NA NA NA ...
 $ Name...26                                                    : chr  "Code" "33253" "33284" "33312" ...
 $ Z8 IPI: MFG., VOLUME INDEX OF PRODUCTION, 2015=100 (WDA) VOLA: chr  "Z8ES493KG" "81" "79.7" "79.400000000000006" ...
 $ ...28                                                        : logi  NA NA NA NA NA NA ...
 $ ...29                                                        : logi  NA NA NA NA NA NA ...
 $ ...30                                                        : logi  NA NA NA NA NA NA ...
 $ ...31                                                        : logi  NA NA NA NA NA NA ...
 $ ...32                                                        : logi  NA NA NA NA NA NA ...
 $ ...33                                                        : logi  NA NA NA NA NA NA ...
 $ ...34                                                        : logi  NA NA NA NA NA NA ...
 $ Name...35                                                    : chr  "Code" "35779" "35810" "35841" ...
 $ EH HICP: ALL-ITEMS NADJ                                      : chr  "EHES795WR" "1.7" "1.6" "1.6" ...
 $ ...37                                                        : logi  NA NA NA NA NA NA ...
 $ ...38                                                        : logi  NA NA NA NA NA NA ...
 $ Name...39                                                    : chr  "Code" "35110" "35139" "35170" ...
 $ EH HICP: ALL-ITEMS (%MOM) NADJ                               : chr  "EHESPQ93R" "0.4" "0.4" "0.3" ...
 $ ...41                                                        : logi  NA NA NA NA NA NA ...
 $ ...42                                                        : logi  NA NA NA NA NA NA ...
 $ ...43                                                        : logi  NA NA NA NA NA NA ...
 $ Name...44                                                    : chr  "Code" "35445" "35476" "35504" ...
 $ EH HICP: ALL-ITEMS HICP (%YOY) NADJ                          : chr  "EHESAKZER" "2.2000000000000002" "2" "1.7" ...
 $ ...46                                                        : logi  NA NA NA NA NA NA ...
 $ ...47                                                        : logi  NA NA NA NA NA NA ...
 $ ...48                                                        : logi  NA NA NA NA NA NA ...
 $ ...49                                                        : logi  NA NA NA NA NA NA ...
 $ Name...50                                                    : chr  "Code" "36206" "36234" "36265" ...
 $ EM EUROSYSTEM: BASE MONEY CURN                               : chr  "EMEBSMYBA" "426.64374199999997" "430.51499999999999" "432.34064499999999" ...
 $ ...52                                                        : logi  NA NA NA NA NA NA ...
 $ ...53                                                        : logi  NA NA NA NA NA NA ...
 $ ...54                                                        : logi  NA NA NA NA NA NA ...
 $ ...55                                                        : logi  NA NA NA NA NA NA ...
 $ Name...56                                                    : chr  "Code" "35703" "35734" "35762" ...
 $ EM EUROSYSTEM: TOTAL ASSETS/LIABILITIES (EP) CURN            : chr  "EMECBSALA" "710257.53500000003" "711193.47100000002" "714957.58900000004" ...
 $ ...58                                                        : logi  NA NA NA NA NA NA ...
 $ ...59                                                        : logi  NA NA NA NA NA NA ...
 $ ...60                                                        : logi  NA NA NA NA NA NA ...
 $ ...61                                                        : logi  NA NA NA NA NA NA ...
 $ ...62                                                        : logi  NA NA NA NA NA NA ...
 $ ...63                                                        : logi  NA NA NA NA NA NA ...
 $ Name...64                                                    : chr  "Code" "41548" "41579" "41609" ...
 $ TR EU FWD INFL-LKD SWAP 10YF20Y - MIDDLE RATE                : chr  "TREFSTT" NA NA NA ...
 $ TR EU FWD INFL-LKD SWAP 10YF10Y - MIDDLE RATE                : chr  "TREFS1T" NA NA NA ...
 $ TR EU FWD INFL-LKD SWAP 2YF2Y - MIDDLE RATE                  : chr  "TREFS22" "1.5158" "1.4669000000000001" "1.4715" ...
 $ TR EU FWD INFL-LKD SWAP 1YF1Y - MIDDLE RATE                  : chr  "TREFS11" "1.4509000000000001" "1.2338" "1.1225000000000001" ...
 $ TR EU FWD INFL-LKD SWAP 2YF3Y - MIDDLE RATE                  : chr  "TREFS23" "1.5906000000000002" "1.5453000000000001" "1.5283000000000002" ...
 $ TR EU FWD INFL-LKD SWAP 5YF10Y - MIDDLE RATE                 : chr  "TREFS5T" "2.3516000000000004" "2.3323" "2.3070000000000004" ...
 $ ...71                                                        : logi  NA NA NA NA NA NA ...
 $ ...72                                                        : logi  NA NA NA NA NA NA ...
 $ ...73                                                        : logi  NA NA NA NA NA NA ...
 $ ...74                                                        : logi  NA NA NA NA NA NA ...
 $ ...75                                                        : logi  NA NA NA NA NA NA ...
 $ Name...76                                                    : chr  "Code" "41255" "41286" "41317" ...
 $ TR EU FWD INFL-LKD SWAP 5YF5Y - MIDDLE RATE                  : chr  "TREFS55" "2.2027000000000001" "2.2637" "2.383" ...

Body:
You have to specify the col_types correctly in the read_excel (or read_xlsx) command. For example:

dataset <- read_xlsx("Data.xlsx",
     col_types=c("numeric","date","numeric","date","numeric", "date", ...))

Edit: Finally after much interrogation, the problem is that your data starts in row 3, not 2. So skip the first row (skip=1) and try again.

dataset <- read_xlsx("Data.xlsx", skip=1)


问:
Does RISC-V mandate two's complement or one's complement signedness, or is it implementation-determined?
I have looked through the ISA spec and searched the internet for the answer to this, but I could not find it.

In the RISC-V ISA, should negative numbers be represented with one's complement or two's complement?  Or, is this decision left to implementors?

The reason I ask is that I am writing an RV32I simulator, and this would affect how I store negative numbers in the simulated memory, for example.

答:
Yes, the RISC-V instruction set architecture (ISA) mandates two's complement:

The base integer instruction sets use a two’s-complement representation for signed integer values.

(Section 1.3 RISC-V ISA Overview, page 4, The RISC-V Instruction Set Manual. Volume I, 2019-06-08, ratified)

General purpose registers x1–x31 hold values that various instructions interpret as a collection of Boolean values, or as two’s complement signed binary integers or unsigned binary integers.

(Section 2.1 Programmers' Model for Base Integer ISA, page 13, The RISC-V Instruction Set Manual. Volume I, 2019-06-08, ratified)

ContentLicense: CC BY-SA 3.0


问:
adding sound to an OpenGL app
i am creating an OpenGL application and decided to look into adding sound...
what is the best sound(api?) i was thinking about using OpenAL but i had issues finding any good resources...
if possible could you please provide tutorial/info of some sort.</p>

答:
I think a lot of people use SDL for that, it provides portable creation of OpenGL contexts as well as sound support.

Here's a tutorial.

Title: adding sound to an OpenGL app


问:
Recursion for my code doesn't seem to work even though I am returning everything
I am making code to check if a number is a prime or not, but I want the argument to be both list and integer. For that I'm using recursion but the recursion doesn't seem to work.</p>

```<code> def prime_checker(suspected_prime):
    if type(suspected_prime) == type(list()):
        result_list = list()
        for x in range(len(suspected_prime)):
            result_list.append(prime_checker(suspected_prime[x]))
        return(result_list)
    else:
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1
</code>```

答:
I think this should work for your code:

```<code>def prime(suspected_prime):
if type(suspected_prime) == list:
    result_list = list()
    for x in suspected_prime:
        result_list.append(prime(x))
    return(result_list)
else:
    factors,suspected_prime = 0,abs(suspected_prime)
    root = int(suspected_prime**0.5)
    for x in range (2,(root+1)):
        if(factors == 1):
            break
        elif(suspected_prime%x == 0):
            factors = 1
            return False

    if (factors == 0):
        return True
</code>```

You can change the if-else statement according to your requirement if you want.

Body:
I am making code to check if a number is a prime or not, but I want the argument to be both list and integer. For that I'm using recursion but the recursion doesn't seem to work.

 def prime_checker(suspected_prime):
    if type(suspected_prime) == type(list()):
        result_list = list()
        for x in range(len(suspected_prime)):
            result_list.append(prime_checker(suspected_prime[x]))
        return(result_list)
    else:
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1

Body:
I think this should work for your code:

def prime(suspected_prime):
if type(suspected_prime) == list:
    result_list = list()
    for x in suspected_prime:
        result_list.append(prime(x))
    return(result_list)
else:
    factors,suspected_prime = 0,abs(suspected_prime)
    root = int(suspected_prime**0.5)
    for x in range (2,(root+1)):
        if(factors == 1):
            break
        elif(suspected_prime%x == 0):
            factors = 1
            return False

    if (factors == 0):
        return True

You can change the if-else statement according to your requirement if you want.


问:
C# String ReadAllFile per lines
I would like that when I press my button it opens an OpenFileDialog to load the content of a test file, e.g. proxys.txt.

I'd like all my proxys in my proxys.txt to be parsed as a string that I can use for a HttpWebRequest.

My code Form1:

```<code>OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.Filter = "Load Proxys File |*.txt";

if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string[] readText = File.ReadAllLines(openFile1.FileName);
    string fileName = openFile1.FileName;
    string[] TEST = File.ReadAllLines(fileName);

    MessageBox.Show(TEST[0]);
}
</code>```

When I use this code, I can see a messagebox with only the first proxy from my list but I would like to load all proxys line by line into a string

答:
You are using File.ReadAllLines which returns an array of strings, each of which is one line in your file, then you are just getting the first line from that array using TEST[0] and displaying it in your message box.

You may want to use File.ReadAllText instead to load all your file contents into a single string and then you can simply display it in your message box:

```<code>string test = File.ReadAllText(fileName);
MessageBox.Show(test);
</code>```

You can get more info here.

Title: C# String ReadAllFile per lines

Body:
I would like that when I press my button it opens an OpenFileDialog to load the content of a test file, e.g. proxys.txt.

I'd like all my proxys in my proxys.txt to be parsed as a string that I can use for a HttpWebRequest.

My code Form1:

OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.Filter = "Load Proxys File |*.txt";

if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string[] readText = File.ReadAllLines(openFile1.FileName);
    string fileName = openFile1.FileName;
    string[] TEST = File.ReadAllLines(fileName);

    MessageBox.Show(TEST[0]);
}

When I use this code, I can see a messagebox with only the first proxy from my list but I would like to load all proxys line by line into a string

Body:
You are using File.ReadAllLines which returns an array of strings, each of which is one line in your file, then you are just getting the first line from that array using TEST[0] and displaying it in your message box.

You may want to use File.ReadAllText instead to load all your file contents into a single string and then you can simply display it in your message box:

string test = File.ReadAllText(fileName);
MessageBox.Show(test);

You can get more info here.


问:
Opening multiple urls with CURL - Using api with CURL - too many urls and too slow
I have a software.

There is a table, there are URLs in this table.

There are 100 URLs on each page.

picture

Then I got an API where I can pull Alexa and DA Values. I wanted to show these values later.

```<code><?php
$cara = str_replace(array("https://", "http://", "www."), "", $row["site_link"]);
$mara = array_shift(explode("/", $cara));
$xx = "https://seo-rank.my-addr.com/api1/myapi/".$mara;

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Connection: Keep-Alive',
    'Keep-Alive: 300'
));
curl_setopt($ch, CURLOPT_URL, $xx);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,0);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
    $vary = curl_exec($ch);
    curl_close($ch);

$result = json_decode($vary, true);

?>
</code>```

Located here;

The $row["site_link"] variable retrieves the site header of each table from the database.

Then http, https, www. I separate the parts and add the link to the end of the API.

As myapi / site.com, I send requests for each site and then alexa, da and pa values are printed on the screen.

However, there is a big delay in doing this.

Then I print the result one by one as follows;

'.$result['da'].'

What should I do to stop this delay?

答:
Is there anyone who can help?

I can manually upload the data to the database and pull it.

Like the variable $row['pa']

So can I make mysql updater?

Body:
I have a software.

There is a table, there are URLs in this table.

There are 100 URLs on each page.

picture

Then I got an API where I can pull Alexa and DA Values. I wanted to show these values later.

<?php
$cara = str_replace(array("https://", "http://", "www."), "", $row["site_link"]);
$mara = array_shift(explode("/", $cara));
$xx = "https://seo-rank.my-addr.com/api1/myapi/".$mara;

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Connection: Keep-Alive',
    'Keep-Alive: 300'
));
curl_setopt($ch, CURLOPT_URL, $xx);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,0);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
    $vary = curl_exec($ch);
    curl_close($ch);

$result = json_decode($vary, true);

?>

Located here;

The $row["site_link"] variable retrieves the site header of each table from the database.

Then http, https, www. I separate the parts and add the link to the end of the API.

As myapi / site.com, I send requests for each site and then alexa, da and pa values are printed on the screen.

However, there is a big delay in doing this.

Then I print the result one by one as follows;

'.$result['da'].'

What should I do to stop this delay?


问:
how to make code check if appium server timed out
my program runs into errors where the appium server hangs indefinitely while trying to find elements using the xpath identifier

i have added the desired capability to my appium test so that it times out after 60 seconds if no code is executed

```<code>cap.setCapability("newCommandTimeout", 60);
</code>```

requirements for my program include that it must reset if the appium server has timed out

but how would i make my program know that the server has timed out so that it can reset itself?

答:
You can simply catch TimeoutException. Try to find an element as below

```<code>try
{
MobileElement mobileElement= (MobileElement) driver.findElement(By.id("ID"));
}
catch (TimeoutException e) {
// Do your stuff here
}
</code>```

Appium java docs for TimeoutException

Body:
my program runs into errors where the appium server hangs indefinitely while trying to find elements using the xpath identifier

i have added the desired capability to my appium test so that it times out after 60 seconds if no code is executed

cap.setCapability("newCommandTimeout", 60);

requirements for my program include that it must reset if the appium server has timed out

but how would i make my program know that the server has timed out so that it can reset itself?

Body:
You can simply catch TimeoutException. Try to find an element as below

try
{
MobileElement mobileElement= (MobileElement) driver.findElement(By.id("ID"));
}
catch (TimeoutException e) {
// Do your stuff here
}

Appium java docs for TimeoutException


问:
CreateTextFile with a Colon in the path , no error is returned. Why?
This is what I tried (C:\temp really exists):

```<code>$fso = New-Object -ComObject Scripting.FileSystemObject
$ts = $fso.CreateTextFile("c:\temp:AAAAA.txt")
$ts.Close()
</code>```

No error returned. The file is created somewhere (but not in c:\temp... if I put something inside, I can later read it)
but I cannot find it.

Could anyone explain me why this code not produce an error & where the file gone?

答:
The reason you don't get an error is probably that the call succeeded!

When you call CreateTextFile and pass the file path C:\temp:AAAAA.txt, you're actually asking to create a file C:\temp with an alternate data stream (an ADS) named AAAAA.txt.

You can see for yourself with Get-Item:

```<code>PS C:\> Get-Item C:\temp -Stream AAAAA.txt

PSPath        : Microsoft.PowerShell.Core\FileSystem::C:\temp:AAAAA.txt
PSParentPath  : Microsoft.PowerShell.Core\FileSystem::C:\
PSChildName   : temp:AAAAA.txt
PSDrive       : C
PSProvider    : Microsoft.PowerShell.Core\FileSystem
PSIsContainer : False
FileName      : C:\temp
Stream        : AAAAA.txt
Length        : 0
</code>```

You can also read and write to alternate data streams (requires PowerShell version 5 or newer):

```<code>PS C:\> "Hello there!" |Set-Content C:\temp -Stream AAAAA.txt
PS C:\> Get-Content C:\temp -Stream AAAAA.txt
Hello there!
</code>```

Please beware that these data streams are intrinsic to NTFS and won't persist if you copy a file to a non-NTFS file system or upload them to a website for example.

Body:
This is what I tried (C:\temp really exists):

$fso = New-Object -ComObject Scripting.FileSystemObject
$ts = $fso.CreateTextFile("c:\temp:AAAAA.txt")
$ts.Close()

No error returned. The file is created somewhere (but not in c:\temp... if I put something inside, I can later read it)
but I cannot find it.

Could anyone explain me why this code not produce an error & where the file gone?

Body:
The reason you don't get an error is probably that the call succeeded!

When you call CreateTextFile and pass the file path C:\temp:AAAAA.txt, you're actually asking to create a file C:\temp with an alternate data stream (an ADS) named AAAAA.txt.

You can see for yourself with Get-Item:

PS C:\> Get-Item C:\temp -Stream AAAAA.txt

PSPath        : Microsoft.PowerShell.Core\FileSystem::C:\temp:AAAAA.txt
PSParentPath  : Microsoft.PowerShell.Core\FileSystem::C:\
PSChildName   : temp:AAAAA.txt
PSDrive       : C
PSProvider    : Microsoft.PowerShell.Core\FileSystem
PSIsContainer : False
FileName      : C:\temp
Stream        : AAAAA.txt
Length        : 0

You can also read and write to alternate data streams (requires PowerShell version 5 or newer):

PS C:\> "Hello there!" |Set-Content C:\temp -Stream AAAAA.txt
PS C:\> Get-Content C:\temp -Stream AAAAA.txt
Hello there!

Please beware that these data streams are intrinsic to NTFS and won't persist if you copy a file to a non-NTFS file system or upload them to a website for example.


问:
How to insert line break after every complete number of three words?
I want to insert a line break
 after every complete three words of a sentence or paragraph using Javascript or typescript or angular 8.

```<code>let temText = 'Dummy text refers to the bits of content that are used to fill a website mock-up.';

let info = temText.replace(/(.{40})/g, '$1<br>');
console.log('After Break: ', info);
</code>```

In this way, the break line inserts exactly 40 characters after.
But I want to insert the break line after complete three words.

答:
this is where javascript reduce comes in handy, you can tailor it on your own needs..</p>

```<code>  const paragraph = "Know someone who can answer? Share a link to this question via email, Twitter, or Facebook"

let paragraphWithBreaks = paragraph.split(' ')
 .reduce((accum, curr, idx) => {
  if (idx && (idx+1)%3 === 1) {
   return [...accum,  "</br>", curr]
  } else return [...accum, curr]
 }, [])
.join(' ')
</code>```

Body:
I want to insert a line break
 after every complete three words of a sentence or paragraph using Javascript or typescript or angular 8.

let temText = 'Dummy text refers to the bits of content that are used to fill a website mock-up.';

let info = temText.replace(/(.{40})/g, '$1
');
console.log('After Break: ', info);

In this way, the break line inserts exactly 40 characters after.
But I want to insert the break line after complete three words.

Body:
this is where javascript reduce comes in handy, you can tailor it on your own needs..

  const paragraph = "Know someone who can answer? Share a link to this question via email, Twitter, or Facebook"

let paragraphWithBreaks = paragraph.split(' ')
 .reduce((accum, curr, idx) => {
  if (idx && (idx+1)%3 === 1) {
   return [...accum,  "</br>", curr]
  } else return [...accum, curr]
 }, [])
.join(' ')


问:
Modal does not close, when clicked
So I have a menu, where models pop-up on click. In each model, there's a close button, marked by an "x". Only problem is, that the model does not close, when the "x" is clicked.

I have tried multiple ways of filing this seemingly simple problem. But with no luck.

I have tried, using a z-index property, I have tried fiddling with the divs. I have tried to link to bootstrap external links. I have tried different kind of "close" button. I have tried to modifying the javascript code. Still I have not arrived at the desired outcome. Can anyone help ?

Here's my code

window.onload = function () {
  list = document.querySelectorAll(".Project");
  for (let i = 0; i < list.length; i++) {
    list[i].addEventListener("click", function (e) {
        e.preventDefault();
        let currentElement = e.target.parentNode;
        let modalId = currentElement.dataset.modal;
        let modal = document.getElementById(modalId);
        modal.style.display = "block";
    });
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}</code>```

     Wer Baut Der Stadt
     2019

        Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.

        ×

 Some text in the Modal..1

```

答:
this is because you have a bad use of JS event delegation.

the corect way is tu use the matches method   https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

like this :

window.onload = function () {

  list = document.querySelectorAll(".Project");

  document.querySelectorAll(".Project").forEach(LIelm=>{
    LIelm.addEventListener('click', showHideModal)
  })
};

function showHideModal(e) {

  if (!e.target.parentNode.matches('.Project , .modal-content' )) return
  e.preventDefault();

  let currentParent = e.target.parentNode;

  if (currentParent.matches('.Project') ){
    document.getElementById( currentParent.dataset.modal ).style.display = "block";
  }
  else {
    currentParent.parentNode.style.display = "";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}</code>```

   Wer Baut Der Stadt ee
   2019

      Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.

      ×

Some text in the Modal..1

```

Title: Modal does not close, when clicked

Body:
So I have a menu, where models pop-up on click. In each model, there's a close button, marked by an "x". Only problem is, that the model does not close, when the "x" is clicked.

I have tried multiple ways of filing this seemingly simple problem. But with no luck.

I have tried, using a z-index property, I have tried fiddling with the divs. I have tried to link to bootstrap external links. I have tried different kind of "close" button. I have tried to modifying the javascript code. Still I have not arrived at the desired outcome. Can anyone help ?

Here's my code

window.onload = function () {
  list = document.querySelectorAll(".Project");
  for (let i = 0; i < list.length; i++) {
    list[i].addEventListener("click", function (e) {
        e.preventDefault();
        let currentElement = e.target.parentNode;
        let modalId = currentElement.dataset.modal;
        let modal = document.getElementById(modalId);
        modal.style.display = "block";
    });
  }
};

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

     Wer Baut Der Stadt
     2019

        Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.

        ×

 Some text in the Modal..1

Body:
this is because you have a bad use of JS event delegation.

the corect way is tu use the matches method   https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

like this :

window.onload = function () {

  list = document.querySelectorAll(".Project");

  document.querySelectorAll(".Project").forEach(LIelm=>{
    LIelm.addEventListener('click', showHideModal)
  })
};

function showHideModal(e) {

  if (!e.target.parentNode.matches('.Project , .modal-content' )) return
  e.preventDefault();

  let currentParent = e.target.parentNode;

  if (currentParent.matches('.Project') ){
    document.getElementById( currentParent.dataset.modal ).style.display = "block";
  }
  else {
    currentParent.parentNode.style.display = "";
  }
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

<li class="Project" data-modal="myModal_1">
  <span id="myBtn_1"> Wer Baut Der Stadt ee</span>
  <span id="year"> 2019 </span>

  <div class="Describtion">
    <p style="display:none;">
      Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.
    </p>
  </div>

  <div id="myModal_1" class="modal">
    <div class="modal-content">
      <img src="https://picsum.photos/200/300"  >

      <span class="close">&times; </span>

      <p>Some text in the Modal..1
      </p>
    </div>
  </div>
</li>


问:
Need Help in Building a Query Expression in Laravel
I recently started using Laravel and got stuck on a query. I'm working on a Tasks App where the user completes different tasks posted by admin.

I want to get only those tasks that are not completed by the login user. when a user completes a task I have a 3rd table completed_tasks where both user_id and task_id stored.

This is how my tables look like:

user table (default table created by Laravel auth)
attributes: id,name,email,password

task table
attributes: id,name,description

Completed_task table
attributes: id, user_id,task_id

I tried using belongsToMany relation between user and tasks using completed_task table as a pivot

Relationship function in users model

public function tasks(){
    return $this->belongsToMany('App\Task', 'completed_task', 'user_id','task_id');
}
```

By using this function I'm getting all tasks that are completed by the login user but I want to get tasks that are not completed by the login user.

答:
Please try this:

```<code>$tasks = Tasks::whereNotIn('id', function($query) {
        $query->select('task_id')
        ->from('completed_task')
        ->where('user_id', '=', auth()->user()->id);
})->get();
</code>```

This should give you all the task that the logged user has not completed yet (please check the table and the fields names)

Body:
I recently started using Laravel and got stuck on a query. I'm working on a Tasks App where the user completes different tasks posted by admin.

I want to get only those tasks that are not completed by the login user. when a user completes a task I have a 3rd table completed_tasks where both user_id and task_id stored.

This is how my tables look like:

user table (default table created by Laravel auth)
attributes: id,name,email,password

task table
attributes: id,name,description

Completed_task table
attributes: id, user_id,task_id

I tried using belongsToMany relation between user and tasks using completed_task table as a pivot

Relationship function in users model

public function tasks(){
    return $this->belongsToMany('App\Task', 'completed_task', 'user_id','task_id');
}

By using this function I'm getting all tasks that are completed by the login user but I want to get tasks that are not completed by the login user.

Body:
Please try this:

$tasks = Tasks::whereNotIn('id', function($query) {
        $query->select('task_id')
        ->from('completed_task')
        ->where('user_id', '=', auth()->user()->id);
})->get();

This should give you all the task that the logged user has not completed yet (please check the table and the fields names)


问:
jQuery remove() within Ajax
I am trying to get Ajax to remove an element within that same Ajax page.  I make a call to a document via Ajax with the following code, but it doesn't remove the element:

```<code><input type="text" value="test" name="someel" class="someelement" />
<script type="text/javascript">
    $('.someelement').remove();
</script>
</code>```

I am using datatype = 'html' and other jquery stuff works, but it only works when I use things like the live function and I don't believe you can use that for removing elements, but I could be wrong.

Thanks.

EDIT:

Ajax Call:

```<code>$.ajax({
    url: someurl,
    type: 'post',
    data: postvars,
    cache: false,
    dataType: "html",
    success: function (html) {
        $('#somediv').html(html);
    }
});
</code>```

EDIT 2:

Example: REMOVED URL

答: .html() function strips out the javascript, so it is not outputting and therefore cannot execute even with dataType set to html.  The html variable from the success function returns the full javascript and can be stripped down to get the desired result.  </p>

Title: jQuery remove() within Ajax

Body:
I am trying to get Ajax to remove an element within that same Ajax page.  I make a call to a document via Ajax with the following code, but it doesn't remove the element:

<input type="text" value="test" name="someel" class="someelement" />

I am using datatype = 'html' and other jquery stuff works, but it only works when I use things like the live function and I don't believe you can use that for removing elements, but I could be wrong.

Thanks.

EDIT:

Ajax Call:

$.ajax({
    url: someurl,
    type: 'post',
    data: postvars,
    cache: false,
    dataType: "html",
    success: function (html) {
        $('#somediv').html(html);
    }
});

EDIT 2:

Example: REMOVED URL


问:
Laravel add calculate the sum where the value is in another table
Basically i have two tables. answers and choices . In my choices table, I got a column choices.value which is has values 0-4. My current query like this

```<code> $answers = \DB::table('answers')
                    ->join('choices','answers.choice_id','=','choices.choice_id')
                    ->select('answers.user_id','choices.choice_id','choices.choice','choices.value')
                    ->where('answers.user_id',\Auth::user()->id)
                    //->groupBy('answers.user_id')
                    ->get();
</code>```

My current response is like this

```<code>    "user_id": 2,
        "choice_id": 2,
        "choice": "I feel discourated about the future",
        "value": 1
    },
    {
        "user_id": 2,
        "choice_id": 2,
        "choice": "I don't enjoy things the way I used to",
        "value": 1
    },
    {
        "user_id": 2,
        "choice_id": 2,
        "choice": "I feel guilty a good part of time",
        "value": 1
</code>```

how do i add the values so that my result will be like this

```<code>"user_id":2,
"total_score":3
</code>```

I tried doing DB::raw(SUM(choices.values)as score) but i get a large amount. I guess its adding all the choices values from the choices table and not in the answers.

My answers db which i only select the answers of the user = 2. I limit to 5

```<code>+---------+-------------+-----------+
| user_id | question_id | choice_id |
+---------+-------------+-----------+
|       2 |           1 |         2 |
|       2 |           2 |         2 |
|       2 |           3 |         2 |
|       2 |           4 |         2 |
|       2 |           5 |         2 |
+---------+-------------+-----------+
</code>```

My choices table, I only select questions 1 and 2 and their choices.

```<code>+-----------+-------------+--------------------------------------------------------------+-------+
| choice_id | question_id | choice                                                       | value |
+-----------+-------------+--------------------------------------------------------------+-------+
|         1 |           1 | I do not feel sad                                            |     0 |
|         2 |           1 | I feel sad                                                   |     1 |
|         3 |           1 | I am sad all the time and I can't snap out of it             |     2 |
|         4 |           1 | I am so sad and unhappy that I can't stand it                |     3 |
|         1 |           2 | I am not particularly discouraged about the future           |     0 |
|         2 |           2 | I feel discourated about the future                          |     1 |
|         3 |           2 | I feel I have nothing to look forward to                     |     2 |
|         4 |           2 | I feel the future is hopeless and that things cannot improve |     3 |
+-----------+-------------+--------------------------------------------------------------+-------+
</code>```

Also i want to make a new table named scores and the columns will be the result of what i want. I want to add the choices.values in the answer in every answers.user_id so that when i view the scores table, it will display the total score in every user or when the user finished answering all 21 questions because i only got 21 items it will automatically add in the scores table. Could I possibly do that?. Is it okay to add a value in the answers table based in the choice_id? That is what im thinking but I think its redundant since the choice_id is there already. Thanks in advance.

PS: Tried writing these queries but always get 441 which is the total value of all the choices in the choices table

```<code>SELECT  answers.user_id,choices.choice_id,choices.value,COALESCE(sum(choices.value),0) as score  FROM
`answers`  JOIN `choices` ON  choices.choice_id = answers.choice_id where
answers.user_id = 2

SELECT answers.user_id,choices.choice_id,choices.value,SUM(choices.value),0 as score FROM `answers`
join choices on choices.choice_id = answers.choice_id
where answers.user_id = 2

SELECT answers.user_id,choices.choice_id, sum(choices.value) from answers
JOIN `choices` ON  choices.choice_id = answers.choice_id
group by answers.user_id
</code>```

答:
Currently you are only matching to a choice but you need to match the choice as well as the question.

I found this after seeng each choices.question_id had choices 1, 2, 3 and 4 in a slack conversation. I didn't know until I actually saw a screenshot of the choices table.

```<code>$answers = \DB::table('answers')
                    ->join('choices', function ($q) {
                    $q->on('answers.choice_id','=','choices.choice_id')
                    ->on('answers.question_id', '=', 'choices.question_id');
                    })
                    ->select('answers.user_id',\DB::raw('sum(choices.value) as total'))
                    ->groupBy('answers.user_id')
                    ->get();
</code>```

Body:
Basically i have two tables. answers and choices . In my choices table, I got a column choices.value which is has values 0-4. My current query like this

 $answers = \DB::table('answers')
                    ->join('choices','answers.choice_id','=','choices.choice_id')
                    ->select('answers.user_id','choices.choice_id','choices.choice','choices.value')
                    ->where('answers.user_id',\Auth::user()->id)
                    //->groupBy('answers.user_id')
                    ->get();

My current response is like this

    "user_id": 2,
        "choice_id": 2,
        "choice": "I feel discourated about the future",
        "value": 1
    },
    {
        "user_id": 2,
        "choice_id": 2,
        "choice": "I don't enjoy things the way I used to",
        "value": 1
    },
    {
        "user_id": 2,
        "choice_id": 2,
        "choice": "I feel guilty a good part of time",
        "value": 1

how do i add the values so that my result will be like this

"user_id":2,
"total_score":3

I tried doing DB::raw(SUM(choices.values)as score) but i get a large amount. I guess its adding all the choices values from the choices table and not in the answers.

My answers db which i only select the answers of the user = 2. I limit to 5

+---------+-------------+-----------+
| user_id | question_id | choice_id |
+---------+-------------+-----------+
|       2 |           1 |         2 |
|       2 |           2 |         2 |
|       2 |           3 |         2 |
|       2 |           4 |         2 |
|       2 |           5 |         2 |
+---------+-------------+-----------+

My choices table, I only select questions 1 and 2 and their choices.

+-----------+-------------+--------------------------------------------------------------+-------+
| choice_id | question_id | choice                                                       | value |
+-----------+-------------+--------------------------------------------------------------+-------+
|         1 |           1 | I do not feel sad                                            |     0 |
|         2 |           1 | I feel sad                                                   |     1 |
|         3 |           1 | I am sad all the time and I can't snap out of it             |     2 |
|         4 |           1 | I am so sad and unhappy that I can't stand it                |     3 |
|         1 |           2 | I am not particularly discouraged about the future           |     0 |
|         2 |           2 | I feel discourated about the future                          |     1 |
|         3 |           2 | I feel I have nothing to look forward to                     |     2 |
|         4 |           2 | I feel the future is hopeless and that things cannot improve |     3 |
+-----------+-------------+--------------------------------------------------------------+-------+

Also i want to make a new table named scores and the columns will be the result of what i want. I want to add the choices.values in the answer in every answers.user_id so that when i view the scores table, it will display the total score in every user or when the user finished answering all 21 questions because i only got 21 items it will automatically add in the scores table. Could I possibly do that?. Is it okay to add a value in the answers table based in the choice_id? That is what im thinking but I think its redundant since the choice_id is there already. Thanks in advance.

PS: Tried writing these queries but always get 441 which is the total value of all the choices in the choices table

SELECT  answers.user_id,choices.choice_id,choices.value,COALESCE(sum(choices.value),0) as score  FROM
`answers`  JOIN `choices` ON  choices.choice_id = answers.choice_id where
answers.user_id = 2

SELECT answers.user_id,choices.choice_id,choices.value,SUM(choices.value),0 as score FROM `answers`
join choices on choices.choice_id = answers.choice_id
where answers.user_id = 2

SELECT answers.user_id,choices.choice_id, sum(choices.value) from answers
JOIN `choices` ON  choices.choice_id = answers.choice_id
group by answers.user_id

Body:
Currently you are only matching to a choice but you need to match the choice as well as the question.

I found this after seeng each choices.question_id had choices 1, 2, 3 and 4 in a slack conversation. I didn't know until I actually saw a screenshot of the choices table.

$answers = \DB::table('answers')
                    ->join('choices', function ($q) {
                    $q->on('answers.choice_id','=','choices.choice_id')
                    ->on('answers.question_id', '=', 'choices.question_id');
                    })
                    ->select('answers.user_id',\DB::raw('sum(choices.value) as total'))
                    ->groupBy('answers.user_id')
                    ->get();