问:
How to compare two lists and if they have an equal value take the two indexes of the lists
How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them.  My code looks like this...

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        /// <summary>
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas,
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        /// </summary>
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter();

        #endregion

        #region Skapa excel

        /// <summary>
        /// Funktion som skapar de nya Excelfilerna
        /// </summary>
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count);
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count);
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    }
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i];
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}
</code>```

TestCode

```<code>    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }

    }

Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys
</code>```

This is an ish result that i whant but im just getting them scrambled so how to do this?

答:
You can create a Dictionary<T, int[]> from one of the lists, say from list2:

```<code>using System.Linq;

...

var list1 = ...
var list2 = ...

var dict = list2
  .Select((value, index) => new {value, index})
  .GroupBy(pair => pair.value, pair => pair.index)
  .ToDictionary(group => group.Key, group => group.ToArray());
</code>```

Now, with a help of dict.TryGetValue you can get all the int[] indexes at which required value appears in list2, e.g.

```<code>foreach (var item in list1) {
  if (dict.TryGetValue(item, out int[] indexes)) {
    // item appears in list2 at indexes
    Console.WriteLine($"value {item} appears at [{string.Join(", ", indexes)}]");
  }
  else {
    // item is not found in list2
  }
}
</code>```

Demo:

```<code>var list1 = new List<string>() {"A", "B", "C", "D", "E"};
var list2 = new List<string>() {"A", "B", "A", "A", "C", "B", "D"};

var dict = list2
  .Select((value, index) => new {value, index})
  .GroupBy(pair => pair.value, pair => pair.index)
  .ToDictionary(group => group.Key, group => group.ToArray());

for (int i = 0; i < list1.Count; ++i) {
  var item = list1[i];

  if (dict.TryGetValue(item, out int[] indexes))
    Console.WriteLine(
      $"value {item} at {index} appears in list2 at [{string.Join(", ", indexes)}]");
  else
    Console.WriteLine($"value {item} at {index} doesn't appear in list2");
}
</code>```

Outcome:

```<code>value A at 0 appears in list2 at [0, 2, 3]
value B at 1 appears in list2 at [1, 5]
value C at 2 appears in list2 at [4]
value D at 3 appears in list2 at [6]
value E at 4 doesn't appear in list2
</code>```

Body:
How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them.  My code looks like this...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        ///
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas,
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        ///
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter();

        #endregion

        #region Skapa excel

        ///
        /// Funktion som skapar de nya Excelfilerna
        ///
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count);
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count);
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    }
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i];
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}

TestCode

    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }

    }

Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys

This is an ish result that i whant but im just getting them scrambled so how to do this?

Body:
You can create a Dictionary<T, int[]> from one of the lists, say from list2:

using System.Linq;

...

var list1 = ...
var list2 = ...

var dict = list2
  .Select((value, index) => new {value, index})
  .GroupBy(pair => pair.value, pair => pair.index)
  .ToDictionary(group => group.Key, group => group.ToArray());

Now, with a help of dict.TryGetValue you can get all the int[] indexes at which required value appears in list2, e.g.

foreach (var item in list1) {
  if (dict.TryGetValue(item, out int[] indexes)) {
    // item appears in list2 at indexes
    Console.WriteLine($"value {item} appears at [{string.Join(", ", indexes)}]");
  }
  else {
    // item is not found in list2
  }
}

Demo:

var list1 = new List<string>() {"A", "B", "C", "D", "E"};
var list2 = new List<string>() {"A", "B", "A", "A", "C", "B", "D"};

var dict = list2
  .Select((value, index) => new {value, index})
  .GroupBy(pair => pair.value, pair => pair.index)
  .ToDictionary(group => group.Key, group => group.ToArray());

for (int i = 0; i < list1.Count; ++i) {
  var item = list1[i];

  if (dict.TryGetValue(item, out int[] indexes))
    Console.WriteLine(
      $"value {item} at {index} appears in list2 at [{string.Join(", ", indexes)}]");
  else
    Console.WriteLine($"value {item} at {index} doesn't appear in list2");
}

Outcome:

value A at 0 appears in list2 at [0, 2, 3]
value B at 1 appears in list2 at [1, 5]
value C at 2 appears in list2 at [4]
value D at 3 appears in list2 at [6]
value E at 4 doesn't appear in list2


来源: stackexchange

问:
What are the compilation errors and how to fix them?
After transferring the project, I get an error while compiling, before that there wasn’t such a thing, what could be the matter?

UPDATE

Build output:

```<code>> Task :clean UP-TO-DATE
> Task :app:clean
> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:checkDebugManifest
> Task :app:generateDebugBuildConfig
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:mainApkListPersistenceDebug
> Task :app:javaPreCompileDebug
> Task :app:generateDebugResValues
> Task :app:generateDebugResources
> Task :app:mergeDebugResources FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> -1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
8 actionable tasks: 7 executed, 1 up-to-date
The build scan was not published due to a configuration problem.
The Gradle Terms of Service have not been agreed to.
For more information, please see https://gradle.com/scans/help/plugin-terms-of-service.
Alternatively, if you are using Gradle Enterprise, specify the server location.
For more information, please see https://gradle.com/scans/help/plugin-enterprise-config.

</code>```

What is this?

答:
Compilation errors are thrown while you are compiling, however, the actual error that you get is ArrayIndexOutOfBoundsException, which looks like a runtime exception and not a compile error. It means that your project attempts to refer to an array item using an index which does not exist.

You can fix this error via making sure that you do not try to refer elements at indexes beyond or below the limits of your array and if you fail to find where this is thrown (the full error message if helpful for this purpose) then you can debug and narrow down the problem-space until you find the line where it is crashing.

ContentLicense: CC BY-SA 4.0

Body:
After transferring the project, I get an error while compiling, before that there wasn’t such a thing, what could be the matter?

UPDATE

Build output:

> Task :clean UP-TO-DATE
> Task :app:clean
> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:checkDebugManifest
> Task :app:generateDebugBuildConfig
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:mainApkListPersistenceDebug
> Task :app:javaPreCompileDebug
> Task :app:generateDebugResValues
> Task :app:generateDebugResources
> Task :app:mergeDebugResources FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> -1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
8 actionable tasks: 7 executed, 1 up-to-date
The build scan was not published due to a configuration problem.
The Gradle Terms of Service have not been agreed to.
For more information, please see https://gradle.com/scans/help/plugin-terms-of-service.
Alternatively, if you are using Gradle Enterprise, specify the server location.
For more information, please see https://gradle.com/scans/help/plugin-enterprise-config.

What is this?


问:
WPF: Binding to a (observable) Dictionary
I'm using this ObservableCollection-Class within my Project: Link

I want to Bind a RibbonMenuButton to a ObservableDictionary<string,bool>:

```<code><r:RibbonMenuButton ItemsSource="{Binding MyDictionary}">
    <r:RibbonMenuButton.ItemContainerStyle>
        <Style TargetType="{x:Type r:RibbonMenuItem}">
            <Setter Property="IsCheckable" Value="true"/>
            <Setter Property="Header" Value="{Binding Path=Key}"/>
            <Setter Property="IsChecked" Value="{Binding Path=Value}"/>
        </style>
    </r:RibbonMenuButton.ItemContainerStyle>
