问:
free(): invalid pointer Aborted (core dumped)
I-m trying to run my python program it seems that it should run smoothly however I encounter an error that I haven't seen before it says:

```<code>free(): invalid pointer
Aborted (core dumped)
</code>```

However I'm not sure how to try and fix error since it doesn't give me too much information about the problem itself.

At first I thought it should be a problem with the sizes of the tensor in my network however they are completely fine. I've google the problem a little and found that I can see that is a problem with allocating memory where I shouldn't, but I don't know how to fix this problem

My code is divided in two different files, and I use two libraries to be able to use Sinkhorn loss function and make sample randomly a mesh.

import argparse
import point_cloud_utils as pcu
import time

import numpy as np
import torch
import torch.nn as nn
from fml.nn import SinkhornLoss

import common
def main():
    # x is a tensor of shape [n, 3] containing the positions of the vertices that
    x = torch._C.from_numpy(common.loadpointcloud("sphere.txt"))
    # t is a tensor of shape [n, 3] containing a set of nicely distributed samples in the unit cube
    v, f = common.unit_cube()
    t = torch._C.sample_mesh_lloyd(pcu.lloyd(v,f,x.shape[0]).astype(np.float32)) # sample randomly a point cloud (cube for now?)

    # The model is a simple fully connected network mapping a 3D parameter point to 3D
    phi = common.MLP(in_dim=3, out_dim=3)

    # Eps is 1/lambda and max_iters is the maximum number of Sinkhorn iterations to do
    emd_loss_fun = SinkhornLoss(eps=1e-3, max_iters=20,
                                stop_thresh=1e-3, return_transport_matrix=True)

    mse_loss_fun = torch.nn.MSELoss()

    # Adam optimizer at first
    optimizer = torch.optim.Adam(phi.parameters(), lr= 10e-3)

    fit_start_time = time.time()

    for epoch in range(100):
        optimizer.zero_grad()

        # Do the forward pass of the neural net, evaluating the function at the parametric points
        y = phi(t)

        # Compute the Sinkhorn divergence between the reconstruction*(using the francis library) and the target
        # NOTE: The Sinkhorn function expects a batch of b point sets (i.e. tensors of shape [b, n, 3])
        # since we only have 1, we unsqueeze so x and y have dimension [1, n, 3]
        with torch.no_grad():
            _, P = emd_loss_fun(phi(t).unsqueeze(0), x.unsqueeze(0))

        # Project the transport matrix onto the space of permutation matrices and compute the L-2 loss
        # between the permuted points
        loss = mse_loss_fun(y[P.squeeze().max(0)[1], :], x)
        # loss = mse_loss_fun(P.squeeze() @ y,  x)  # Use the transport matrix directly

        # Take an optimizer step
        loss.backward()
        optimizer.step()

        print("Epoch %d, loss = %f" % (epoch, loss.item()))

    fit_end_time = time.time()

    print("Total time = %f" % (fit_end_time - fit_start_time))
    # Plot the ground truth, reconstructed points, and a mesh representing the fitted function, phi
    common.visualitation(x,t,phi)

if __name__ == "__main__":
    main()
```

The error message is:
free(): invalid pointer
Aborted (core dumped)

That again doesn't help me that much. I'll appreciate it a lot if someone has any idea what is happening or if you know more about this error.

答:
Edit: The cause is actually known. The recommended solution is to build both packages from source.

There is a known issue with importing both open3d and PyTorch. The cause is unknown. https://github.com/pytorch/pytorch/issues/19739

A few possible workarounds exist:

(1) Some people have found that changing the order in which you import the two packages can resolve the issue, though in my personal testing both ways crash.

(2) Other people have found compiling both packages from source to help.

(3) Still others have found that moving open3d and PyTorch to be called from separate scripts resolves the issue.

Body:
I-m trying to run my python program it seems that it should run smoothly however I encounter an error that I haven't seen before it says:

free(): invalid pointer
Aborted (core dumped)

However I'm not sure how to try and fix error since it doesn't give me too much information about the problem itself.

At first I thought it should be a problem with the sizes of the tensor in my network however they are completely fine. I've google the problem a little and found that I can see that is a problem with allocating memory where I shouldn't, but I don't know how to fix this problem

My code is divided in two different files, and I use two libraries to be able to use Sinkhorn loss function and make sample randomly a mesh.

import argparse
import point_cloud_utils as pcu
import time

import numpy as np
import torch
import torch.nn as nn
from fml.nn import SinkhornLoss

import common
def main():
    # x is a tensor of shape [n, 3] containing the positions of the vertices that
    x = torch._C.from_numpy(common.loadpointcloud("sphere.txt"))
    # t is a tensor of shape [n, 3] containing a set of nicely distributed samples in the unit cube
    v, f = common.unit_cube()
    t = torch._C.sample_mesh_lloyd(pcu.lloyd(v,f,x.shape[0]).astype(np.float32)) # sample randomly a point cloud (cube for now?)

    # The model is a simple fully connected network mapping a 3D parameter point to 3D
    phi = common.MLP(in_dim=3, out_dim=3)

    # Eps is 1/lambda and max_iters is the maximum number of Sinkhorn iterations to do
    emd_loss_fun = SinkhornLoss(eps=1e-3, max_iters=20,
                                stop_thresh=1e-3, return_transport_matrix=True)

    mse_loss_fun = torch.nn.MSELoss()

    # Adam optimizer at first
    optimizer = torch.optim.Adam(phi.parameters(), lr= 10e-3)

    fit_start_time = time.time()

    for epoch in range(100):
        optimizer.zero_grad()

        # Do the forward pass of the neural net, evaluating the function at the parametric points
        y = phi(t)

        # Compute the Sinkhorn divergence between the reconstruction*(using the francis library) and the target
        # NOTE: The Sinkhorn function expects a batch of b point sets (i.e. tensors of shape [b, n, 3])
        # since we only have 1, we unsqueeze so x and y have dimension [1, n, 3]
        with torch.no_grad():
            _, P = emd_loss_fun(phi(t).unsqueeze(0), x.unsqueeze(0))

        # Project the transport matrix onto the space of permutation matrices and compute the L-2 loss
        # between the permuted points
        loss = mse_loss_fun(y[P.squeeze().max(0)[1], :], x)
        # loss = mse_loss_fun(P.squeeze() @ y,  x)  # Use the transport matrix directly

        # Take an optimizer step
        loss.backward()
        optimizer.step()

        print("Epoch %d, loss = %f" % (epoch, loss.item()))

    fit_end_time = time.time()

    print("Total time = %f" % (fit_end_time - fit_start_time))
    # Plot the ground truth, reconstructed points, and a mesh representing the fitted function, phi
    common.visualitation(x,t,phi)

if __name__ == "__main__":
    main()

The error message is:
free(): invalid pointer
Aborted (core dumped)

That again doesn't help me that much. I'll appreciate it a lot if someone has any idea what is happening or if you know more about this error.


来源: stackexchange

问:
How to extract WinZip Self-Extracting exe in silent mode
I have create a exe file using WinZip Self-Extractor. It extracts the file in UI mode, that is while dobule click the setup a new window opened that shows unzipping setupname.exe. I need to extract the same exe in silent mode which should not show unzipping UI info.

Is it possible to extract the exe using WinZip Self-Extractor in both UI mode and Silent mode? Please share the steps if available to do this.

答:
I had a similar problem but found Powershells Expand-Archive command worked.

e.g. Expand-Archive C:\\path_to_exe.exe -DestinationPath C:\\path_to_extract_to -Force

ContentLicense: CC BY-SA 4.0


问:
PartialView convert from MVC to .NET Core 2.2
I have the following MVC code:

```<code>
**** Edit.cshtml
@Html.Action("_Customer", "Orders", new { idCustomer = @Model.idCliente })

**** Controller.cs
        public IActionResult _Customer(int idCustomer)
        {
            var model = new Customer();

            // Ricavo Dati
            Utente u = new Utente();
            model = u.aDettagliCustomer(idCustomer, conn);

            return PartialView(model);
        }

**** View _Customer.cshtml
@model Models.Customer

Ragione Sociale: @Model.RagioneSociale<br />
@Model.Nome @Model.Cognome<br />
@Model.Sesso<br />
@Model.Indirizzo<br />
@Model.CAP @Model.Citta (@Model.Provincia)<br />
@Model.Stato
Tel: @Model.Telefono<br />
Cod.Fiscale: @Model.CodiceFiscale<br />
P.IVA: @Model.PartitaIVA<br />
email: @Model.Email

</code>```

I have read that it is advisable to use @await Html.PartialAsync, but how convert this code?

I Tried to convert the code with View Component.

But i get the error:
InvalidOperationException: A view component named 'CustomerViewComponent' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.

The Code:

```<code>    public class CustomerViewComponent: ViewComponent
    {
        private readonly IOptions<ConnectionStrings> conn;

        public CustomerViewComponent(IOptions<ConnectionStrings> config)
        {
            this.conn = config;
        }

        public async Task<IViewComponentResult> InvokeAsync(int idCustomer)
        {
            var items = await GetItemsAsync(idCustomer);
            return View("_Customer", items);
        }

        private Task<Customer> GetItemsAsync(int idCustomer)
        {
            var model = new Customer();

            // Ricavo Dati
            Utente u = new Utente();
            model = u.aDettagliCustomer(idCustomer, conn);

            return Task.FromResult<Customer>(model);
        }

    }
