问:
Improve the cyclomatic complexity code for if-else statements
I have a block of if-else statements in a method for which I am getting cyclomatic complexity issue. I have tried using switch statement for this but still the issue remains.</p>

```<code>if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS)) {
    method1()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS)) {
    method2()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS)) {
    method3()...
} and so on...

public static void method1(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException {
        //logic for the method
    }
</code>```

答:
Edit: as you mentioned you have checked Exceptions that can be thrown and arguments in your method. As a Runnable doesn't declare that it can throw Exceptions and also doens't accept any parameters you have to create your own FunctionalInterface (click here to see what they really are):

```<code>public interface ThrowingRunnable {
    void run(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException;
}
</code>```

Then you just have to replace Runnable with ThrowingRunnable in my earlier proposed code below and you should be fine.

You can create a mapping of HwErrorsEtlConstants to the specific method (uses java 8):

```<code>static final Map<String, Runnable> MAPPING;
static {
    Map<String, Runnable> temp = new HashMap<>();
    temp.put(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS, this::method1);
    temp.put(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS, this::method2);
    temp.put(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS, this::method3);
    MAPPING = Collections.unmodifiableMap(temp);
}
</code>```

Then in your method you can use Streams introduced also in Java 8:

```<code>// Optional indicates a potentially absent value, it's just a wrapper around a Runnable
Optional<Runnable> optional = MAPPING
    // create a Stream from the entries
    .entrySet().stream()
    // keep the items that match the condition and drop every other
    .filter(e -> filename.startsWith(e.getKey()))
    // we had Map.Entry<String, Runnable>, but now we only need the value e.g. the Runnable
    .map(Map.Entry::getValue)
    // short circuit, e.g. we only want the first value that matches
    .findFirst();

// checks if anything is present, this is used as the MAPPING "could" be empty
if(optional.isPresent()) {
    // unpack the value and call it with arguments
    optional.get().run(aWriter, someFileName, anInputStream);
} else {
    // nothing matched, throw error or log etc.
}
</code>```

Though as has been mentioned, your current solution does look fine, I guess you're using Sonar for code analysis. Sometimes Sonar just has false positives, so you can also safely ignore them.

Further reads to help you understand Java 8:

What are the advantages of using lambda expressions in java 8?

In Java, what are the advantages of streams over loops?

Stream javadoc

Optional javadoc

Body:
I have a block of if-else statements in a method for which I am getting cyclomatic complexity issue. I have tried using switch statement for this but still the issue remains.

if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS)) {
    method1()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS)) {
    method2()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS)) {
    method3()...
} and so on...

