问:
Process sometimes hangs while waiting for Exit
What may be the reason of my process hanging while waiting for exit?

This code has to start powershell script which inside performs many action e.g start recompiling code via MSBuild, but probably the problem is that it generates too much output and this code gets stuck while waiting to exit even after power shell script executed correctly

it's kinda "weird" because sometimes this code works fine and sometimes it just gets stuck.

Code hangs at:

process.WaitForExit(ProcessTimeOutMiliseconds);

Powershell script executes in like 1-2sec meanwhile timeout is 19sec.

```<code>public static (bool Success, string Logs) ExecuteScript(string path, int ProcessTimeOutMiliseconds, params string[] args)
{
    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();

    using (var outputWaitHandle = new AutoResetEvent(false))
    using (var errorWaitHandle = new AutoResetEvent(false))
    {
        try
        {
            using (var process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "powershell.exe",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    Arguments = $"-ExecutionPolicy Bypass -File \"{path}\"",
                    WorkingDirectory = Path.GetDirectoryName(path)
                };

                if (args.Length > 0)
                {
                    var arguments = string.Join(" ", args.Select(x => $"\"{x}\""));
                    process.StartInfo.Arguments += $" {arguments}";
                }

                output.AppendLine($"args:'{process.StartInfo.Arguments}'");

                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit(ProcessTimeOutMiliseconds);

                var logs = output + Environment.NewLine + error;

                return process.ExitCode == 0 ? (true, logs) : (false, logs);
            }
        }
        finally
        {
            outputWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
            errorWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
        }
    }
}
</code>```

Script:

```<code>start-process $args[0] App.csproj -Wait -NoNewWindow

[string]$sourceDirectory  = "\bin\Debug\*"
[int]$count = (dir $sourceDirectory | measure).Count;

If ($count -eq 0)
{
    exit 1;
}
Else
{
    exit 0;
}
</code>```

where

$args[0] = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"

Edit

To @ingen's solution I added small wrapper which retries to execute hanged up MS Build

```<code>public static void ExecuteScriptRx(string path, int processTimeOutMilliseconds, out string logs, out bool success, params string[] args)
{
    var current = 0;
    int attempts_count = 5;
    bool _local_success = false;
    string _local_logs = "";

    while (attempts_count > 0 && _local_success == false)
    {
        Console.WriteLine($"Attempt: {++current}");
        InternalExecuteScript(path, processTimeOutMilliseconds, out _local_logs, out _local_success, args);
        attempts_count--;
    }

    success = _local_success;
    logs = _local_logs;
}
</code>```

Where InternalExecuteScript is ingen's code

答:
The problem is that if you redirect StandardOutput and/or StandardError the internal buffer can become full.

To solve the issues aforementioned you can run the process in separate threads. I do not use WaitForExit, I utilize the process exited event which will return the ExitCode of the process asynchronously ensuring it has completed.

```<code>public async Task<int> RunProcessAsync(params string[] args)
    {
        try
        {
            var tcs = new TaskCompletionSource<int>();

            var process = new Process
            {
                StartInfo = {
                    FileName = 'file path',
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    Arguments = "shell command",
                    UseShellExecute = false,
                    CreateNoWindow = true
                },
                EnableRaisingEvents = true
            };

            process.Exited += (sender, args) =>
            {
                tcs.SetResult(process.ExitCode);
                process.Dispose();
            };

            process.Start();
            // Use asynchronous read operations on at least one of the streams.
            // Reading both streams synchronously would generate another deadlock.
            process.BeginOutputReadLine();
            string tmpErrorOut = await process.StandardError.ReadToEndAsync();
            //process.WaitForExit();

            return await tcs.Task;
        }
        catch (Exception ee) {
            Console.WriteLine(ee.Message);
        }
        return -1;
    }
</code>```

The above code is battle tested calling FFMPEG.exe with command line arguments. I was converting mp4 files to mp3 files and doing over 1000 videos at a time without failing. Unfortunately I do not have direct power shell experience but hope this helps.

Body:
What may be the reason of my process hanging while waiting for exit?

This code has to start powershell script which inside performs many action e.g start recompiling code via MSBuild, but probably the problem is that it generates too much output and this code gets stuck while waiting to exit even after power shell script executed correctly

it's kinda "weird" because sometimes this code works fine and sometimes it just gets stuck.

Code hangs at:

process.WaitForExit(ProcessTimeOutMiliseconds);

Powershell script executes in like 1-2sec meanwhile timeout is 19sec.

public static (bool Success, string Logs) ExecuteScript(string path, int ProcessTimeOutMiliseconds, params string[] args)
{
    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();

    using (var outputWaitHandle = new AutoResetEvent(false))
    using (var errorWaitHandle = new AutoResetEvent(false))
    {
        try
        {
            using (var process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "powershell.exe",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    Arguments = $"-ExecutionPolicy Bypass -File \"{path}\"",
                    WorkingDirectory = Path.GetDirectoryName(path)
                };

                if (args.Length > 0)
                {
                    var arguments = string.Join(" ", args.Select(x => $"\"{x}\""));
                    process.StartInfo.Arguments += $" {arguments}";
                }

                output.AppendLine($"args:'{process.StartInfo.Arguments}'");

                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit(ProcessTimeOutMiliseconds);

                var logs = output + Environment.NewLine + error;

                return process.ExitCode == 0 ? (true, logs) : (false, logs);
            }
        }
        finally
        {
            outputWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
            errorWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
        }
    }
}

Script:

start-process $args[0] App.csproj -Wait -NoNewWindow

[string]$sourceDirectory  = "\bin\Debug\*"
[int]$count = (dir $sourceDirectory | measure).Count;

If ($count -eq 0)
{
    exit 1;
}
Else
{
    exit 0;
}

where

$args[0] = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"

Edit

To @ingen's solution I added small wrapper which retries to execute hanged up MS Build

public static void ExecuteScriptRx(string path, int processTimeOutMilliseconds, out string logs, out bool success, params string[] args)
{
    var current = 0;
    int attempts_count = 5;
    bool _local_success = false;
    string _local_logs = "";

    while (attempts_count > 0 && _local_success == false)
    {
        Console.WriteLine($"Attempt: {++current}");
        InternalExecuteScript(path, processTimeOutMilliseconds, out _local_logs, out _local_success, args);
        attempts_count--;
    }

    success = _local_success;
    logs = _local_logs;
}

Where InternalExecuteScript is ingen's code

Body:
The problem is that if you redirect StandardOutput and/or StandardError the internal buffer can become full.

To solve the issues aforementioned you can run the process in separate threads. I do not use WaitForExit, I utilize the process exited event which will return the ExitCode of the process asynchronously ensuring it has completed.

public async Task<int> RunProcessAsync(params string[] args)
    {
        try
        {
            var tcs = new TaskCompletionSource<int>();

            var process = new Process
            {
                StartInfo = {
                    FileName = 'file path',
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    Arguments = "shell command",
                    UseShellExecute = false,
                    CreateNoWindow = true
                },
                EnableRaisingEvents = true
            };

            process.Exited += (sender, args) =>
            {
                tcs.SetResult(process.ExitCode);
                process.Dispose();
            };

            process.Start();
            // Use asynchronous read operations on at least one of the streams.
            // Reading both streams synchronously would generate another deadlock.
            process.BeginOutputReadLine();
            string tmpErrorOut = await process.StandardError.ReadToEndAsync();
            //process.WaitForExit();

            return await tcs.Task;
        }
        catch (Exception ee) {
            Console.WriteLine(ee.Message);
        }
        return -1;
    }

The above code is battle tested calling FFMPEG.exe with command line arguments. I was converting mp4 files to mp3 files and doing over 1000 videos at a time without failing. Unfortunately I do not have direct power shell experience but hope this helps.


来源: stackexchange

问:
Which is quicker/more efficient?
Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.

Imagine a Vector3f class with an add method.

Code One:

```<code>Vector3f Vector3f::add(const Vector3f &rhs) const {
    Vector3f result;
    result.x(x() + rhs.x());
    result.y(y() + rhs.y());
    result.z(z() + rhs.z());
    return result;
}
</code>```

Code Two:

```<code>Vector3f Vector3f::add(const Vector3f &rhs) const {
    return Vector3f(
                x() + rhs.x(),
                y() + rhs.y(),
                z() + rhs.z());
}
</code>```

I know that the second code segment is more efficient, and I was hoping someone could give me a definitive answer as to why. I'm sure it's something to do with temporary objects.

答:
Actually, it has more to do with initialization:  when you 'default construct' your Vector3f result, the x, y, z members will be initialized.  You don't always control the cost of that, especially with 'heavy' members.

Calling a constructor with all member values allows the object to initialize it's members first time right.

But if you really want to save some intermediate steps, you can create a mutator on the class Vector3f, eliminating the need for a temporary:

```<code>class Vector3f {
   ...
   Vector3f& operator+=( const Vector3f& other ) {
      x += other.x;
      y += other.y;
      z += other.z;
      return *this;
   }
};
</code>```

and use it like