</r:RibbonMenuButton>
</code>```

But I get exceptions because the Value-Properties of the internal IDictionary-KeyValuePairs are readonly. Any Idea how to solve this?

I thought about something like:

```<code><Setter Property="IsChecked" Value="{Binding Source=MyDictionary[{Binding Path=Key}]}"/>
</code>```

But this won't work 'cause of {Binding} in {Binding}...

答:
This doesn't work, because your dictionary isn't treated as a dictionary but as an IEnumerable<KeyValuePair<string, bool>>. So each RibbonMenuItem is bound to a KeyValuePair<string, bool> with readonly properties Key and Value.

You can do two one things:

  1. Use an ObservableCollection<Tuple<string, bool>> instead of the dictionary and bind IsChecked to Item2.

  2. Create a little helper class that contains a IsChecked property and change your dictionary to contain that class as the value and bind IsChecked to Value.IsChecked.

I would go with answer two, because the needed changes and possible side effects are smaller.

My answer assumes that you want to have a two way binding on IsChecked. If not, go with the answer of slugster.

ContentLicense: CC BY-SA 3.0

Body:
I'm using this ObservableCollection-Class within my Project: Link

I want to Bind a RibbonMenuButton to a ObservableDictionary<string,bool>:

<r:RibbonMenuButton ItemsSource="{Binding MyDictionary}">
    <r:RibbonMenuButton.ItemContainerStyle>

    </r:RibbonMenuButton.ItemContainerStyle>
</r:RibbonMenuButton>

But I get exceptions because the Value-Properties of the internal IDictionary-KeyValuePairs are readonly. Any Idea how to solve this?

I thought about something like:

<Setter Property="IsChecked" Value="{Binding Source=MyDictionary[{Binding Path=Key}]}"/>

But this won't work 'cause of {Binding} in {Binding}...


问:
Set value to a variable in a CASE statement
Background:
I have a tabel called History. In this table i have 3 different columns that represents 3 different types of adresses (domestic adress, foreign adress and other adress). A record set from this tabel may contain values for one, more or none of these adress types. I am therefore trying to retrieve the adresstype and it's value by using a CASE statement and assigning the value to a variable.

Question:
I get no errors in my query but it returns nothing. What am i doing wrong?

```<code>DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND @vAdress = CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END
</code>```

答:
With no sample data, this is impossible to say what's "wrong" apart from to say that the reason it's failing is because there's no rows that meet the criteria.

I would, however, write the above using boolean logic; perhaps that would give you the answer:

```<code>SELECT H.FIRSTNAME,
       H.LASTNAME,
       @vAdress,
       C.COUNTRY
FROM History H
     LEFT JOIN COUNTRY C ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
  AND (H.D_ADRESS = @vAdress
   OR  (H.D_ADRESS IS NULL AND H.F_ADRESS = @vAdress)
   OR  (H.D_ADRESS IS NULL AND H.F_ADDRESS IS NULL AND H.O_ADRESS = @vAdress))
</code>```

Of course, this assumes you've assigned a value to @vAdress. Nothing equals NULL, so if @vAdress is NULL, it'll never return any results.

Body:
Background:
I have a tabel called History. In this table i have 3 different columns that represents 3 different types of adresses (domestic adress, foreign adress and other adress). A record set from this tabel may contain values for one, more or none of these adress types. I am therefore trying to retrieve the adresstype and it's value by using a CASE statement and assigning the value to a variable.

Question:
I get no errors in my query but it returns nothing. What am i doing wrong?

DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND @vAdress = CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END

Body:
With no sample data, this is impossible to say what's "wrong" apart from to say that the reason it's failing is because there's no rows that meet the criteria.

I would, however, write the above using boolean logic; perhaps that would give you the answer:

SELECT H.FIRSTNAME,
       H.LASTNAME,
       @vAdress,
       C.COUNTRY
FROM History H
     LEFT JOIN COUNTRY C ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
  AND (H.D_ADRESS = @vAdress
   OR  (H.D_ADRESS IS NULL AND H.F_ADRESS = @vAdress)
   OR  (H.D_ADRESS IS NULL AND H.F_ADDRESS IS NULL AND H.O_ADRESS = @vAdress))

Of course, this assumes you've assigned a value to @vAdress. Nothing equals NULL, so if @vAdress is NULL, it'll never return any results.


问:
Designing your own button in SwiftUI
I'm trying to draw the following picture with each circle segment consisting of 3 buttons which can be clicked.

I've copied code from this forum, but when I try to use it, I get an error message and the code will not compile. Tried various versions (latest one printed), but none work. What am I doing wrong? Also, will the integers i and j be passed on to the call of the class CustomShapeButton?

```<code>import SwiftUI
import UIKit

struct ContentView: View {

    static let segmentCount = 4
    static let circleCount = 4

    var i: Int = 0
    var j: Int = 0
    var NewButtons: CustomShapeButton

    var body: some View {
        ZStack {
            ForEach(1..<ContentView.circleCount){ j in
                ForEach(1..<ContentView.segmentCount){ i in
                    NewButtons = CustomShapeButton()
                }
            }
        }
    }
}

class CustomShapeButton: UIButton {

    lazy var pantsShapeBezierPath: UIBezierPath = {
        // Crate new path
        let path = UIBezierPath()

        var r = CGFloat(75.0)
        r = CGFloat(50.0 + (CGFloat(j) - 1.0) * 50.0)
        let center_x = CGFloat(200.0)
        let center_y = CGFloat(200.0)
        var arc_start = CGFloat(45.0 * CGFloat(Double.pi) / 180.0)
        arc_start = CGFloat((45.0 + (CGFloat(i) - 1.0) * 90.0)) * CGFloat(Double.pi) / 180.0

        let arc_length = CGFloat(90.0 * CGFloat(Double.pi) / 180.0)
        let arc_width = CGFloat(45.0)
        let line0Target_x = center_x + r * CGFloat(cos(Double(arc_start)))
        let line0Target_y = center_y + r * CGFloat(sin(Double(arc_start)))
        let line1Target_x = center_x + (r + arc_width) * CGFloat(cos(Double(arc_start + arc_length)))
        let line1Target_y = center_x + (r + arc_width) * CGFloat(sin(Double(arc_start + arc_length)))

        path.move(to: CGPoint(x: line0Target_x, y: line0Target_y))
        path.addArc(center: CGPoint(x: center_x, y: center_y), radius: r, startAngle: Angle(radians: Double(arc_start)), endAngle: Angle(radians: Double(arc_start + arc_length)), clockwise: false)
        path.addLine(to: CGPoint(x: line1Target_x, y: line1Target_y))
        path.addArc(center: CGPoint(x: center_x, y: center_y), radius: (r + arc_width), startAngle: Angle(radians: Double(arc_start + arc_length)), endAngle: Angle(radians: Double(arc_start)), clockwise: true)
        path.addLine(to: CGPoint(x: line0Target_x, y: line0Target_y))
        path.close()

        return path
    }()

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        // Set shape filling color
        UIColor.red.setFill()

        // Fill the shape
        pantsShapeBezierPath.fill()
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        // Handling touch events

        if (pantsShapeBezierPath.contains(point)) {
            return self

        } else {
            return nil
        }
    }

</code>```

答:
Here you go. You just need to implement the button style first then use it. This result is 9 buttons. I would suggest having 9 functions for each button and not using the same one.</p>

```<code>struct CustomShapeButtonStyle: ButtonStyle {
    var j: Int
    var i: Int
    var fillColor: Color

    func makeBody(configuration: Self.Configuration) -> some View {
        GeometryReader { geometry in
            Path { path in
                var r = CGFloat(75.0)
                r = CGFloat(50.0 + (CGFloat(self.j) - 1.0) * 50.0)
                let center_x = CGFloat(200.0)
                let center_y = CGFloat(200.0)
                var arc_start = CGFloat(45.0 * CGFloat(Double.pi) / 180.0)
                arc_start = CGFloat((45.0 + (CGFloat(self.i) - 1.0) * 90.0)) * CGFloat(Double.pi) / 180.0
                let arc_length = CGFloat(90.0 * CGFloat(Double.pi) / 180.0)
                let arc_width = CGFloat(45.0)
                let line0Target_x = center_x + r * CGFloat(cos(Double(arc_start)))
                let line0Target_y = center_y + r * CGFloat(sin(Double(arc_start)))
                let line1Target_x = center_x + (r + arc_width) * CGFloat(cos(Double(arc_start + arc_length)))
                let line1Target_y = center_x + (r + arc_width) * CGFloat(sin(Double(arc_start + arc_length)))

                path.move(to: CGPoint(x: line0Target_x, y: line0Target_y))
                path.addArc(center: CGPoint(x: center_x, y: center_y), radius: r, startAngle: Angle(radians: Double(arc_start)), endAngle: Angle(radians: Double(arc_start + arc_length)), clockwise: false)
                path.addLine(to: CGPoint(x: line1Target_x, y: line1Target_y))
                path.addArc(center: CGPoint(x: center_x, y: center_y), radius: (r + arc_width), startAngle: Angle(radians: Double(arc_start + arc_length)), endAngle: Angle(radians: Double(arc_start)), clockwise: true)
                path.addLine(to: CGPoint(x: line0Target_x, y: line0Target_y))
                path.closeSubpath()
            }.fill(self.fillColor)
        }
    }
}