public static void method1(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException {
        //logic for the method
    }

Body:
Edit: as you mentioned you have checked Exceptions that can be thrown and arguments in your method. As a Runnable doesn't declare that it can throw Exceptions and also doens't accept any parameters you have to create your own FunctionalInterface (click here to see what they really are):

public interface ThrowingRunnable {
    void run(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException;
}

Then you just have to replace Runnable with ThrowingRunnable in my earlier proposed code below and you should be fine.

You can create a mapping of HwErrorsEtlConstants to the specific method (uses java 8):

static final Map<String, Runnable> MAPPING;
static {
    Map<String, Runnable> temp = new HashMap<>();
    temp.put(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS, this::method1);
    temp.put(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS, this::method2);
    temp.put(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS, this::method3);
    MAPPING = Collections.unmodifiableMap(temp);
}

Then in your method you can use Streams introduced also in Java 8:

// Optional indicates a potentially absent value, it's just a wrapper around a Runnable
Optional<Runnable> optional = MAPPING
    // create a Stream from the entries
    .entrySet().stream()
    // keep the items that match the condition and drop every other
    .filter(e -> filename.startsWith(e.getKey()))
    // we had Map.Entry<String, Runnable>, but now we only need the value e.g. the Runnable
    .map(Map.Entry::getValue)
    // short circuit, e.g. we only want the first value that matches
    .findFirst();

// checks if anything is present, this is used as the MAPPING "could" be empty
if(optional.isPresent()) {
    // unpack the value and call it with arguments
    optional.get().run(aWriter, someFileName, anInputStream);
} else {
    // nothing matched, throw error or log etc.
}

Though as has been mentioned, your current solution does look fine, I guess you're using Sonar for code analysis. Sometimes Sonar just has false positives, so you can also safely ignore them.

Further reads to help you understand Java 8:

What are the advantages of using lambda expressions in java 8?

In Java, what are the advantages of streams over loops?

Stream javadoc

Optional javadoc


来源: stackexchange

问:
how can I put shadow and gradient effects on solid gauge in hightcharts?
I am learning about highcharts.

I want to put inner shadow effect and gradient on solid gauge chart in highcharts as a images below.

It doesn`t matter inner shadow position.

Have a good day.

答:
Use linear gradients in your js like below

```<code>stops: [
        [0.5, {
          linearGradient: {
            x1: 0,
            x2: 0,
            y1: 0,
            y2: 1
          },
          stops: [
            [0, '#0000ff'],
            [1, '#b2b2ff']
          ]
        }]
      ]
</code>```

$(function() {

  var gaugeOptions = {
    chart: {
      type: 'solidgauge'
    },
    title: null,
    pane: {
      center: ['50%', '85%'],
      size: '140%',
      startAngle: -90,
      endAngle: 90,
      background: {
        backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
        innerRadius: '60%',
        outerRadius: '100%',
        shape: 'arc'
      }
    },
    // the value axis
    yAxis: {
      stops: [
        [0.5, {
          linearGradient: {
            x1: 0,
            x2: 0,
            y1: 0,
            y2: 1
          },
           stops: [
            [0, '#0000ff'],
            [1, '#e3e3f4']
          ]
        }]
      ],
      lineWidth: 0,
      minorTickInterval: null,
      tickPixelInterval: 400,
      tickWidth: 0,
      title: {
        y: -70
      },
      labels: {
        y: 16
      }
    },

    plotOptions: {
      solidgauge: {
        dataLabels: {
          y: 5,
          borderWidth: 0,
          useHTML: true
        }
      }
    }
  };

  // The speed gauge
  $('#container-speed').highcharts(Highcharts.merge(gaugeOptions, {
    yAxis: {
      min: 0,
      max: 200,
    },

    series: [{
      data: [120],
    }]

  }));

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<script src="https://code.highcharts.com/modules/solid-gauge.js"></script>

<div style="width: 500px; height: 400px; margin: 0 auto">
  <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
Use linear gradients in your js like below

stops: [
        [0.5, {
          linearGradient: {
            x1: 0,
            x2: 0,
            y1: 0,
            y2: 1
          },
          stops: [
            [0, '#0000ff'],
            [1, '#b2b2ff']
          ]
        }]
      ]

$(function() {

  var gaugeOptions = {
    chart: {
      type: 'solidgauge'
    },
    title: null,
    pane: {
      center: ['50%', '85%'],
      size: '140%',
      startAngle: -90,
      endAngle: 90,
      background: {
        backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
        innerRadius: '60%',
        outerRadius: '100%',
        shape: 'arc'
      }
    },
    // the value axis
    yAxis: {
      stops: [
        [0.5, {
          linearGradient: {
            x1: 0,
            x2: 0,
            y1: 0,
            y2: 1
          },
           stops: [
            [0, '#0000ff'],
            [1, '#e3e3f4']
          ]
        }]
      ],
      lineWidth: 0,
      minorTickInterval: null,
      tickPixelInterval: 400,
      tickWidth: 0,
      title: {
        y: -70
      },
      labels: {
        y: 16
      }
    },

    plotOptions: {
      solidgauge: {
        dataLabels: {
          y: 5,
          borderWidth: 0,
          useHTML: true
        }
      }
    }
  };

  // The speed gauge
  $('#container-speed').highcharts(Highcharts.merge(gaugeOptions, {
    yAxis: {
      min: 0,
      max: 200,
    },

    series: [{
      data: [120],
    }]

  }));

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<script src="https://code.highcharts.com/modules/solid-gauge.js"></script>

<div style="width: 500px; height: 400px; margin: 0 auto">
  <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
</div>


问:
Visual Basic : setting a workbook or sheet returns Nothing
I have a problem that prevents me from continuing on my task. With all variables declared, and with the two Workbooks I have to work with opened, I don't manage to make the macro read values from both workbooks. When I use Set wbSource = workbooks.open(sFileName), it returns Nothing to wbSource. The same with all other variables:

```<code>Dim nColumnas As Double

Dim nFilas As Double

Dim mec, dis, trans As Double

Dim rnData As Range

Dim i, j As Double

Dim Z As Double

Dim rango As Range

Dim hojaOrigen As String

Dim hojaDestino As String

Dim temporal As Variant

Dim N, Q, E As Long

Dim lo As ListObject

Dim op As Variant

Dim y, m, y_n As Long

Dim hojaGrafico As String

Dim wbSource As Workbook

Dim wbDest As Workbook

Dim QvsE As Worksheet, Requisitos As Worksheet, shEC As Worksheet

Dim myTable As Range

Dim permisos As String

'Filtro

Call AbrirCarpeta(permisos)

Set wbSource = Workbooks.Open(sFileName)
If Err.Number <> 0 Then Debug.Print ("Error number en Libro Formato: " & Err.Number)
If Err.Number = 0 Then Debug.Print ("No ha habido error en libro Formato")

Set wbDest = Workbooks("Nuevo Hoja de cálculo de Microsoft Excel.xlsx")
If Err.Number <> 0 Then Debug.Print ("Error number en Nuevo hoja formato: " & Err.Number)
Workbooks("Nuevo Hoja de cálculo de Microsoft Excel.xlsx").Worksheets("Seleccion_ECs").Activate

Set shEC = wbDest.Worksheets("Seleccion_ECs")
If Err.Number <> 0 Then Debug.Print ("Error number en hoja Seleccion_ECs: " & Err.Number)

Set Requisitos = wbSource.Worksheets("Requisitos Contenedor + ATI")

Set QvsE = wbSource.Worksheets("Curva - QvsE")

'definir bien rango
Q = shEC.Range("1:1").Find(what:="BU Descarga (MWd/tU)", After:=Range("A1")).Column
E = shEC.Range("1:1").Find(what:="Enriq. [%]", After:=Range("A1")).Column
d = Requisitos.Cells(41 + Z, 4).Value
</code>```

I expect to read values from both worksheets (decimal numbers), but I don't manage to read them. For example, d returns "Empty" as the variable Requisitos is Nothing, even if I connected it to wbSource.Worksheets("Requisitos Contenedor + ATI"), cause wbSource is Nothing. What can I do so it doesn't return Nothing?
I previously have the Workbook "Nuevo Hoja de cálculo de Microsoft Excel.xlsx" Activated, but afterwards with Call AbrirCarpeta(permisos), I open the other Workbook "Formato CO-08a (rev.1).xlsx", so I suppose the last one becomes the activated workbook.
I usually have errors like 91, 92 or 1004 in Err.number.

Thanks in advance

答:
What Vincent G said helped me a lot. Seems it works now:

```<code>Call AbrirCarpeta(sFileName)

Set wbSource = Workbooks.Open(sFileName)

Debug.Print (wbSource.Name) '"Formato permisos.xlsm"

If Err.Number <> 0 Then Debug.Print ("Error number en Libro gráficas: " & Err.Number)

If Err.Number = 0 Then Debug.Print ("No ha habido error en libro gráficas")

Set Requisitos = wbSource.Worksheets("Requisitos Contenedor + ATI")
Set wbDest = ThisWorkbook 'Workbooks("Rober.xlsm")
If Err.Number <> 0 Then Debug.Print ("Error number en Libro Rober: " & Err.Number)
Set shEC = wbDest.Worksheets("Seleccion_ECs")
If Err.Number <> 0 Then Debug.Print ("Error number en hoja Seleccion_ECs: " & Err.Number)

Q = shEC.Range("1:1").Find(what:="BU Descarga (MWd/tU)", After:=Range("A1")).Column

E = shEC.Range("1:1").Find(what:="Enriq. [%]", After:=Range("A1")).Column

For i = 1 To nFilas ' Sheets("Seleccion_ECs").listaopciones.ListCount

    For Z = 0 To 6

        'Si %enriq está entre dos valores de enriquecimiento de la tabla requisitos

        If Requisitos.Cells(41 + Z, 4).Value - Requisitos.Cells(40 + Z, 4).Value = 0 Then

        Debug.Print ("Intervalo es cero:" & Requisitos.Cells(41 + Z, 2).Value & Requisitos.Cells(40 + Z, 2).Value)

         ElseIf (CDbl(shEC.Cells(i + 1, E).Value) >= Requisitos.Cells(40 + Z, 4).Value) And (CDbl(shEC.Cells(i + 1, E).Value) <= Requisitos.Cells(41 + Z, 4).Value) Then

            'Cuidado con volver a nombrar el workbook, así sale mal: wbSource.Requisitos.Cells(41 + Z, 4).Value

            m = (Requisitos.Cells(41 + Z, 2).Value - Requisitos.Cells(40 + Z, 2).Value) / (Requisitos.Cells(41 + Z, 4).Value - Requisitos.Cells(40 + Z, 4).Value)

            a = shEC.Cells(i + 1, E).Value

            y = m * (CDbl(shEC.Cells(i + 1, E).Value) - Requisitos.Cells(40 + Z, 4).Value) + Requisitos.Cells(40 + Z, 2).Value

            y_n = CDbl(shEC.Cells(i + 1, Q).Value)

            Debug.Print ("Se ha encontrado un intervalo en:")

            Debug.Print (Requisitos.Cells(41 + Z, 2).Value)

            Debug.Print (Requisitos.Cells(40 + Z, 2).Value)

            Debug.Print ("Enriquecimiento EC: " & CDbl(shEC.Cells(i + 1, E).Value))

            Debug.Print ("Quemado EC y_n: " & y_n)

            Debug.Print ("m: " & m)

            Debug.Print ("y: " & y)

            If y_n > 1.02 * y Then 'Si se sale en un 2 por ciento de la zona aceptada, se elimina la fila.

                shEC.Rows(i + 1).Delete

                Debug.Print ("Se ha eliminado un elemento")

                Exit For

            Else:

                Exit For

            End If

        End If

    Next Z

Next i
</code>```

The only thing I find a problem now is to assign a Chart Sheet called "Curva-QvsE":

```<code>Set QvsE = wbSource.Charts("Curva - QvsE")
</code>```

QvsE returns Nothing. I also tried

```<code>Set QvsE = ThisWorkbook.Charts("Curva - QvsE")
</code>```

And other forms

Thank you for all your help

Body:
I have a problem that prevents me from continuing on my task. With all variables declared, and with the two Workbooks I have to work with opened, I don't manage to make the macro read values from both workbooks. When I use Set wbSource = workbooks.open(sFileName), it returns Nothing to wbSource. The same with all other variables:

Dim nColumnas As Double

Dim nFilas As Double

Dim mec, dis, trans As Double

Dim rnData As Range

Dim i, j As Double

Dim Z As Double

Dim rango As Range

Dim hojaOrigen As String

Dim hojaDestino As String

Dim temporal As Variant

Dim N, Q, E As Long

Dim lo As ListObject

Dim op As Variant

Dim y, m, y_n As Long

Dim hojaGrafico As String

Dim wbSource As Workbook

Dim wbDest As Workbook

Dim QvsE As Worksheet, Requisitos As Worksheet, shEC As Worksheet

Dim myTable As Range

Dim permisos As String

'Filtro

Call AbrirCarpeta(permisos)

Set wbSource = Workbooks.Open(sFileName)
If Err.Number <> 0 Then Debug.Print ("Error number en Libro Formato: " & Err.Number)
If Err.Number = 0 Then Debug.Print ("No ha habido error en libro Formato")

Set wbDest = Workbooks("Nuevo Hoja de cálculo de Microsoft Excel.xlsx")
If Err.Number <> 0 Then Debug.Print ("Error number en Nuevo hoja formato: " & Err.Number)
Workbooks("Nuevo Hoja de cálculo de Microsoft Excel.xlsx").Worksheets("Seleccion_ECs").Activate

Set shEC = wbDest.Worksheets("Seleccion_ECs")
If Err.Number <> 0 Then Debug.Print ("Error number en hoja Seleccion_ECs: " & Err.Number)

Set Requisitos = wbSource.Worksheets("Requisitos Contenedor + ATI")

Set QvsE = wbSource.Worksheets("Curva - QvsE")

'definir bien rango
Q = shEC.Range("1:1").Find(what:="BU Descarga (MWd/tU)", After:=Range("A1")).Column
E = shEC.Range("1:1").Find(what:="Enriq. [%]", After:=Range("A1")).Column
d = Requisitos.Cells(41 + Z, 4).Value

I expect to read values from both worksheets (decimal numbers), but I don't manage to read them. For example, d returns "Empty" as the variable Requisitos is Nothing, even if I connected it to wbSource.Worksheets("Requisitos Contenedor + ATI"), cause wbSource is Nothing. What can I do so it doesn't return Nothing?
I previously have the Workbook "Nuevo Hoja de cálculo de Microsoft Excel.xlsx" Activated, but afterwards with Call AbrirCarpeta(permisos), I open the other Workbook "Formato CO-08a (rev.1).xlsx", so I suppose the last one becomes the activated workbook.
I usually have errors like 91, 92 or 1004 in Err.number.

Thanks in advance

Body:
What Vincent G said helped me a lot. Seems it works now:

Call AbrirCarpeta(sFileName)

Set wbSource = Workbooks.Open(sFileName)

Debug.Print (wbSource.Name) '"Formato permisos.xlsm"

If Err.Number <> 0 Then Debug.Print ("Error number en Libro gráficas: " & Err.Number)

If Err.Number = 0 Then Debug.Print ("No ha habido error en libro gráficas")

Set Requisitos = wbSource.Worksheets("Requisitos Contenedor + ATI")
Set wbDest = ThisWorkbook 'Workbooks("Rober.xlsm")
If Err.Number <> 0 Then Debug.Print ("Error number en Libro Rober: " & Err.Number)
Set shEC = wbDest.Worksheets("Seleccion_ECs")
If Err.Number <> 0 Then Debug.Print ("Error number en hoja Seleccion_ECs: " & Err.Number)

Q = shEC.Range("1:1").Find(what:="BU Descarga (MWd/tU)", After:=Range("A1")).Column

E = shEC.Range("1:1").Find(what:="Enriq. [%]", After:=Range("A1")).Column

For i = 1 To nFilas ' Sheets("Seleccion_ECs").listaopciones.ListCount

    For Z = 0 To 6

        'Si %enriq está entre dos valores de enriquecimiento de la tabla requisitos

        If Requisitos.Cells(41 + Z, 4).Value - Requisitos.Cells(40 + Z, 4).Value = 0 Then

        Debug.Print ("Intervalo es cero:" & Requisitos.Cells(41 + Z, 2).Value & Requisitos.Cells(40 + Z, 2).Value)

         ElseIf (CDbl(shEC.Cells(i + 1, E).Value) >= Requisitos.Cells(40 + Z, 4).Value) And (CDbl(shEC.Cells(i + 1, E).Value) <= Requisitos.Cells(41 + Z, 4).Value) Then

            'Cuidado con volver a nombrar el workbook, así sale mal: wbSource.Requisitos.Cells(41 + Z, 4).Value

            m = (Requisitos.Cells(41 + Z, 2).Value - Requisitos.Cells(40 + Z, 2).Value) / (Requisitos.Cells(41 + Z, 4).Value - Requisitos.Cells(40 + Z, 4).Value)

            a = shEC.Cells(i + 1, E).Value

            y = m * (CDbl(shEC.Cells(i + 1, E).Value) - Requisitos.Cells(40 + Z, 4).Value) + Requisitos.Cells(40 + Z, 2).Value

            y_n = CDbl(shEC.Cells(i + 1, Q).Value)

            Debug.Print ("Se ha encontrado un intervalo en:")

            Debug.Print (Requisitos.Cells(41 + Z, 2).Value)

            Debug.Print (Requisitos.Cells(40 + Z, 2).Value)

            Debug.Print ("Enriquecimiento EC: " & CDbl(shEC.Cells(i + 1, E).Value))

            Debug.Print ("Quemado EC y_n: " & y_n)

            Debug.Print ("m: " & m)

            Debug.Print ("y: " & y)

            If y_n > 1.02 * y Then 'Si se sale en un 2 por ciento de la zona aceptada, se elimina la fila.

                shEC.Rows(i + 1).Delete

                Debug.Print ("Se ha eliminado un elemento")

                Exit For

            Else:

                Exit For

            End If

        End If

    Next Z

Next i

The only thing I find a problem now is to assign a Chart Sheet called "Curva-QvsE":

Set QvsE = wbSource.Charts("Curva - QvsE")

QvsE returns Nothing. I also tried

Set QvsE = ThisWorkbook.Charts("Curva - QvsE")

And other forms

Thank you for all your help


问:
How to use where to query the database using mongoose
I want to create an endpoint for the user to search for something, so im querying the database using where a particular row inlcudes the text the user has searched but $where keeps giving me an error that it is not a function

I have tried using the $where but to no avail

```<code>router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const search = await Course.find()
        search.$where(function () {
            return req.params.search_text.toLowerCase().includes(this.course_name.toLowerCase())
        })
        if (!search){
            return res.status(404).send({result: 'No Result found'})
        }

        res.status(200).send({result: search})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})