```<code>Vector3f a( 1,2,3 );
a += Vector3f( 0,0,1 );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Which is quicker/more efficient?

Body:
Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.

Imagine a Vector3f class with an add method.

Code One:

Vector3f Vector3f::add(const Vector3f &rhs) const {
    Vector3f result;
    result.x(x() + rhs.x());
    result.y(y() + rhs.y());
    result.z(z() + rhs.z());
    return result;
}

Code Two:

Vector3f Vector3f::add(const Vector3f &rhs) const {
    return Vector3f(
                x() + rhs.x(),
                y() + rhs.y(),
                z() + rhs.z());
}

I know that the second code segment is more efficient, and I was hoping someone could give me a definitive answer as to why. I'm sure it's something to do with temporary objects.

Body:
Actually, it has more to do with initialization:  when you 'default construct' your Vector3f result, the x, y, z members will be initialized.  You don't always control the cost of that, especially with 'heavy' members.

Calling a constructor with all member values allows the object to initialize it's members first time right.

But if you really want to save some intermediate steps, you can create a mutator on the class Vector3f, eliminating the need for a temporary:

class Vector3f {
   ...
   Vector3f& operator+=( const Vector3f& other ) {
      x += other.x;
      y += other.y;
      z += other.z;
      return *this;
   }
};

and use it like

Vector3f a( 1,2,3 );
a += Vector3f( 0,0,1 );


问:
Text Selection highlighting expanding to the whole div's width (CSS)
I am working on a website but when I select (highlight) the text paragraphs, the selection expands to the whole section width. How do I avoid this?

This is the HTML code:

.intro-project {
  font: 140%/1.5;
  width: 100vw;
  height: auto;
  margin: 0 auto;
  padding-top: 5%;
  color: rgba(29, 29, 27, 1)
}

.intro-project p {
  width: 55%;
  margin: 0 auto
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="intro-project">
    <p>
      Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex
      ea commodo consequat.
    </p>
    <ul>
      <li>Lorem Ipsum</li>
      <li>Lorem Ipsum</li>
      <li>Lorem Ipsum</li>
    </ul>
  </div>
</section></code>```

And this is how it looks like:

答:
Without seeing the additional code you've applied already, a simple CSS solution could be:

```<code>p{
  -webkit-user-select: all;
  -moz-user-select: all;
  -ms-user-select: all;
  user-select: all;
}
</code>```

When you click on the p it should highlight the inner text. If you don't wish this to be applied to all P tags then you can add a class to the P tags, specifying which should highlight.

Note: Not sure if MS supports yet.

ContentLicense: CC BY-SA 4.0

Body:
I am working on a website but when I select (highlight) the text paragraphs, the selection expands to the whole section width. How do I avoid this?

This is the HTML code:

.intro-project {
  font: 140%/1.5;
  width: 100vw;
  height: auto;
  margin: 0 auto;
  padding-top: 5%;
  color: rgba(29, 29, 27, 1)
}

.intro-project p {
  width: 55%;
  margin: 0 auto
}

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex
      ea commodo consequat.

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

And this is how it looks like:

Body:
Without seeing the additional code you've applied already, a simple CSS solution could be:

p{
  -webkit-user-select: all;
  -moz-user-select: all;
  -ms-user-select: all;
  user-select: all;
}

When you click on the p it should highlight the inner text. If you don't wish this to be applied to all P tags then you can add a class to the P tags, specifying which should highlight.

Note: Not sure if MS supports yet.


问:
Angular / JS generate random Uniq Serial ID
I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :

```<code>public generateUniqSerial() {
   return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
     let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
     return v.toString(16)
   })
 }
</code>```

it give a result like that : "7f8f-0d9a-fd5-450f"
, how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?

答: When I'm asked to do things like this I like to start with a "string of letters" and a "string of digits."  My logic then simply consists of choosing a random index into the appropriate source string to get each character that I need.  I like to do it this way because to me it's "extremely obvious" what I am doing and equally easy to desk-check that it will work.</p>

Body:
I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :

public generateUniqSerial() {
   return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
     let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
     return v.toString(16)
   })
 }

it give a result like that : "7f8f-0d9a-fd5-450f"
, how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?


问:
How to use the GWT EventBus
I wonder how to use the EventBus or whether there are some better solutions to send an Event through the project.

Widget1 has a Button. Widget2 has a Label, that should change when I press the button. These widgets are in a DockLayout:

```<code>RootLayoutPanel rootLayoutPanel = RootLayoutPanel.get();
DockLayoutPanel dock = new DockLayoutPanel(Unit.EM);

dock.addWest(new Widget1(), 10);
dock.add(new Widget2());

rootLayoutPanel.add(dock);
</code>```

I have declared an handleClickAlert in Widget1:

```<code>@UiHandler("button")
void handleClickAlert(ClickEvent e) {
    //fireEvent(e);
}
</code>```

答:
When you divide the project into logical parts (for example with MVP), then the different parts sometimes need to communicate. Typical this communication is done by sending status changes, e.g.:

user logged-in / logged-out.

user navigated directly via URL to a page, so the menu needs to be updated.

Using the event bus is quite logical in those cases.

To use it you instantiate one EventBus per app which is then used by all other classes. To achieve this use a static field, factory or dependency injection (GIN in case of GWT).

Example with your own event types:

```<code>public class AppUtils{

    public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);
}
</code>```

Normally you'd also create your own event types and handlers:

```<code>public class AuthenticationEvent extends GwtEvent<AuthenticationEventHandler> {

public static Type<AuthenticationEventHandler> TYPE = new Type<AuthenticationEventHandler>();

  @Override
public Type<AuthenticationEventHandler> getAssociatedType() {
    return TYPE;
}

@Override
protected void dispatch(AuthenticationEventHandler handler) {
    handler.onAuthenticationChanged(this);
}
}
</code>```

and the handler:

```<code>public interface AuthenticationEventHandler extends EventHandler {
    void onAuthenticationChanged(AuthenticationEvent authenticationEvent);
}
</code>```

Then you use it like this:

```<code>AppUtils.EVENT_BUS.addHandler(AuthenticationEvent.TYPE, new AuthenticationEventHandler()     {
        @Override
        public void onAuthenticationChanged(AuthenticationEvent authenticationEvent) {
            // authentication changed - do something
        }
    });
</code>```

and fire the event:

```<code>AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent());
</code>```

Title: How to use the GWT EventBus

Body:
I wonder how to use the EventBus or whether there are some better solutions to send an Event through the project.

Widget1 has a Button. Widget2 has a Label, that should change when I press the button. These widgets are in a DockLayout:

RootLayoutPanel rootLayoutPanel = RootLayoutPanel.get();
DockLayoutPanel dock = new DockLayoutPanel(Unit.EM);

dock.addWest(new Widget1(), 10);
dock.add(new Widget2());

rootLayoutPanel.add(dock);

I have declared an handleClickAlert in Widget1:

@UiHandler("button")
void handleClickAlert(ClickEvent e) {
    //fireEvent(e);
}

Body:
When you divide the project into logical parts (for example with MVP), then the different parts sometimes need to communicate. Typical this communication is done by sending status changes, e.g.:

user logged-in / logged-out.

user navigated directly via URL to a page, so the menu needs to be updated.

Using the event bus is quite logical in those cases.

To use it you instantiate one EventBus per app which is then used by all other classes. To achieve this use a static field, factory or dependency injection (GIN in case of GWT).

Example with your own event types:

public class AppUtils{

    public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);
}

Normally you'd also create your own event types and handlers:

public class AuthenticationEvent extends GwtEvent<AuthenticationEventHandler> {

public static Type<AuthenticationEventHandler> TYPE = new Type<AuthenticationEventHandler>();

  @Override
public Type<AuthenticationEventHandler> getAssociatedType() {
    return TYPE;
}

@Override
protected void dispatch(AuthenticationEventHandler handler) {
    handler.onAuthenticationChanged(this);
}
}

and the handler:

public interface AuthenticationEventHandler extends EventHandler {
    void onAuthenticationChanged(AuthenticationEvent authenticationEvent);
}

Then you use it like this:

AppUtils.EVENT_BUS.addHandler(AuthenticationEvent.TYPE, new AuthenticationEventHandler()     {
        @Override
        public void onAuthenticationChanged(AuthenticationEvent authenticationEvent) {
            // authentication changed - do something
        }
    });

and fire the event:

AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent());


问:
Is there a workaround for argmin/argmax aggregation in Snowflake?
I am looking into a way of computing argmin or argmax aggregation of multiple rows in Snowflake similar to Hive or Presto.

In Hive, one can use a workaround with (named) structs because the aggregation function gets applied to the first element of the struct. Here is an example:

SELECT max(named_struct('y', y, 'x', x)).x FROM t
```

<p>Now I am asking myself if there is a similar way to do this in Snowflake.</p>

<p>In Snowflake we have an <code>OBJECT</code> datatype with similar properties. Can I use the following code to compute argmin or argmax like in the Hive example? Are min/max aggregations for objects also performed on the first element of the object?</p>

<pre class="lang-sql prettyprint-override"><code>SELECT max(object_construct('y', y, 'x', x)).x FROM t
</code>```

Running the above code returns an error: SQL compilation error: Function MAX does not support OBJECT argument type.. It actually doesn't support any complex type.

答:
If I have correctly understood the logic of argmin(), then you could implement it as a javascript UDF like so:

```<code>create or replace function argmin("a" object, "b" object)
  returns object
  language javascript
as
$$

    for (let [k,v] of Object.entries(a))
        if (v==b[k])
            continue
        else
            return v < b[k] ? a : b

    return b

$$;
</code>```

And applied like this:

```<code>with t as (
  select
     object_construct('x',1, 'y',2) a,
     object_construct('x',2, 'y',1) b
)
select argmin(t.a,t.b):y from t;
</code>```

Actually this functionality is built in:

```<code>select
    object_construct('x',1, 'y',2) a,
    object_construct('x',2, 'y',1) b,
    iff(a<b, a, b) : y
;
</code>```

Even more concisely:

```<code>select
   object_construct('x',1, 'y',2) a,
   object_construct('x',2, 'y',1) b,
   least(a,b):y,
   greatest(a,b):y;
</code>```

Body:
I am looking into a way of computing argmin or argmax aggregation of multiple rows in Snowflake similar to Hive or Presto.

In Hive, one can use a workaround with (named) structs because the aggregation function gets applied to the first element of the struct. Here is an example:

SELECT max(named_struct('y', y, 'x', x)).x FROM t