</code>```

```<code>@await Component.InvokeAsync("CustomerViewComponent", new { idCustomer = @Model.idCliente })
</code>```

答:
use  <partial name="partialName" model="ModelName" /> instead of returning partial view in controller.
you can use this n

Body:
I have the following MVC code:

**** Edit.cshtml
@Html.Action("_Customer", "Orders", new { idCustomer = @Model.idCliente })

**** Controller.cs
        public IActionResult _Customer(int idCustomer)
        {
            var model = new Customer();

            // Ricavo Dati
            Utente u = new Utente();
            model = u.aDettagliCustomer(idCustomer, conn);

            return PartialView(model);
        }

**** View _Customer.cshtml
@model Models.Customer

Ragione Sociale: @Model.RagioneSociale

@Model.Nome @Model.Cognome

@Model.Sesso

@Model.Indirizzo

@Model.CAP @Model.Citta (@Model.Provincia)

@Model.Stato
Tel: @Model.Telefono

Cod.Fiscale: @Model.CodiceFiscale

P.IVA: @Model.PartitaIVA

email: @Model.Email

I have read that it is advisable to use @await Html.PartialAsync, but how convert this code?

I Tried to convert the code with View Component.

But i get the error:
InvalidOperationException: A view component named 'CustomerViewComponent' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.

The Code:

    public class CustomerViewComponent: ViewComponent
    {
        private readonly IOptions<ConnectionStrings> conn;

        public CustomerViewComponent(IOptions<ConnectionStrings> config)
        {
            this.conn = config;
        }

        public async Task<IViewComponentResult> InvokeAsync(int idCustomer)
        {
            var items = await GetItemsAsync(idCustomer);
            return View("_Customer", items);
        }

        private Task<Customer> GetItemsAsync(int idCustomer)
        {
            var model = new Customer();

            // Ricavo Dati
            Utente u = new Utente();
            model = u.aDettagliCustomer(idCustomer, conn);

            return Task.FromResult<Customer>(model);
        }

    }

@await Component.InvokeAsync("CustomerViewComponent", new { idCustomer = @Model.idCliente })


问:
Title in CSV file when converting from XML to CSV using XML
I am trying to convert the XML to CSV using XSLT , I am getting the record but I need title in CSV file.

Eg:

```<code>Name    EmailAddress
Gaurav   Gaur@yopmail.com
Satya    Satya@yopmail.com
</code>```

XML

```<code><?xml version="1.0"?>
<SearchResults>
<Columns>
    <Column Label="Name">Name</Column>
    <Column Label="Email Addresses">EmailAddress</Column>
</Columns>
<Rows>
    <Row>
        <Name>Gaurav Joshi</Name>
        <EmailAddress>ybenipohe-3888@yopmail.com</EmailAddress>

    </Row>
    <Row>
        <Name>Satya</Name>
        <EmailAddress>eqaddoxoqu-8703@yopmail.com</EmailAddress>
     </Row>
</code>```

XSLT

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <!-- This transform is used to generate a CSV file.-->
  <xsl:output method="text" indent="no" />
  <xsl:template match="/">
    <xsl:apply-templates select="/SearchResults/Rows/Row" />
  </xsl:template>
  <xsl:template match="/SearchResults/Rows/Row">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>"</xsl:text>
    <xsl:for-each select="*">
      <xsl:text>,"</xsl:text>
      <xsl:value-of select="." />
      <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>
    </xsl:text>
  </xsl:template>
  <xsl:template match="/SearchResults/Columns" />
</xsl:stylesheet>
</code>```

答:
You currently have a template matching /SearchResults/Columns, which is actually redundant at the moment, because you don't have any templates that explicitly select these (Due to you doing <xsl:apply-templates select="/SearchResults/Rows/Row" />).

But you can easily adapt it to output the headings, and then you would just need an xsl:apply-templates to select it.

Try this XSLT

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <!-- This transform is used to generate a CSV file.-->
  <xsl:output method="text" indent="no" />

  <xsl:template match="/">
    <xsl:apply-templates select="/SearchResults/Columns" />
    <xsl:apply-templates select="/SearchResults/Rows/Row" />
  </xsl:template>

  <xsl:template match="Row">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>"</xsl:text>
    <xsl:for-each select="*">
      <xsl:text>,"</xsl:text>
      <xsl:value-of select="." />
      <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>
</xsl:text>
  </xsl:template>

  <xsl:template match="Columns">
    <xsl:text>"Row"</xsl:text>
    <xsl:for-each select="Column">
       <xsl:text>,"</xsl:text>
       <xsl:value-of select="@Label" />
       <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>
</xsl:text>
  </xsl:template>
</xsl:stylesheet>
</code>```

But this makes the (big?) assumption that the child nodes of each Row are in the same order as the relevant Column nodes. If this is not the case, you have work to do. Try replacing the template matching Row with this one instead

```<code>  <xsl:template match="Row">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>"</xsl:text>
    <xsl:variable name="Row" select="." />
    <xsl:for-each select="/SearchResults/Columns/Column">
      <xsl:text>,"</xsl:text>
      <xsl:value-of select="$Row/*[name() = current()]" />
      <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>
</xsl:text>
  </xsl:template>
</code>```

Body:
I am trying to convert the XML to CSV using XSLT , I am getting the record but I need title in CSV file.

Eg:

Name    EmailAddress
Gaurav   Gaur@yopmail.com
Satya    Satya@yopmail.com

XML

<?xml version="1.0"?>
<SearchResults>
<Columns>
    <Column Label="Name">Name</Column>
    <Column Label="Email Addresses">EmailAddress</Column>
</Columns>
<Rows>
    <Row>
        <Name>Gaurav Joshi</Name>
        <EmailAddress>ybenipohe-3888@yopmail.com</EmailAddress>

    </Row>
    <Row>
        <Name>Satya</Name>
        <EmailAddress>eqaddoxoqu-8703@yopmail.com</EmailAddress>
     </Row>

XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

  <xsl:output method="text" indent="no" />
  <xsl:template match="/">
    <xsl:apply-templates select="/SearchResults/Rows/Row" />
  </xsl:template>
  <xsl:template match="/SearchResults/Rows/Row">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>"</xsl:text>
    <xsl:for-each select="*">
      <xsl:text>,"</xsl:text>
      <xsl:value-of select="." />
      <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>
    </xsl:text>
  </xsl:template>
  <xsl:template match="/SearchResults/Columns" />
</xsl:stylesheet>

Body:
You currently have a template matching /SearchResults/Columns, which is actually redundant at the moment, because you don't have any templates that explicitly select these (Due to you doing <xsl:apply-templates select="/SearchResults/Rows/Row" />).

But you can easily adapt it to output the headings, and then you would just need an xsl:apply-templates to select it.

Try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <!-- This transform is used to generate a CSV file.-->
  <xsl:output method="text" indent="no" />

  <xsl:template match="/">
    <xsl:apply-templates select="/SearchResults/Columns" />
    <xsl:apply-templates select="/SearchResults/Rows/Row" />
  </xsl:template>

  <xsl:template match="Row">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>"</xsl:text>
    <xsl:for-each select="*">
      <xsl:text>,"</xsl:text>
      <xsl:value-of select="." />
      <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>&#10;</xsl:text>
  </xsl:template>

  <xsl:template match="Columns">
    <xsl:text>"Row"</xsl:text>
    <xsl:for-each select="Column">
       <xsl:text>,"</xsl:text>
       <xsl:value-of select="@Label" />
       <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>&#10;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

But this makes the (big?) assumption that the child nodes of each Row are in the same order as the relevant Column nodes. If this is not the case, you have work to do. Try replacing the template matching Row with this one instead

  <xsl:template match="Row">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>"</xsl:text>
    <xsl:variable name="Row" select="." />
    <xsl:for-each select="/SearchResults/Columns/Column">
      <xsl:text>,"</xsl:text>
      <xsl:value-of select="$Row/*[name() = current()]" />
      <xsl:text>"</xsl:text>
    </xsl:for-each>
    <xsl:text>&#10;</xsl:text>
  </xsl:template>


问:
How to solve a function acting differently based on callsite?
Not sure how to word the title so feel free to rename, but the issue I'm having is that I've got a function that works in one project, but fails in another. Below is rough pseudocode to show that one call in LibraryProject works, whereas the call in GameProject doesn't.

In ChildClass::do_stuff, the win32_window HWND is valid,  whereas the second one, failed_win32_window is null and glfw throws an error saying it isn't initialized, despite it already having been initialized (since the first glfw call was successful and I've manually stepped through to verify it was):

```<code>GLFWError #65537 Happen, The GLFW library is not initialized
</code>```

Here's pseudocode showing the two projects, and the files. GLFW is set initialized properly since if I do all my glfw logic within LibraryProject, the window shows up as normal.

```<code>//LibraryProject

////library_header.h
class ParentClass {
  GLFW* _mainWindow; //filled in elsewhere in the real code
  HWND getWin32Window() { return glfwGetWin32Window(_mainWindow); }
}

//GameProject

////game_header.h
#include "library_header.h" //from other Project

class ChildClass : public ParentClass {
  void do_stuff() {
    HWND win32_window = this->getWin32Window(); //this works because it goes down into LibraryProject.dll's module
    HWND failed_win32_window = glfwGetWin32Window(_mainWindow); //but literally the same call here doesn't because it happens within GameProject.exe
  }
}

////game_body.cpp