</code>```

I want to be able to query the database for what the user has searched from a particular column (course_name) and return a response of the rows containing that at least three letters from the text the user searched

答:
You can directly use mongoDB $regex option in query to search your text:</p>

```<code>router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const searchedItems = await Course.find({
            course_name: {
                $regex: req.params.search_text,
                $options: 'i' // case insensitive
            }
        })
        if (!searchedItems.length){
            return res.status(404).send({result: 'No Result found'})
        }
        res.status(200).send({result: searchedItems})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})
</code>```

Body:
I want to create an endpoint for the user to search for something, so im querying the database using where a particular row inlcudes the text the user has searched but $where keeps giving me an error that it is not a function

I have tried using the $where but to no avail

router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const search = await Course.find()
        search.$where(function () {
            return req.params.search_text.toLowerCase().includes(this.course_name.toLowerCase())
        })
        if (!search){
            return res.status(404).send({result: 'No Result found'})
        }

        res.status(200).send({result: search})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})

I want to be able to query the database for what the user has searched from a particular column (course_name) and return a response of the rows containing that at least three letters from the text the user searched

Body:
You can directly use mongoDB $regex option in query to search your text:

router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const searchedItems = await Course.find({
            course_name: {
                $regex: req.params.search_text,
                $options: 'i' // case insensitive
            }
        })
        if (!searchedItems.length){
            return res.status(404).send({result: 'No Result found'})
        }
        res.status(200).send({result: searchedItems})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})


问:
How to use grep match as a variable (and not whole line)
This is the sample file

```<code>[user@linux]$ cat DeviceA
DeviceA#sh ver
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$
</code>```

Version 15.1(4)M10 will be highligted

```<code>[user@linux]$ egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$
</code>```

Using grep output as variable var

```<code>[user@linux]$ var=$(egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA)
[user@linux]$
</code>```

Print variable var

```<code>[user@linux]$ echo $var
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$
</code>```

Instead of getting the whole line as var, can I just get Version 15.1(4)M10 when executing echo $var?

Desired Output

```<code>[user@linux]$ echo $var
Version 15.1(4)M10
[user@linux]$
</code>```

答:
As mentioned by Jww, this can easily be achieved using the -o flag:

Commandline:

```<code>fgrep -o "Version 15.1(4)M10" testtttt.txt, or, for introducing variable handling:
echo $(fgrep -o "Version 15.1(4)M10" testtttt.txt)
</code>```

In a script, you might do something like (not tested):

```<code>var=$(fgrep -o "Version 15.1(4)M10" testtttt.txt)
echo $var
</code>```

Body:
This is the sample file

[user@linux]$ cat DeviceA
DeviceA#sh ver
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Version 15.1(4)M10 will be highligted

[user@linux]$ egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Using grep output as variable var

[user@linux]$ var=$(egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA)
[user@linux]$

Print variable var

[user@linux]$ echo $var
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Instead of getting the whole line as var, can I just get Version 15.1(4)M10 when executing echo $var?

Desired Output

[user@linux]$ echo $var
Version 15.1(4)M10
[user@linux]$

Body:
As mentioned by Jww, this can easily be achieved using the -o flag:

Commandline:

fgrep -o "Version 15.1(4)M10" testtttt.txt, or, for introducing variable handling:
echo $(fgrep -o "Version 15.1(4)M10" testtttt.txt)

In a script, you might do something like (not tested):

var=$(fgrep -o "Version 15.1(4)M10" testtttt.txt)
echo $var


问:
Flash Lite 3.1 + javascript
I know almost nothing about actionscript.  Is it possible for Flash Lite 3.1 to use the flash.external.ExternalInterface to allow javascript interaction?

If it is possible, can someone explain why jPlayer (open source) doesn't work on the Wii?

I have been looking for a flash mp3 player that will work on the Nintendo Wii and which supports javascript interaction (for instance, I need to be able to assign event handlers like TrackEnded() and be able to issue PlayTrack() commands) and haven't found anything.  There are many flash mp3 players out there, but none of them are able to do what I require on the Wii.  This leads me to wonder if what I'm after is not actually possible.  Is there something about Flash Lite 3.1 (which is used by the Opera browser on the Wii) that precludes javascript interaction with flash objects?

答:
The answer from ezekielDFM is wrong - i think

my understanding is that the version 3.1 flash lite plugin used in opera on the wii has a knackered externalinterface - so will not work - and there is not much you can do to fix it - so you have to work around it - though i am not sure how - maybe with localconnection...

ezekielDFM - feel free to correct me if you have actually created a swf with externalinterface and observed it to work on the wii ! - regardless of what the docs may claim

EDIT : here is a hand written replacement - though i haven't tested it
https://github.com/aadsm/customExternalInterface/blob/master/src/ExternalInterface.as

ContentLicense: CC BY-SA 2.5

Title: Flash Lite 3.1 + javascript

ContentLicense: CC BY-SA 3.0


问:
How to send request post with file and json?
I have a form to send to back-end. This form has entry fields and a file upload.

This is the send of my form.

```<code>submit () {
      console.log(this.banners)
      const banners = new FormData()
      banners.append('banners', this.banners)
      this.$axios.post(api.insertBanner, banners).then(response => response.data)
        .catch(error => {
          console.log(error)
        })
    },