Now I am asking myself if there is a similar way to do this in Snowflake.

In Snowflake we have an OBJECT datatype with similar properties. Can I use the following code to compute argmin or argmax like in the Hive example? Are min/max aggregations for objects also performed on the first element of the object?

SELECT max(object_construct('y', y, 'x', x)).x FROM t

Running the above code returns an error: SQL compilation error: Function MAX does not support OBJECT argument type.. It actually doesn't support any complex type.

Body:
If I have correctly understood the logic of argmin(), then you could implement it as a javascript UDF like so:

create or replace function argmin("a" object, "b" object)
  returns object
  language javascript
as
$$

    for (let [k,v] of Object.entries(a))
        if (v==b[k])
            continue
        else
            return v < b[k] ? a : b

    return b

$$;

And applied like this:

with t as (
  select
     object_construct('x',1, 'y',2) a,
     object_construct('x',2, 'y',1) b
)
select argmin(t.a,t.b):y from t;

Actually this functionality is built in:

select
    object_construct('x',1, 'y',2) a,
    object_construct('x',2, 'y',1) b,
    iff(a<b, a, b) : y
;

Even more concisely:

select
   object_construct('x',1, 'y',2) a,
   object_construct('x',2, 'y',1) b,
   least(a,b):y,
   greatest(a,b):y;


问:
Can't connect from azure resource to Azure database for postgres server
I can't connect from azure resource (aks node) to Azure postgres using pgcli. I also tried directly from node and got the same error message:

FATAL:  Client from Azure Virtual Networks is not allowed to access the server. Please make sure your Virtual Network is correctly configured.

Firewall rules in the resource are on:
Allow access to Azure services: ON

Running the same pgcli login command on my computer and on another azure resource seems to work fine.

Adding Firewall rules to all IPs return the same error.

Curl from the problematic server (host:5432) returns a reply, so it's not an outbound issue.

答:
I encountered the same problem.
All I did was to switch Allow access to Azure services to ON .


问:
Is Linq2XSD Dead?
Does anyone have any updates on this since the alpha 0.2?</p>

答:
Interesting idea, and is actually what I thought LINQ to XML would be until I looked in to it.

This is a semi-official blog from the Microsoft XML team:
http://blogs.msdn.com/xmlteam/archive/2006/11/27/typed-xml-programmer-welcome-to-linq.aspx

The series of posts dried up sometime ago:
http://blogs.msdn.com/ralflammel/archive/2006/11/13/table-of-contents-for-typed-xml-programmer-series.aspx

Perhaps its been shelved for now.

OwnerDisplayName: Jonathan Parker

ContentLicense: CC BY-SA 2.5

Title: Is Linq2XSD Dead?

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: MattH


问:
return code of console application

Possible Duplicate:

  How do I get the application exit code from a Windows command line?

I have a console application. It will be executed from command prompt. It will return either 0 or 1 from main method. How can I know that what value is returned by the application?

答:
Assuming you're on Windows (C# tag)</p>

```<code>echo %errorlevel%
</code>```

Title: return code of console application

Body:
Assuming you're on Windows (C# tag)

echo %errorlevel%


问:
Should I still truncate a postgresql database if I am truncating and refilling the tables instead of deleting/inserting/upserting?
The production database at my company is running significantly slower than the test database (local ~5ms, test ~18ms, production ~1-2 sec). We've been trying to look into why and will be doing some EXPLAIN ANALYZE on key queries on a secure shell psql instance in our cloud.

I've been trying to read up on database optimization and have come across postgresql's VACUUM and am wondering if running this might help. We don't update the production database often -- once each release, though the migrations involve dropping or truncating tables as necessary and then importing new data. I'm curious if VACUUM would be potentially helpful here? If it would be, would we be seeing similar slowdowns in a spiped instance of our test database?

答:
VACUUM could help if there are a lots of DELETE and UPDATE in the database.

See https://dba.stackexchange.com/questions/36984/how-to-determine-if-a-postgres-database-needs-to-be-vaccumed


问:
Micronaut multiple JDBC templates not working
I am trying to write a micronaut function which is deploying as AWS Lambda.

With my micronaut function, I need to connect to multiple databases and get the data and put details into AWS SQS. In this regard, I am trying to use JDBC template approach to get data from different data sources. But I am getting error: Multiple possible bean candidates found: [org.springframework.jdbc.core.JdbcTemplate, org.springframework.jdbc.core.JdbcTemplate, org.springframework.jdbc.core.JdbcTemplate] error

```<code>package io.test.invoice;

import io.micronaut.context.annotation.Factory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.inject.Named;
import javax.inject.Singleton;
import javax.sql.DataSource;

@Factory
public class JdbcTemplateFactory {

    @Singleton
    JdbcTemplate jdbcTemplateOne(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Singleton
    JdbcTemplate jdbcTemplateTwo(@Named(value = "database2") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
</code>```

```<code>package io.test.invoice;

import io.micronaut.context.annotation.Requires;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.inject.Singleton;
import java.util.List;

@Singleton
@Requires(beans = JdbcTemplate.class)
public class CodeSetRepository {
    private final JdbcTemplate jdbcTemplateOne;
    private final JdbcTemplate jdbcTemplateTwo;

    public CodeSetRepository(JdbcTemplate jdbcTemplateOne, JdbcTemplate jdbcTemplateTwo) {
        this.jdbcTemplateOne = jdbcTemplateOne;
        this.jdbcTemplateTwo = jdbcTemplateTwo;
    }

    public List<CodeSet> getAllCodeSets() {
        String SELECT_QUERY = "SELECT * FROM public.code_set";
        return this.jdbcTemplateTwo.query(SELECT_QUERY, new BeanPropertyRowMapper(CodeSet.class));
    }

    public List<Country> getAllCountries() {
        String SELECT_QUERY = "SELECT * FROM public.country";
        return this.jdbcTemplateOne.query(SELECT_QUERY, new BeanPropertyRowMapper(Country.class));
    }
}
</code>```

Could anyone help with this please?

答:
The name of the parameter jdbcTemplateOne has no bearing on the injection. So both parameters are asking for the same thing. There are multiple templates thus Micronaut doesn't know which one to inject.

In your factory you can create a template for each datasource with

```<code>@EachBean(DataSource.class)
JdbcTemplate jdbcTemplateOne(DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}
</code>```

Then the named qualifier of the datasource will transfer to the template. That means in your example you could inject @Named("database2") JdbcTemplate jdbcTemplate.

Alternatively you can add @Named qualifiers to the factory methods and then inject the jdbc templates with those qualifiers.

Body:
I am trying to write a micronaut function which is deploying as AWS Lambda.

With my micronaut function, I need to connect to multiple databases and get the data and put details into AWS SQS. In this regard, I am trying to use JDBC template approach to get data from different data sources. But I am getting error: Multiple possible bean candidates found: [org.springframework.jdbc.core.JdbcTemplate, org.springframework.jdbc.core.JdbcTemplate, org.springframework.jdbc.core.JdbcTemplate] error

package io.test.invoice;

import io.micronaut.context.annotation.Factory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.inject.Named;
import javax.inject.Singleton;
import javax.sql.DataSource;

@Factory
public class JdbcTemplateFactory {