void function_called_elsewhere_in_game() {
    //called from GameProject.exe
    auto child = ChildClass();
    child.do_stuff();
}
</code>```

I'm not sure if this is an issue with glfw and my setup, or just my misunderstanding how projects and dependencies work.

Things I've tried:

Downloading the latest glfw3

Rebuilding the entire solution

Toggling with References and Linking Dependency Inputs

Things to note:

This is happening in the main thread, nothing else is using glfw at the same time. Its 100% reproducible too.

glfw3.lib is always being created in my GameProject output folder, based on the one inside LibraryProject

Stepping through the disassembly for each of the two glfwGetWin32Window calls has different addresses in disassembly, leading me to believe they're two different copies of the same library, but I'm not sure.

This is not an issue with cocos2d, the game engine I'm using as starting a blank project and calling glfwGetWin32Window(..) returns a valid pointer, even in GameProject, so there's something that I'm doing wrong, but I don't know what.

Images showing off the actual behaviour. magnolia_cocos_proj is GameProject and is the exe I'm running, and libcocos2d is LibraryProject I'm using as a DLL (I'm unfamiliar with the details of how linking and dlls work).

win32_window has valid value

definition of getWin32Window() to be 100% sure. Notice the module is in libcocos2d.dll now.

after going over the second line, the error throws and the second window is null

答: As I understood from "glfw3.lib is always being created" you use static linking. Static linking of a lib to different dll and exe lead to duplicating of all static memory of the lib. You should use a dynamic library for GLFW in the case. It's glfw3dll.lib.

Body:
Not sure how to word the title so feel free to rename, but the issue I'm having is that I've got a function that works in one project, but fails in another. Below is rough pseudocode to show that one call in LibraryProject works, whereas the call in GameProject doesn't.

In ChildClass::do_stuff, the win32_window HWND is valid,  whereas the second one, failed_win32_window is null and glfw throws an error saying it isn't initialized, despite it already having been initialized (since the first glfw call was successful and I've manually stepped through to verify it was):

GLFWError #65537 Happen, The GLFW library is not initialized

Here's pseudocode showing the two projects, and the files. GLFW is set initialized properly since if I do all my glfw logic within LibraryProject, the window shows up as normal.

//LibraryProject

////library_header.h
class ParentClass {
  GLFW* _mainWindow; //filled in elsewhere in the real code
  HWND getWin32Window() { return glfwGetWin32Window(_mainWindow); }
}

//GameProject

////game_header.h
#include "library_header.h" //from other Project

class ChildClass : public ParentClass {
  void do_stuff() {
    HWND win32_window = this->getWin32Window(); //this works because it goes down into LibraryProject.dll's module
    HWND failed_win32_window = glfwGetWin32Window(_mainWindow); //but literally the same call here doesn't because it happens within GameProject.exe
  }
}

////game_body.cpp

void function_called_elsewhere_in_game() {
    //called from GameProject.exe
    auto child = ChildClass();
    child.do_stuff();
}

I'm not sure if this is an issue with glfw and my setup, or just my misunderstanding how projects and dependencies work.

Things I've tried:

Downloading the latest glfw3

Rebuilding the entire solution

Toggling with References and Linking Dependency Inputs

Things to note:

This is happening in the main thread, nothing else is using glfw at the same time. Its 100% reproducible too.

glfw3.lib is always being created in my GameProject output folder, based on the one inside LibraryProject

Stepping through the disassembly for each of the two glfwGetWin32Window calls has different addresses in disassembly, leading me to believe they're two different copies of the same library, but I'm not sure.

This is not an issue with cocos2d, the game engine I'm using as starting a blank project and calling glfwGetWin32Window(..) returns a valid pointer, even in GameProject, so there's something that I'm doing wrong, but I don't know what.

Images showing off the actual behaviour. magnolia_cocos_proj is GameProject and is the exe I'm running, and libcocos2d is LibraryProject I'm using as a DLL (I'm unfamiliar with the details of how linking and dlls work).

win32_window has valid value

definition of getWin32Window() to be 100% sure. Notice the module is in libcocos2d.dll now.

after going over the second line, the error throws and the second window is null


问:
ojdbc8 DB_URL for fail over
I'm using ojdbc8 driver which gets a connection string format as the following:

```<code>"jdbc:oracle:thin:@amrood:1521:EMP"
</code>```

however, I'd like to use a fail over connection string with the following format:

```<code>"jdbc:oracle:thin:@(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS =
      (PROTOCOL = TCP)
      (HOST = site1)
      (PORT = 1521)
    )
    (ADDRESS =
      (PROTOCOL = TCP)
      (HOST = site2)
      (PORT = 1521)
    )
  )
  (FAILOVER=ON)
  (FAILOVER_MODE=
    (TYPE=SELECT)
    (METHOD=BASIC)
    (RETRIES=20)
    (DELAY=3)
  )
  (LOAD_BALANCE = OFF)
  (CONNECT_DATA =
    (SERVER = DEDICATED)
    (SERVICE_NAME = MYDB)
  )
)"
</code>```

.
when I'm using the fail over format I get an error message:
"Invalid connection string format, a valid format is: "host:port:sid" "

the none fail over connection string which is working:

```<code>String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
</code>```

*any suggestions on how solving it ? *

答:
This can't be done with just the JDBC connection URL, you will require at least The Universal Connection Pool (UCP) to be enabled in the client.

You should start by reading the 10.1.1 Configuring Fast Connection Failover for JDBC Clients chapter in the documentation. Make sure to read the documentation specific to your database version because JDBC driver might have different features e.g. odjcb6 in 11g vs ojdbc8 in 12c.

Title: ojdbc8 DB_URL for fail over

Body:
I'm using ojdbc8 driver which gets a connection string format as the following:

"jdbc:oracle:thin:@amrood:1521:EMP"

however, I'd like to use a fail over connection string with the following format:

"jdbc:oracle:thin:@(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS =
      (PROTOCOL = TCP)
      (HOST = site1)
      (PORT = 1521)
    )
    (ADDRESS =
      (PROTOCOL = TCP)
      (HOST = site2)
      (PORT = 1521)
    )
  )
  (FAILOVER=ON)
  (FAILOVER_MODE=
    (TYPE=SELECT)
    (METHOD=BASIC)
    (RETRIES=20)
    (DELAY=3)
  )
  (LOAD_BALANCE = OFF)
  (CONNECT_DATA =
    (SERVER = DEDICATED)
    (SERVICE_NAME = MYDB)
  )
)"

.
when I'm using the fail over format I get an error message:
"Invalid connection string format, a valid format is: "host:port:sid" "

the none fail over connection string which is working:

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);

*any suggestions on how solving it ? *


问:
Grouping/expanding ExtJS Grid with subrows
So here's the case that I'm working on: I have an ExtJS grid of data items that should have collapsible rows of sub-items. That is, most of the data on the grid need not be visible to begin with, but there should be the ability to expand the sub-rows of a "master row" by clicking on some kind of a [+]-icon.

GroupingView doesn't seem to do, as the group row is not a normal data row on the grid. RowExpander is more like it when it comes to having the "grouping rows" as normal rows, but then, I'm not sure how to approach actually having sub-rows in the expanded part of the grid.

I found this so far and it seems like it might have something to do with what I'm after...

http://www.sencha.com/forum/showthread.php?53289-EXTJS-RowExpander

Any pointers of the most reasonable way to approach this, hopefully with ExtJS 2.0.2?

答: Have a look at the answer I posted to  this question</p>

ContentLicense: CC BY-SA 3.0


问:
How are these X and Y variables used in Linear regression?
I am trying to predict the cost of a certain item using simple linear regression. As input data I Use the cost of the item.

The code seems to work, but i somehow cannot comprehend how the X and Y are used when applying linear regression. I use X as the item cost and Y as the label (creating a new row with shifted data of X)

df = df[['Item Price']]
forecast_col = 'Item Price'
forecast_out = int(math.ceil(0.0000005 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)

X = df[['Item Price']]
X = preprocessing.scale(X)
X_lately = X[forecast_out:]
X = X[:-forecast_out]

df.dropna(inplace=True)

y = np.array(df['label'])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)

forecast_set = clf.predict(X)
```

How are the X and Y variables used in solving the linear regression equation of Y = a + bX

答:
Your line :

```<code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
</code>```

splits each of your X and y into two samples each : a train with 80% of the data and a test with the other 20%. Then the line :

```<code>clf = LinearRegression(n_jobs=-1)
</code>```

creates a Linear Model. And with your last line :

```<code>clf.fit(X_train, y_train)
</code>```

the linear model uses all the (x,y) in X_train and Y_train to compute the best linear regressor.

In a more mathematical approach, the algorithm uses all the (x, y) contained in your X_train and Y_train to find a and b that minimises the equation E :

E = SUM(y_i - a*x_i - b)

The a and b values are found by finding where the derivative of E and the second derivative of E are equal to 0

Body:
I am trying to predict the cost of a certain item using simple linear regression. As input data I Use the cost of the item.

The code seems to work, but i somehow cannot comprehend how the X and Y are used when applying linear regression. I use X as the item cost and Y as the label (creating a new row with shifted data of X)

df = df[['Item Price']]
forecast_col = 'Item Price'
forecast_out = int(math.ceil(0.0000005 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)

X = df[['Item Price']]
X = preprocessing.scale(X)
X_lately = X[forecast_out:]
X = X[:-forecast_out]

df.dropna(inplace=True)

y = np.array(df['label'])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)

forecast_set = clf.predict(X)

How are the X and Y variables used in solving the linear regression equation of Y = a + bX

Body:
Your line :

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

splits each of your X and y into two samples each : a train with 80% of the data and a test with the other 20%. Then the line :

clf = LinearRegression(n_jobs=-1)

creates a Linear Model. And with your last line :

clf.fit(X_train, y_train)

the linear model uses all the (x,y) in X_train and Y_train to compute the best linear regressor.

In a more mathematical approach, the algorithm uses all the (x, y) contained in your X_train and Y_train to find a and b that minimises the equation E :

E = SUM(y_i - a*x_i - b)

The a and b values are found by finding where the derivative of E and the second derivative of E are equal to 0