</code>```

console.log results in

My method POST:

```<code>public async Task<ActionResult> Post(BannersDTO banners)
</code>```

BannersDTO.cs

```<code>public class BannersDTO
{
    public Microsoft.AspNetCore.Http.IFormFile Files { get; set; }
    public string TermoOrSku { get; set; }
    public bool InserirImediato { get; set; }
    public string DataAtivacao { get; set; }
    public string DataVigencia { get; set; }
}
</code>```

Problem: I have received status code 400(badRequest), that is, i need to modify the input because it is not correct. What is wrong?

If I modify the parts of code:

```<code>public async Task<ActionResult> Post(Microsoft.AspNetCore.Http.IFormFile Files)

banners.append('files', this.banners.files)
</code>```

My code works fine, but in the case I only get the file, and I also need the data.

答:
If you are posting with form data . Code below is for your reference :

HTML :

```<code><form >
    Email:  <input asp-for="TermoOrSku" /> <br />
    files:  <input type="file" name="Files">
</form>
<input id="Button1" type="button" value="button" onclick="Upload()" />
</code>```

JS:

```<code>@section Scripts{
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

        function Upload() {
            var data = new FormData($('form').get(0));

            axios({
                method: 'post',
                url: '/home/UploadFiles',
                data: data,
                config: { headers: { 'Content-Type': 'multipart/form-data' } }
            })
                .then(function (response) {
                    //handle success
                    console.log(response);
                })
                .catch(function (response) {
                    //handle error
                    console.log(response);
                });

        }
    </script>

}
</code>```

On controller side , you can get the data including the file and other input values :

```<code>[HttpPost]
public ActionResult UploadFiles(BannersDTO model)
{
    // to do : read values of model and use it
    // to do : return something
    return View();
}
</code>```

Body:
I have a form to send to back-end. This form has entry fields and a file upload.

This is the send of my form.

submit () {
      console.log(this.banners)
      const banners = new FormData()
      banners.append('banners', this.banners)
      this.$axios.post(api.insertBanner, banners).then(response => response.data)
        .catch(error => {
          console.log(error)
        })
    },

console.log results in

My method POST:

public async Task<ActionResult> Post(BannersDTO banners)

BannersDTO.cs

public class BannersDTO
{
    public Microsoft.AspNetCore.Http.IFormFile Files { get; set; }
    public string TermoOrSku { get; set; }
    public bool InserirImediato { get; set; }
    public string DataAtivacao { get; set; }
    public string DataVigencia { get; set; }
}

Problem: I have received status code 400(badRequest), that is, i need to modify the input because it is not correct. What is wrong?

If I modify the parts of code:

public async Task<ActionResult> Post(Microsoft.AspNetCore.Http.IFormFile Files)

banners.append('files', this.banners.files)

My code works fine, but in the case I only get the file, and I also need the data.

Body:
If you are posting with form data . Code below is for your reference :

HTML :

<form >
    Email:  <input asp-for="TermoOrSku" /> <br />
    files:  <input type="file" name="Files">
</form>
<input id="Button1" type="button" value="button" onclick="Upload()" />

JS:

@section Scripts{
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

        function Upload() {
            var data = new FormData($('form').get(0));

            axios({
                method: 'post',
                url: '/home/UploadFiles',
                data: data,
                config: { headers: { 'Content-Type': 'multipart/form-data' } }
            })
                .then(function (response) {
                    //handle success
                    console.log(response);
                })
                .catch(function (response) {
                    //handle error
                    console.log(response);
                });

        }
    </script>

}

On controller side , you can get the data including the file and other input values :

[HttpPost]
public ActionResult UploadFiles(BannersDTO model)
{
    // to do : read values of model and use it
    // to do : return something
    return View();
}


问:
Launch UWP app from Windows Form - entry point?
I have two projects in my VS2013 solution:

A UWP app that consumes/produces data from/to  local json files

this gets sideloaded and works a treat

A Windows Form that gets the data from a remote server
        with Web Services

I want a button on my Form to launch the UWP app once the data is fetched.
(I cannot integrate the two as the webservice authentication libraries won't work with W8.1 )

This method launches only my UWP splash screen however. It doesn't get into the code.

```<code> Process.Start("MyUWPApp:");
</code>```

Do I need something like this:

```<code> Process.Start("MyUWPApp:MyEntryPoint");
</code>```

Where MyEntryPoint is going to go in the Manifest File on the UWP? I've been trying out all sorts of values for  MyentryPoint in the file like:
App, MainPage.cs, Main() etc.. I'm not sure if this is the way to go.. anyone?

答:
The below code helps for me.Add the code in App.Xaml.cs file.</p>

```<code>protected override void OnActivated(IActivatedEventArgs args)
    {
        Initialize(args);
        if (args.Kind == ActivationKind.Protocol)
        {
            ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            // Always navigate for a protocol launch
            rootFrame.Navigate(typeof(MainPage), eventArgs.Uri.AbsoluteUri);
            // Ensure the current window is active
            Window.Current.Activate();
        }
    }