    @Singleton
    JdbcTemplate jdbcTemplateOne(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Singleton
    JdbcTemplate jdbcTemplateTwo(@Named(value = "database2") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

package io.test.invoice;

import io.micronaut.context.annotation.Requires;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.inject.Singleton;
import java.util.List;

@Singleton
@Requires(beans = JdbcTemplate.class)
public class CodeSetRepository {
    private final JdbcTemplate jdbcTemplateOne;
    private final JdbcTemplate jdbcTemplateTwo;

    public CodeSetRepository(JdbcTemplate jdbcTemplateOne, JdbcTemplate jdbcTemplateTwo) {
        this.jdbcTemplateOne = jdbcTemplateOne;
        this.jdbcTemplateTwo = jdbcTemplateTwo;
    }

    public List<CodeSet> getAllCodeSets() {
        String SELECT_QUERY = "SELECT * FROM public.code_set";
        return this.jdbcTemplateTwo.query(SELECT_QUERY, new BeanPropertyRowMapper(CodeSet.class));
    }

    public List<Country> getAllCountries() {
        String SELECT_QUERY = "SELECT * FROM public.country";
        return this.jdbcTemplateOne.query(SELECT_QUERY, new BeanPropertyRowMapper(Country.class));
    }
}

Could anyone help with this please?

Body:
The name of the parameter jdbcTemplateOne has no bearing on the injection. So both parameters are asking for the same thing. There are multiple templates thus Micronaut doesn't know which one to inject.

In your factory you can create a template for each datasource with

@EachBean(DataSource.class)
JdbcTemplate jdbcTemplateOne(DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}

Then the named qualifier of the datasource will transfer to the template. That means in your example you could inject @Named("database2") JdbcTemplate jdbcTemplate.

Alternatively you can add @Named qualifiers to the factory methods and then inject the jdbc templates with those qualifiers.


问:
Get exit code of SFTP command run by system()
my program created a script that executes sftp command using expect. The script should download a file from SFTP server. When the script is generated, my program call system command to run the script. The script should exit when an error is encountered. For example, if the password is wrong. How am I be able to get the error returned by sftp command?

Below is the code that generates and run the script:

```<code>downloadFileFromServer()
{
    ofstream downloadScript;
    string  result, command;

    downloadScript.open("/temp/download.sh");

    downloadScript << "#!/usr/bin/expect -f \n";
    downloadScript << "spawn sftp -P " + <port number> +
                      " " + <user name> +
                      "@" + <IP> + "\n";
    downloadScript << "expect { \ntimeout {\nsend_user \"Permission denied\\n\"\nexit\n}\n}\n";

    downloadScript << "send \"" + <password> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"cd " + <source directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"lcd " + <destination directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"get " + <file name> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"exit\\n\"\n";
    downloadScript << "expect -exact \"$\"""\n";

    downloadScript.close();

    command = "chmod +x /temp/download.sh && /temp/download.sh";
    system(command.c_str());

}
</code>```

Below is the script created:

```<code>#!/usr/bin/expect -f
spawn sftp -P <port numner> <user name>@<IP>
expect "<user name>@<IP>'s password:"
expect {
timeout {
send_user "Permission denied\n"
exit
}
}
send "<password>\n"
expect "sftp>"
send "cd <source directory>\n"
expect "sftp>"
send "lcd <destination directory>\n"
expect "sftp>"
send "get <file name>\n"
expect "sftp>"
send "exit\n"
expect -exact "$"
</code>```

I want my program to catch the "Permission denied" error.

答:
All processes set a numeric exit code (0..255) when they end. Change the expect script so that you can distinguish between the script ending normally (when usually the exit code will be 0) and the explicit exit after an error. Do this by adding a parameter to that line, eg:

```<code>...
send_user "Permission denied\n"
exit 77
...
</code>```

You can recover this code in a C/C++ program with

```<code>int wstatus = system(command.c_str());
if (WIFEXITED(wstatus))
  int exit_code = WEXITSTATUS(wstatus);
</code>```

The wstatus is formed of 2 parts, the exit code of the process, and a some flags giving information about whether the process ran or was interrupted and so on. Use the above macros to extract the information.
See man 3 exit, man waitpid.

Body:
my program created a script that executes sftp command using expect. The script should download a file from SFTP server. When the script is generated, my program call system command to run the script. The script should exit when an error is encountered. For example, if the password is wrong. How am I be able to get the error returned by sftp command?

Below is the code that generates and run the script:

downloadFileFromServer()
{
    ofstream downloadScript;
    string  result, command;

    downloadScript.open("/temp/download.sh");

    downloadScript << "#!/usr/bin/expect -f \n";
    downloadScript << "spawn sftp -P " + <port number> +
                      " " + <user name> +
                      "@" + <IP> + "\n";
    downloadScript << "expect { \ntimeout {\nsend_user \"Permission denied\\n\"\nexit\n}\n}\n";

    downloadScript << "send \"" + <password> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"cd " + <source directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"lcd " + <destination directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"get " + <file name> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"exit\\n\"\n";
    downloadScript << "expect -exact \"$\"""\n";

    downloadScript.close();

    command = "chmod +x /temp/download.sh && /temp/download.sh";
    system(command.c_str());

}

Below is the script created:

#!/usr/bin/expect -f
spawn sftp -P <port numner> <user name>@<IP>
expect "<user name>@<IP>'s password:"
expect {
timeout {
send_user "Permission denied\n"
exit
}
}
send "<password>\n"
expect "sftp>"
send "cd <source directory>\n"
expect "sftp>"
send "lcd <destination directory>\n"
expect "sftp>"
send "get <file name>\n"
expect "sftp>"
send "exit\n"
expect -exact "$"

I want my program to catch the "Permission denied" error.

Body:
All processes set a numeric exit code (0..255) when they end. Change the expect script so that you can distinguish between the script ending normally (when usually the exit code will be 0) and the explicit exit after an error. Do this by adding a parameter to that line, eg:

...
send_user "Permission denied\n"
exit 77
...

You can recover this code in a C/C++ program with

int wstatus = system(command.c_str());
if (WIFEXITED(wstatus))
  int exit_code = WEXITSTATUS(wstatus);

The wstatus is formed of 2 parts, the exit code of the process, and a some flags giving information about whether the process ran or was interrupted and so on. Use the above macros to extract the information.
See man 3 exit, man waitpid.


问:
Passing spring active profile to Spark App in EMR
I have developed a Spark App which is using Spring Boot and a Spark Job is submitted to EMR Cluster an EMR Cluster based on an Event.

This works as expected if the Spark app is not a Spring Boot App. With Spring Boot app we needed to change the way uber JAR Files are built.

How ever when we submit the job spring active profile is not getting passed correctly.

spark-submit --verbose --master yarn --executor-memory 4g --class com.test.ConsoleApplication /home/hadoop/test.jar --driver-java-options='arg1 -Dspring.profiles.active=dev' --deploy-mode cluster --conf "spark.executor.extraJavaOptions=-Dspring.profiles.active=dev" --conf "spark.driver.extraJavaOptions=-Dspring.profiles.active=dev"```

What ever i do active profile is not getting passed and it is picking up the default "local" profile and running the spark app accordingly.

Converting Spark app to non-spring boot app is an option. But don't want to go that route unless there is no other option.

Thanks
Sateesh

答:
Able to resolve the issue by using bootstrap action on EMR Cluster. I am setting the environment variable to set the proper profile.

I am also able to pass using --conf option

```<code>--conf spark.driver.extraJavaOptions=-Dspring.profiles.active=prod
--conf spark.executor.extraJavaOptions=-Dspring.profiles.active=prod
</code>```

Body:
I have developed a Spark App which is using Spring Boot and a Spark Job is submitted to EMR Cluster an EMR Cluster based on an Event.

This works as expected if the Spark app is not a Spring Boot App. With Spring Boot app we needed to change the way uber JAR Files are built.

How ever when we submit the job spring active profile is not getting passed correctly.

spark-submit --verbose --master yarn --executor-memory 4g --class com.test.ConsoleApplication /home/hadoop/test.jar --driver-java-options='arg1 -Dspring.profiles.active=dev' --deploy-mode cluster --conf "spark.executor.extraJavaOptions=-Dspring.profiles.active=dev" --conf "spark.driver.extraJavaOptions=-Dspring.profiles.active=dev"

What ever i do active profile is not getting passed and it is picking up the default "local" profile and running the spark app accordingly.

Converting Spark app to non-spring boot app is an option. But don't want to go that route unless there is no other option.

Thanks
Sateesh

Body:
Able to resolve the issue by using bootstrap action on EMR Cluster. I am setting the environment variable to set the proper profile.

I am also able to pass using --conf option

--conf spark.driver.extraJavaOptions=-Dspring.profiles.active=prod
--conf spark.executor.extraJavaOptions=-Dspring.profiles.active=prod


问:
Reading variables of a function
I have a function with some code in it, but I'm not allowed to touch it (ie: add more code). Is there a way in PHP to get variables defined in that function?

Thank you for helping...

Ok, I've not been very clear. Here's what I'm trying to do.

```<code>$hello(function() {
    $a = "this is a variable!";
});
</code>```

I want this code to serve a file (a view), capable of reading variable $a.

I've recently tried playing around with php's reflection and found a way to extract static variables.... don't think there's a way for all other variables, but I'll keep searching.

```<code>$obj = new ReflectionFunction($my_closure);
print_r($obj->getStaticVariables());
</code>```

答: Variables defined in the function will only be visible within the scope of the function and so have no relevance to any other code on your site.</p>

Title: Reading variables of a function

Body:
I have a function with some code in it, but I'm not allowed to touch it (ie: add more code). Is there a way in PHP to get variables defined in that function?

Thank you for helping...

Ok, I've not been very clear. Here's what I'm trying to do.

$hello(function() {
    $a = "this is a variable!";
});

I want this code to serve a file (a view), capable of reading variable $a.

I've recently tried playing around with php's reflection and found a way to extract static variables.... don't think there's a way for all other variables, but I'll keep searching.

$obj = new ReflectionFunction($my_closure);
print_r($obj->getStaticVariables());


问:
Collecting comments from Reddit, outputting to CSV file
I'm trying to scrape comments from a certain submission on Reddit and output them to a CSV file.

```<code>import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)
</code>```

The problem is that for each cell the comments seem to be randomly split up. I want each comment in its own cell. Any ideas on how to achieve this?

答:
I'm guessing that the cells are not being split randomly, but being split at a comma, space semi-colon. You can choose what character you want the cells to be split at by using the delimiter parameter.</p>

```<code>import csv

with open('Reddit.csv', 'w') as csvfile:
    comments = ['comment one','comment two','comment three']
    csv_writer = csv.writer(csvfile, delimiter='-')
    csv_writer.writerow(comments)
</code>```

Body:
I'm trying to scrape comments from a certain submission on Reddit and output them to a CSV file.

import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)

The problem is that for each cell the comments seem to be randomly split up. I want each comment in its own cell. Any ideas on how to achieve this?

Body:
I'm guessing that the cells are not being split randomly, but being split at a comma, space semi-colon. You can choose what character you want the cells to be split at by using the delimiter parameter.

import csv

with open('Reddit.csv', 'w') as csvfile:
    comments = ['comment one','comment two','comment three']
    csv_writer = csv.writer(csvfile, delimiter='-')
    csv_writer.writerow(comments)


问:
Delete Duplicated with Right function
I'm looking for a macro to delete duplicates in a column, regarding their last value
e.g.

```<code>DES_FFAs_556
asda_FRF_556
</code>```

Because 556 is same, it should be deleted.

right now im getting the last 4 digits of each cell but i dont know how to remove duplicates with it

```<code>Sub duplicates()

Dim i As Long
Dim res As String
Dim WB As Workbook
Dim WS As Worksheet
Dim total As Long

Set WB = Workbooks("MQB37W - SW Architecture Matrix_Nw")
Set WS = WB.Sheets("SW Architecture Main - In...")

With WS
    total = .Cells(Rows.Count, 1).End(xlUp).Row

    For i = 4 To total
        res = Right(Cells(i, "A").Value, 4)
        WS.Range("A4:total").RemoveDuplicates Columns:=1, Header:=xlNo
    Next
End With
End Sub
</code>```

答: You do not need VBA for this. You can just use code from this tutorial in a new column and than based on that column you can filter, conditional format or delete rows. If you would like to indicate only rows after the first occurrence you can use COUNTIF. Ofcourse if you need VBA for something else you can apply the same logic I described above inside the VBA code.</p>

Title: Delete Duplicated with Right function

Body:
I'm looking for a macro to delete duplicates in a column, regarding their last value
e.g.

DES_FFAs_556
asda_FRF_556

Because 556 is same, it should be deleted.

right now im getting the last 4 digits of each cell but i dont know how to remove duplicates with it

Sub duplicates()

Dim i As Long
Dim res As String
Dim WB As Workbook
Dim WS As Worksheet
Dim total As Long

Set WB = Workbooks("MQB37W - SW Architecture Matrix_Nw")
Set WS = WB.Sheets("SW Architecture Main - In...")

With WS
    total = .Cells(Rows.Count, 1).End(xlUp).Row

    For i = 4 To total
        res = Right(Cells(i, "A").Value, 4)
        WS.Range("A4:total").RemoveDuplicates Columns:=1, Header:=xlNo
    Next
End With
End Sub


问:
How to display the list response which inside the object - react js
How to display the data in the below from the below json.

```<code>{
"a":
{
"b":[
  {"id":"ef718cce-1269-4fbd-827c-832f7824c025","name":"Veera6"},
  {"id":"0cda5ae9-e287-4666-804a-03f25e642d1f","name":"Veera9"},
  {"id":"31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39","name":"Veera8"},
  {"id":"6292054c-8bfc-4d2d-b2f8-92e2bac5a578","name":"Veera7"},
  {"id":"c6756e5c-8fa5-40a9-ab92-5242bda97de3","name":"Veera10"}]
}
}
</code>```

code snipped below.

```<code>render() {

        return (
            <table>
                <thead>
                    <tr>
                    {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            )
                        })
                    }
                    </tr>
                </thead>
                <tbody>
                    {
                        this.state.tags.b.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.id}</td>
                                  <td>{item.name}</td>
                                </tr>
                            )
                        })
                    }
                </tbody>
            </table>
        )

    }
}
</code>```

How to display the data in table. Here i need to get the array/list b. Tried different approaches to get the data from the object array but no luck.

答:
```<code>import React from 'react';
import './App.css';
import { useQuery } from '@apollo/react-hooks';
import gql from "graphql-tag";