问:
Exporting Separate Custom Elements from Svelte Components
I'm trying to find out if it's possible to export each Svelte component as a separate Custom Element (with Shadow DOM) in its own js file (with imports for any child elements - i.e. dependencies aren't included in the same file). Is it even possible?

Thanks

答:
I'm assuming you're using rollup and rollup-plugin-svelte

the way to do it is to use code splitting. You can define the inputs separately and that will create individual outputs. Instead of using a file name output, you would use an output dir.

example:

import svelte from 'rollup-plugin-svelte';

export default [
    {
        input: ['src/main-a.js', 'src/main-b.js'],
        output: {
            dir: 'public/module',
            format: 'es',
            sourcemap: true
        },
        plugins: [svelte()],
        experimentalCodeSplitting: true,
        experimentalDynamicImport: true
    },
];
```

source/reference/example: https://github.com/Rich-Harris/rollup-svelte-code-splitting

Body:
I'm assuming you're using rollup and rollup-plugin-svelte

the way to do it is to use code splitting. You can define the inputs separately and that will create individual outputs. Instead of using a file name output, you would use an output dir.

example:

import svelte from 'rollup-plugin-svelte';

export default [
    {
        input: ['src/main-a.js', 'src/main-b.js'],
        output: {
            dir: 'public/module',
            format: 'es',
            sourcemap: true
        },
        plugins: [svelte()],
        experimentalCodeSplitting: true,
        experimentalDynamicImport: true
    },
];

source/reference/example: https://github.com/Rich-Harris/rollup-svelte-code-splitting


问:
How to limit the input length on a v-select element?
I use the Vue-select feature on my project, and in a v-select element I want to set up a maximum input length (45 characters), but I'm failing to do so. I managed to treat this on the back-end, but I'd like to prevent the user from inputing more than it's allowed.

I tried to use the property :maxlength="45" but it seems that it have absolutely no effect on the input length.

Here's what I have:

            <v-select taggable pushTags :maxlength="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
                Digite o nome de um lote e clique "Enter" para adicionar...
            </v-select>

            Descarte

```

<pre class="lang-js prettyprint-override"><code>selecionarLote() {
    let vm = this;
    if (this.lotes.length) {
        if (!this.lote || !this.lote.label) return;

        if (this.lote.label.length > 45) {
            this.lote.label = this.lote.label.substring(0, 45);
        }
</code>```

As I said, I can handle the inputs that are above 45 characters, but I'd like to prevent it, just like this code do: https://codepen.io/CSWApps/pen/RQbvvp, I searched the vue-select documentation and wasn't able to find a way to limit the input length.

Thanks for any help in advance.

--------------- EDIT ----------------------

I tried to use Michael's answer, but I could still type more than 45 characters:

  data() {
    return {
      maxlength: [v => v.length < 45 || "Sorry you have exceeded the max length of input"],
      lote: null,
      descarte: false,
      modelValidations: {
        requiredText: {
          required: true
        }
      }
    };
  }
```

<pre class="lang-js prettyprint-override"><code>      <div class="form-group">
        <div class="row">
          <div class="col-xs-8">
            <v-select taggable pushTags :rules="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
              <span slot="no-options">Digite o nome de um lote e clique "Enter" para adicionar...</span>
            </v-select>
          </div>
          <div class="col-xs-4">
            <label class="control-label">Descarte</label>
            <p-switch v-model="descarte" type="primary" on-text="SIM" off-text="NÃO"></p-switch>
          </div>
        </div>
      </div>
</code>```

答:
You need to provide it with one of the props of v-select, In this you can use rules like this:

```<code><v-select taggable pushTags :rules="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
                <span slot="no-options">Digite o nome de um lote e clique "Enter" para adicionar...</span>
            </v-select>

data(){
  return {
    maxlength: [v => v.length < 45 || "Sorry you have exceeded the max length of input"]
   }

</code>```

Body:
I use the Vue-select feature on my project, and in a v-select element I want to set up a maximum input length (45 characters), but I'm failing to do so. I managed to treat this on the back-end, but I'd like to prevent the user from inputing more than it's allowed.

I tried to use the property :maxlength="45" but it seems that it have absolutely no effect on the input length.

Here's what I have:

            <v-select taggable pushTags :maxlength="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
                Digite o nome de um lote e clique "Enter" para adicionar...
            </v-select>

            Descarte

selecionarLote() {
    let vm = this;
    if (this.lotes.length) {
        if (!this.lote || !this.lote.label) return;

        if (this.lote.label.length > 45) {
            this.lote.label = this.lote.label.substring(0, 45);
        }

As I said, I can handle the inputs that are above 45 characters, but I'd like to prevent it, just like this code do: https://codepen.io/CSWApps/pen/RQbvvp, I searched the vue-select documentation and wasn't able to find a way to limit the input length.

Thanks for any help in advance.

--------------- EDIT ----------------------

I tried to use Michael's answer, but I could still type more than 45 characters:

  data() {
    return {
      maxlength: [v => v.length < 45 || "Sorry you have exceeded the max length of input"],
      lote: null,
      descarte: false,
      modelValidations: {
        requiredText: {
          required: true
        }
      }
    };
  }

            <v-select taggable pushTags :rules="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
              Digite o nome de um lote e clique "Enter" para adicionar...
            </v-select>

            Descarte

Body:
You need to provide it with one of the props of v-select, In this you can use rules like this:

<v-select taggable pushTags :rules="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
                <span slot="no-options">Digite o nome de um lote e clique "Enter" para adicionar...</span>
            </v-select>

data(){
  return {
    maxlength: [v => v.length < 45 || "Sorry you have exceeded the max length of input"]
   }


问:
Can i compare these two dates in JS?
```<code>console.log("201905300545_201905300555"  < "201905300535_201905300545")
</code>```

How can i compare two dates in string format?

答:
Here's a solution that uses only JavaScript :</p>

```<code>let parseDate = (date => {
    let [l, year, month, day, hour, minute, ...r] = date.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/);
    return new Date(year, month-1, day, hour, minute);
});

let [d1, d2] = '201905300545_201905300555'.split('_').map(parseDate);
let [d3, d4] = '201905300535_201905300545'.split('_').map(parseDate);

console.log(d2 - d1 < d4 - d3);
</code>```

Title: Can i compare these two dates in JS?

Body:
console.log("201905300545_201905300555"  < "201905300535_201905300545")

How can i compare two dates in string format?

Body:
Here's a solution that uses only JavaScript :

let parseDate = (date => {
    let [l, year, month, day, hour, minute, ...r] = date.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/);
    return new Date(year, month-1, day, hour, minute);
});

let [d1, d2] = '201905300545_201905300555'.split('_').map(parseDate);
let [d3, d4] = '201905300535_201905300545'.split('_').map(parseDate);

console.log(d2 - d1 < d4 - d3);


问:
Pandas DataFrame construction from a list of OrderedDict: preserving columns order
pd.__version__ = 0.18.0

Suppose you have a list of  OrderedDict:

```<code>[OrderedDict([('SecurityCode', 'IDX.MSDENON'), ('DescriptionLong', 'MSCI Norway NR USD (EUR)'), ('DataSrc', 'BGN.COB'), ('Ticker', 'MSDENON Index'), ('LastRun', None)])]
</code>```

if you construct a DataFrame from default constructor (or even with .from_dict() method)

```<code>df = pd.DataFrame(mylist)
</code>```

it does not preserve column order:

```<code>      DataSrc  DescriptionLong    LastRun SecurityCode         Ticker
   0  BGN.COB  MSCI Norway NR USD (EUR)    None  IDX.MSDENON  MSDENON Index
</code>```

whereas :

```<code>df = pd.DataFrame(data, columns=data[0].keys())

     SecurityCode           DescriptionLong  DataSrc         Ticker LastRun
  0  IDX.MSDENON  MSCI Norway NR USD (EUR)  BGN.COB  MSDENON Index    None
</code>```

does perserve column order.

I read on StackOverflow that such bug was present in 0.11 but IMHO we shouldn't have to specify columns= option in default constructor. Am I missing something or it is a bug that calls for a report ?

EDIT:
A github issue on pydata/pandas repo has been created and accepted. It's a "bug" in default constructor, overriding OrderedDict column order in any cases. A correction has been planed for next major release (commit accepted for 0.18.2)

答:
Roll your own....</p>

```<code>newList = list()
columnNames = df.columns
for index, row in df.iterrows():
    newDict = OrderedDict()
    for key in columnNames:
        newDict[key] = row[key]
    newList.append(newDict)
</code>```

Body:
pd.__version__ = 0.18.0

Suppose you have a list of  OrderedDict:

[OrderedDict([('SecurityCode', 'IDX.MSDENON'), ('DescriptionLong', 'MSCI Norway NR USD (EUR)'), ('DataSrc', 'BGN.COB'), ('Ticker', 'MSDENON Index'), ('LastRun', None)])]

if you construct a DataFrame from default constructor (or even with .from_dict() method)

df = pd.DataFrame(mylist)

it does not preserve column order:

      DataSrc  DescriptionLong    LastRun SecurityCode         Ticker
   0  BGN.COB  MSCI Norway NR USD (EUR)    None  IDX.MSDENON  MSDENON Index

whereas :

df = pd.DataFrame(data, columns=data[0].keys())

     SecurityCode           DescriptionLong  DataSrc         Ticker LastRun
  0  IDX.MSDENON  MSCI Norway NR USD (EUR)  BGN.COB  MSDENON Index    None

does perserve column order.

I read on StackOverflow that such bug was present in 0.11 but IMHO we shouldn't have to specify columns= option in default constructor. Am I missing something or it is a bug that calls for a report ?

EDIT:
A github issue on pydata/pandas repo has been created and accepted. It's a "bug" in default constructor, overriding OrderedDict column order in any cases. A correction has been planed for next major release (commit accepted for 0.18.2)

Body:
Roll your own....

newList = list()
columnNames = df.columns
for index, row in df.iterrows():
    newDict = OrderedDict()
    for key in columnNames:
        newDict[key] = row[key]
    newList.append(newDict)


问:
Laravel JSON Where Clauses with number in key
I have table with json column "options".
Exemple:

```<code> {"language":"en" }
</code>```

When i doing query, it's OK:

```<code>DB::table('users')->where('options->language', 'en')->get();
</code>```

But if i have number key:

```<code>{"221":"en" }
</code>```

I get empty array:

```<code>DB::table('users')->where('options->221', 'en')->get();
</code>```

How i can get true query?
Laravel 5.2

答:
If you upgrade your version of Laravel to 5.6 or newer the ->whereJsonContains() will be available.

If you do not want that, you can do it with a whereRaw query. The exact implementation depends on what DBMS you have:

SQL Server 2016

```<code>->whereRaw("JSON_VALUE(options, '$.221') = ?", ['en'])
</code>```

MySQL

```<code>->whereRaw("JSON_CONTAINS(options, 'en', '$.221') = 1")
</code>```

Body:
I have table with json column "options".
Exemple:

 {"language":"en" }

When i doing query, it's OK:

DB::table('users')->where('options->language', 'en')->get();

But if i have number key:

{"221":"en" }

I get empty array:

DB::table('users')->where('options->221', 'en')->get();

How i can get true query?
Laravel 5.2

Body:
If you upgrade your version of Laravel to 5.6 or newer the ->whereJsonContains() will be available.

If you do not want that, you can do it with a whereRaw query. The exact implementation depends on what DBMS you have:

SQL Server 2016

->whereRaw("JSON_VALUE(options, '$.221') = ?", ['en'])

MySQL

->whereRaw("JSON_CONTAINS(options, 'en', '$.221') = 1")


问:
Logging Application Block - Priority, Category values
I am looking for the best practices regarding the usage of the Enterprise Library's Logging Application Block and the Priority, Category and Severity values that one should use.

When it comes to Severity, the answer is quite simple: use one of the System.Diagnostics.TraceEventType enums.

But Priority is an int and Category is an array of strings. So I am not sure what is the best practice when it comes to these 2 values....

Here are two schemes that I have come up with when it comes to Category:

Use the class name for the category

Use a predefined category for different types of messages you except from your application (eg: Exception, Information, etc...).

Advantage of 1: It allows you to give great control over exactly which classes you want logging at any given point. (specify the class name and the severity to control what is logged and where its logged).

Disadvantage of 1: It can get unwieldy, as you may have 100s of categories and there is no easy way to setup configuration to capture all exceptions in the application.

Advantage of 2: Exact opposite of 1, so it makes it real easy to specify where you want all your exception messages to go and just as easily allows you to turn off logging of all unnecessary information.

Disadvantage of 2: Its not as configurable as (1).

Looking for other ideas when it comes to Priority and Category.

答:
But Priority is an int and Category is
  an array of strings. So I am not sure
  what is the best practice when it
  comes to these 2 values....

In terms of priority I would recommend not using priority unless you have a specific requirement to log based on priority. If you don't explicitly need priority it causes more headaches than it's worth.

Here are two schemes that I have come
  up with when it comes to Category:

Use the class name for the category

Use a predefined category for different types of messages you except
  from your application (eg: Exception,
  Information, etc...).

In my experience the above two options are common choices.  But why choose? Since (as you mention) you can have more than one category there is no reason to choose one over the other.  If you wish, you can have multiple categories and enable only the ones you are interested in at the time.

For example, in addition to adding your class name (MyCompany.BusinessLogic.Processor) as a category you could also add the namespace or assembly name as a category (MyCompany.BusinessLogic).

Other categories that you could consider adding are categories by functional area or application layer. e.g. "DataAccess" or "UI".

I think if you use both of the approaches from your list that should cover most situations.  Enable "Exception" and if you need more granular logging you could turn Information on for specific classes or enable Information globally.


问:
Excel Vba stops excution after deleting sheet
I am new to VBA. I have written a code to delete a particular sheet. After execution of that delete sheet macro, excel macro stopped execution. It didnt execute futher..

Here is my code..

```<code>Sub CopyAcross()
Dim sheetName As String
sheetName = "Master_Base"
If WorksheetExists(sheetName) Then
 DeleteSheet (sheetName)
End If
MsgBox "Debug"

Workbooks("Master_Base.csv").Sheets("Master_Base").Copy Before:=Workbooks("Copy of    test.xlsm").Worksheets("Sheet3")
End Sub

Sub DeleteSheet(strSheetName As String)
' deletes a sheet named strSheetName in the active workbook
Application.DisplayAlerts = False
Sheets(strSheetName).Delete
Application.DisplayAlerts = True
End Sub
</code>```

Can any one help on this,

Thanks in advance.

答:
I was experiencing the same issue, on a Windows 7 computer with Excel version 16.0.10730.20264 32-bit, the code ran fine without issue. However, on a Windows 10 computer with the same Excel install version, the macro would immediately stop execution following the Sheets.Delete line.

I found that this was only happening where I was attempting to manipulate a workbook that contained VBA code, that I had opened during the macro.

The issue is caused by the macro security settings on the computer. If you set Automation Security to Low before opening the workbook, you should no longer get the error:

Use the code:

```<code>Application.AutomationSecurity = msoAutomationSecurityLow
</code>```

Body:
I am new to VBA. I have written a code to delete a particular sheet. After execution of that delete sheet macro, excel macro stopped execution. It didnt execute futher..

Here is my code..

Sub CopyAcross()
Dim sheetName As String
sheetName = "Master_Base"
If WorksheetExists(sheetName) Then
 DeleteSheet (sheetName)
End If
MsgBox "Debug"

Workbooks("Master_Base.csv").Sheets("Master_Base").Copy Before:=Workbooks("Copy of    test.xlsm").Worksheets("Sheet3")
End Sub

Sub DeleteSheet(strSheetName As String)
' deletes a sheet named strSheetName in the active workbook
Application.DisplayAlerts = False
Sheets(strSheetName).Delete
Application.DisplayAlerts = True
End Sub

Can any one help on this,

Thanks in advance.

Body:
I was experiencing the same issue, on a Windows 7 computer with Excel version 16.0.10730.20264 32-bit, the code ran fine without issue. However, on a Windows 10 computer with the same Excel install version, the macro would immediately stop execution following the Sheets.Delete line.

I found that this was only happening where I was attempting to manipulate a workbook that contained VBA code, that I had opened during the macro.

The issue is caused by the macro security settings on the computer. If you set Automation Security to Low before opening the workbook, you should no longer get the error:

Use the code:

Application.AutomationSecurity = msoAutomationSecurityLow


问:
Display dynamic number of fields
I'm new to progress and I'm trying to learn dynamic queries. As a Task I gave to myself I want to read a csv file and create a table based on the contents of said file. So far everything works but I can't really seem to find a way to display the contents properly.

I have a temp-table created based on a csv input with the first line being the columns or fields of the table and everything after being the records.

```<code>Field1,Field2,Field3,Field4,Fieldn...
Value1.1,Value2.1,Value3.1,Value4.1,Valuen.1...
Value1.2,Value2.2,Value3.2,Value4.2,Valuen.1...
Value1.3,Value2.3,Value3.3,Value4.3,Valuen.1...
Value1.4,Value2.4,Value3.4,Value4.4,Valuen.1...
etc...
</code>```

How can I display a dynamic number of fields and their names properly?

The following things are unknown:

Number of fields

Name of fields

Values of records

The following works and shows the data in the desired format (but it's hard coded):

```<code>DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.
</code>```

I'm trying to loop over the buffer fields but I can't find a way to do it without redefining the DISPLAY command every iteration. Also I don't know how to display the labels of the fields in as a header row.

I'm looking for something like this :

```<code>/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i].
    END.
END.
</code>```

This would be the full code:

```<code>/*
Variables
*/
DEF VAR i AS INTEGER INITIAL 0 NO-UNDO. //Counter
DEF VAR iEntry AS INTEGER INITIAL 0 NO-UNDO. //Counter2
DEF VAR cTitleRow AS CHARACTER NO-UNDO. //Fields csv
DEF VAR cDataRow AS CHARACTER NO-UNDO. //Entries csv
DEF VAR cFieldName AS CHARACTER NO-UNDO. //Field
DEF VAR iNumFields AS INTEGER NO-UNDO. //Amount of Fields
DEF VAR iNumLines AS INTEGER NO-UNDO. //Amount of records
DEF VAR cTitleArray AS CHARACTER EXTENT NO-UNDO. //Fields Array
/*
Handles
*/
DEF VAR ttMyTable AS HANDLE NO-UNDO. //Temp table
DEF VAR bMyTable AS HANDLE NO-UNDO. //Buffer
DEF VAR qMyTable AS HANDLE NO-UNDO. //Query

INPUT FROM 'C:\Path\To\CSV\mycsv.csv'.

/*
Get first row for fields and field names
*/
IMPORT UNFORMATTED cTitleRow.
iNumFields = NUM-ENTRIES(cTitleRow) + 1. //Additional field for PK
EXTENT(cTitleArray) = iNumFields.

/*
Dynamic table creation
*/
CREATE TEMP-TABLE ttMyTable.
ttMyTable:ADD-NEW-FIELD('PK', 'integer').
cTitleArray[1] = 'PK'.
DO i = 2 to iNumFields:
    iEntry = i - 1.
    cFieldName = ENTRY(iEntry,cTitleRow).
    ttMyTable:ADD-NEW-FIELD(cFieldName, 'character').
    cTitleArray[i] = cFieldName.
END.

/*
Adding and defining indexes
*/
ttMyTable:ADD-NEW-INDEX('idx', TRUE, TRUE).
ttMyTable:ADD-INDEX-FIELD('idx', 'PK', 'asc').
ttMyTable:TEMP-TABLE-PREPARE('myTable').

/*
Creating buffer
*/
bMyTable = ttMyTable:DEFAULT-BUFFER-HANDLE.

/*
Populating data
*/
REPEAT:
    IMPORT UNFORMATTED cDataRow.
    bMyTable:BUFFER-CREATE.
    bMyTable::pk = iNumLines.
    DO i = 2 to iNumFields:
        iEntry = i - 1.
        bMyTable:BUFFER-FIELD(i):BUFFER-VALUE = ENTRY(iEntry,cDataRow).
        bMyTable:BUFFER-FIELD(i):COLUMN-LABEL = cTitleArray[i].
        bMyTable:BUFFER-FIELD(i):LABEL = cTitleArray[i].
    END.

    iNumLines = iNumLines + 1.
END.

/*
Creating query
*/
CREATE QUERY qMyTable.
qMyTable:SET-BUFFERS(bMyTable).
qMyTable:QUERY-PREPARE('for each myTable').
qMyTable:QUERY-OPEN().

/*
/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE.
    END.
END.
*/

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

qMyTable:QUERY-CLOSE().

DELETE OBJECT qMyTable.
</code>```

答:
I'd do it this way. It would show the field value next to its name, and one record at a time. I hope this helps:</p>

```<code>DO WHILE qMyTable:GET-NEXT():
   DO i = 1 to iNumFields:
      DISPLAY bMyTable:BUFFER-FIELD(i):NAME
              bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i] WITH FRAME f DOWN.
      DOWN WITH FRAME f.
   END.
   CLEAR FRAME f ALL.
END.
</code>```

Title: Display dynamic number of fields

Body:
I'm new to progress and I'm trying to learn dynamic queries. As a Task I gave to myself I want to read a csv file and create a table based on the contents of said file. So far everything works but I can't really seem to find a way to display the contents properly.

I have a temp-table created based on a csv input with the first line being the columns or fields of the table and everything after being the records.

Field1,Field2,Field3,Field4,Fieldn...
Value1.1,Value2.1,Value3.1,Value4.1,Valuen.1...
Value1.2,Value2.2,Value3.2,Value4.2,Valuen.1...
Value1.3,Value2.3,Value3.3,Value4.3,Valuen.1...
Value1.4,Value2.4,Value3.4,Value4.4,Valuen.1...
etc...

How can I display a dynamic number of fields and their names properly?

The following things are unknown:

Number of fields

Name of fields

Values of records

The following works and shows the data in the desired format (but it's hard coded):

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

I'm trying to loop over the buffer fields but I can't find a way to do it without redefining the DISPLAY command every iteration. Also I don't know how to display the labels of the fields in as a header row.

I'm looking for something like this :

/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i].
    END.
END.

This would be the full code:

/*
Variables
*/
DEF VAR i AS INTEGER INITIAL 0 NO-UNDO. //Counter
DEF VAR iEntry AS INTEGER INITIAL 0 NO-UNDO. //Counter2
DEF VAR cTitleRow AS CHARACTER NO-UNDO. //Fields csv
DEF VAR cDataRow AS CHARACTER NO-UNDO. //Entries csv
DEF VAR cFieldName AS CHARACTER NO-UNDO. //Field
DEF VAR iNumFields AS INTEGER NO-UNDO. //Amount of Fields
DEF VAR iNumLines AS INTEGER NO-UNDO. //Amount of records
DEF VAR cTitleArray AS CHARACTER EXTENT NO-UNDO. //Fields Array
/*
Handles
*/
DEF VAR ttMyTable AS HANDLE NO-UNDO. //Temp table
DEF VAR bMyTable AS HANDLE NO-UNDO. //Buffer
DEF VAR qMyTable AS HANDLE NO-UNDO. //Query

INPUT FROM 'C:\Path\To\CSV\mycsv.csv'.

/*
Get first row for fields and field names
*/
IMPORT UNFORMATTED cTitleRow.
iNumFields = NUM-ENTRIES(cTitleRow) + 1. //Additional field for PK
EXTENT(cTitleArray) = iNumFields.

/*
Dynamic table creation
*/
CREATE TEMP-TABLE ttMyTable.
ttMyTable:ADD-NEW-FIELD('PK', 'integer').
cTitleArray[1] = 'PK'.
DO i = 2 to iNumFields:
    iEntry = i - 1.
    cFieldName = ENTRY(iEntry,cTitleRow).
    ttMyTable:ADD-NEW-FIELD(cFieldName, 'character').
    cTitleArray[i] = cFieldName.
END.

/*
Adding and defining indexes
*/
ttMyTable:ADD-NEW-INDEX('idx', TRUE, TRUE).
ttMyTable:ADD-INDEX-FIELD('idx', 'PK', 'asc').
ttMyTable:TEMP-TABLE-PREPARE('myTable').

/*
Creating buffer
*/
bMyTable = ttMyTable:DEFAULT-BUFFER-HANDLE.

/*
Populating data
*/
REPEAT:
    IMPORT UNFORMATTED cDataRow.
    bMyTable:BUFFER-CREATE.
    bMyTable::pk = iNumLines.
    DO i = 2 to iNumFields:
        iEntry = i - 1.
        bMyTable:BUFFER-FIELD(i):BUFFER-VALUE = ENTRY(iEntry,cDataRow).
        bMyTable:BUFFER-FIELD(i):COLUMN-LABEL = cTitleArray[i].
        bMyTable:BUFFER-FIELD(i):LABEL = cTitleArray[i].
    END.

    iNumLines = iNumLines + 1.
END.

/*
Creating query
*/
CREATE QUERY qMyTable.
qMyTable:SET-BUFFERS(bMyTable).
qMyTable:QUERY-PREPARE('for each myTable').
qMyTable:QUERY-OPEN().

/*
/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE.
    END.
END.
*/

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

qMyTable:QUERY-CLOSE().

DELETE OBJECT qMyTable.

Body:
I'd do it this way. It would show the field value next to its name, and one record at a time. I hope this helps:

DO WHILE qMyTable:GET-NEXT():
   DO i = 1 to iNumFields:
      DISPLAY bMyTable:BUFFER-FIELD(i):NAME
              bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i] WITH FRAME f DOWN.
      DOWN WITH FRAME f.
   END.
   CLEAR FRAME f ALL.
END.


问:
How to create autocomplete suggestion menu in interactive command line application?
Suppose I have this code:

```<code>choices = [
    'north',
    'south',
    'east',
    'west',
]

direction = input('Direction: ')
</code>```

When this is run from the bash shell using python3 myprogram.py, the user will be prompted to type in a direction. There are only four choices, so I would like to show the user an autocomplete suggestion menu similar to this example in vim, except that the menu should appear in the bash shell:

The user should be able to cycle through the available choices by pressing Tab or the up and down arrow keys.

How can I use Python to build an autocomplete suggestion menu that appears in the bash shell?

I tried the curses module, but it is not suitable because it clears the screen (similar to this problem). Do I have to manually manipulate ANSI escape characters?

答:
You can try using the Python Prompt Toolkit, a library for building interactive command line applications in Python.

The library makes it easy to add interactive autocompletion menus:

(Image source: pcgli)

Body:
Suppose I have this code:

choices = [
    'north',
    'south',
    'east',
    'west',
]

direction = input('Direction: ')

When this is run from the bash shell using python3 myprogram.py, the user will be prompted to type in a direction. There are only four choices, so I would like to show the user an autocomplete suggestion menu similar to this example in vim, except that the menu should appear in the bash shell:

The user should be able to cycle through the available choices by pressing Tab or the up and down arrow keys.

How can I use Python to build an autocomplete suggestion menu that appears in the bash shell?

I tried the curses module, but it is not suitable because it clears the screen (similar to this problem). Do I have to manually manipulate ANSI escape characters?


问:
TERADATA: WHILE LOOP works as SELECT but not in my SPROC
I created the following stored procedure in teradata to start with current run day and pull all invoices within that particular week. Then continue going back for 52 weeks, and insert the records into my holder table.

However I can run the SELECT fine without the WHILE loop. But when I create a stored procedure of this successfully and run I receiving the following message:

OUTLETLOOPMG:An owner referenced by user does not have SELECT access to CORP_INVOICE_VIEWS.INVOICE_CORP.Ownrshp_ID

Which I don't understand being the select works fine without the loop.

So two question:

What's up with that error?

Based off logic I describe in initial paragraph, does my WHILE loop achieve this?

Code:

```<code>CREATE  PROCEDURE OutletLoopMG()
BEGIN
    DECLARE iVAR INT DEFAULT 52;
    DECLARE dVAR DATE DEFAULT current_date;

    --SET iVAR = 52;
    --SET dVAR = current_date;

    WHILE  iVAR > 0
    DO
    BEGIN
        INSERT INTO dlccc_cust_cntc_cntr_lab.OutletHolder
            SELECT
                invcorp.OWNRSHP_ID, invcorp.BTLR_DLVR_PNT_NO,
                snap.btlr_branch_nm, snap.dlvr_pnt_nm,
                invcorp.inv_no, invcorp.inv_dt,
                cal.week_of_year, cal.year_of_calendar
            FROM
                corp_invoice_VIEWS.invoice_corp invcorp
            LEFT JOIN
                CHR_VIEWS.DPT_SNAPSHOT_SELECT snap ON invcorp.BTLR_DLVR_PNT_NO = snap.BTLR_DLVR_PNT_NO
                                                   AND invcorp.OWNRSHP_ID = snap.OWNRSHP_ID
            INNER JOIN
                sys_calendar.calendar cal ON invcorp.inv_dt = cal.calendar_date
            WHERE
                1 = 1
                AND invcorp.inv_dt = dVAR;
    END;

    SET dVAR = (CAST(dVAR AS DATE) - 7);
    SET iVAR = (iVAR-1);

END WHILE;
END;
</code>```

答:
This question is a little long in the tooth, but thanks to a recent edit, it's popped back up to the top of the queue:

With procedures there are three "roles" under which security can be assigned (actually 4 but I'll get to that)

OWNER - This is the database/user under which the procedure is being created. If you are using default SQL SECURITY settings for the procedure than OWNER will need to have access to the objects being used in the procedure WITH GRANT OPTION. So: GRANT SELECT ON corp_invoice_VIEWS TO <whatever database this proc is in> WITH GRANT OPTION you will need to grant that access for each database/view/table that is being selected here in the FROM clause.

CREATOR - This is you since you are compiling the procedure. With default SQL SECURITY settings for the procedure you will need to have access to the objects used in the procedure. You must have that access already in order to run the SELECT by itself. So this is all good.

INVOKER - This is the user that will execute/call the procedure. With default SQL SECURITY Settings for the procedure the INVOKER merely needs to have EXECUTE procedure to the procedure.

The default SQL SECURITY settings on a procedure (Which can be overridden when writing the procedure) is SQL SECURITY DEFINER. This is the "4th" role I mentioned above. Definer security checks that both the CREATOR and OWNER of the procedure have access to the objects in the procedure when the procedure is compiled. Furthermore when the procedure is executed OWNER privileges are checked once again. It throws an error at the time of compile if you and the database in which this procedure resides doesn't have access. It will throw an error at execution time if the OWNER (database in which the procedure resides) doesn't have access as well.

Your options to get around this error:

Grant the owner of the procedure SELECT access to the tables, views, or databases containing those tables/views WITH GRANT OPTION so that the SQL SECURITY DEFINER default is satisfied. This is the more secure and less volatile route.

Change the sql security on the procedure to SQL SECURITY CREATOR so that only your credentials (the creator of the procedure) are checked at compile and execution. This is a cheap fix, but understandable if you lack permissions to change security for the database you are working in.

Change the sql security on the procedure to SQL SECURITY INVOKER so that only the person executing the procedure after it's compiled is used for checking privileges. This means that the user executing will not only have to have EXECUTE PROCEDURE access to the procedure but will need to have SELECT access to the views/tables used within. This is probably a safer option than number 2, but less robust then option 1 (where creator and owner are checked).

You can read more about the procedure security at the documentation site.

Body:
I created the following stored procedure in teradata to start with current run day and pull all invoices within that particular week. Then continue going back for 52 weeks, and insert the records into my holder table.

However I can run the SELECT fine without the WHILE loop. But when I create a stored procedure of this successfully and run I receiving the following message:

OUTLETLOOPMG:An owner referenced by user does not have SELECT access to CORP_INVOICE_VIEWS.INVOICE_CORP.Ownrshp_ID

Which I don't understand being the select works fine without the loop.

So two question:

What's up with that error?

Based off logic I describe in initial paragraph, does my WHILE loop achieve this?

Code:

CREATE  PROCEDURE OutletLoopMG()
BEGIN
    DECLARE iVAR INT DEFAULT 52;
    DECLARE dVAR DATE DEFAULT current_date;

    --SET iVAR = 52;
    --SET dVAR = current_date;

    WHILE  iVAR > 0
    DO
    BEGIN
        INSERT INTO dlccc_cust_cntc_cntr_lab.OutletHolder
            SELECT
                invcorp.OWNRSHP_ID, invcorp.BTLR_DLVR_PNT_NO,
                snap.btlr_branch_nm, snap.dlvr_pnt_nm,
                invcorp.inv_no, invcorp.inv_dt,
                cal.week_of_year, cal.year_of_calendar
            FROM
                corp_invoice_VIEWS.invoice_corp invcorp
            LEFT JOIN
                CHR_VIEWS.DPT_SNAPSHOT_SELECT snap ON invcorp.BTLR_DLVR_PNT_NO = snap.BTLR_DLVR_PNT_NO
                                                   AND invcorp.OWNRSHP_ID = snap.OWNRSHP_ID
            INNER JOIN
                sys_calendar.calendar cal ON invcorp.inv_dt = cal.calendar_date
            WHERE
                1 = 1
                AND invcorp.inv_dt = dVAR;
    END;

    SET dVAR = (CAST(dVAR AS DATE) - 7);
    SET iVAR = (iVAR-1);

END WHILE;
END;


问:
Reference property in Gradle Properties
My gradle.properties.kts files has the following contents:

```<code>build_version=develop
build_version_code=2
include_vas=false
</code>```

In my build.gradle.kts looks as follows:

```<code>plugins {
    id(Plugins.androidApplication)
    kotlin(Plugins.kotlinAndroid)
    kotlin(Plugins.kotlinExtensions)
    kotlin(Plugins.kapt)
}

android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }

  buildTypes{

  }
    repositories {
        flatDir {
            dirs("libs")
        }
    }

    dependencies {
        implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.arr"))))
        implementation(Libs.stdLib)
        implementation(Libs.sunmiui)
        implementation(Libs.slf4j)
        implementation(Libs.appCompact)
        implementation(Libs.otpView)
        implementation(Libs.vectordrawableAnimated)
        implementation(Libs.materialComponents)
        implementation(Libs.recyclerView)
        implementation(Libs.constraintLayout)
        implementation(Libs.junit)
        implementation(Libs.testRunner)
        implementation(Libs.expressoCore)
        implementation(Libs.lifecyleExtensions)
        implementation(Libs.lifecyleCompiler)
        implementation(Libs.roomRuntime)
        implementation(Libs.databindingCompiler)
        implementation(Libs.rxjava)
        implementation(Libs.rxjavaAndroid)
        implementation(Libs.glide)
        implementation(Libs.glideCompiler)
        implementation(Libs.gson)
        implementation(Libs.joda)
        implementation(Libs.countrycodePicker)
        implementation(Libs.timber)
        implementation(Libs.daggerandroidSupport)
        implementation(Libs.daggerandroidProcessor)
    }