struct ContentView: View {
    static let segmentCount = 4
    static let circleCount = 4

    var body: some View {
        ZStack {
            ForEach(1..<Self.circleCount) { j in
                ForEach(1..<Self.segmentCount) { i in
                    Button(action: {
                        print("I was clicked")
                    }) {
                        Text("") // Just a placeholder
                    }.buttonStyle(CustomShapeButtonStyle(j: j, i: i, fillColor: Color(red: 177/255, green: 152/255, blue: 177/255)))
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Title: Designing your own button in SwiftUI

Body:
I'm trying to draw the following picture with each circle segment consisting of 3 buttons which can be clicked.

I've copied code from this forum, but when I try to use it, I get an error message and the code will not compile. Tried various versions (latest one printed), but none work. What am I doing wrong? Also, will the integers i and j be passed on to the call of the class CustomShapeButton?

import SwiftUI
import UIKit

struct ContentView: View {

    static let segmentCount = 4
    static let circleCount = 4

    var i: Int = 0
    var j: Int = 0
    var NewButtons: CustomShapeButton

    var body: some View {
        ZStack {
            ForEach(1..<ContentView.circleCount){ j in
                ForEach(1..<ContentView.segmentCount){ i in
                    NewButtons = CustomShapeButton()
                }
            }
        }
    }
}

class CustomShapeButton: UIButton {

    lazy var pantsShapeBezierPath: UIBezierPath = {
        // Crate new path
        let path = UIBezierPath()

        var r = CGFloat(75.0)
        r = CGFloat(50.0 + (CGFloat(j) - 1.0) * 50.0)
        let center_x = CGFloat(200.0)
        let center_y = CGFloat(200.0)
        var arc_start = CGFloat(45.0 * CGFloat(Double.pi) / 180.0)
        arc_start = CGFloat((45.0 + (CGFloat(i) - 1.0) * 90.0)) * CGFloat(Double.pi) / 180.0

        let arc_length = CGFloat(90.0 * CGFloat(Double.pi) / 180.0)
        let arc_width = CGFloat(45.0)
        let line0Target_x = center_x + r * CGFloat(cos(Double(arc_start)))
        let line0Target_y = center_y + r * CGFloat(sin(Double(arc_start)))
        let line1Target_x = center_x + (r + arc_width) * CGFloat(cos(Double(arc_start + arc_length)))
        let line1Target_y = center_x + (r + arc_width) * CGFloat(sin(Double(arc_start + arc_length)))

        path.move(to: CGPoint(x: line0Target_x, y: line0Target_y))
        path.addArc(center: CGPoint(x: center_x, y: center_y), radius: r, startAngle: Angle(radians: Double(arc_start)), endAngle: Angle(radians: Double(arc_start + arc_length)), clockwise: false)
        path.addLine(to: CGPoint(x: line1Target_x, y: line1Target_y))
        path.addArc(center: CGPoint(x: center_x, y: center_y), radius: (r + arc_width), startAngle: Angle(radians: Double(arc_start + arc_length)), endAngle: Angle(radians: Double(arc_start)), clockwise: true)
        path.addLine(to: CGPoint(x: line0Target_x, y: line0Target_y))
        path.close()

        return path
    }()

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        // Set shape filling color
        UIColor.red.setFill()

        // Fill the shape
        pantsShapeBezierPath.fill()
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        // Handling touch events

        if (pantsShapeBezierPath.contains(point)) {
            return self

        } else {
            return nil
        }
    }

Body:
Here you go. You just need to implement the button style first then use it. This result is 9 buttons. I would suggest having 9 functions for each button and not using the same one.

struct CustomShapeButtonStyle: ButtonStyle {
    var j: Int
    var i: Int
    var fillColor: Color

    func makeBody(configuration: Self.Configuration) -> some View {
        GeometryReader { geometry in
            Path { path in
                var r = CGFloat(75.0)
                r = CGFloat(50.0 + (CGFloat(self.j) - 1.0) * 50.0)
                let center_x = CGFloat(200.0)
                let center_y = CGFloat(200.0)
                var arc_start = CGFloat(45.0 * CGFloat(Double.pi) / 180.0)
                arc_start = CGFloat((45.0 + (CGFloat(self.i) - 1.0) * 90.0)) * CGFloat(Double.pi) / 180.0
                let arc_length = CGFloat(90.0 * CGFloat(Double.pi) / 180.0)
                let arc_width = CGFloat(45.0)
                let line0Target_x = center_x + r * CGFloat(cos(Double(arc_start)))
                let line0Target_y = center_y + r * CGFloat(sin(Double(arc_start)))
                let line1Target_x = center_x + (r + arc_width) * CGFloat(cos(Double(arc_start + arc_length)))
                let line1Target_y = center_x + (r + arc_width) * CGFloat(sin(Double(arc_start + arc_length)))

                path.move(to: CGPoint(x: line0Target_x, y: line0Target_y))
                path.addArc(center: CGPoint(x: center_x, y: center_y), radius: r, startAngle: Angle(radians: Double(arc_start)), endAngle: Angle(radians: Double(arc_start + arc_length)), clockwise: false)
                path.addLine(to: CGPoint(x: line1Target_x, y: line1Target_y))
                path.addArc(center: CGPoint(x: center_x, y: center_y), radius: (r + arc_width), startAngle: Angle(radians: Double(arc_start + arc_length)), endAngle: Angle(radians: Double(arc_start)), clockwise: true)
                path.addLine(to: CGPoint(x: line0Target_x, y: line0Target_y))
                path.closeSubpath()
            }.fill(self.fillColor)
        }
    }
}

struct ContentView: View {
    static let segmentCount = 4
    static let circleCount = 4

    var body: some View {
        ZStack {
            ForEach(1..<Self.circleCount) { j in
                ForEach(1..<Self.segmentCount) { i in
                    Button(action: {
                        print("I was clicked")
                    }) {
                        Text("") // Just a placeholder
                    }.buttonStyle(CustomShapeButtonStyle(j: j, i: i, fillColor: Color(red: 177/255, green: 152/255, blue: 177/255)))
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
Open My application from my keyboard extension in swift 3.0
I am trying to open from my keyboard extension. I am having custom keyboard and I have add that keyboard from setting. On my custom keyboard there is one button “Show More”, and I want to open my app on this button click.

So I have tried following code :

```<code>let context = NSExtensionContext()
 context.open(url! as URL, completionHandler: nil)

 var responder = self as UIResponder?

 while (responder != nil) {

      if responder?.responds(to: Selector("openURL:")) == true {

           responder?.perform(Selector("openURL:"), with: url)
      }
      responder = responder!.next
 }
</code>```

It is working successfully, but as we know in swift Selector("method_name:") is deprecated and use #selector(classname.methodname(_:)) instead so it is giving warning. And I want to solve that warning. So I have tried as Xcode automatically suggested :

```<code> if responder?.responds(to: #selector(UIApplication.openURL(_:))) == true {

      responder?.perform(#selector(UIApplication.openURL(_:)), with: url)
 }
</code>```

Also tried :

```<code> if responder?.responds(to: #selector(NSExtensionContext.open(_:))) == true {

      responder?.perform(#selector(NSExtensionContext.open(_:)), with: url)
 }
</code>```

I have also tried others possible ways, but no luck. If anyone know how to do, please let me know.

I referred this link, Julio Bailon’s answer :

openURL not work in Action Extension

答:
Swift 5.0:

Open Info.plist of hosting app.

Add Url Types -> Item 0 -> Url Schemes -> Item 0 : "yourappname"

Add
Url Types -> Item 0 ->  Url Schemes -> URL Identifier: "your bundle
id"

Go to Keyboard App:

Add following code properly:

```<code>@objc func openURL(_ url: URL) {
       return
    }

    func openApp(_ urlstring:String) {

       var responder: UIResponder? = self as UIResponder
       let selector = #selector(openURL(_:))
       while responder != nil {
          if responder!.responds(to: selector) && responder != self {
             responder!.perform(selector, with: URL(string: urlstring)!)
             return
          }
          responder = responder?.next
        }
     }
</code>```

Call : openApp ("yourappname://your bundle id")

Body:
I am trying to open from my keyboard extension. I am having custom keyboard and I have add that keyboard from setting. On my custom keyboard there is one button “Show More”, and I want to open my app on this button click.

So I have tried following code :

let context = NSExtensionContext()
 context.open(url! as URL, completionHandler: nil)

 var responder = self as UIResponder?

 while (responder != nil) {

      if responder?.responds(to: Selector("openURL:")) == true {

           responder?.perform(Selector("openURL:"), with: url)
      }
      responder = responder!.next
 }

It is working successfully, but as we know in swift Selector("method_name:") is deprecated and use #selector(classname.methodname(_:)) instead so it is giving warning. And I want to solve that warning. So I have tried as Xcode automatically suggested :

 if responder?.responds(to: #selector(UIApplication.openURL(_:))) == true {

      responder?.perform(#selector(UIApplication.openURL(_:)), with: url)
 }

Also tried :

 if responder?.responds(to: #selector(NSExtensionContext.open(_:))) == true {

      responder?.perform(#selector(NSExtensionContext.open(_:)), with: url)
 }

I have also tried others possible ways, but no luck. If anyone know how to do, please let me know.

I referred this link, Julio Bailon’s answer :

openURL not work in Action Extension

Body:
Swift 5.0:

Open Info.plist of hosting app.

Add Url Types -> Item 0 -> Url Schemes -> Item 0 : "yourappname"

Add
Url Types -> Item 0 ->  Url Schemes -> URL Identifier: "your bundle
id"

Go to Keyboard App:

Add following code properly:

@objc func openURL(_ url: URL) {
       return
    }

    func openApp(_ urlstring:String) {

       var responder: UIResponder? = self as UIResponder
       let selector = #selector(openURL(_:))
       while responder != nil {
          if responder!.responds(to: selector) && responder != self {
             responder!.perform(selector, with: URL(string: urlstring)!)
             return
          }
          responder = responder?.next
        }
     }

Call : openApp ("yourappname://your bundle id")


答:
WPF binding is two-way by default. Make it one-way and see if that solves your issue.

```<code><r:RibbonMenuButton ItemsSource="{Binding MyDictionary}">
    <r:RibbonMenuButton.ItemContainerStyle>
        <Style TargetType="{x:Type r:RibbonMenuItem}">
            <Setter Property="IsCheckable" Value="true"/>
            <Setter Property="Header" Value="{Binding Key, Mode=OneWay}"/>
            <Setter Property="IsChecked" Value="{Binding Value, Mode=OneWay}"/>
        </style>
    </r:RibbonMenuButton.ItemContainerStyle>
</r:RibbonMenuButton>
</code>```

Here is a reference for you: MSDN Windows Presentation Foundation Data Binding: Part 1 (specifically check the section Binding Mode close to the bottom of the page)

Title: WPF: Binding to a (observable) Dictionary

Body:
WPF binding is two-way by default. Make it one-way and see if that solves your issue.

<r:RibbonMenuButton ItemsSource="{Binding MyDictionary}">
    <r:RibbonMenuButton.ItemContainerStyle>
        <Style TargetType="{x:Type r:RibbonMenuItem}">
            <Setter Property="IsCheckable" Value="true"/>
            <Setter Property="Header" Value="{Binding Key, Mode=OneWay}"/>
            <Setter Property="IsChecked" Value="{Binding Value, Mode=OneWay}"/>
        </style>
    </r:RibbonMenuButton.ItemContainerStyle>
</r:RibbonMenuButton>

Here is a reference for you: MSDN Windows Presentation Foundation Data Binding: Part 1 (specifically check the section Binding Mode close to the bottom of the page)


问:
Overlapping double arrows in drop down menu
The arrows in the drop down menu have two sets of arrows and they overlap each other (picture in the link below). This is in a ruby on rails app.

The arrows disappear when the drop down menu is enabled.

A drop down menu with two sets of drop down arrows overlapping

```<code>display: block;
font-family: "Roboto", sans-serif;
color: #212121;
font-size: 16px;
line-height: 1.5;
</code>```

答:
try adding to the element.</p>

```<code>    -webkit-appearance: none;
    -moz-appearance: none;
</code>```

Body:
The arrows in the drop down menu have two sets of arrows and they overlap each other (picture in the link below). This is in a ruby on rails app.

The arrows disappear when the drop down menu is enabled.

A drop down menu with two sets of drop down arrows overlapping

display: block;
font-family: "Roboto", sans-serif;
color: #212121;
font-size: 16px;
line-height: 1.5;

Body:
try adding to the element.

    -webkit-appearance: none;
    -moz-appearance: none;


问:
C# remove a full string from an array based on a substring
Say I have an array of strings

string[] my_array = { "XY:1234567;ZW:124", "XY:124252"};

And a user inputs string user_input = "1234567";

how can I remove the entire string from my_array

so after remove XY:1234567;ZQ:124 is removed based on the partial input

my_array = { "XY:124252" };

My first attempt:

```<code>string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "1234567";
if(my_array.Contains(user_input))
    Console.WriteLine("Inside");
else
    Console.WriteLine("Not Inside");
</code>```

Outputted Not Inside

My second attempt:

```<code>string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "%1234567%"; // Tried % to do a partial string I think?
if(my_array.Contains(user_input))
    Console.WriteLine("Inside");
else
    Console.WriteLine("Not Inside");
</code>```

Outputted Not Inside

Im out of ideas

答:
you need String.Contains(). Try like:

```<code>string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "1234567";
foreach( var item in my_array)
{
   if(item.Contains(user_input))
      Console.WriteLine("Inside");
   else
      Console.WriteLine("Not Inside");
}
</code>```

Body:
Say I have an array of strings

string[] my_array = { "XY:1234567;ZW:124", "XY:124252"};

And a user inputs string user_input = "1234567";

how can I remove the entire string from my_array

so after remove XY:1234567;ZQ:124 is removed based on the partial input

my_array = { "XY:124252" };

My first attempt:

string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "1234567";
if(my_array.Contains(user_input))
    Console.WriteLine("Inside");
else
    Console.WriteLine("Not Inside");

Outputted Not Inside

My second attempt:

string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "%1234567%"; // Tried % to do a partial string I think?
if(my_array.Contains(user_input))
    Console.WriteLine("Inside");
else
    Console.WriteLine("Not Inside");

Outputted Not Inside

Im out of ideas

Body:
you need String.Contains(). Try like:

string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "1234567";
foreach( var item in my_array)
{
   if(item.Contains(user_input))
      Console.WriteLine("Inside");
   else
      Console.WriteLine("Not Inside");
}


答:
Try:</p>

```<code>DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND (CASE
        WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
        WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
        ELSE H.O_ADRESS
     END);
</code>```

Title: Set value to a variable in a CASE statement

Body:
Try:

DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND (CASE
        WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
        WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
        ELSE H.O_ADRESS
     END);


问:
laravel 6 authentication "npm run dev not working"
Since laravel 6 the new way to implement authentication you have to get laravel/ui package via composer by running composer require larvel/ui then you have to generate the scaffolding you need here mine is bootstrap php artisan ui bootstrap --auth then you run npm install to get the node_modules and lastly you run npm run dev to build your assets. But the problem is when I run npm run dev nothing happens and I have no errors displayed in the console. When I opened the package.json file I've noticed that the npm run dev executes the npm run development command. So I tried to directly run npm run development and still nothing happened. The npm run development command consist of running this command "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" So I tried to run that and it compiled all the assets. So it is working but what I don't get is why npm commands aren't working either it is  "npm run development" "npm run watch" or any other command they don't execute they just throw a new prompt with no error message.

(node -v) v12.16.0

(npm -v) 6.12.0

(laravel -v) Laravel Installer 3.0.1

(composer -v) version 1.9.0

答: This did the trick for me guys. I remember that I've once put npm config set ignore-scripts to true and that's the reason why it ignores the scripts in package.json. The solution is to change it to false


问:
PHP add missing key in loop
I have the following array.

```<code>    [rows] => Array
            (
                [0] => Array
                    (
                        [id] => 2704783858001796
                        [rowNumber] => 1
                        [expanded] => 1
                        [createdAt] => 2020-02-18T18:42:54Z
                        [modifiedAt] => 2020-02-18T22:07:36Z
                        [cells] => Array
                            (
                                    [0] => Array
                                        (
                                            [columnId] => 1676391784703876
                                            [value] => Approved
                                            [displayValue] => Approved
                                        )

                                    [1] => Array
                                        (
                                            [columnId] => 1225963934640004
                                            [value] => Submitted
                                            [displayValue] => Submitted
                                        )

                                    [2] => Array
                                        (
                                            [columnId] => 4979307467564932
                                            [value] => 2020-02-18
                                        )
                                    [3] => Array
                                        (
                                            [columnId] => 3203730339325828
</code>```

Where [value] and [displayValue] are not always shown.  When I loop through the array, I need to be able to insert a [value] as blank or 0.  I cannot have the loop skip over the key.

```<code>$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column($dataID['rows'][$i]['cells'], 'value'));
}
</code>```

答:
Welcome to stackoverflow :-)

In this case array_column is skipping if the column does not exist. I would add a user-function where you can control your default values and use array_map instead.

Your custom function:

```<code>function array_column_with_default(array $array, string $key, $default = null)
{
    return array_map(function ($item) use ($key, $default) {
        if (false === array_key_exists($key, $item)) {
            return $default;
        }
        return $item[$key];
    }, $array);
}
</code>```

And here is your code-example with array_map() instead of array_column:

```<code>$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column_with_default($rows[$i]['cells'], 'value', ''));
}
</code>```

Below you'll see a test dataset and example output

```<code>$rows = [
    [
        // ... other attributes
        'cells' => [
            ['value' => 'Approved'],
            ['value' => 'Submitted'],
            ['value' => '2020-02-18'],
        ],
    ],
    [
        // ... other attributes
        'cells' => [
            ['value' => 'Not Approved'],
            ['value' => 'Not Submitted'],
            [], // i.e. no date given
        ],
    ],
];
</code>```

will output the following

```<code>array(2) {
  [0] =>
  array(3) {
    [0] =>
    string(8) "Approved"
    [1] =>
    string(9) "Submitted"
    [2] =>
    string(10) "2020-02-18"
  }
  [1] =>
  array(3) {
    [0] =>
    string(12) "Not Approved"
    [1] =>
    string(13) "Not Submitted"
    [2] =>
    string(0) ""
  }
}

</code>```

Title: PHP add missing key in loop

Body:
I have the following array.

    [rows] => Array
            (
                [0] => Array
                    (
                        [id] => 2704783858001796
                        [rowNumber] => 1
                        [expanded] => 1
                        [createdAt] => 2020-02-18T18:42:54Z
                        [modifiedAt] => 2020-02-18T22:07:36Z
                        [cells] => Array
                            (
                                    [0] => Array
                                        (
                                            [columnId] => 1676391784703876
                                            [value] => Approved
                                            [displayValue] => Approved
                                        )

                                    [1] => Array
                                        (
                                            [columnId] => 1225963934640004
                                            [value] => Submitted
                                            [displayValue] => Submitted
                                        )

                                    [2] => Array
                                        (
                                            [columnId] => 4979307467564932
                                            [value] => 2020-02-18
                                        )
                                    [3] => Array
                                        (
                                            [columnId] => 3203730339325828

Where [value] and [displayValue] are not always shown.  When I loop through the array, I need to be able to insert a [value] as blank or 0.  I cannot have the loop skip over the key.

$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column($dataID['rows'][$i]['cells'], 'value'));
}

Body:
Welcome to stackoverflow :-)

In this case array_column is skipping if the column does not exist. I would add a user-function where you can control your default values and use array_map instead.

Your custom function:

function array_column_with_default(array $array, string $key, $default = null)
{
    return array_map(function ($item) use ($key, $default) {
        if (false === array_key_exists($key, $item)) {
            return $default;
        }
        return $item[$key];
    }, $array);
}

And here is your code-example with array_map() instead of array_column:

$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column_with_default($rows[$i]['cells'], 'value', ''));
}

Below you'll see a test dataset and example output

$rows = [
    [
        // ... other attributes
        'cells' => [
            ['value' => 'Approved'],
            ['value' => 'Submitted'],
            ['value' => '2020-02-18'],
        ],
    ],
    [
        // ... other attributes
        'cells' => [
            ['value' => 'Not Approved'],
            ['value' => 'Not Submitted'],
            [], // i.e. no date given
        ],
    ],
];

will output the following

array(2) {
  [0] =>
  array(3) {
    [0] =>
    string(8) "Approved"
    [1] =>
    string(9) "Submitted"
    [2] =>
    string(10) "2020-02-18"
  }
  [1] =>
  array(3) {
    [0] =>
    string(12) "Not Approved"
    [1] =>
    string(13) "Not Submitted"
    [2] =>
    string(0) ""
  }
}


问:
How to retrieve all the paragraph in the specified particullar page using C#(4.0) and Open Xml Sdk(2.0)?
We are developing C#.Net(4.0) Windows Form Based Application with the use of Open Xml Sdk(2.0) for manipulating MS-WORD Files.Now i want to get the all the paragraphs in particular page.The user prompted for getting particular page no of the word file to get the all the paragraphs inside the user selected page number. How i do it?</p>

答:
Taking a quick look at the underlying XML it doesn't look like there is an attribute on the paragraph element that will tell you which page it will appear on.  The best suggestion I can give you is to have some placeholder text at the top and bottom of each page.  Then search for the a certain instance of the placeholder text based on which page the user specifies. Once you have a starting point you could retrieve all paragraphs between the two placeholder paragraph elements.

For example, if a user enters in page two, you would search for the third instance of a paragraph that contains this placeholder text and then retrieve all paragraphs until you reach the next instance of the placeholder text.  I know this isn't ideal, but its one workaround I could think of that might be feasible.


问:
Distributed atomic list: synchronization between microservices
Currently, I've deployed two services: front and back:

back asks to front for pending resources to be digested by back.

back asks for pending resources ids to front.

For each received resource id:

back downloads the entire resource according to its id.

back digests received resource.

back sends confirmation to front.

It's working well, but it doesn't scale. I mean, what about if I want to scale back up to 2 replicas?

Then, two back instances are going to pull for pending resources regardless of whether the other one is digesting the same resource.

I hope I've explained so well.

Any ideas?

答:
Not quite sure if I got your context, but it sounds like what many database (+like) services offer.  Etcd, for example, is a distributed key-value store rather than traditional database.  It uses versioning of the keys ( key + count ) to track historical versions, and provides a sort of distributed transaction monitor based on the raft consensus algorithm (https://raft.github.io/).

There are many similar services to choose from with various niches.
They are considered lightweight in the same way unix instances are considered microservices.


问:
Spring Cloud Config Server - Connect to Github account with 2FA
I'm trying to create a Spring Cloud Config Server to retrieve configuration files from a private GitHub repository. My GitHub account has 2 Factor Authentication activated so I wasn't expecting the below configuration to work, which it didn't but I can't find any documentation to suggest what I need to do in order to make it work.

What configuration do I need to set that will allow the connection to work?

```<code>spring.cloud.config.server.git.uri=https://github.com/DanBonehill/photo-app-config
spring.cloud.config.server.git.username=USERNAME
spring.cloud.config.server.git.password=PASSWORD
</code>```

Error

org.eclipse.jgit.api.errors.TransportException: https://github.com/DanBonehill/photo-app-config: not authorized

答: Instead of using username and password you should use an ssh key, the official documentation can guide you through it!

Body:
I'm trying to create a Spring Cloud Config Server to retrieve configuration files from a private GitHub repository. My GitHub account has 2 Factor Authentication activated so I wasn't expecting the below configuration to work, which it didn't but I can't find any documentation to suggest what I need to do in order to make it work.

What configuration do I need to set that will allow the connection to work?

spring.cloud.config.server.git.uri=https://github.com/DanBonehill/photo-app-config
spring.cloud.config.server.git.username=USERNAME
spring.cloud.config.server.git.password=PASSWORD

Error

org.eclipse.jgit.api.errors.TransportException: https://github.com/DanBonehill/photo-app-config: not authorized


问:
VBA. Deleting multiple cells in a row if one cell is blank
I have multiple columns in an excel sheet...say A1:D10.
I want to find any blank cells in column C, delete that cell as well as the A,B, and D cells of that same row, then shift up.  But only in the range of A1:D10.  I have other information in this excel sheet outside this range that I want to perserve in its original position.  Therefore I can not use somthing like this:

```<code>.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
</code>```

Nor can I get something like the following to work, because it only shifts the single column up, not all four columns.

```<code>Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp
</code>```

答:
Using Variant Array Method</p>

```<code>Sub test2()
    Dim rngDB As Range, vDB As Variant
    Dim i As Integer, j As Integer, n As Integer
    Dim k As Integer

    Set rngDB = Range("a1:d10")

    vDB = rngDB

    n = UBound(vDB, 1)
    For i = 1 To n
        If IsEmpty(vDB(i, 3)) Then
            For j = 1 To 4
                If j <> 3 Then
                    vDB(i, j) = Empty
                End If
            Next j
        End If
    Next i
    For j = 1 To 4
        If j <> 3 Then
            For i = 1 To n - 1
                For k = i To n - 1
                    If vDB(k, j) = Empty Then
                        vDB(k, j) = vDB(k + 1, j)
                        vDB(k + 1, j) = Empty
                    End If
                Next k
            Next i
        End If
    Next j
    rngDB = vDB
End Sub
</code>```

Body:
I have multiple columns in an excel sheet...say A1:D10.
I want to find any blank cells in column C, delete that cell as well as the A,B, and D cells of that same row, then shift up.  But only in the range of A1:D10.  I have other information in this excel sheet outside this range that I want to perserve in its original position.  Therefore I can not use somthing like this:

.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Nor can I get something like the following to work, because it only shifts the single column up, not all four columns.

Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp

Body:
Using Variant Array Method

Sub test2()
    Dim rngDB As Range, vDB As Variant
    Dim i As Integer, j As Integer, n As Integer
    Dim k As Integer

    Set rngDB = Range("a1:d10")

    vDB = rngDB

    n = UBound(vDB, 1)
    For i = 1 To n
        If IsEmpty(vDB(i, 3)) Then
            For j = 1 To 4
                If j <> 3 Then
                    vDB(i, j) = Empty
                End If
            Next j
        End If
    Next i
    For j = 1 To 4
        If j <> 3 Then
            For i = 1 To n - 1
                For k = i To n - 1
                    If vDB(k, j) = Empty Then
                        vDB(k, j) = vDB(k + 1, j)
                        vDB(k + 1, j) = Empty
                    End If
                Next k
            Next i
        End If
    Next j
    rngDB = vDB
End Sub


问:
Custom React Hook with callback is making closure
What I am trying to achieve is a custom hook that calls a callback on particular keypress. The thing is that the callback is dependant on component prop. Unfortunately callback is passed to the hook only once and it makes closure on prop value.

Hook Code:

```<code>export default function useKeyPress(targetKey, callback) {
  const keyPressedHandler = ({ key }) => {
    if (key === targetKey && callback && typeof callback === 'function') {
      callback();
    }
  };

  useEffect(() => {
    window.addEventListener('keyup', keyPressedHandler);
    return () => {
      window.removeEventListener('keyup', keyPressedHandler);
    };
  }, []);
}
</code>```

Component that uses a hook:

```<code>const Component = ({ isActive }) => {
  // isActive is changing here
  useKeyPress('ArrowRight', () => {
    if (isActive) // isActive always has the initial value
      // do something if isActive is true
  });
}
</code>```

How can I rewrite my hook or how should I handle this kind of situation?

答:
I have reproduced the issue on Codepen https://codepen.io/tedseds/pen/oNXzvoK

When you press arrow right it always logs isActive as false even when the prop is changed.

Solution https://codepen.io/tedseds/pen/ZEGpzPm

You need to pass prop callback as a dependancy to the useEffect.
It will reattach the event listener with the latest callback.

Code:

```<code>function useKeyPress(targetKey, callback) {
  const keyPressedHandler = ({ key }) => {
    if (key === targetKey && callback && typeof callback === "function") {
      callback();
    }
  };

  useEffect(() => {
    window.addEventListener("keyup", keyPressedHandler);
    return () => {
      window.removeEventListener("keyup", keyPressedHandler);
    };
  }, [callback]);
}
</code>```

Body:
What I am trying to achieve is a custom hook that calls a callback on particular keypress. The thing is that the callback is dependant on component prop. Unfortunately callback is passed to the hook only once and it makes closure on prop value.

Hook Code:

export default function useKeyPress(targetKey, callback) {
  const keyPressedHandler = ({ key }) => {
    if (key === targetKey && callback && typeof callback === 'function') {
      callback();
    }
  };

  useEffect(() => {
    window.addEventListener('keyup', keyPressedHandler);
    return () => {
      window.removeEventListener('keyup', keyPressedHandler);
    };
  }, []);
}

Component that uses a hook:

const Component = ({ isActive }) => {
  // isActive is changing here
  useKeyPress('ArrowRight', () => {
    if (isActive) // isActive always has the initial value
      // do something if isActive is true
  });
}

How can I rewrite my hook or how should I handle this kind of situation?

Body:
I have reproduced the issue on Codepen https://codepen.io/tedseds/pen/oNXzvoK

When you press arrow right it always logs isActive as false even when the prop is changed.

Solution https://codepen.io/tedseds/pen/ZEGpzPm

You need to pass prop callback as a dependancy to the useEffect.
It will reattach the event listener with the latest callback.

Code:

function useKeyPress(targetKey, callback) {
  const keyPressedHandler = ({ key }) => {
    if (key === targetKey && callback && typeof callback === "function") {
      callback();
    }
  };

  useEffect(() => {
    window.addEventListener("keyup", keyPressedHandler);
    return () => {
      window.removeEventListener("keyup", keyPressedHandler);
    };
  }, [callback]);
}


问:
SQL - sum data for all time, 30 days and 90 days for multiple columns indiviually
BACKGROUND:

I have data that looks like this

```<code>date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34
</code>```

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

```<code>src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2
</code>```

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

```<code>SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src
</code>```

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.

答:
Your query looks quite good; conditional aggregation is the canonical method to pivot a dataset.

One way to possibly increase performance would be to change the date filter in the conditional expressions: using a date function precludes the use of an index.

Instead, you could phrase this as:

```<code>select
    src,
    subsrc,
    subsubsrc,
    sum(param1) as param1_all,
    sum(case when date >= current_date - interval 30 day then param1 end) as param1_30,
    sum(case when date >= current_date - interval 90 day then param1 end) as param1_90,
    sum(param2) as param2_all,
    sum(case when date >= current_date - interval 30 day then param2 end) as param2_30,
    sum(case when date >= current_date - interval 90 day then param2 end) as param2_90
from my_table
group by src, subsrc, subsubsrc
order by src, subsrc, subsubsrc
</code>```

For performance, the following index may be helpul: (src, subsrc, subsubsrc, date).

Note that I included all three non-aggregated columns (src, subsrc, subsubsrc) in the group by clause: starting MySQL 5.7, this is by default mandatory (although you can play around with sql modes to alter that behavior) - and most other databases implement the same constraint.

Body:
BACKGROUND:

I have data that looks like this

date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.

Body:
Your query looks quite good; conditional aggregation is the canonical method to pivot a dataset.

One way to possibly increase performance would be to change the date filter in the conditional expressions: using a date function precludes the use of an index.

Instead, you could phrase this as:

select
    src,
    subsrc,
    subsubsrc,
    sum(param1) as param1_all,
    sum(case when date >= current_date - interval 30 day then param1 end) as param1_30,
    sum(case when date >= current_date - interval 90 day then param1 end) as param1_90,
    sum(param2) as param2_all,
    sum(case when date >= current_date - interval 30 day then param2 end) as param2_30,
    sum(case when date >= current_date - interval 90 day then param2 end) as param2_90
from my_table
group by src, subsrc, subsubsrc
order by src, subsrc, subsubsrc

For performance, the following index may be helpul: (src, subsrc, subsubsrc, date).

Note that I included all three non-aggregated columns (src, subsrc, subsubsrc) in the group by clause: starting MySQL 5.7, this is by default mandatory (although you can play around with sql modes to alter that behavior) - and most other databases implement the same constraint.


问:
boost xml parsingl send a path of xml as variable
read_xml() function get a parameter of xml name and ptree member, but i want to send file's file directory such as C:\Users\serhan.erkovan\Desktop\ddd.xml as a variable. When i tried to do that it gives me error that cannot open file. How can i send file directory as a variable ?

My example code like this

```<code>ptree pt;
    try
    {
        read_xml("C:\\Users\serhan.erkovan\Desktop\ddd.xml", pt);
    }
    catch (const boost::property_tree::xml_parser::xml_parser_error &ex)
    {
        cerr << ex.what();
    }

</code>```

Working example like this

```<code>ptree pt;
    try
    {
        read_xml("ddd.xml", pt);
    }
    catch (const boost::property_tree::xml_parser::xml_parser_error &ex)
    {
        cerr << ex.what();
    }
</code>```

答:
Working form is C:\\Users/serhan.erkovan/Desktop/ddd.xml as mentioned @Gupta and working example like this

```<code>ptree pt;
    try
    {
        read_xml("C:\\Users/serhan.erkovan/Desktop/ddd.xml", pt);
    }
    catch (const boost::property_tree::xml_parser::xml_parser_error &ex)
    {
        cerr << ex.what();
    }

</code>```

Body:
read_xml() function get a parameter of xml name and ptree member, but i want to send file's file directory such as C:\Users\serhan.erkovan\Desktop\ddd.xml as a variable. When i tried to do that it gives me error that cannot open file. How can i send file directory as a variable ?

My example code like this

ptree pt;
    try
    {
        read_xml("C:\\Users\serhan.erkovan\Desktop\ddd.xml", pt);
    }
    catch (const boost::property_tree::xml_parser::xml_parser_error &ex)
    {
        cerr << ex.what();
    }

Working example like this

ptree pt;
    try
    {
        read_xml("ddd.xml", pt);
    }
    catch (const boost::property_tree::xml_parser::xml_parser_error &ex)
    {
        cerr << ex.what();
    }

Body:
Working form is C:\\Users/serhan.erkovan/Desktop/ddd.xml as mentioned @Gupta and working example like this

ptree pt;
    try
    {
        read_xml("C:\\Users/serhan.erkovan/Desktop/ddd.xml", pt);
    }
    catch (const boost::property_tree::xml_parser::xml_parser_error &ex)
    {
        cerr << ex.what();
    }


问:
Razor to produce single line text
I want to write Razor view helper to produce single line content:

```<code>@helper Format(obj) {
   <text>
       @obj.Title
       @obj.FormatInnerData() (obj.User != null)
       {
          @obj.User.Name
       }
   <text>
}
</code>```

But of course I get

```<code>Title
Inner Data
User Name
</code>```

Currently I have to do

```<code><text>@obj.Title @obj.FormatInnerData() @(obj.User != null ? obj.User.Name : "")</text>
</code>```

to produce text output as single line without line breaks, but this can grow quite long / unreadable for many properties.

In other words, how do I more conveniently use Razor to generate text content, not markup content?

UPD: Ideally that would be something like

```<code>   <content>@obj.Title</content>
   <content>@obj.Format()
 @obj.User.Name</content>
</code>```

i.e. only parts between content tags go into output stream. Of course maybe a simpler syntax, like @: instead of <text>.

An example use case would be to generate JavaScript string content with markup inside, or, generate text files with license details in format "Key: Name (details)" on each line, padded with spaces for grouping.

答:
Have you tried</p>

```<code>@helper Format(obj) {
   <text>
       @( obj.Title +
          obj.FormatInnerData() +
         obj.User != null ? obj.User.Name : ""
        )
   <text>
}
</code>```

Title: Razor to produce single line text

Body:
I want to write Razor view helper to produce single line content:

@helper Format(obj) {
   <text>
       @obj.Title
       @obj.FormatInnerData() (obj.User != null)
       {
          @obj.User.Name
       }
   <text>
}

But of course I get

Title
Inner Data
User Name

Currently I have to do

<text>@obj.Title @obj.FormatInnerData() @(obj.User != null ? obj.User.Name : "")</text>

to produce text output as single line without line breaks, but this can grow quite long / unreadable for many properties.

In other words, how do I more conveniently use Razor to generate text content, not markup content?

UPD: Ideally that would be something like

   <content>@obj.Title</content>
   <content>@obj.Format()
 @obj.User.Name</content>

i.e. only parts between content tags go into output stream. Of course maybe a simpler syntax, like @: instead of <text>.

An example use case would be to generate JavaScript string content with markup inside, or, generate text files with license details in format "Key: Name (details)" on each line, padded with spaces for grouping.

Body:
Have you tried

@helper Format(obj) {
   <text>
       @( obj.Title +
          obj.FormatInnerData() +
         obj.User != null ? obj.User.Name : ""
        )
   <text>
}


问:
Issues with csrf token field being empty
I'm pretty brand new to php/laravel (bear with me!) and am having some issues with csrf tokens for one of my forms. I've included the code to the entire view, but the form I'm having issues with is the #editActionDueDate modal. When hitting edit on the modal form, it returns a 419 error. I've tried passing the csrf token with every way I can think of, but I can't get the token through. It just passes an empty value for that token parameter.

Every other form on my site is working just fine, so I'm a little confused.

The only difference I can think of with this form is that it has a modified script to pass the information of the current due_date to the form itself - everything else is identical and from what I've asked some of our developers, this should not affect it.

Also, if I exclude this uri from the csrf verification middleware, it works fine.

Any ideas of what could be causing the token field to be empty?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>View Action Details</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

    <script>
    // Open "edit due date" modal and pass due_date info
    $(document).ready(function() {
        $('#editActionDueDate').on('show.bs.modal', function (event) {

        var button = $(event.relatedTarget) // Button that triggered the modal
        var due_date = button.data('due_date') // Extract info from data-* attributes
        var modal = $(this)

        modal.find('.modal-body input').val(due_date)
        });
    })
    </script>
    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    @include('nav')
    <div>

        @foreach($action as $act)
        <a href="{{ route('patient', $act->patient_id) }}">Return to patient profile</a>
        @endforeach

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#insertActionNote">
            + Action Note
        </button>

    </div>
    <div>
        <h3>Action View</h3>
        @foreach($action as $act)
        <table class="table">
            <tr>
                <th>Action ID</th>
                <th>Patient</th>
                <th>Created Date</th>
                <th>Last Modified Date</th>
            </tr>
            <tr>
                <td>{{ $act->action_id}}</td>
                <td>{{ $act->first_name.' '.$act->last_name}}</td>
                <td>{{ $act->created_at}}</td>
                <td>{{ $act->updated_at}}</td>
            </tr>
            <tr>
                <th>Action</th>
                <th>Status</th>
                <th>Due Date</th>
            </tr>
            <tr>
                <td>{{ $act->option_text}}</td>
                <td>{{ $act->action_status_name}}</td>
                <td>{{ $act->due_date}}</td>
                <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editActionDueDate" data-due_date="{{ $act->due_date }}">Edit</button></td>
            </tr>
        </table>
        @endforeach
    </div>
    <div>
    <h3>Notes</h3>
    <table class="table">
        @foreach($notes as $note)
        <tr>
            <td><strong>Date: {{$note->created_at}}</strong></td>
            <td><strong>Submitted By: {{$note->user_name}}</strong></td>
        </tr>
        <tr>
            <td>{{$note->note_text}}</td>
        </tr>
        @endforeach
    </table>

    {{ $notes->links() }}

    </div>

    <!-- This modal form works fine -->
    <div class="modal fade" id="insertActionNote" tabindex="-1" role="dialog" aria-labelledby="insertActionNoteLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="insertActionNoteLabel">Add New Note</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="{{ route('addActionNote') }}">
                    {{ csrf_field() }}

                    <input id="user_id" type="hidden" name="user_id" value="{{ Auth::user()->user_id }}" >
                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                    <div class="form-group row">
                        <label for="note_text" class="col-md-2 col-form-label text-md-right">{{ __('Note') }}</label>

                        <div class="col-md-10">
                            <textarea id="note_text" name="note_text" type="text" class="form-control @error('note_text') is-invalid @enderror" rows="4" value="{{ old('note_text') }}" required autofocus></textarea>

                            @error('note_text')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Add Note') }}
                        </button>
                    </div>
                    </form>
                </div>

            </div>
        </div>
    </div>

    <!-- This modal form is passing an empty token-->
    <div class="modal fade" id="editActionDueDate" tabindex="-1" role="dialog" aria-labelledby="editActionDueDateLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editActionDueDateLabel">Edit Due Date</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="{{ route('editActionDueDate') }}">
                        {!! csrf_field() !!}

                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                    <div class="form-group row">
                        <label for="note_text" class="col-md-4 col-form-label text-md-right">{{ __('Due Date') }}</label>

                        <div class="col-md-6">
                            <input id="due_date" type="text" class="form-control @error('due_date') is-invalid @enderror" name="due_date" value="{{ old('due_date') }}" placeholder="MM/DD/YYYY" autofocus>

                            @error('due_date')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Edit Due Date') }}
                        </button>
                    </div>
                    </form>
                </div>

            </div>
        </div>
    </div>

</body>
</html>
</code>```

```<code><?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\Http\Controllers\PatientController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/home', 'HomeController@index')->name('home');

Route::post('/addAction', 'ActionController@store')->name('addAction');
Route::post('/addPatientNote', 'PatientNoteController@store')->name('addPatientNote');
Route::post('/addActionNote', 'ActionNoteController@store')->name('addActionNote');
Route::post('/editActionDueDate/{action_id}', 'ActionController@editActionDueDate')->name('editActionDueDate');

Auth::routes();

Route::get('/registerPatient', 'PatientController@showPatientRegistrationForm')->name('registerPatient');
Route::post('/registerPatient', 'PatientController@store');
Route::post('/editPatient', 'PatientController@update')->name('editPatient');
Route::get('/patient/{patient_id}', 'PatientController@show')->name('patient');

Route::get('/viewAction/{action_id}', 'ActionController@show')->name('viewAction');

Route::get('dashboard', 'ActionController@index')->name('actions.index');
Route::get('getActions', 'ActionController@getActionsTable')->name('get.actions');

Route::resource('users', 'UserController');

Route::get('/addQuestion', 'QuestionController@showNewQuestions')->name('addQuestion');
Route::post('/addQuestion', 'QuestionController@storeNewQuestionAndOptions');
</code>```

答:
It could be a problem with your route. Are you using the "web" middleware? It not try moving your route inside.

The laravel documentation on this subject is pretty good:
https://laravel.com/docs/6.x/middleware

Body:
I'm pretty brand new to php/laravel (bear with me!) and am having some issues with csrf tokens for one of my forms. I've included the code to the entire view, but the form I'm having issues with is the #editActionDueDate modal. When hitting edit on the modal form, it returns a 419 error. I've tried passing the csrf token with every way I can think of, but I can't get the token through. It just passes an empty value for that token parameter.

Every other form on my site is working just fine, so I'm a little confused.

The only difference I can think of with this form is that it has a modified script to pass the information of the current due_date to the form itself - everything else is identical and from what I've asked some of our developers, this should not affect it.

Also, if I exclude this uri from the csrf verification middleware, it works fine.

Any ideas of what could be causing the token field to be empty?

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>View Action Details</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    @include('nav')

        @foreach($action as $act)
        patient_id) }}">Return to patient profile
        @endforeach

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#insertActionNote">
            + Action Note
        </button>

Action View

        @foreach($action as $act)

                Action ID
                Patient
                Created Date
                Last Modified Date

                {{ $act->action_id}}
                {{ $act->first_name.' '.$act->last_name}}
                {{ $act->created_at}}
                {{ $act->updated_at}}

                Action
                Status
                Due Date

                {{ $act->option_text}}
                {{ $act->action_status_name}}
                {{ $act->due_date}}
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editActionDueDate" data-due_date="{{ $act->due_date }}">Edit</button>

        @endforeach

Notes

        @foreach($notes as $note)

            Date: {{$note->created_at}}
            Submitted By: {{$note->user_name}}

            {{$note->note_text}}

        @endforeach

    {{ $notes->links() }}

Add New Note

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <form method="POST" action="{{ route('addActionNote') }}">
                    {{ csrf_field() }}

                    <input id="user_id" type="hidden" name="user_id" value="{{ Auth::user()->user_id }}" >
                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                        {{ __('Note') }}

                            <textarea id="note_text" name="note_text" type="text" class="form-control @error('note_text') is-invalid @enderror" rows="4" value="{{ old('note_text') }}" required autofocus></textarea>

                            @error('note_text')

                                    {{ $message }}

                            @enderror

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Add Note') }}
                        </button>

                    </form>

Edit Due Date

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <form method="POST" action="{{ route('editActionDueDate') }}">
                        {!! csrf_field() !!}

                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                        {{ __('Due Date') }}

                            <input id="due_date" type="text" class="form-control @error('due_date') is-invalid @enderror" name="due_date" value="{{ old('due_date') }}" placeholder="MM/DD/YYYY" autofocus>

                            @error('due_date')

                                    {{ $message }}

                            @enderror

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Edit Due Date') }}
                        </button>

                    </form>

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\Http\Controllers\PatientController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/home', 'HomeController@index')->name('home');

Route::post('/addAction', 'ActionController@store')->name('addAction');
Route::post('/addPatientNote', 'PatientNoteController@store')->name('addPatientNote');
Route::post('/addActionNote', 'ActionNoteController@store')->name('addActionNote');
Route::post('/editActionDueDate/{action_id}', 'ActionController@editActionDueDate')->name('editActionDueDate');

Auth::routes();

Route::get('/registerPatient', 'PatientController@showPatientRegistrationForm')->name('registerPatient');
Route::post('/registerPatient', 'PatientController@store');
Route::post('/editPatient', 'PatientController@update')->name('editPatient');
Route::get('/patient/{patient_id}', 'PatientController@show')->name('patient');

Route::get('/viewAction/{action_id}', 'ActionController@show')->name('viewAction');

Route::get('dashboard', 'ActionController@index')->name('actions.index');
Route::get('getActions', 'ActionController@getActionsTable')->name('get.actions');

Route::resource('users', 'UserController');

Route::get('/addQuestion', 'QuestionController@showNewQuestions')->name('addQuestion');
Route::post('/addQuestion', 'QuestionController@storeNewQuestionAndOptions');