const GET_GRPHQL_API = gql`
{
  getTags
  {
    id
    tagName
    tagDesc
    tagVersion
    tagVersion
  }
  }
  `
function App() {
  const { data, loading, error } = useQuery(GET_GRPHQL_API);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error</p>;

  return (
    <React.Fragment>

<table>
        <thead>

        </thead>
        <tbody>
          {data &&
          data.getTags &&
          data.getTags.map(function(item, key) {
              return (
                <tr key={key}>
                  <td>{item.id}</td>
                  <td>{item.tagName}</td>
                  <td>{item.tagDesc}</td>
                  <td>{item.tagVersion}</td>
                </tr>
              );
            })}
        </tbody>
      </table>

    </React.Fragment>
  );
}

export default App;
</code>```

Body:
How to display the data in the below from the below json.

{
"a":
{
"b":[
  {"id":"ef718cce-1269-4fbd-827c-832f7824c025","name":"Veera6"},
  {"id":"0cda5ae9-e287-4666-804a-03f25e642d1f","name":"Veera9"},
  {"id":"31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39","name":"Veera8"},
  {"id":"6292054c-8bfc-4d2d-b2f8-92e2bac5a578","name":"Veera7"},
  {"id":"c6756e5c-8fa5-40a9-ab92-5242bda97de3","name":"Veera10"}]
}
}

code snipped below.

render() {

        return (

                    {
                        this.headers.map(function(h) {
                            return (
                                {h.label}
                            )
                        })
                    }

                    {
                        this.state.tags.b.map(function(item, key) {
                        return (

                                  {item.id}
                                  {item.name}

                            )
                        })
                    }

        )

    }
}

How to display the data in table. Here i need to get the array/list b. Tried different approaches to get the data from the object array but no luck.


问:
Segmentation Fault while running PAM functions
I'm relatively new to C and cannot figure out why this program seg faults.
It could be a stupid error on my behalf but cannot seem to figure it out. </p>

<p>I also know its unusual using the embedding method I am, but this was down for sheer familiarity with Python3 and the ease of use. </p>

```<code>#define PY_SSIZE_T_CLEAN
#define PAM_SM_AUTH
#define PAM_SM_ACCOUNT
//#define PAM_SM_SESSION

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include </usr/include/python3.6m/Python.h>

/* expected hook */
/*
PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags, int argc, const char **argv ) {
    return PAM_SUCCESS;
}

PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) {
    printf("Acct mgmt\n");
    return PAM_SUCCESS;
}
*/

/* expected hook, this is where custom stuff happens */
PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv )

{
    chdir("../code/facial"); // this changes it to the correct directory to execute

    dlopen("/usr/lib/x86_64-linux-gnu/libpython3.6m.so",RTLD_LAZY | RTLD_GLOBAL);
    Py_Initialize(); // Starts python interpreter
    PyRun_SimpleString("import os\nimport sys\nsys.path.append(os.getcwd())"); // lets python know where we are

    PyObject *mymod, *func1, *ret1;

    mymod = PyImport_ImportModule("pam_detect"); // This is the .py

    if (mymod != 0){ // check if the file file was loaded
        func1 =  PyObject_GetAttrString(mymod, "detect"); // hel is the function name in the file you declared earlier
        ret1 = PyObject_CallObject(func1, NULL); // Null because the function doesnt take an argument.
        if (ret1 == 1){
            Py_Finalize();
            return PAM_SUCCESS;
        }
        else{
            Py_Finalize();
            return PAM_AUTH_ERR;

        }

    }

    else{
            //printf("Error: can't find file!\n");
            return 1;
    }

    Py_Finalize();

    return 0;
}

</code>```

答:
You have defined the pointers but haven't assigned them to a memory address.

PyObject *mymod, *func1, *ret1;
```

This line in your code makes a pointer named mymod which can point to a memory containing PyObject, but you haven't given the memory address to it yet.

I don't know if calling the functions will return pointers correctly or not,  So when you try to put anything there, it gives segmentation fault if you are trying to assign a variable to a pointer without a memory address.

I can only say this much without knowing where the fault occurred. try putting printf statement before assigning of all 3 pointers and see.

Body:
I'm relatively new to C and cannot figure out why this program seg faults.
It could be a stupid error on my behalf but cannot seem to figure it out.

I also know its unusual using the embedding method I am, but this was down for sheer familiarity with Python3 and the ease of use.

#define PY_SSIZE_T_CLEAN
#define PAM_SM_AUTH
#define PAM_SM_ACCOUNT
//#define PAM_SM_SESSION

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include </usr/include/python3.6m/Python.h>

/* expected hook */
/*
PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags, int argc, const char **argv ) {
    return PAM_SUCCESS;
}

PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) {
    printf("Acct mgmt\n");
    return PAM_SUCCESS;
}
*/

/* expected hook, this is where custom stuff happens */
PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv )

{
    chdir("../code/facial"); // this changes it to the correct directory to execute

    dlopen("/usr/lib/x86_64-linux-gnu/libpython3.6m.so",RTLD_LAZY | RTLD_GLOBAL);
    Py_Initialize(); // Starts python interpreter
    PyRun_SimpleString("import os\nimport sys\nsys.path.append(os.getcwd())"); // lets python know where we are

    PyObject *mymod, *func1, *ret1;

    mymod = PyImport_ImportModule("pam_detect"); // This is the .py

    if (mymod != 0){ // check if the file file was loaded
        func1 =  PyObject_GetAttrString(mymod, "detect"); // hel is the function name in the file you declared earlier
        ret1 = PyObject_CallObject(func1, NULL); // Null because the function doesnt take an argument.
        if (ret1 == 1){
            Py_Finalize();
            return PAM_SUCCESS;
        }
        else{
            Py_Finalize();
            return PAM_AUTH_ERR;

        }

    }

    else{
            //printf("Error: can't find file!\n");
            return 1;
    }

    Py_Finalize();

    return 0;
}

Body:
You have defined the pointers but haven't assigned them to a memory address.

PyObject *mymod, *func1, *ret1;

This line in your code makes a pointer named mymod which can point to a memory containing PyObject, but you haven't given the memory address to it yet.

I don't know if calling the functions will return pointers correctly or not,  So when you try to put anything there, it gives segmentation fault if you are trying to assign a variable to a pointer without a memory address.

I can only say this much without knowing where the fault occurred. try putting printf statement before assigning of all 3 pointers and see.


问:
django : 'LoginForm' object has no attribute 'cleaned_data'
I'm trying to make a Login but it doesn't work.
the error is
form.is_valid() return False and

'LoginForm' object has no attribute 'cleaned_data'

I can't figure out out is the problem.

user/forms.py

```<code>class LoginForm(forms.Form):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'style': 'width:100%; height:100%;'}))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'style': 'width:100%; height:100%;'}))

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['email'].label = "이메일"
        self.fields['password'].label = "비밀번호"

    def clean(self):
        super().clean()
        email = self.cleaned_data.get("email")
        password = self.cleaned_data.get("password")
        try:
            user = models.User.objects.get(email=email)
            if user.check_password(password):
                return self.cleaned_data
            else:
                self.add_error("password", forms.ValidationError(
                    "비밀번호가 틀렸습니다."))
        except models.User.DoesNotExist:
            self.add_error("email", forms.ValidationError(
                "존재하지 않는 계정입니다."))
</code>```

users/views.py