</code>```

Body:
I have two projects in my VS2013 solution:

A UWP app that consumes/produces data from/to  local json files

this gets sideloaded and works a treat

A Windows Form that gets the data from a remote server
        with Web Services

I want a button on my Form to launch the UWP app once the data is fetched.
(I cannot integrate the two as the webservice authentication libraries won't work with W8.1 )

This method launches only my UWP splash screen however. It doesn't get into the code.

 Process.Start("MyUWPApp:");

Do I need something like this:

 Process.Start("MyUWPApp:MyEntryPoint");

Where MyEntryPoint is going to go in the Manifest File on the UWP? I've been trying out all sorts of values for  MyentryPoint in the file like:
App, MainPage.cs, Main() etc.. I'm not sure if this is the way to go.. anyone?

Body:
The below code helps for me.Add the code in App.Xaml.cs file.

protected override void OnActivated(IActivatedEventArgs args)
    {
        Initialize(args);
        if (args.Kind == ActivationKind.Protocol)
        {
            ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            // Always navigate for a protocol launch
            rootFrame.Navigate(typeof(MainPage), eventArgs.Uri.AbsoluteUri);
            // Ensure the current window is active
            Window.Current.Activate();
        }
    }


Title: How to create a pivot table with columns to rows and rows to columns using mysql

Body:
Got a table in mysql with the below columns and rows

Table1
-------------------------------------------------------------
date_time           Place         Cat 1 Cat 2   Cat 3
-------------------------------------------------------------
5/14/2019 3:54           FUJ                     Yes
5/14/2019 4:19           FUJ                Yes      Yes
5/15/2019 1:22           FUJ                     Yes
5/14/2019 11:08          MUM            Yes Yes
5/15/2019  16:34:00 PM   MUM                     Yes

Need help in getting a pivot table as below desired output

Places  Categories  5/14/2019   5/15/2019
-------------------------------------------------------------
FUJ Cat 1               0               0
    Cat 2               1               0
    Cat 3               2               1
MUM Cat 1               1               0
    Cat 2               1               0
    Cat 3               0               1

Thank you in advance...

Body:
A better schema might look as follows:

-----------------------------
date_time           Place Cat
-----------------------------
2019-05-14 03:54:00 FUJ     3
2019-05-14 04:19:00 FUJ     1
2019-05-14 04:19:00 FUJ     3
2019-05-15 01:22:00 FUJ     2
2019-05-14 11:08:00 MUM     1
2019-05-14 11:08:00 MUM     2
2019-05-15 16:34:00 MUM     3

This isn't an answer, but it is a better place to start; the rest of the problem would ordinarily be solved in your application code/presentation layer (i.e. php)


问:
Styling a Twitter feed - CSS won't target .timeline-Tweet-text
I'm bringing a Twitter feed through to my site using the following code which is described on https://publish.twitter.com/

```<code><a class="twitter-timeline" href="https://twitter.com/ACCOUNT-HERE" data-tweet-limit="3">Tweets by</a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</code>```

The feed is displayed correctly. However it uses CSS which is provided via Twitter.

When I inspect it using Chrome dev tools I can see the following classes around the Tweets:

```<code><p class="timeline-Tweet-text" lang="en" dir="ltr">
</code>```

So I thought it would be a simple case of targetting this in CSS, e.g.

```<code>.timeline-Tweet-text {
}
</code>```

However, this doesn't apply any styles to the Tweets. Why not?

I have also referred to Twitters guidance on this here https://dev.twitter.com/web/overview/css but that also doesn't work.

The only reason I want to do this is so the font used within the widget matches the font used by the rest of the body text on my website.

答:
I have implemented a simple solution in my project recently, you can customize all kinds of styles to have it fit in seamlessly with your website branding. </p>

```<code>jQuery('.twitter-block').delegate('#twitter-widget-0','DOMSubtreeModified propertychange', function() {
    //function call to override the base twitter styles
    customizeTweetMedia();
});

var customizeTweetMedia = function() {

    // overrides font styles and removes the profile picture and media from twitter feed
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-media').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('img.Avatar').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-avatar.Identity-avatar').remove();

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-family', "'Proxima Nova', lato, sans-serif");

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-family', "'Proxima Nova', lato, sans-serif");

    // also call the function on dynamic updates in addition to page load
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-TweetList').bind('DOMSubtreeModified propertychange', function() {
        customizeTweetMedia(this);
    });
}
</code>```

<p>Link to my complete example </p>

Body:
I'm bringing a Twitter feed through to my site using the following code which is described on https://publish.twitter.com/

Tweets by

The feed is displayed correctly. However it uses CSS which is provided via Twitter.

When I inspect it using Chrome dev tools I can see the following classes around the Tweets:

So I thought it would be a simple case of targetting this in CSS, e.g.

.timeline-Tweet-text {
}

However, this doesn't apply any styles to the Tweets. Why not?

I have also referred to Twitters guidance on this here https://dev.twitter.com/web/overview/css but that also doesn't work.

The only reason I want to do this is so the font used within the widget matches the font used by the rest of the body text on my website.

Body:
I have implemented a simple solution in my project recently, you can customize all kinds of styles to have it fit in seamlessly with your website branding.

jQuery('.twitter-block').delegate('#twitter-widget-0','DOMSubtreeModified propertychange', function() {
    //function call to override the base twitter styles
    customizeTweetMedia();
});

var customizeTweetMedia = function() {

    // overrides font styles and removes the profile picture and media from twitter feed
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-media').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('img.Avatar').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-avatar.Identity-avatar').remove();

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-family', "'Proxima Nova', lato, sans-serif");

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-family', "'Proxima Nova', lato, sans-serif");

    // also call the function on dynamic updates in addition to page load
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-TweetList').bind('DOMSubtreeModified propertychange', function() {
        customizeTweetMedia(this);
    });
}

Link to my complete example


问:
Read from App.config in a Class Library project
I am developing a simple class library project, which will give me a dll.

I wanted a particular value to be read from a config file. So I have added an App.config file to my project.

```<code> <?xml version="1.0" encoding="utf-8" ?>
 <configuration>

  <appSettings>
  <add key="serviceUrl" value="test value" />
  </appSettings>

  </configuration>