</code>```

I am in the process of converting my current gradle scripts to kotlin DSL. The current challenge I am facing is that in the defaultConfig:

```<code>android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }
</code>```

I refer to the versionCode that is defined in the gradle.properties. The code below was how it was done before the conversion.

```<code>defaultConfig
        {

            multiDexEnabled true
            applicationId "jfjfjrjrjr.comn.jejeu"
            minSdkVersion 24
            targetSdkVersion 28
            versionCode build_version_code as Integer
            versionName build_version
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
</code>```

How can I do this in Kotlin

答:
There's no clean way about obtaining it, but you can use Project interface and use it's property() method to obtain your gradle.properties.kts variables from it like below code:

```<code>project.property('your_variable_name_here')
</code>```

For your instance:

```<code>versionCode project.property('build_version_code')
</code>```

This is how you can set all your variables from your property file.

Title: Reference property in Gradle Properties

Body:
My gradle.properties.kts files has the following contents:

build_version=develop
build_version_code=2
include_vas=false

In my build.gradle.kts looks as follows:

plugins {
    id(Plugins.androidApplication)
    kotlin(Plugins.kotlinAndroid)
    kotlin(Plugins.kotlinExtensions)
    kotlin(Plugins.kapt)
}

android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }

  buildTypes{

  }
    repositories {
        flatDir {
            dirs("libs")
        }
    }

    dependencies {
        implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.arr"))))
        implementation(Libs.stdLib)
        implementation(Libs.sunmiui)
        implementation(Libs.slf4j)
        implementation(Libs.appCompact)
        implementation(Libs.otpView)
        implementation(Libs.vectordrawableAnimated)
        implementation(Libs.materialComponents)
        implementation(Libs.recyclerView)
        implementation(Libs.constraintLayout)
        implementation(Libs.junit)
        implementation(Libs.testRunner)
        implementation(Libs.expressoCore)
        implementation(Libs.lifecyleExtensions)
        implementation(Libs.lifecyleCompiler)
        implementation(Libs.roomRuntime)
        implementation(Libs.databindingCompiler)
        implementation(Libs.rxjava)
        implementation(Libs.rxjavaAndroid)
        implementation(Libs.glide)
        implementation(Libs.glideCompiler)
        implementation(Libs.gson)
        implementation(Libs.joda)
        implementation(Libs.countrycodePicker)
        implementation(Libs.timber)
        implementation(Libs.daggerandroidSupport)
        implementation(Libs.daggerandroidProcessor)
    }

I am in the process of converting my current gradle scripts to kotlin DSL. The current challenge I am facing is that in the defaultConfig:

android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }

I refer to the versionCode that is defined in the gradle.properties. The code below was how it was done before the conversion.

defaultConfig
        {

            multiDexEnabled true
            applicationId "jfjfjrjrjr.comn.jejeu"
            minSdkVersion 24
            targetSdkVersion 28
            versionCode build_version_code as Integer
            versionName build_version
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }

How can I do this in Kotlin

Body:
There's no clean way about obtaining it, but you can use Project interface and use it's property() method to obtain your gradle.properties.kts variables from it like below code:

project.property('your_variable_name_here')

For your instance:

versionCode project.property('build_version_code')

This is how you can set all your variables from your property file.


问:
Using Lodash to find a partial string in any property value of an object
I want to use Lodash to return true when an object contains in any of its values, a match for a partial string. I've tried this with _.includes as follows.

```<code>const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false
</code>```

I've also tried this using a regular expression instead of a string for the search term.

```<code>const search = /stone/gi;
</code>```

Both times result returns false. I want result to return true. How can I do this in Lodash?

答:
That's not how lodash's includes works.

You should search the values of the object, not the object itself. And you should check each value in turn.

Also you don't need lodash for that.

```<code>const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = Object.values(ob).some(value => value.indexOf(search) !== -1);
console.log(result); // true
</code>```

Body:
I want to use Lodash to return true when an object contains in any of its values, a match for a partial string. I've tried this with _.includes as follows.

const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false

I've also tried this using a regular expression instead of a string for the search term.

const search = /stone/gi;

Both times result returns false. I want result to return true. How can I do this in Lodash?

Body:
That's not how lodash's includes works.

You should search the values of the object, not the object itself. And you should check each value in turn.

Also you don't need lodash for that.

const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = Object.values(ob).some(value => value.indexOf(search) !== -1);
console.log(result); // true


问:
Get all results of rows with matching criteria from a range
As mentioned in another question, I'm on a few Discord servers that allow players to auction in-game content for trade.  Use sheets to keep track of my own auctions, I copy the tag (name#xxxx) and ID (long number) into a list so I can filter out anyone who fails to follow through on a winning auction.

What I'm looking to do now is two fold.

One is to have an automated list of duplicate ID's that have different tags (someone changed their name).  The list would show the ID number in one cell, then in the next cell, show all of the tags they have used (using textJoin() and sort() to make it easier to read).

The second is to grab a list of tags used based on a separate list of ID's (known list of users who have failed to follow through).

I've tried and failed with vlookup(), filter(), query(), and regular lookup().  When I tried filter() for using a list, it only seems to look at the first item, but ignores anything after that.  If I try to expand the length of the list (instead of F2 I make it F2:F) it turns red and won't work.

Using conditional formatting, I'm able to get duplicates to highlight within the range.  However, I'm trying to take it a step further and retrieve matches.  Sort of like an automated filter system to show known duplicates.

What am I not thinking of here?

Edit:
Here is some dummy info to give an idea...

```<code>Alred         970192322624802134
Barry         493288047120884104
Clark         648567312202297155
Dick          336368714780211631
Enigma        513446866409315771
Flash         493288047120884104
Green Arrow   382294342593163268
Harley        894386762337961412
Ivy           192571739320652789
Jimmy         662344040550649441
Krypto        944264752128564134
Lois          608531705193876711
Mera          461451144314768165
Nyssa         533348352505340666
Oliver        382294342593163268
Perry         877529730964781752
Robin         336368714780211631
Superman      648567312202297155
Thomas        969367121152160055
</code>```

Obviously the names would have a # sign followed by a 4 digit number, but it's an irrelevant factor for this matter.

Looking at the list, you can see that some of the ID's (column of numbers) are the same, but with different names.

So the goal is to have a separate column that would go through, find ID's that are duplicated, and then list all names with that matching ID.

Example:

```<code>648567312202297155   Clark, Superman
336368714780211631   Dick, Robin
382294342593163268   Green Arrow, Oliver
etc
</code>```

For the second one, a list of ID's where matching ID's would show all matching names.  Sort of like if the above only listed ID's that have more than one entry, and then that list were to be used to find names, except the list of ID's could be generated by other means.  To break it down into two simplified tasks...  One finds duplicate ID's and simply lists those ID's (one time each), then another looks up those ID's and lists all matching entries (ie, the names).

Edit:
This link is an example of what I'm trying to do, but it's not working for me.
Google Sheet Query - Group / concatenate multiple rows

I have A(A2:A)=Names/tag, B(B2:B)=ID, F(F2:F)=ID's to filter.
When I try =join(",",filter(A:A,B:B=F2)) it returns the first entry but then stops.

Also, when I try to simulate the other page (values and formulas), it only returns the results for Bill (Red,Blue,Yellow), but not for Sarah.

By simulate, I mean that I added an empty sheet and filled in the values and formulas as shown in the image.

答:
The solution combines the functions TEXTJOIN with ARRAYFORMULA. Given your sample data, you can create a list of the unique user IDs with the UNIQUE formula. So cell D1 has =UNIQUE($B$1:$B$19). This fills in the data in column D.

The formula in column E then matches each of the unique user IDs in column B with any of the names in column A using ARRAYFORMULA to return all of the names, then concatenates the list of names using TEXTJOIN. The formula in column E is

```<code>=TEXTJOIN(",",true,arrayformula(if($D7=$B$1:$B$19,$A$1:$A$19,"")))
</code>```

Body:
As mentioned in another question, I'm on a few Discord servers that allow players to auction in-game content for trade.  Use sheets to keep track of my own auctions, I copy the tag (name#xxxx) and ID (long number) into a list so I can filter out anyone who fails to follow through on a winning auction.

What I'm looking to do now is two fold.

One is to have an automated list of duplicate ID's that have different tags (someone changed their name).  The list would show the ID number in one cell, then in the next cell, show all of the tags they have used (using textJoin() and sort() to make it easier to read).

The second is to grab a list of tags used based on a separate list of ID's (known list of users who have failed to follow through).

I've tried and failed with vlookup(), filter(), query(), and regular lookup().  When I tried filter() for using a list, it only seems to look at the first item, but ignores anything after that.  If I try to expand the length of the list (instead of F2 I make it F2:F) it turns red and won't work.

Using conditional formatting, I'm able to get duplicates to highlight within the range.  However, I'm trying to take it a step further and retrieve matches.  Sort of like an automated filter system to show known duplicates.

What am I not thinking of here?

Edit:
Here is some dummy info to give an idea...

Alred         970192322624802134
Barry         493288047120884104
Clark         648567312202297155
Dick          336368714780211631
Enigma        513446866409315771
Flash         493288047120884104
Green Arrow   382294342593163268
Harley        894386762337961412
Ivy           192571739320652789
Jimmy         662344040550649441
Krypto        944264752128564134
Lois          608531705193876711
Mera          461451144314768165
Nyssa         533348352505340666
Oliver        382294342593163268
Perry         877529730964781752
Robin         336368714780211631
Superman      648567312202297155
Thomas        969367121152160055

Obviously the names would have a # sign followed by a 4 digit number, but it's an irrelevant factor for this matter.

Looking at the list, you can see that some of the ID's (column of numbers) are the same, but with different names.

So the goal is to have a separate column that would go through, find ID's that are duplicated, and then list all names with that matching ID.

Example:

648567312202297155   Clark, Superman
336368714780211631   Dick, Robin
382294342593163268   Green Arrow, Oliver
etc

For the second one, a list of ID's where matching ID's would show all matching names.  Sort of like if the above only listed ID's that have more than one entry, and then that list were to be used to find names, except the list of ID's could be generated by other means.  To break it down into two simplified tasks...  One finds duplicate ID's and simply lists those ID's (one time each), then another looks up those ID's and lists all matching entries (ie, the names).

Edit:
This link is an example of what I'm trying to do, but it's not working for me.
Google Sheet Query - Group / concatenate multiple rows

I have A(A2:A)=Names/tag, B(B2:B)=ID, F(F2:F)=ID's to filter.
When I try =join(",",filter(A:A,B:B=F2)) it returns the first entry but then stops.

Also, when I try to simulate the other page (values and formulas), it only returns the results for Bill (Red,Blue,Yellow), but not for Sarah.

By simulate, I mean that I added an empty sheet and filled in the values and formulas as shown in the image.

Body:
The solution combines the functions TEXTJOIN with ARRAYFORMULA. Given your sample data, you can create a list of the unique user IDs with the UNIQUE formula. So cell D1 has =UNIQUE($B$1:$B$19). This fills in the data in column D.

The formula in column E then matches each of the unique user IDs in column B with any of the names in column A using ARRAYFORMULA to return all of the names, then concatenates the list of names using TEXTJOIN. The formula in column E is

=TEXTJOIN(",",true,arrayformula(if($D7=$B$1:$B$19,$A$1:$A$19,"")))


问:
Getting 404 on all outbound HTTP calls from pods inside istio mesh
I have istio v1.1.6 installed on Kubernetes v1.11 using Helm chart provided in istio repository with bunch of overrides including:

```<code>global:
  outboundTrafficPolicy:
    mode: ALLOW_ANY
pilot:
  env:
    PILOT_ENABLE_FALLTHROUGH_ROUTE: "1"
mixer:
  enabled: true
galley:
  enabled: true
security:
  enabled: false
</code>```

The problem is that I can't make any simple outbound HTTP request to a service running on port 80 (inside & outside of the mesh) from a pod which is inside istio mesh and has istio-proxy injected as sidecar. The response is always 404:

user@pod-12345-12345$ curl -v http://httpbin.org/headers
* Hostname was NOT found in DNS cache
*   Trying 52.200.83.146...
* Connected to httpbin.org (52.200.83.146) port 80 (#0)
> GET /headers HTTP/1.1
> User-Agent: curl/7.38.0
> Host: httpbin.org
> Accept: */*
>
< HTTP/1.1 404 Not Found
< date: Wed, 15 May 2019 05:43:24 GMT
* Server envoy is not blacklisted
< server: envoy
< content-length: 0
<
* Connection #0 to host httpbin.org left intact
```

<p>The response flag in the istio-proxy logs from envoy states that it can't find the proper route:</p>

```"GET / HTTP/1.1" 404 NR "-" 0 0 0 - "-" "curl/7.38.0" "238d0799-f83d-4e5e-94e7-79de4d14fa53" "httpbin.org" "-" - - 172.217.27.14:80 100.99.149.201:52892 -
```

NR: No route configured for a given request in addition to 404 response code.

Probably worths to add that:

Other outbound calls to any ports other than 80 works perfectly fine.

Checking proxy-status also shows nothing: all pods are SYNCED.

mTLS is disabled

The example above is a call to external service but calls to internal services (eg: curl another-service.svc.cluster.local/health) have the same issue.

I expecte calls to internal mesh services work out of the box, tho even I tried to define DestinationRoute and ServiceEntry and that did not help as well.

I don't really want to add  traffic.sidecar.istio.io/excludeOutboundIPRanges: "0.0.0.0/0" annotation to deployment as according to docs:

this approach completely bypasses the sidecar, essentially disabling all of Istio’s features for the specified IPs

Any idea where else I can look or what is missing?

答:
To me it looks like you have a short connection timeouts defined in your istio-proxy sidecar, please check here similar github issue of Envoy's project.

btw. as @Robert Panzer mentioned, sharing the whole dump of istio-proxy config would help much in investigating your particular case.

Body:
I have istio v1.1.6 installed on Kubernetes v1.11 using Helm chart provided in istio repository with bunch of overrides including:

global:
  outboundTrafficPolicy:
    mode: ALLOW_ANY
pilot:
  env:
    PILOT_ENABLE_FALLTHROUGH_ROUTE: "1"
mixer:
  enabled: true
galley:
  enabled: true
security:
  enabled: false

The problem is that I can't make any simple outbound HTTP request to a service running on port 80 (inside & outside of the mesh) from a pod which is inside istio mesh and has istio-proxy injected as sidecar. The response is always 404:

user@pod-12345-12345$ curl -v http://httpbin.org/headers
* Hostname was NOT found in DNS cache
*   Trying 52.200.83.146...
* Connected to httpbin.org (52.200.83.146) port 80 (#0)
> GET /headers HTTP/1.1
> User-Agent: curl/7.38.0
> Host: httpbin.org
> Accept: */*
>
< HTTP/1.1 404 Not Found
< date: Wed, 15 May 2019 05:43:24 GMT
* Server envoy is not blacklisted
< server: envoy
< content-length: 0
<
* Connection #0 to host httpbin.org left intact

The response flag in the istio-proxy logs from envoy states that it can't find the proper route:

"GET / HTTP/1.1" 404 NR "-" 0 0 0 - "-" "curl/7.38.0" "238d0799-f83d-4e5e-94e7-79de4d14fa53" "httpbin.org" "-" - - 172.217.27.14:80 100.99.149.201:52892 -

NR: No route configured for a given request in addition to 404 response code.

Probably worths to add that:

Other outbound calls to any ports other than 80 works perfectly fine.

Checking proxy-status also shows nothing: all pods are SYNCED.

mTLS is disabled

The example above is a call to external service but calls to internal services (eg: curl another-service.svc.cluster.local/health) have the same issue.

I expecte calls to internal mesh services work out of the box, tho even I tried to define DestinationRoute and ServiceEntry and that did not help as well.

I don't really want to add  traffic.sidecar.istio.io/excludeOutboundIPRanges: "0.0.0.0/0" annotation to deployment as according to docs:

this approach completely bypasses the sidecar, essentially disabling all of Istio’s features for the specified IPs

Any idea where else I can look or what is missing?


问:
Questions about Raft consensus configuration
I have a question about raft configuration on Hyperledger Fabric 1.41, why on configtx.yaml file you configure all your raft orderers to listen on 7050 port, however on the docker-compose file all the orderers are listening to 7050,8050,9050, etc ? How does this works?

Configtx.yaml

```<code> Orderer:
            <<: *OrdererDefaults
            OrdererType: etcdraft
            EtcdRaft:
                Consenters:
                - Host: orderer.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt
                - Host: orderer2.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt
                - Host: orderer3.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt
                - Host: orderer4.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt
                - Host: orderer5.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/server.crt
            Addresses:
                - orderer.example.com:7050
                - orderer2.example.com:7050
                - orderer3.example.com:7050
                - orderer4.example.com:7050
                - orderer5.example.com:7050
</code>```

Docker-compose-etcdraft2.yaml (eg. orderer3 section)

```<code>
  orderer3.example.com:
    extends:
      file: base/peer-base.yaml
      service: orderer-base
    container_name: orderer3.example.com
    networks:
    - byfn
    volumes:
        - ./channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block
        - ./crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/msp:/var/hyperledger/orderer/msp
        - ./crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/:/var/hyperledger/orderer/tls
        - orderer3.example.com:/var/hyperledger/production/orderer
    ports:
    - 9050:7050

</code>```

Following the same pattern I think that connection.json should be updated including all the orderers with its port, right?

答:
All orderers are listening on port 7050 of the containers.

The code below maps the port of the host to container, so your host will redirect traffic to container 7050 port when receiving on 9050.

```<code>ports:
- 9050:7050
</code>```

Its Because the containers inside the same docker compose can reach each other by using the container port.

This 9050, 8050, would only be useful in case you need to reach them from outside docker-compose.

Body:
I have a question about raft configuration on Hyperledger Fabric 1.41, why on configtx.yaml file you configure all your raft orderers to listen on 7050 port, however on the docker-compose file all the orderers are listening to 7050,8050,9050, etc ? How does this works?

Configtx.yaml

 Orderer:
            <<: *OrdererDefaults
            OrdererType: etcdraft
            EtcdRaft:
                Consenters:
                - Host: orderer.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt
                - Host: orderer2.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt
                - Host: orderer3.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt
                - Host: orderer4.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt
                - Host: orderer5.example.com
                  Port: 7050
                  ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/server.crt
                  ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/server.crt
            Addresses:
                - orderer.example.com:7050
                - orderer2.example.com:7050
                - orderer3.example.com:7050
                - orderer4.example.com:7050
                - orderer5.example.com:7050

Docker-compose-etcdraft2.yaml (eg. orderer3 section)

  orderer3.example.com:
    extends:
      file: base/peer-base.yaml
      service: orderer-base
    container_name: orderer3.example.com
    networks:
    - byfn
    volumes:
        - ./channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block
        - ./crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/msp:/var/hyperledger/orderer/msp
        - ./crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/:/var/hyperledger/orderer/tls
        - orderer3.example.com:/var/hyperledger/production/orderer
    ports:
    - 9050:7050

Following the same pattern I think that connection.json should be updated including all the orderers with its port, right?

Body:
All orderers are listening on port 7050 of the containers.

The code below maps the port of the host to container, so your host will redirect traffic to container 7050 port when receiving on 9050.

ports:
- 9050:7050

Its Because the containers inside the same docker compose can reach each other by using the container port.

This 9050, 8050, would only be useful in case you need to reach them from outside docker-compose.