```<code>class LoginView(mixins.LoggedOutOnlyView, View):
    def get(self, request):
        form = forms.LoginForm(request.POST)
        return render(request, "users/login.html", {"form": form})

    def post(self, request):
        form = forms.LoginForm(request.POST or None)
        print(form.is_valid())
        if form.is_valid():
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")

            get_user_name = user_models.User.objects.get(email=email)
            user = authenticate(
                request, username=get_user_name, password=password)
            if user is not None:
                login(request, user)
                return redirect(reverse("cores:home"))
        else:
            return render(request, "users/login.html", {"form": form})
</code>```

答:
You need to set a local variable with the return value of the super() call. In your fields you'd no longer call the self.cleaned_data variant but the local variable cleaned_data. Also return the cleaned_data at the end of the def clean() method - even if errors occurred.

```<code>    def clean(self):
        cleaned_data = super().clean()

        email = cleaned_data.get("email")
        password = cleaned_data.get("password")
        ...

        # Don't forget to return the cleaned_data after everything
        return cleaned_data
</code>```

This is documented in the django docs:

https://docs.djangoproject.com/en/3.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Body:
I'm trying to make a Login but it doesn't work.
the error is
form.is_valid() return False and

'LoginForm' object has no attribute 'cleaned_data'

I can't figure out out is the problem.

user/forms.py

class LoginForm(forms.Form):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'style': 'width:100%; height:100%;'}))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'style': 'width:100%; height:100%;'}))

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['email'].label = "이메일"
        self.fields['password'].label = "비밀번호"

    def clean(self):
        super().clean()
        email = self.cleaned_data.get("email")
        password = self.cleaned_data.get("password")
        try:
            user = models.User.objects.get(email=email)
            if user.check_password(password):
                return self.cleaned_data
            else:
                self.add_error("password", forms.ValidationError(
                    "비밀번호가 틀렸습니다."))
        except models.User.DoesNotExist:
            self.add_error("email", forms.ValidationError(
                "존재하지 않는 계정입니다."))

users/views.py

class LoginView(mixins.LoggedOutOnlyView, View):
    def get(self, request):
        form = forms.LoginForm(request.POST)
        return render(request, "users/login.html", {"form": form})

    def post(self, request):
        form = forms.LoginForm(request.POST or None)
        print(form.is_valid())
        if form.is_valid():
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")

            get_user_name = user_models.User.objects.get(email=email)
            user = authenticate(
                request, username=get_user_name, password=password)
            if user is not None:
                login(request, user)
                return redirect(reverse("cores:home"))
        else:
            return render(request, "users/login.html", {"form": form})

Body:
You need to set a local variable with the return value of the super() call. In your fields you'd no longer call the self.cleaned_data variant but the local variable cleaned_data. Also return the cleaned_data at the end of the def clean() method - even if errors occurred.

    def clean(self):
        cleaned_data = super().clean()

        email = cleaned_data.get("email")
        password = cleaned_data.get("password")
        ...

        # Don't forget to return the cleaned_data after everything
        return cleaned_data

This is documented in the django docs:

https://docs.djangoproject.com/en/3.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other


问:
Is it possible to dereference an object to another object inside his own method?
I have a question about some C++ problem. Let's say I have a really big class called BigClass and I say BigClass* foo = new BigClass();

Let's say I have a method inside BigClass that defines another local object tmp of type BigClass and at the end of the method, I check if there was the error by doing some stuff with tmp and if not I want to dereference this to that object. I don't want to copy all the arguments from tmp to this, because the object is too big and the process would be slow. Is there any way to dereference the object inside its own method?

Example:

```<code>class BigClass
{
    int a;
    long b;
    std::vector<int> c;
    // other members...

    void replace()
    {
        BigClass* tmp = new BigClass();
        // do some calculations with tmp
        *this = tmp; // problem
    }
}
</code>```

Why is *this = tmp a problem?

I defined an operator= that just does something like this:

```<code>this.a = src.a;
this.b = src.b;
this.c = src.c;
.
.
.
</code>```

But there I make a copy of all member variables and that is slow. I want to simply dereference the object instead of copying all member variables.

答:
If you don't want to copy, you can move it instead:

```<code>struct BigClass {
    void func() {
        BigClass tmp;

        *this = std::move(tmp);
    }
};
</code>```

A move operation usually don't involve dynamic allocation or the copying of large buffers.

If you follow the rule of zero, the move assignment operator will be defined for you.

Otherwise, you can always define it using a defaulted operator:

```<code>struct BigClass {
    BigClass& operator=(BigClass&&) = default;

    // ...
};
</code>```

You could also write your own operator, but the defaulted one usually does the job very well.

```<code>struct BigClass {
    //          quite important ----v------v
    BigClass& operator=(BigClass&& rhs) noexcept {
        this->a = std::move(rhs.a);
        this->b = std::move(rhs.b);
        this->c = std::move(rhs.c);
    }

    // ...
};
</code>```

A move operation is usually very fast, and much faster than new.

Alternatively, you can also newing an object and assign the pointer to it:

```<code>struct BigClass {
    auto replace() -> BigClass* {
        auto tmp = new BigClass{};

        // ...

        return tmp;
    }
};
</code>```

Beware as it is much slower since it involve dynamic allocations.

Body:
I have a question about some C++ problem. Let's say I have a really big class called BigClass and I say BigClass* foo = new BigClass();

Let's say I have a method inside BigClass that defines another local object tmp of type BigClass and at the end of the method, I check if there was the error by doing some stuff with tmp and if not I want to dereference this to that object. I don't want to copy all the arguments from tmp to this, because the object is too big and the process would be slow. Is there any way to dereference the object inside its own method?

Example:

class BigClass
{
    int a;
    long b;
    std::vector<int> c;
    // other members...

    void replace()
    {
        BigClass* tmp = new BigClass();
        // do some calculations with tmp
        *this = tmp; // problem
    }
}

Why is *this = tmp a problem?

I defined an operator= that just does something like this:

this.a = src.a;
this.b = src.b;
this.c = src.c;
.
.
.

But there I make a copy of all member variables and that is slow. I want to simply dereference the object instead of copying all member variables.

Body:
If you don't want to copy, you can move it instead:

struct BigClass {
    void func() {
        BigClass tmp;

        *this = std::move(tmp);
    }
};

A move operation usually don't involve dynamic allocation or the copying of large buffers.

If you follow the rule of zero, the move assignment operator will be defined for you.

Otherwise, you can always define it using a defaulted operator:

struct BigClass {
    BigClass& operator=(BigClass&&) = default;

    // ...
};

You could also write your own operator, but the defaulted one usually does the job very well.

struct BigClass {
    //          quite important ----v------v
    BigClass& operator=(BigClass&& rhs) noexcept {
        this->a = std::move(rhs.a);
        this->b = std::move(rhs.b);
        this->c = std::move(rhs.c);
    }

    // ...
};

A move operation is usually very fast, and much faster than new.

Alternatively, you can also newing an object and assign the pointer to it:

struct BigClass {
    auto replace() -> BigClass* {
        auto tmp = new BigClass{};

        // ...

        return tmp;
    }
};

Beware as it is much slower since it involve dynamic allocations.


答:
There is an argument in auto.arima called D. We need to set it to 1 in order to force arima to use a seasonal model. In this case,

```<code>m1 <- ts(df$Value, start = min(df$BelegDat), frequency = 12)
autoplot(forecast(auto.arima(m1, D = 1), 24))
</code>```

which gives,

Title: small Time Series Analysis

Body:
I need to make a prediction for the next 2 years. However, I have a very small amount of Data.
Data:

   structure(list(BelegDat = structure(c(16801, 16832, 16861, 16892,
    16922, 16953, 16983, 17014, 17045, 17075, 17106, 17136, 17167,
    17198, 17226, 17257, 17287, 17318, 17348, 17379, 17410, 17440,
    17471, 17501, 17532, 17563, 17591, 17622, 17652, 17683, 17713,
    17744, 17775, 17805, 17836, 17866, 17897, 17928, 17956, 17987,
    18017, 18048, 18078, 18109, 18140, 18170, 18201, 18231), class = "Date"),
        Value = c(37, 28, 37, 47, 37, 28, 37, 37, 19, 37, 37, 28,
        40, 30, 40, 50, 40, 30, 40, 40, 20, 40, 40, 30, 30, 40, 30,
        30, 40, 30, 30, 50, 30, 50, 20, 20, 60, 20, 60, 40, 20, 10,
        40, 20, 20, 10, 44, 33)), row.names = c(NA, -48L), class = "data.frame")

I am using ARIMA:

myts <- ts(df_ready[,2], start=c(2016,01), end=c(2019,12), frequency = 12)

fit <- auto.arima(myts)

pred <- forecast(fit, 24) # next 2 years (24 Months)
plot(pred)

My output:
  Output

Could you, please, show me my mistake / suggest some other way how this prediction can be done?

Thank you in advance!

Body:
There is an argument in auto.arima called D. We need to set it to 1 in order to force arima to use a seasonal model. In this case,

m1 <- ts(df$Value, start = min(df$BelegDat), frequency = 12)
autoplot(forecast(auto.arima(m1, D = 1), 24))

which gives,


答: Users must use sql query to have acccess to a shared partitioned in-memory table.</p>

Title: size(SharedPartitionedTable)=0 in DolphinDB

Body:
sym = `C`MS`MS`MS`IBM`IBM`C`C`C
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12]
t=Table(timestamp,sym,price,qty)
db=database("",VALUE,09:32:00..09:40:00)
pt=db.createPartitionedTable(t,`pt,`timestamp)
pt.append!(t)
share(pt,`sharet)
size(pt)

result=0

I want to know the reason why size(pt)=0.


问:
Iterate through JSON and get image for each data key
I have this table