</code>```

Above is my App.config file, and now I am trying to read it as following

```<code>  string strVal = System.Configuration.ConfigurationManager.AppSettings["serviceUrl"];
</code>```

But I am not getting any value in my string variable.

I had done this for a web application in a similar way and it worked.
But somehow I am not able to get this working.

Is the idea of having App.config in a class library project correct in the first place ?

答:
Solved

I have encountered this issue. What I did is below.

This is what code look likes

App.config

From Class Library

Body:
I am developing a simple class library project, which will give me a dll.

I wanted a particular value to be read from a config file. So I have added an App.config file to my project.

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>

  <appSettings>
  <add key="serviceUrl" value="test value" />
  </appSettings>

  </configuration>

Above is my App.config file, and now I am trying to read it as following

  string strVal = System.Configuration.ConfigurationManager.AppSettings["serviceUrl"];

But I am not getting any value in my string variable.

I had done this for a web application in a similar way and it worked.
But somehow I am not able to get this working.

Is the idea of having App.config in a class library project correct in the first place ?


问:
Opencms change directory of site
I have opencms 10.5.4, tomcat 8.5.37.

I have a site "localhost:8080", now i have to move the site to "localhost:8080/mydirectory"

I tried to change opencms-system.xml

```<code><sites>
            <workplace-server>http://localhost:8080/mydirectory</workplace-server>
            <default-uri>/sites/default/</default-uri>
            <shared-folder>/shared/</shared-folder>
            <site server="http://localhost:8080" uri="/sites/default/" title="Demo Site" position="3.4028235E38" webserver="true">
                <parameters>
                    <param name="locale.main">it</param>
                    <param name="locale.secondary">en</param>
                </parameters>
            </site>
        </sites>
</code>```

I restarted catalina but nothing happens.

What is the best way to change domain url without breaking the links of the css and files that are in the modules?

答:
I am not sure what you want to achieve. If you just want to access your website through an additional folder to let's say distinguish from other sites you could just create a folder within the OpenCms workplace and move all your content to that folder.
Create the folder in the root directory of your site (e. g. /sites/default/mydirectory/).

Changes to opencms-system.xml are not necessary for this. So please remove mydirectoryfrom your workplace-server configuration.

HTH

Best regards

Kai

Title: Opencms change directory of site

Body:
I have opencms 10.5.4, tomcat 8.5.37.

I have a site "localhost:8080", now i have to move the site to "localhost:8080/mydirectory"

I tried to change opencms-system.xml

<sites>
            <workplace-server>http://localhost:8080/mydirectory</workplace-server>
            <default-uri>/sites/default/</default-uri>
            <shared-folder>/shared/</shared-folder>
            <site server="http://localhost:8080" uri="/sites/default/" title="Demo Site" position="3.4028235E38" webserver="true">
                <parameters>
                    <param name="locale.main">it</param>
                    <param name="locale.secondary">en</param>
                </parameters>
            </site>
        </sites>

I restarted catalina but nothing happens.

What is the best way to change domain url without breaking the links of the css and files that are in the modules?


问:
Where i can check the main standards for making android user interfaces?
i need a link where i can read and understand the main standards to follow where making android user interfaces

i can't find it on google

thanks

答:
Probably related and useful: How can I improve the look and feel of an Android app?

Lots of useful links listed there.


问:
how to write SQL Query in cakephp?
```<code>select campaign,lead_status,COUNT(id)
from buyers
where lead_status IN('Very Hot','Hot', 'Warm', 'Cold', 'Not Contacted')
    and campaign IN('stage1','stage2','stage3','stage4') and created_on >='2012-10-01'
    and is_put_for_exchange='0' and transaction_type='First Sale'
    and propertytype='Residential'
group by campaign,lead_status
ORDER BY campaign asc, field(lead_status,'Very Hot','Hot', 'Warm', 'Cold', 'Not Contacted')
</code>```

convert in cakephp Syntax plz It Argent?

答:
For reference to others, this query will be look like this if we convert into CakePHP method</p>

```<code>$result = $this->ModelName->find("all",array(
    'fields' => array('campaign','lead_status','count(id') as counts),
    'conditions' => array(
        'lead_status' => array('Very Hot','Hot', 'Warm', 'Cold', 'Not Contacted'),
        'campaign' => array('stage1','stage2','stage3','stage4'),
        "created_on >='2012-10-01' ",
        'is_put_for_exchange' => 0,
        'transaction_type' => 'First Sale',
        'propertytype' => 'Residential'
    ),
    'group' => array('Buyer.campaign','Buyer.lead_status'),
    'order' => 'Buyer.campaign'
));
</code>```

Title: how to write SQL Query in cakephp?

Body:
select campaign,lead_status,COUNT(id)
from buyers
where lead_status IN('Very Hot','Hot', 'Warm', 'Cold', 'Not Contacted')
    and campaign IN('stage1','stage2','stage3','stage4') and created_on >='2012-10-01'
    and is_put_for_exchange='0' and transaction_type='First Sale'
    and propertytype='Residential'
group by campaign,lead_status
ORDER BY campaign asc, field(lead_status,'Very Hot','Hot', 'Warm', 'Cold', 'Not Contacted')

convert in cakephp Syntax plz It Argent?

Body:
For reference to others, this query will be look like this if we convert into CakePHP method

$result = $this->ModelName->find("all",array(
    'fields' => array('campaign','lead_status','count(id') as counts),
    'conditions' => array(
        'lead_status' => array('Very Hot','Hot', 'Warm', 'Cold', 'Not Contacted'),
        'campaign' => array('stage1','stage2','stage3','stage4'),
        "created_on >='2012-10-01' ",
        'is_put_for_exchange' => 0,
        'transaction_type' => 'First Sale',
        'propertytype' => 'Residential'
    ),
    'group' => array('Buyer.campaign','Buyer.lead_status'),
    'order' => 'Buyer.campaign'
));


问:
strange class behavior in the python pattern decorator
I want to impose a Berserk effect on the hero.
Abstract classes: AbstractEffect and AbstractPositive (class heir), can accept the base parameter. Next, AbstractNegative will also be created. I am not sure whether the inheritance scheme is correct (Hero ---> AbstractEffect).

```<code>from abc import ABC, abstractmethod
class Hero:
    def __init__(self):
        self.stats = {"HP": 128}
    def get_stats(self):
        return self.stats.copy()

class AbstractEffect(ABC):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class AbstractPositive(AbstractEffect):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class Berserk(AbstractPositive):
    def __init__(self, base):
        self.base = base
        self.stats= self.base.stats
        self.stats["HP"] += 7
    def get_stats(self):
        return self.stats

hero = Hero()
brs1 = Berserk(hero)
print('brs1', brs1.get_stats())
brs2 = Berserk(brs1)
print('brs2', brs2.get_stats())
print('brs1', brs1.get_stats())
</code>```

I want to receive

```<code>brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 135}
</code>```

but I get

```<code>brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 142}
</code>```

what's my mistake?

答:
bacause of the following code

self.stats = {"HP": 128}
```

<p>{"HP": 128} is a container<br>
and,</p>

<pre class="lang-py prettyprint-override"><code>self.stats = self.base.stats
</code>```

Therefore,

when you use Berserk(heroxxx) to enhance hero, self.stats["HP"] += 7 is actually modifying the original data. So you need to change it to self.stats = self.base.get_stats(),then you can get what you want. You can use the following code to test.

from abc import ABC, abstractmethod
class Hero:
    def __init__(self):
        self.stats = {"HP": 128}
    def get_stats(self):
        return self.stats.copy()

class AbstractEffect(ABC):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats

class AbstractPositive(AbstractEffect):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats

class Berserk(AbstractPositive):
    def __init__(self, base):
        self.base = base
        self.stats = self.base.get_stats()
        self.stats["HP"] += 7

    def get_stats(self):
        return self.stats.copy()

hero = Hero()
brs1 = Berserk(hero)
print('brs1', brs1.get_stats())
brs2 = Berserk(brs1)
print('brs2', brs2.get_stats())
print('brs1', brs1.get_stats())
```