```<code><table id="player_info">
<tr>
<th>Position</th>
<th>Club</th>
<th>Points</th>
<th>Matches Played</th>
<th>Wins</th>
<th>Draws</th>
<th>Losses</th>
<th>Goals For</th>
<th>Goals Against</th>
<th>Goal Difference</th>
<th>Form</th>
</tr>
</table>
</code>```

And I have this function which iterates through JSON keys and creates a new table cell with each key. I would like to have the logo of each club appear next to its name in the table cell. The logo URL is stored in the JSON.

My current code

```<code>data.api.standings[0].forEach(elements => {

        var tr = document.createElement('tr');

        var img = new Image();

        img.src = elements.logo;

        tr.innerHTML = '<td>' + elements.rank + '</td>' +
                       '<td>' + elements.teamName +  img + '</td>' +
                       '<td>' + elements.points + '</td>' +
                       '<td>' + elements.all.matchsPlayed + '</td>' +
                       '<td>' + elements.all.win + '</td>' +
                       '<td>' + elements.all.draw + '</td>' +
                    '<td>' + elements.all.lose + '</td>' +
                    '<td>' + elements.all.goalsFor + '</td>' +
                    '<td>' + elements.all.goalsAgainst + '</td>' +
                    '<td>' + elements.goalsDiff + '</td>' +
                    '<td>' + elements.forme + '</td>';

        table.appendChild(tr);

    });
</code>```

However I am getting the team name and [object HTMLImageElement] and no image.

答:
In your case you can do this instead

```<code>var img = '<img src="' + elements.logo + '" />'
</code>```

instead of making an img element

Body:
I have this table

Position
Club
Points
Matches Played
Wins
Draws
Losses
Goals For
Goals Against
Goal Difference
Form

And I have this function which iterates through JSON keys and creates a new table cell with each key. I would like to have the logo of each club appear next to its name in the table cell. The logo URL is stored in the JSON.

My current code

data.api.standings[0].forEach(elements => {

        var tr = document.createElement('tr');

        var img = new Image();

        img.src = elements.logo;

        tr.innerHTML = '' + elements.rank + '	' +
                       '' + elements.teamName +  img + '	' +
                       '' + elements.points + '	' +
                       '' + elements.all.matchsPlayed + '	' +
                       '' + elements.all.win + '	' +
                       '' + elements.all.draw + '	' +
                    '' + elements.all.lose + '	' +
                    '' + elements.all.goalsFor + '	' +
                    '' + elements.all.goalsAgainst + '	' +
                    '' + elements.goalsDiff + '	' +
                    '' + elements.forme + '	';

        table.appendChild(tr);

    });

However I am getting the team name and [object HTMLImageElement] and no image.

Body:
In your case you can do this instead

var img = '<img src="' + elements.logo + '" />'

instead of making an img element


答:
This question is already done. But I want to leave another way using data.table for you. I read your comment above. Hence my output is different from tmfmnk's. Here I used subsets as joins. I am basically creating all possible combinations of var1, var2, and var3. The lengths of var2 and var3 (var3 has 1:6 for each value of var2) are arranged such that their lengths match. After this, I replaced NAs with 0 using nafill().

```<code>library(data.table)

setDT(foo)[.(var1,
             rep(unique(var2), each = max(var3)),
             rep(1:max(var3), times = uniqueN(var2))),
             on = .(var1, var2, var3)][, count := nafill(count, fill = 0)][]

    var1 var2 var3 count
 1:  123   45    1     1
 2:  123   45    2     0
 3:  123   45    3     0
 4:  123   45    4     0
 5:  123   45    5     0
 6:  123   45    6     0
 7:  123   57    1     0
 8:  123   57    2     0
 9:  123   57    3     1
10:  123   57    4     0
11:  123   57    5     0
12:  123   57    6     1
</code>```

If you want to get the expected result that you provided, you can do the following.

```<code>setDT(foo)[, group := 1:.N][.(var1,
                              rep(var2, each = max(var3)),
                              rep(1:max(var3), times = nrow(foo)),
                              rep(group, each = max(var3))),
                             on = .(var1, var2, var3, group)][, `:=` (count = nafill(count, fill = 0),
                                                                      group = NULL)][]

    var1 var2 var3 count
 1:  123   45    1     1
 2:  123   45    2     0
 3:  123   45    3     0
 4:  123   45    4     0
 5:  123   45    5     0
 6:  123   45    6     0
 7:  123   57    1     0
 8:  123   57    2     0
 9:  123   57    3     1
10:  123   57    4     0
11:  123   57    5     0
12:  123   57    6     0
13:  123   57    1     0
14:  123   57    2     0
15:  123   57    3     0
16:  123   57    4     0
17:  123   57    5     0
18:  123   57    6     1
</code>```

Title: R insert rows with sequence

Body:
foo <- data.frame("var1"=c(123,123,123),"var2"=c(45,57,57),"var3"=c(1,3,6),"count"=c(1,1,1))

  var1 var2 var3 count
1  123   45    1     1
2  123   57    3     1
3  123   57    6     1

I want to populate var3 with numbers from 1 to 6 for every obs in var2, retain the data from the original dataframe, and count to be 0.

   var1 var2 var3 count
1   123   45    1     1
2   123   45    2     0
3   123   45    3     0
4   123   45    4     0
5   123   45    5     0
6   123   45    6     0
7   123   57    1     0
8   123   57    2     0
9   123   57    3     1
10  123   57    4     0
11  123   57    5     0
12  123   57    6     0
13  123   57    1     0
14  123   57    2     0
15  123   57    3     0
16  123   57    4     0
17  123   57    5     0
18  123   57    6     1

Body:
This question is already done. But I want to leave another way using data.table for you. I read your comment above. Hence my output is different from tmfmnk's. Here I used subsets as joins. I am basically creating all possible combinations of var1, var2, and var3. The lengths of var2 and var3 (var3 has 1:6 for each value of var2) are arranged such that their lengths match. After this, I replaced NAs with 0 using nafill().

library(data.table)

setDT(foo)[.(var1,
             rep(unique(var2), each = max(var3)),
             rep(1:max(var3), times = uniqueN(var2))),
             on = .(var1, var2, var3)][, count := nafill(count, fill = 0)][]

    var1 var2 var3 count
 1:  123   45    1     1
 2:  123   45    2     0
 3:  123   45    3     0
 4:  123   45    4     0
 5:  123   45    5     0
 6:  123   45    6     0
 7:  123   57    1     0
 8:  123   57    2     0
 9:  123   57    3     1
10:  123   57    4     0
11:  123   57    5     0
12:  123   57    6     1

If you want to get the expected result that you provided, you can do the following.

setDT(foo)[, group := 1:.N][.(var1,
                              rep(var2, each = max(var3)),
                              rep(1:max(var3), times = nrow(foo)),
                              rep(group, each = max(var3))),
                             on = .(var1, var2, var3, group)][, `:=` (count = nafill(count, fill = 0),
                                                                      group = NULL)][]

    var1 var2 var3 count
 1:  123   45    1     1
 2:  123   45    2     0
 3:  123   45    3     0
 4:  123   45    4     0
 5:  123   45    5     0
 6:  123   45    6     0
 7:  123   57    1     0
 8:  123   57    2     0
 9:  123   57    3     1
10:  123   57    4     0
11:  123   57    5     0
12:  123   57    6     0
13:  123   57    1     0
14:  123   57    2     0
15:  123   57    3     0
16:  123   57    4     0
17:  123   57    5     0
18:  123   57    6     1


问:
Precedence in checkbox list in javascript
I'm attempting to store records in 3 different list in order of their precedence. \

My requirement is as follows:

Say I have 10 records rows in the table with 3 checkboxes (Checkbox1, Checkbox2, Checkbox3) on each record.

Checkbox1 has the highest and the Checkbox3 has the lowest priority.

Use case: If I select all the 3 checkboxes for 1 record, only Checkbox1 will be considered.

Use case: If I select Checkbox2 and Checkbox3, only Checkbox2 will be considered.

Use case: If I select Checkbox1 and Checkbox3, only Checkbox1 will be considered and hence for all other similar condition.

I have attempted and works perfectly on all conditions, EXCEPT on unchecking of a higher precedance. Here allRecordList will have all the ids present on the screen.

```<code>   for (var i = 0; i < this.allRecordList.length; i++) {

        if (this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id) != -1) {
            this.Checkbox1SelectedRecords.push(this.allRecordList[i]);
            //removing from c2 list
            if (this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox2Ids.splice(this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id),1);

            }
            //removing from c3 list
            if (this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox3Ids.splice(this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id),1);

            }

        if (this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id) != -1 ) {
            this.referralSelectedRecords.push(this.allRecordList[i]);
            //removing from c3 list
            if (this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox3Ids.splice(this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id),1);

            //removing from c1 list
            if (this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox1Ids.splice(this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id),1);
            }

        }
        // c3 handle
        if (this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id) != -1 ) {
            this.informationSelectedRecords.push(this.allRecordList[i]);
            console.log('Select Selected Info '+this.selectedCheckbox3Ids);
            ////removing from c2 list
            if (this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox2Ids.splice(this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id),1);
            }
            //removing from c1 list
            if (this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox1Ids.splice(this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id),1);
            }
        }

    }
</code>```

Is there any efficient way to handle this? I am unable to re-calculate the priority logic.
Any helps would be appreciated.

答:
javascript already has Map which allows to store key,value pair.Maybe you can use Map for mapping every row and its priority something like key as row id  and value as the priority and update value for key based on priority selected. You can find
Working example on this link </p>

```<code>
function updateMap(rowid, boxid, box) {
if (box.checked) {
 if (testMap.get(rowid) === undefined || testMap.get(rowid) === -1 || testMap.get(rowid) > boxid) {
   testMap.set(rowid, boxid)
 }
} else {
 for (i = 1; i <= 4; i++) {
   if (i === 4) {
     testMap.set(rowid, -1)
     break;
   }

   if (document.getElementById("row" + rowid + "box" + i).checked) {
     testMap.set(rowid, i);
     break;
   }

 }
}

}

function logresulty() {
document.getElementById("result").innerHTML = ""
testMap.forEach((value, key) => {
 document.getElementById("result").innerHTML = document.getElementById("result").innerHTML + " row:" + key + " Priority:" + value + "<br>";
});
}

</code>```

Body:
I'm attempting to store records in 3 different list in order of their precedence. \

My requirement is as follows:

Say I have 10 records rows in the table with 3 checkboxes (Checkbox1, Checkbox2, Checkbox3) on each record.

Checkbox1 has the highest and the Checkbox3 has the lowest priority.

Use case: If I select all the 3 checkboxes for 1 record, only Checkbox1 will be considered.

Use case: If I select Checkbox2 and Checkbox3, only Checkbox2 will be considered.

Use case: If I select Checkbox1 and Checkbox3, only Checkbox1 will be considered and hence for all other similar condition.

I have attempted and works perfectly on all conditions, EXCEPT on unchecking of a higher precedance. Here allRecordList will have all the ids present on the screen.

   for (var i = 0; i < this.allRecordList.length; i++) {

        if (this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id) != -1) {
            this.Checkbox1SelectedRecords.push(this.allRecordList[i]);
            //removing from c2 list
            if (this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox2Ids.splice(this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id),1);

            }
            //removing from c3 list
            if (this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox3Ids.splice(this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id),1);

            }

        if (this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id) != -1 ) {
            this.referralSelectedRecords.push(this.allRecordList[i]);
            //removing from c3 list
            if (this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox3Ids.splice(this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id),1);

            //removing from c1 list
            if (this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox1Ids.splice(this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id),1);
            }

        }
        // c3 handle
        if (this.selectedCheckbox3Ids.indexOf(this.allRecordList[i].Id) != -1 ) {
            this.informationSelectedRecords.push(this.allRecordList[i]);
            console.log('Select Selected Info '+this.selectedCheckbox3Ids);
            ////removing from c2 list
            if (this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox2Ids.splice(this.selectedCheckbox2Ids.indexOf(this.allRecordList[i].Id),1);
            }
            //removing from c1 list
            if (this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id)  != -1){
                this.selectedCheckbox1Ids.splice(this.selectedCheckbox1Ids.indexOf(this.allRecordList[i].Id),1);
            }
        }

    }

Is there any efficient way to handle this? I am unable to re-calculate the priority logic.
Any helps would be appreciated.

Body:
javascript already has Map which allows to store key,value pair.Maybe you can use Map for mapping every row and its priority something like key as row id  and value as the priority and update value for key based on priority selected. You can find
Working example on this link

function updateMap(rowid, boxid, box) {
if (box.checked) {
 if (testMap.get(rowid) === undefined || testMap.get(rowid) === -1 || testMap.get(rowid) > boxid) {
   testMap.set(rowid, boxid)
 }
} else {
 for (i = 1; i <= 4; i++) {
   if (i === 4) {
     testMap.set(rowid, -1)
     break;
   }

   if (document.getElementById("row" + rowid + "box" + i).checked) {
     testMap.set(rowid, i);
     break;
   }

 }
}

}

function logresulty() {
document.getElementById("result").innerHTML = ""
testMap.forEach((value, key) => {
 document.getElementById("result").innerHTML = document.getElementById("result").innerHTML + " row:" + key + " Priority:" + value + "<br>";
});
}


问:
Most elegant way to start several scotty servers in the same application?
Is there a standard way to start two scotty servers in the same application? In a toy project I'm trying:

main :: IO ()
main = do
  scotty 3000 $ do
    get "/" $ do
      text "hello"
  scotty 4000 $ do
    post "/" $ do
      text "world"
```

The first server spins up but the second one does not. It could also be a flaw in the way I'm understanding Haskell IO. Thanks!

答:
I would use async:</p>

```<code>import Control.Concurrent.Async

main :: IO ()
main = do
  a1 <- async $ scotty 3000 $ do
    get "/" $ do
      text "hello"
  a2 <- async $ scotty 4000 $ do
    post "/" $ do
      text "world"
  waitAnyCatchCancel [a1, a2]
</code>```

Body:
Is there a standard way to start two scotty servers in the same application? In a toy project I'm trying:

main :: IO ()
main = do
  scotty 3000 $ do
    get "/" $ do
      text "hello"
  scotty 4000 $ do
    post "/" $ do
      text "world"

The first server spins up but the second one does not. It could also be a flaw in the way I'm understanding Haskell IO. Thanks!

Body:
I would use async:

import Control.Concurrent.Async

main :: IO ()
main = do
  a1 <- async $ scotty 3000 $ do
    get "/" $ do
      text "hello"
  a2 <- async $ scotty 4000 $ do
    post "/" $ do
      text "world"
  waitAnyCatchCancel [a1, a2]


问:
Is there a way to make a "reusable snapshot" of a program?
Here's the situation: I am working on a relatively big C++ program (in Linux). This program can be separated in two parts. Part A is just a bunch of precomputations based in some data that remains the same over time that builds a pretty complex and big data structure. The problem is that part A takes too much time (around a minute), and you can assume that it cannot be significantly optimized further. Part B, which goes right after part A, is basically some queries on the data loaded in part A.

So, here's what I want to do: since the data structure built in part A is always the same, wouldn't it be nice to have a "snapshot" of it, and so, every time you load the program you can just retrieve the data from the snapshot very quickly and just jump right to B?

And here's the question: Is there a way to do that?

答: For an automagic solution that doesn't require code you can take a look at CRIU (Checkpoint/Restore In Userspace) which allows you to freeze a running process and checkpoint its state to disk. To then restore the process and run it exactly as it was during the time of the freeze.</p>


问:
Create 2 routes using only one controller
I have a controller called Contacts as well as my resources, but I need an action called vendors but if I add the route to my contacts resources I get

contacts/:id/vendors

I need it to be

vendors/:id

but without creating another controller for vendors

答:
I think it should help you. But I recommend you to search documentation next time, it should be more informative for you.</p>

```<code>resources :contacts
get '/vendors/:id', to: 'contacts#vendor'
</code>```

Body:
I think it should help you. But I recommend you to search documentation next time, it should be more informative for you.

resources :contacts
get '/vendors/:id', to: 'contacts#vendor'


问:
Find out which rows are duplicates when inserting into a DB table?
I have the following scenario:

Database table, let's call it ZDBX with primary keys:

```<code>MATNR, LIFNR, ZART
</code>```

In a report i have internal table lt_table TYPE TABLE OF ZDBX

```<code>DELETE ADJACENT DUPLICATES FROM lt_table
   COMPARING matnr lifnr zart fact_code.

DELETE FROM ZDBX.
INSERT ZDBX FROM TABLE lt_table.
</code>```

The INSERT statement will lead to a short dump because there are rows in the internal table with identical primary keys, but different fact_code.

Now, I know that the obvious solution is to only compare primary keys in the DELETE ADJACENT DUPLICATES statement, but this does not work in my case, because the user wants to decide which fact_code will be deleted.

For now, my solution is to export the local table (right before INSERT) into a excel and find the duplicates and ask the user which fact_code he wants.

Can I find out (trough a system variable or in ST22) at which line the INSERT crashed?
(So I dont have to do all the excel work)

My ideal solution would be to put the INSERT into a TRY-CATCH, find the duplicate row, and write a message into the Job-Log with the duplicate data.

Is it possible ?

(Also, setting the column fact_code as primary key is not a solution that the user agrees with)

答:
You can use FOR ALL ENTRIES directive for finding existing items.

```<code>  SELECT *
    FROM ZDBX
    INTO TABLE lt_dublicates
    FOR ALL ENTRIES IN lt_table
    WHERE MATNR EQ lt_table-MATNR
      AND LIFNR EQ lt_table-LIFNR
      AND ZART  EQ lt_table-ZART.
</code>```

I prefer create ABAP report for listing and choosing undesirable records. You can add checkbox column for marking rows and auto unmark same other records by primary keys.

Body:
I have the following scenario:

Database table, let's call it ZDBX with primary keys:

MATNR, LIFNR, ZART

In a report i have internal table lt_table TYPE TABLE OF ZDBX

DELETE ADJACENT DUPLICATES FROM lt_table
   COMPARING matnr lifnr zart fact_code.

DELETE FROM ZDBX.
INSERT ZDBX FROM TABLE lt_table.

The INSERT statement will lead to a short dump because there are rows in the internal table with identical primary keys, but different fact_code.

Now, I know that the obvious solution is to only compare primary keys in the DELETE ADJACENT DUPLICATES statement, but this does not work in my case, because the user wants to decide which fact_code will be deleted.

For now, my solution is to export the local table (right before INSERT) into a excel and find the duplicates and ask the user which fact_code he wants.

Can I find out (trough a system variable or in ST22) at which line the INSERT crashed?
(So I dont have to do all the excel work)

My ideal solution would be to put the INSERT into a TRY-CATCH, find the duplicate row, and write a message into the Job-Log with the duplicate data.

Is it possible ?

(Also, setting the column fact_code as primary key is not a solution that the user agrees with)

Body:
You can use FOR ALL ENTRIES directive for finding existing items.

  SELECT *
    FROM ZDBX
    INTO TABLE lt_dublicates
    FOR ALL ENTRIES IN lt_table
    WHERE MATNR EQ lt_table-MATNR
      AND LIFNR EQ lt_table-LIFNR
      AND ZART  EQ lt_table-ZART.

I prefer create ABAP report for listing and choosing undesirable records. You can add checkbox column for marking rows and auto unmark same other records by primary keys.