Body:
I want to impose a Berserk effect on the hero.
Abstract classes: AbstractEffect and AbstractPositive (class heir), can accept the base parameter. Next, AbstractNegative will also be created. I am not sure whether the inheritance scheme is correct (Hero ---> AbstractEffect).

from abc import ABC, abstractmethod
class Hero:
    def __init__(self):
        self.stats = {"HP": 128}
    def get_stats(self):
        return self.stats.copy()

class AbstractEffect(ABC):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class AbstractPositive(AbstractEffect):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class Berserk(AbstractPositive):
    def __init__(self, base):
        self.base = base
        self.stats= self.base.stats
        self.stats["HP"] += 7
    def get_stats(self):
        return self.stats

hero = Hero()
brs1 = Berserk(hero)
print('brs1', brs1.get_stats())
brs2 = Berserk(brs1)
print('brs2', brs2.get_stats())
print('brs1', brs1.get_stats())

I want to receive

brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 135}

but I get

brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 142}

what's my mistake?

Body:
bacause of the following code

self.stats = {"HP": 128}

{"HP": 128} is a container

and,

self.stats = self.base.stats

Therefore,

when you use Berserk(heroxxx) to enhance hero, self.stats["HP"] += 7 is actually modifying the original data. So you need to change it to self.stats = self.base.get_stats(),then you can get what you want. You can use the following code to test.

from abc import ABC, abstractmethod
class Hero:
    def __init__(self):
        self.stats = {"HP": 128}
    def get_stats(self):
        return self.stats.copy()

class AbstractEffect(ABC):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats

class AbstractPositive(AbstractEffect):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats

class Berserk(AbstractPositive):
    def __init__(self, base):
        self.base = base
        self.stats = self.base.get_stats()
        self.stats["HP"] += 7

    def get_stats(self):
        return self.stats.copy()

hero = Hero()
brs1 = Berserk(hero)
print('brs1', brs1.get_stats())
brs2 = Berserk(brs1)
print('brs2', brs2.get_stats())
print('brs1', brs1.get_stats())


问:
Rolebinding with ClusterRole is not restricted to namespace when using a ServiceAccount
I want to set a serviceaccount authorizations by associating it to a clusterRole but restricted to a namespace using a rolebinding.

I declared one clusterrole and I configured a rolebinding in a namespace pointing to that clusterrole.
However when I access the cluster with the serviceaccount token defined in the rolebinding I'm not restricted to the namespace.

On the other hand, when I'm accessing the cluster with a "User" certificate, this is working. I have only access to the namespace.

Kubernetes v1.13.5

The Rolebinding I defined:

```<code>apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: exploitant
  namespace: myNamespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: view
subjects:
- kind: ServiceAccount
  name: default
  namespace: myNamespace
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: myUser
</code>```

This is what I get:

kubectl auth can-i --token=XXXXXXXX get po -n myNamespace
yes
```

<p>--> as expected</p>

<pre class="lang-sh prettyprint-override"><code>kubectl auth can-i --token=XXXXXXXX get po -n kube-system
yes
</code>```

--> not expected !!!

答: The solution is to create a specific ServiceAccount. The "default" serviceAccount should not be used. By default all pods run with the default service account (if you dont specify one). So, the default service account exist in all namespace, so default service account can read pods in all namespace. </p>

Body:
I want to set a serviceaccount authorizations by associating it to a clusterRole but restricted to a namespace using a rolebinding.

I declared one clusterrole and I configured a rolebinding in a namespace pointing to that clusterrole.
However when I access the cluster with the serviceaccount token defined in the rolebinding I'm not restricted to the namespace.

On the other hand, when I'm accessing the cluster with a "User" certificate, this is working. I have only access to the namespace.

Kubernetes v1.13.5

The Rolebinding I defined:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: exploitant
  namespace: myNamespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: view
subjects:
- kind: ServiceAccount
  name: default
  namespace: myNamespace
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: myUser

This is what I get:

kubectl auth can-i --token=XXXXXXXX get po -n myNamespace
yes

--> as expected

kubectl auth can-i --token=XXXXXXXX get po -n kube-system
yes

--> not expected !!!


问:
CodeIgniter - Code repetition and passing variables to functions
I have the following code in a controller:

```<code><?php

class Student extends CI_Controller
{

function index()
{
    $data = $this->init->set();

    $this->parser->parse('include/header', $data);
    $this->parser->parse('student/student_index', $data);
    $this->parser->parse('include/footer', $data);
}

function planner()
{
    $data = $this->init->set();

    $this->parser->parse('include/header', $data);
    $this->parser->parse('student/student_cal', $data);
    $this->parser->parse('include/footer', $data);
}

}
?>
</code>```

As you can see, there's a lot of repetition here. Basically all of it. I already put my variables in a model so I only have to call the model function each time instead of putting the whole $data array at the start of each function. Anyway, I tried to reduce the repetition here by doing the following:

```<code><?php

class Student extends CI_Controller
{

function index()
{
    $data = $this->init->set();

    $this->parser->parse('include/header', $data);

    switch($this->uri->segment(2))
    {
        case '': $this->home($data); break;
        case 'planner': $this->planner($data); break;
    }
    $this->parser->parse('include/footer', $data);
}

function home($data)
{
    $this->parser->parse('student/student_index', $data);
}

function planner($data)
{
    $this->parser->parse('student/student_cal', $data);
}

}
?>
</code>```

This, somehow, works fine for my homepage. It parses the variables and there's no problem whatsoever. However, on the 'planner' page, I get errors:

Message: Missing argument 1 for Student::planner()

Message: Undefined variable: data

Message: Invalid argument supplied for foreach()

I'm quite sure I get these errors because the function somehow doesn't receive the $data array. I also read in the CI docs that the third segment in a URL gets passed as argument, and in this case the third segment is non-existent, thus nothing gets passed. However, the CI docs didn't tell me how I could pass my $data array from the index() function to my planner() function. I also wonder why the home function works fine, without errors.

答:
Now, I don't see the reason for that refactoring if it's going to make the code really hard to look at. I'm not entirely sure what the parse function does, so the way I changed it was to actually pass the parameter as a string, but preferably I'd load the content into a buffer and pass it in that way. But here's some cleaner and hopefully readable removable of the duplication... and hopefully it works :).</p>

```<code>

class Student extends CI_Controller
{

  private function load_student_page($content){
      $data = $this->init->set();

      $this->parser->parse('include/header', $data);
      $this->parser->parse($content, $data);
      $this->parser->parse('include/footer', $data);

  }

  function index()
  {
    $this->load_student_page('student/student_index');
  }

  function planner()
  {
    $this->load_student_page('student/student_cal');
  }

}
</code>```

Body:
I have the following code in a controller:

<?php

class Student extends CI_Controller
{

function index()
{
    $data = $this->init->set();

    $this->parser->parse('include/header', $data);
    $this->parser->parse('student/student_index', $data);
    $this->parser->parse('include/footer', $data);
}

function planner()
{
    $data = $this->init->set();

    $this->parser->parse('include/header', $data);
    $this->parser->parse('student/student_cal', $data);
    $this->parser->parse('include/footer', $data);
}

}
?>

As you can see, there's a lot of repetition here. Basically all of it. I already put my variables in a model so I only have to call the model function each time instead of putting the whole $data array at the start of each function. Anyway, I tried to reduce the repetition here by doing the following:

<?php

class Student extends CI_Controller
{

function index()
{
    $data = $this->init->set();

    $this->parser->parse('include/header', $data);

    switch($this->uri->segment(2))
    {
        case '': $this->home($data); break;
        case 'planner': $this->planner($data); break;
    }
    $this->parser->parse('include/footer', $data);
}

function home($data)
{
    $this->parser->parse('student/student_index', $data);
}

function planner($data)
{
    $this->parser->parse('student/student_cal', $data);
}

}
?>

This, somehow, works fine for my homepage. It parses the variables and there's no problem whatsoever. However, on the 'planner' page, I get errors:

Message: Missing argument 1 for Student::planner()

Message: Undefined variable: data

Message: Invalid argument supplied for foreach()

I'm quite sure I get these errors because the function somehow doesn't receive the $data array. I also read in the CI docs that the third segment in a URL gets passed as argument, and in this case the third segment is non-existent, thus nothing gets passed. However, the CI docs didn't tell me how I could pass my $data array from the index() function to my planner() function. I also wonder why the home function works fine, without errors.

Body:
Now, I don't see the reason for that refactoring if it's going to make the code really hard to look at. I'm not entirely sure what the parse function does, so the way I changed it was to actually pass the parameter as a string, but preferably I'd load the content into a buffer and pass it in that way. But here's some cleaner and hopefully readable removable of the duplication... and hopefully it works :).

class Student extends CI_Controller
{

  private function load_student_page($content){
      $data = $this->init->set();

      $this->parser->parse('include/header', $data);
      $this->parser->parse($content, $data);
      $this->parser->parse('include/footer', $data);

  }

  function index()
  {
    $this->load_student_page('student/student_index');
  }

  function planner()
  {
    $this->load_student_page('student/student_cal');
  }

}


问:
Formatting in netbeans?
I want to know how can I configure my netbeans ide to format my code in my specific need.
I need all my assignment in same line to easily distinguish it.
for eg:</p>

```<code> $a    = 1;
 $b    = 1;
 $c    = 1;
 $a++;
 some code

 $d    = 1;
</code>```

答: Formatting in NetBeans can be configured under "Tools / Options / Editor / Formatting", but I don't think that you can configure NetBeans to use your desired format.

Title: Formatting in netbeans?

Body:
I want to know how can I configure my netbeans ide to format my code in my specific need.
I need all my assignment in same line to easily distinguish it.
for eg:

 $a    = 1;
 $b    = 1;
 $c    = 1;
 $a++;
 some code

 $d    = 1;


问:
Login even after wrong creditionals flutter firebase
i get navigate to the home page even i entered the wrong credentials. i get the error that 'no user fond' but how to stop it.</p>

```<code>signIn() async {
    if (formkey.currentState.validate()) {
        formkey.currentState.save();
        try {
            _auth.signInWithEmailAndPassword(email: email, password: password);
            Navigator.push(context, MaterialPageRoute(builder: (context)=> Home()));
        } catch (e) {
            print(e.message);
        }
    }
}
</code>```

答:
There are 2 solutions, one is

```<code>signIn() async {
  if (formkey.currentState.validate()) {
    formkey.currentState.save();
    try {
      FirebaseUser user = await _auth.signInWithEmailAndPassword(email: email, password: password);

      if (user != null && await user.getIdToken() != null) {
        final FirebaseUser currentUser = await auth.currentUser();
        if (currentUser.uid == user.uid) {
          print("Success in signing, you can now navigate");
          Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
        }
      }
    } catch (e) {
      print(e.message);
    }
  }
}
</code>```

other is (thanks to Frank)

```<code>signIn() async {
  if (formkey.currentState.validate()) {
    formkey.currentState.save();
    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(email: "nope@stackhack.com", password: "secret");
      print("Signed in, you may want to navigate now");
      Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
    }
    catch (e) {
      if (e.code == "ERROR_USER_NOT_FOUND") {
        print("User not found");
      }
    }
  }
}
</code>```

Body:
i get navigate to the home page even i entered the wrong credentials. i get the error that 'no user fond' but how to stop it.

signIn() async {
    if (formkey.currentState.validate()) {
        formkey.currentState.save();
        try {
            _auth.signInWithEmailAndPassword(email: email, password: password);
            Navigator.push(context, MaterialPageRoute(builder: (context)=> Home()));
        } catch (e) {
            print(e.message);
        }
    }
}

Body:
There are 2 solutions, one is

signIn() async {
  if (formkey.currentState.validate()) {
    formkey.currentState.save();
    try {
      FirebaseUser user = await _auth.signInWithEmailAndPassword(email: email, password: password);

      if (user != null && await user.getIdToken() != null) {
        final FirebaseUser currentUser = await auth.currentUser();
        if (currentUser.uid == user.uid) {
          print("Success in signing, you can now navigate");
          Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
        }
      }
    } catch (e) {
      print(e.message);
    }
  }
}

other is (thanks to Frank)

signIn() async {
  if (formkey.currentState.validate()) {
    formkey.currentState.save();
    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(email: "nope@stackhack.com", password: "secret");
      print("Signed in, you may want to navigate now");
      Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
    }
    catch (e) {
      if (e.code == "ERROR_USER_NOT_FOUND") {
        print("User not found");
      }
    }
  }
}


问:
Numpy Zero Padding to match a certain shape
I have a file with arrays or different shapes. I want to zeropad all the array to match the largest shape. The largest shape is (93,13).

To test this I have the following code:

```<code>testarray = np.ones((41,13))
</code>```

how can I zero pad this array to match the shape of (93,13)? And ultimately, how can I do it for thousands of rows?

Edit: The solution was found in the comments:

```<code>for index, array in enumerate(mfcc):
    testarray = np.zeros((93,13))
    for index,row in enumerate(array):
        for i in range(0,len(row)-1):
            testarray[index][i]= row[i]
            mfcc[index] = testarray
</code>```

答:
If you want to pad to the right and to the bottom of your original array in 2D, here's what you want:

```<code>import numpy as np
a = np.ones((41,11))

desired_rows = 91
desired_cols = 13
b = np.pad(a, ((0, desired_rows-a.shape[0]), (0, desired_cols-a.shape[1])), 'constant', constant_values=0)
print(b)
"""
prints
[[1. 1. 1. ... 1. 0. 0.]
 [1. 1. 1. ... 1. 0. 0.]
 [1. 1. 1. ... 1. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]
"""
</code>```

Of course it's not error-proof solution, e.g. if your desired number of rows or columns is smaller than corresponding size of the original array, you'll get ValueError: index can't contain negative values.

Body:
I have a file with arrays or different shapes. I want to zeropad all the array to match the largest shape. The largest shape is (93,13).

To test this I have the following code:

testarray = np.ones((41,13))

how can I zero pad this array to match the shape of (93,13)? And ultimately, how can I do it for thousands of rows?

Edit: The solution was found in the comments:

for index, array in enumerate(mfcc):
    testarray = np.zeros((93,13))
    for index,row in enumerate(array):
        for i in range(0,len(row)-1):
            testarray[index][i]= row[i]
            mfcc[index] = testarray

Body:
If you want to pad to the right and to the bottom of your original array in 2D, here's what you want:

import numpy as np
a = np.ones((41,11))

desired_rows = 91
desired_cols = 13
b = np.pad(a, ((0, desired_rows-a.shape[0]), (0, desired_cols-a.shape[1])), 'constant', constant_values=0)
print(b)
"""
prints
[[1. 1. 1. ... 1. 0. 0.]
 [1. 1. 1. ... 1. 0. 0.]
 [1. 1. 1. ... 1. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]
"""

Of course it's not error-proof solution, e.g. if your desired number of rows or columns is smaller than corresponding size of the original array, you'll get ValueError: index can't contain negative values.