问:
RubyZip docx issues with write_buffer instead of open
I'm adapting the RubyZip recursive zipping example (found here) to work with write_buffer instead of open and am coming across a host of issues. I'm doing this because the zip archive I'm producing has word documents in it and I'm getting errors on opening those word documents. Therefore, I'm trying the work-around that RubyZip suggests, which is using write_buffer instead of open (example found here).

The problem is, I'm getting errors because I'm using an absolute path, but I'm not sure how to get around that. I'm getting the error "#//', name must not start with />"

Second, I'm not sure what to do to mitigate the issue with word documents. When I used my original code, which worked and created an actual zip file, any word document in that zip file had the following error upon opening: "Word found unreadable content in  Do you want to recover the contents of this document? If you trust the source of this document, click Yes." The unreadable content error is the reason why I went down the road of attempting to use write_buffer.

Any help would be appreciated.

Here is the code that I'm currently using:

```<code>require 'zip'
require 'zip/zipfilesystem'

module AdvisoryBoard
  class ZipService
    def initialize(input_dir, output_file)
      @input_dir = input_dir
      @output_file = output_file
    end

    # Zip the input directory.
    def write
      entries = Dir.entries(@input_dir) - %w[. ..]
      path = ""

      buffer = Zip::ZipOutputStream.write_buffer do |zipfile|
        entries.each do |e|
          zipfile_path = path == '' ? e : File.join(path, e)
          disk_file_path = File.join(@input_dir, zipfile_path)

          @file = nil
          @data = nil

          if !File.directory?(disk_file_path)
            @file = File.open(disk_file_path, "r+b")
            @data = @file.read

            unless [@output_file, @input_dir].include?(e)
              zipfile.put_next_entry(e)
              zipfile.write @data
            end

            @file.close
          end
        end

        zipfile.put_next_entry(@output_file)

        zipfile.put_next_entry(@input_dir)
      end

      File.open(@output_file, "wb") { |f| f.write(buffer.string) }
    end
  end
end
</code>```

答:
I was able to get word documents to open without any warnings or corruption! Here's what I ended up doing:</p>

```<code>require 'nokogiri'
require 'zip'
require 'zip/zipfilesystem'

  class ZipService
    # Initialize with the directory to zip and the location of the output archive.
    def initialize(input_dir, output_file)
      @input_dir = input_dir
      @output_file = output_file
    end

    # Zip the input directory.
    def write
      entries = Dir.entries(@input_dir) - %w[. ..]

      ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |zipfile|
        write_entries entries, '', zipfile
      end
    end

    private

    # A helper method to make the recursion work.
    def write_entries(entries, path, zipfile)
      entries.each do |e|
        zipfile_path = path == '' ? e : File.join(path, e)
        disk_file_path = File.join(@input_dir, zipfile_path)

        if File.directory? disk_file_path
          recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
        else
          put_into_archive(disk_file_path, zipfile, zipfile_path, e)
        end
      end
    end

    def recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
      zipfile.mkdir zipfile_path
      subdir = Dir.entries(disk_file_path) - %w[. ..]
      write_entries subdir, zipfile_path, zipfile
    end

    def put_into_archive(disk_file_path, zipfile, zipfile_path, entry)
      if File.extname(zipfile_path) == ".docx"
        Zip::File.open(disk_file_path) do |zip|
          doc = zip.read("word/document.xml")
          xml = Nokogiri::XML.parse(doc)
          zip.get_output_stream("word/document.xml") {|f| f.write(xml.to_s)}
        end
        zipfile.add(zipfile_path, disk_file_path)
      else
        zipfile.add(zipfile_path, disk_file_path)
      end
    end
  end

</code>```

Body:
I'm adapting the RubyZip recursive zipping example (found here) to work with write_buffer instead of open and am coming across a host of issues. I'm doing this because the zip archive I'm producing has word documents in it and I'm getting errors on opening those word documents. Therefore, I'm trying the work-around that RubyZip suggests, which is using write_buffer instead of open (example found here).

The problem is, I'm getting errors because I'm using an absolute path, but I'm not sure how to get around that. I'm getting the error "#//', name must not start with />"

Second, I'm not sure what to do to mitigate the issue with word documents. When I used my original code, which worked and created an actual zip file, any word document in that zip file had the following error upon opening: "Word found unreadable content in  Do you want to recover the contents of this document? If you trust the source of this document, click Yes." The unreadable content error is the reason why I went down the road of attempting to use write_buffer.

Any help would be appreciated.

Here is the code that I'm currently using:

require 'zip'
require 'zip/zipfilesystem'

module AdvisoryBoard
  class ZipService
    def initialize(input_dir, output_file)
      @input_dir = input_dir
      @output_file = output_file
    end

    # Zip the input directory.
    def write
      entries = Dir.entries(@input_dir) - %w[. ..]
      path = ""

      buffer = Zip::ZipOutputStream.write_buffer do |zipfile|
        entries.each do |e|
          zipfile_path = path == '' ? e : File.join(path, e)
          disk_file_path = File.join(@input_dir, zipfile_path)

          @file = nil
          @data = nil

          if !File.directory?(disk_file_path)
            @file = File.open(disk_file_path, "r+b")
            @data = @file.read

            unless [@output_file, @input_dir].include?(e)
              zipfile.put_next_entry(e)
              zipfile.write @data
            end

            @file.close
          end
        end

        zipfile.put_next_entry(@output_file)

        zipfile.put_next_entry(@input_dir)
      end

      File.open(@output_file, "wb") { |f| f.write(buffer.string) }
    end
  end
end

Body:
I was able to get word documents to open without any warnings or corruption! Here's what I ended up doing:

require 'nokogiri'
require 'zip'
require 'zip/zipfilesystem'

  class ZipService
    # Initialize with the directory to zip and the location of the output archive.
    def initialize(input_dir, output_file)
      @input_dir = input_dir
      @output_file = output_file
    end

    # Zip the input directory.
    def write
      entries = Dir.entries(@input_dir) - %w[. ..]

      ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |zipfile|
        write_entries entries, '', zipfile
      end
    end

    private

    # A helper method to make the recursion work.
    def write_entries(entries, path, zipfile)
      entries.each do |e|
        zipfile_path = path == '' ? e : File.join(path, e)
        disk_file_path = File.join(@input_dir, zipfile_path)

        if File.directory? disk_file_path
          recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
        else
          put_into_archive(disk_file_path, zipfile, zipfile_path, e)
        end
      end
    end

    def recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
      zipfile.mkdir zipfile_path
      subdir = Dir.entries(disk_file_path) - %w[. ..]
      write_entries subdir, zipfile_path, zipfile
    end

    def put_into_archive(disk_file_path, zipfile, zipfile_path, entry)
      if File.extname(zipfile_path) == ".docx"
        Zip::File.open(disk_file_path) do |zip|
          doc = zip.read("word/document.xml")
          xml = Nokogiri::XML.parse(doc)
          zip.get_output_stream("word/document.xml") {|f| f.write(xml.to_s)}
        end
        zipfile.add(zipfile_path, disk_file_path)
      else
        zipfile.add(zipfile_path, disk_file_path)
      end
    end
  end


来源: stackexchange

问:
How to make a triangle that always faces at the same point?

In a p5/processing project i have been working on, i need to create a line that has a triangle in the middle which always faces one of the connection points of the line.
It is pretty easy to create one that stands still, but my endpoints move around and rotate.
I need to find a way to also rotate the little triangle when the line shifts to this "|" from this "---".
My current code goes like this:

      let middleX = (fromX + toX)/2;
      let middleY = (fromY + toY)/2;
      triangle(middleX,middleY+5,middleX+5,middleY,middleX,middleY-5);
      line(fromX , fromY, toX, toY);
```

As you can anticipate, this doesn't work with rotations.
I need help :).
Thanks for your attention.

答:
You can:

use atan2() to calculate the rotation between the two points,

use push() to isolate the coordinate space (rotate locally without affecting the rest of the sketch (e.g. the line)

simply call rotate(): it takes in an angle in radians which is what atan2() returns

Here's an example based on your snippet:

let fromX = 200;
let fromY = 200;
let toX = 300;
let toY = 100;
let triangleSize = 5;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);

  // test: change to position
  toX = mouseX;
  toY = mouseY;

  let middleX = (fromX + toX) / 2;
  let middleY = (fromY + toY) / 2;
  // calculate the angle between from -> to points
  let angle = atan2(toY - fromY, toX - fromX);
  // isolate coordinate system (indenting is purely visual, not required)
  push();
    // move to central position
    translate(middleX, middleY);
    // rotate from translated position
    rotate(angle);
    // render triangle
    triangle(0, triangleSize, triangleSize, 0, 0, -triangleSize);
  pop();

  line(fromX, fromY, toX, toY);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script></code>```

Note that the order of transformations (translation, rotation, scale) is important.
(e.g. if rotate, then translate the triangle will land in a different location)

Also you draw the triangle as pointing to the right by default which aligns nicely with 0 radians rotation.

ContentLicense: CC BY-SA 4.0

Body:
In a p5/processing project i have been working on, i need to create a line that has a triangle in the middle which always faces one of the connection points of the line.
It is pretty easy to create one that stands still, but my endpoints move around and rotate.
I need to find a way to also rotate the little triangle when the line shifts to this "|" from this "---".
My current code goes like this:

      let middleX = (fromX + toX)/2;
      let middleY = (fromY + toY)/2;
      triangle(middleX,middleY+5,middleX+5,middleY,middleX,middleY-5);
      line(fromX , fromY, toX, toY);

As you can anticipate, this doesn't work with rotations.
I need help :).
Thanks for your attention.

Body:
You can:

use atan2() to calculate the rotation between the two points,

use push() to isolate the coordinate space (rotate locally without affecting the rest of the sketch (e.g. the line)

simply call rotate(): it takes in an angle in radians which is what atan2() returns

Here's an example based on your snippet:

let fromX = 200;
let fromY = 200;
let toX = 300;
let toY = 100;
let triangleSize = 5;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);

  // test: change to position
  toX = mouseX;
  toY = mouseY;

  let middleX = (fromX + toX) / 2;
  let middleY = (fromY + toY) / 2;
  // calculate the angle between from -> to points
  let angle = atan2(toY - fromY, toX - fromX);
  // isolate coordinate system (indenting is purely visual, not required)
  push();
    // move to central position
    translate(middleX, middleY);
    // rotate from translated position
    rotate(angle);
    // render triangle
    triangle(0, triangleSize, triangleSize, 0, 0, -triangleSize);
  pop();

  line(fromX, fromY, toX, toY);

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Note that the order of transformations (translation, rotation, scale) is important.
(e.g. if rotate, then translate the triangle will land in a different location)

Also you draw the triangle as pointing to the right by default which aligns nicely with 0 radians rotation.


问:
An interface that "extends itself" is ensuring what?
I was following a tutorial for an EventBus in and came across the following Interface:

```<code>public interface IEventHandler<in TEvent> : IEventHandler where TEvent : Event
{
    Task Handle(TEvent @event);
}

public interface IEventHandler
{

}
</code>```

Now, I get the generics part and the restriction, but I'm missing the point where the Interface extends itself.
It's the first time I've seen it being used like this. What does it accomplish?
Can anybody please shed some light on this subject? Thanks!

答:
In C# the types Interface and Interface<T> (you will sometimes see this as Interface`1) are distinct types. They have no relation inside the type system (unless one interface extends the other).

This can be confusing when you come from a Java background, where you have "raw types" and a List<T> is always a List at the same time. This is not true for C#.

You could rename the interfaces to make this distinction clearer:

```<code>IEventHandler<in TEvent> : IEventHandlerRaw
</code>```

(this is only to make the explanation clearer. It is not recommended in production code)

Body:
I was following a tutorial for an EventBus in and came across the following Interface:

public interface IEventHandler<in TEvent> : IEventHandler where TEvent : Event
{
    Task Handle(TEvent @event);
}

public interface IEventHandler
{

}

Now, I get the generics part and the restriction, but I'm missing the point where the Interface extends itself.
It's the first time I've seen it being used like this. What does it accomplish?
Can anybody please shed some light on this subject? Thanks!

Body:
In C# the types Interface and Interface<T> (you will sometimes see this as Interface`1) are distinct types. They have no relation inside the type system (unless one interface extends the other).

This can be confusing when you come from a Java background, where you have "raw types" and a List<T> is always a List at the same time. This is not true for C#.

You could rename the interfaces to make this distinction clearer:

IEventHandler<in TEvent> : IEventHandlerRaw

(this is only to make the explanation clearer. It is not recommended in production code)


问:
Why cant @ViewChild run outside AfterViewInit?
so I am trying to do some events base on the scrolling of my Angular application.

I have a problem since I am trying to access a element in my HTML with the help of @ViewChild.

I can access the element inside ngAfterViewInit() but I can't access it outside of it. It always shows undefined.

Here is my component class:

```<code>export class NavBarComponent implements OnInit {

  @ViewChild('navBar')
  navBar:ElementRef;

  constructor(private renderer: Renderer2) {
  }

  ngAfterViewInit(){
    window.addEventListener('scroll', this.onScroll, true);
    console.log(this.navBar.nativeElement);
  }

  ngOnInit(): void {

  }

  onScroll(){
    console.log("I am scrolling right now.")
    console.log(this.navBar.nativeElement)
  }

  onResize(){

  }

  onTabClick(){

  }
}
</code>```

When i console log inside ngAfterViewInit() i get the HTML element but when i console log inside onScroll() it is undetfined.

Why does my element disappears and gets undefined after viewinit? I am not using any ngIf or anything that removes the element.

Here is the component HTML code.

```<code>  <section class="et-hero-tabs" >
    <h1>STICKY SLIDER NAV</h1>
    <h3>Sliding content with sticky tab nav</h3>
    <div class="et-hero-tabs-container" #navBar>
      <a class="et-hero-tab" href="">ES6</a>
      <a class="et-hero-tab" href="">Flexbox</a>
      <a class="et-hero-tab" href="">React</a>
      <a class="et-hero-tab" href="">Angular</a>
      <a class="et-hero-tab" href="">Other</a>
      <span class="et-hero-tab-slider"></span>
    </div>
  </section>
</code>```

Here is the console error:

答:
You could bind the meaning of this keyword in the callback function using bind() method. Try the following

ngAfterViewInit(){
  window.addEventListener('scroll', this.onScroll.bind(this), true);
  console.log(this.navBar.nativeElement);
}
```

Without binding, the scope of this keyword in the onScroll() callback doesn't point to scope of the class.

Body:
so I am trying to do some events base on the scrolling of my Angular application.

I have a problem since I am trying to access a element in my HTML with the help of @ViewChild.

I can access the element inside ngAfterViewInit() but I can't access it outside of it. It always shows undefined.

Here is my component class:

export class NavBarComponent implements OnInit {

  @ViewChild('navBar')
  navBar:ElementRef;

  constructor(private renderer: Renderer2) {
  }

  ngAfterViewInit(){
    window.addEventListener('scroll', this.onScroll, true);
    console.log(this.navBar.nativeElement);
  }

  ngOnInit(): void {

  }

  onScroll(){
    console.log("I am scrolling right now.")
    console.log(this.navBar.nativeElement)
  }

  onResize(){

  }

  onTabClick(){

  }
}

When i console log inside ngAfterViewInit() i get the HTML element but when i console log inside onScroll() it is undetfined.

Why does my element disappears and gets undefined after viewinit? I am not using any ngIf or anything that removes the element.

Here is the component HTML code.

STICKY SLIDER NAV

Sliding content with sticky tab nav

      ES6
      Flexbox
      React
      Angular
      Other

Here is the console error:

Body:
You could bind the meaning of this keyword in the callback function using bind() method. Try the following

ngAfterViewInit(){
  window.addEventListener('scroll', this.onScroll.bind(this), true);
  console.log(this.navBar.nativeElement);
}

Without binding, the scope of this keyword in the onScroll() callback doesn't point to scope of the class.


Title: How to create a list from a string

Body:
I have the following question;

Given this string:

(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334, -9.175614100000001 38.7277934, -9.174941499999999 38.7276969, -9.174286 38.7273452, -9.1739754 38.7269114, -9.173853299999999 38.7266373, -9.173908000000001 38.726382, -9.174462200000001 38.725427, -9.174693700000001 38.7252121, -9.1753494 38.7249695, -9.1772258 38.724483, -9.177979300000001 38.7241841, -9.1781305 38.7240326, -9.178122200000001 38.7237591, -9.174915199999999 38.7229978, -9.172651999999999 38.7224599, -9.1716237 38.7223014, -9.170840099999999 38.7223315, -9.1661269 38.7232445, -9.1631047 38.7238009, -9.1621644 38.7239822, -9.1611914 38.7241708, -9.161030500000001 38.7242016, -9.1606402 38.7242798, -9.1605509 38.7242976, -9.1597224 38.7244719, -9.1588452 38.7246248, -9.1574752 38.7248025, -9.1563748 38.7248708, -9.157024399999999 38.7252864, -9.160008299999999 38.7284055, -9.158204400000001 38.7296856, -9.1554751 38.7316224, -9.158455399999999 38.7338999, -9.159123599999999 38.7336254, -9.159243399999999 38.733823, -9.1590688 38.734304, -9.1587736 38.7343032, -9.1585287 38.7344595, -9.1584726 38.7346586, -9.158265099999999 38.7346166, -9.157652300000001 38.7361352, -9.1579041 38.7362527, -9.1576316 38.7366198, -9.1577363 38.7366731, -9.1574563 38.7371094, -9.1564187 38.737462, -9.157724699999999 38.7388573, -9.1598056 38.7379811, -9.1602277 38.73791, -9.165917800000001 38.738966, -9.166425500000001 38.7392131, -9.167036400000001 38.7396749, -9.168542199999999 38.7416702, -9.169788499999999 38.740959, -9.170749499999999 38.7402073, -9.171019899999999 38.7398203, -9.1712919 38.7392233, -9.1716798 38.7391685, -9.1719215 38.7391826, -9.172312700000001 38.7392701, -9.1727472 38.7394396, -9.1738649 38.7388609, -9.174271299999999 38.7365449, -9.174486099999999 38.7343981, -9.1743024 38.734297, -9.174186000000001 38.7341419, -9.1741347 38.7338797, -9.174625199999999 38.7332609, -9.1749603 38.7329354, -9.175330799999999 38.7327162, -9.1756046 38.7326312, -9.176090200000001 38.7325687, -9.1776274 38.7328163, -9.177988300000001 38.7328404, -9.178248099999999 38.7328097, -9.1799505 38.7322568, -9.1801505 38.7320159)

How can I turn it into a list of lists?

For instance this string:(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334) would become this:

[[-9.1801505, 38.7320159], [-9.1800081, 38.7316384], [-9.1760106, 38.7280334]]

Body:
if your data is a tuple of strings then this can be useful:

data = ("-9.1801505 38.7320159", "-9.1800081 38.7316384", "-9.1760106 38.7280334")

output = [t.split() for t in data]

display(output)

[['-9.1801505', '38.7320159'],
 ['-9.1800081', '38.7316384'],
 ['-9.1760106', '38.7280334']]


问:
python .max() giving multiple values as opposed to one
I have to read in a CSV file and print the highest value. However, when I do I get two values rather than one.

Code:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

A = pd.read_csv("Test4.csv")
B=A.max()
print("The maximum usage rate is: ", B)
</code>```

Output:
The maximum usage rate is:  1.000041738    1.000369

dtype: float64

Process finished with exit code 0

CSV file:

1.000041738

1.000354758

1.000368539

1.000013902

Im curious how i should modify my code to give one single value. Thank you for any and all help

答:
The 1.000041738 is actually the name of the columns because you are reading in the first record as the column name.

Instead of

```<code>A = pd.read_csv("Test4.csv")
</code>```

Try

```<code>A = pd.read_csv("Test4.csv", names=['values'])
</code>```

and A['values'].max() will give one single number.

Body:
I have to read in a CSV file and print the highest value. However, when I do I get two values rather than one.

Code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

A = pd.read_csv("Test4.csv")
B=A.max()
print("The maximum usage rate is: ", B)

Output:
The maximum usage rate is:  1.000041738    1.000369

dtype: float64

Process finished with exit code 0

CSV file:

1.000041738

1.000354758

1.000368539

1.000013902

Im curious how i should modify my code to give one single value. Thank you for any and all help

Body:
The 1.000041738 is actually the name of the columns because you are reading in the first record as the column name.

Instead of

A = pd.read_csv("Test4.csv")

Try

A = pd.read_csv("Test4.csv", names=['values'])

and A['values'].max() will give one single number.


问:
Returning output parameter from stored procedure
I created a stored procedure based on the example from here on SO. However, I am getting an error. What am I missing here?

```<code>CREATE PROCEDURE SFT.usp_GetPrefix
(@p_table  VARCHAR(30),
 @p_prefix VARCHAR(3) OUTPUT
)
AS
    BEGIN
        DECLARE @lv_prefix VARCHAR(3);

        SELECT @lv_prefix = SUBSTRING(@p_table, 1, 3);

        IF(@lv_prefix = 'MAC')
            BEGIN
                SET @p_prefix = @lv_prefix;
                RETURN;
            END;
        ELSE
            SET @p_prefix = 'UNK';
            RETURN;
    END;
</code>```

This is how I am executing:

```<code>EXEC SFT.usp_GetPrefix @p_table = 'MAC_CHEESE';
</code>```

Msg 201, Level 16, State 4, Procedure SFT.usp_GetPrefix, Line 0 [Batch
  Start Line 6] Procedure or function 'usp_GetPrefix' expects parameter
  '@p_prefix', which was not supplied.

Also tried:

```<code>EXEC SFT.usp_GetPrefix @p_table = 'MAC_CHEESE', @p_prefix OUTPUT

Msg 137, Level 15, State 2, Line 6
Must declare the scalar variable "@p_prefix".
</code>```

答:
You need to pass parameters, as neither have default values. As @p_prefix is an OUTPUT parameter, in order to consume that value, you need to declare a variable to pass to the parameter:

```<code>DECLARE @p_prefix varchar(3);
EXEC SFT.usp_GetPrefix @p_table = 'MAC_CHEESE', @p_prefix OUTPUT;

--PRINT @p_prefix; --Or whatever you're going to do with the value.
</code>```

As a side note, you can make your Procedure considerably shorter:

```<code>CREATE PROCEDURE SFT.usp_GetPrefix @p_table  VARCHAR(30), @p_prefix VARCHAR(3) OUTPUT AS
BEGIN

    SET @p_prefix = CASE LEFT(@p_table,3) WHEN 'MAC' THEN 'MAC' ELSE 'UNK' END;

END
</code>```

Body:
I created a stored procedure based on the example from here on SO. However, I am getting an error. What am I missing here?

CREATE PROCEDURE SFT.usp_GetPrefix
(@p_table  VARCHAR(30),
 @p_prefix VARCHAR(3) OUTPUT
)
AS
    BEGIN
        DECLARE @lv_prefix VARCHAR(3);

        SELECT @lv_prefix = SUBSTRING(@p_table, 1, 3);

        IF(@lv_prefix = 'MAC')
            BEGIN
                SET @p_prefix = @lv_prefix;
                RETURN;
            END;
        ELSE
            SET @p_prefix = 'UNK';
            RETURN;
    END;

This is how I am executing:

EXEC SFT.usp_GetPrefix @p_table = 'MAC_CHEESE';

Msg 201, Level 16, State 4, Procedure SFT.usp_GetPrefix, Line 0 [Batch
  Start Line 6] Procedure or function 'usp_GetPrefix' expects parameter
  '@p_prefix', which was not supplied.

Also tried:

EXEC SFT.usp_GetPrefix @p_table = 'MAC_CHEESE', @p_prefix OUTPUT

Msg 137, Level 15, State 2, Line 6
Must declare the scalar variable "@p_prefix".

Body:
You need to pass parameters, as neither have default values. As @p_prefix is an OUTPUT parameter, in order to consume that value, you need to declare a variable to pass to the parameter:

DECLARE @p_prefix varchar(3);
EXEC SFT.usp_GetPrefix @p_table = 'MAC_CHEESE', @p_prefix OUTPUT;

--PRINT @p_prefix; --Or whatever you're going to do with the value.

As a side note, you can make your Procedure considerably shorter:

CREATE PROCEDURE SFT.usp_GetPrefix @p_table  VARCHAR(30), @p_prefix VARCHAR(3) OUTPUT AS
BEGIN

    SET @p_prefix = CASE LEFT(@p_table,3) WHEN 'MAC' THEN 'MAC' ELSE 'UNK' END;

END


问:
How can I have access into *argv[ ] in C?
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!</p>

```<code>int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}
</code>```

答:
Note that argv[1] and argv[2] are only valid if argc >= 3.
Thus accessing them is of course wrong.

Then if you want to read the arguments from stdin, you must make sure that you have memory where those strings are kept.
You might use something like

```<code>char filename1[20], filename2[20];
char *f1, *f2;
if (argc == 3) {
  f1 = argv[1];
  f2 = argv[2];
} else {
  f1 = filename1;
  f2 = filename2;
  /* add code to read into filename1 and filename2 */
}
/* use f1 and f2 */
</code>```

You can see that I only reserved 20 bytes for each filename, which was arbitrary chosen by me.
It is critical here to not write more than 20 bytes into those arrays (including the terminating NUL char), so you should not use scanf like this.

You can see that this is not really straight-forward in C so there is also not an answer that suites all purposes.

Edit: also be sure to never write into any argc[...] memory, as it is supplied from the system. Although not marked const I would rather consider it as such.

Body:
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!

int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}

Body:
Note that argv[1] and argv[2] are only valid if argc >= 3.
Thus accessing them is of course wrong.

Then if you want to read the arguments from stdin, you must make sure that you have memory where those strings are kept.
You might use something like

char filename1[20], filename2[20];
char *f1, *f2;
if (argc == 3) {
  f1 = argv[1];
  f2 = argv[2];
} else {
  f1 = filename1;
  f2 = filename2;
  /* add code to read into filename1 and filename2 */
}
/* use f1 and f2 */

You can see that I only reserved 20 bytes for each filename, which was arbitrary chosen by me.
It is critical here to not write more than 20 bytes into those arrays (including the terminating NUL char), so you should not use scanf like this.

You can see that this is not really straight-forward in C so there is also not an answer that suites all purposes.

Edit: also be sure to never write into any argc[...] memory, as it is supplied from the system. Although not marked const I would rather consider it as such.


问:
Force Oracle SQL query to return at least one row when using GROUP BY
Using an empty grouping set, Oracle will not return any rows even when using aggregate functions.

For example, this query without a GROUP BY clause:

```<code>select count(*)
from dual
where 1 = 0;
</code>```

yields:

```<code>  COUNT(*)
----------
         0
</code>```

whereas this query with GROUP BY ():

```<code>select count(*)
from dual
where 1 = 0
group by ();
</code>```

doesn't return any rows.

How can I force Oracle to return at least one row, even when the query contains a GROUP BY clause?

Can it be done with GROUPING SETS, ROLLUP, CUBE or some other GROUP BY clause?

I would like to avoid using UNION ALL.

答:
You can write the conditional aggregation without any WHERE clause in the query as follows:

```<code>SQL> select sum(case when 1 = 0 then 1 else 0 end) as res
  2    from dual
  3  group by 1;

       RES
----------
         0

SQL>
</code>```

Body:
Using an empty grouping set, Oracle will not return any rows even when using aggregate functions.

For example, this query without a GROUP BY clause:

select count(*)
from dual
where 1 = 0;

yields:

  COUNT(*)
----------
         0

whereas this query with GROUP BY ():

select count(*)
from dual
where 1 = 0
group by ();

doesn't return any rows.

How can I force Oracle to return at least one row, even when the query contains a GROUP BY clause?

Can it be done with GROUPING SETS, ROLLUP, CUBE or some other GROUP BY clause?

I would like to avoid using UNION ALL.

Body:
You can write the conditional aggregation without any WHERE clause in the query as follows:

SQL> select sum(case when 1 = 0 then 1 else 0 end) as res
  2    from dual
  3  group by 1;

       RES
----------
         0

SQL>


问:
typeahead multiline List items
i am using typeahead using twitter bootstrap and angularjs .its showing autocomplete suggestions as shown in below screenshot.but i want to show big cities name in different lines.for example London Borough of Harrow in two lines using twitter bootstrap typehead .How to acheive that ??any help is appreciable i am using http://angular-ui.github.io/bootstrap/ .

答:
you can have template for this

```<code><input id="id" type="text" name="name" ng-model="binding" typeahead-min-length="0" uib-typeahead="x as x.name for xyz in alphabet" typeahead-popup-template-url="url/to/template" typeahead-editable="false" autocomplete="off" typeahead-on-select="yourMethodCall()" ng-change="yourMethodCall()">
</code>```

in your template file i.e. some_template.html

```<code><div class="design class" aria-hidden="{{!isOpen()}}">
    <div class="container" ng-repeat="match in matches">
      <div> your design here... </div>
  </div>
</div>
</code>```

and boom you are done

ContentLicense: CC BY-SA 3.0

Title: typeahead multiline List items

Body:
you can have template for this

<input id="id" type="text" name="name" ng-model="binding" typeahead-min-length="0" uib-typeahead="x as x.name for xyz in alphabet" typeahead-popup-template-url="url/to/template" typeahead-editable="false" autocomplete="off" typeahead-on-select="yourMethodCall()" ng-change="yourMethodCall()">

in your template file i.e. some_template.html

<div class="design class" aria-hidden="{{!isOpen()}}">
    <div class="container" ng-repeat="match in matches">
      <div> your design here... </div>
  </div>
</div>

and boom you are done


问:
Can REST API PATCH responses with different resource that should be applied to confirm the patch?
I'm working on a server developing REST API.

The structure by now (at least what is needed to know for this question) is that I have a products collection retrievable via GET /products, GET /products/:id. I want to be able to edit these products, but I want to be able also to make drafts. This will be useful for save the edits but apply them only when done and make a history of the edits.

I thought that a possible way could be develop this endpoints:

```<code>GET /products/:id/drafts
 this will retrieve all the drafts made for this product

GET /products/:id/draft
 this will retrieve the last non applied draft, if any

POST /products/:id/draft/apply
 this will apply the last non applied draft, if any
</code>```

To this point, all seems fine, but I am struggling finding a good way for handling the creation of the drafts. I thought that it could be POST /products/:id/drafts but, because of there can be only one draft a time, should this response with 409 Conflict if is there any non applied draft yet?

So I thought that it could be PATCH /products/:id, so if there is yet a non applied draft, then it will be edited else it will be created. Could it be done?

Can the PATCH /products/:id return a representation of the draft (created or edited)?

Is it better the POST approach described before?

Is there another way that I can't think of?

答:
You seem to be trying to change the semantics of PATCH, which is not a good idea.

HTTP includes methods that support remote authoring use cases; for instance, if I wanted to change the title of the home page on my web site, the sequence of steps might look like

```<code>GET /home.html
</code>```
```<code>200 OK
Content-Type: text/html

<html>...
</code>```

(make local changes)

```<code>PUT /home.html
Content-Type: text/html

<html>...
</code>```
```<code>200 OK
</code>```

Now, if home.html were very big (relative to the size of the standard HTTP headers) and the changes we were making were very small, then we might instead want to send a patch document instead of sending the entire mostly unchanged file.

```<code>PATCH /home.html
Content-Type: text/prs.patch

????
</code>```
```<code>200 OK
</code>```

If we wanted to create a draft, using the general purpose remote authoring interface, then our sequence of requests would look something like

```<code>GET /documents/123
PUT /drafts/456
</code>```

and publish would look something like

```<code>GET /drafts/456
PUT /documents/123
</code>```

What it sounds like you want is to achieve this without sending the documents over the wire, allowing the server to manage the process.  The usual way to do that is with POST

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.”

```<code>POST /documents/123

???
</code>```
```<code>201 Created
Location: /drafts/456
</code>```
```<code>200 OK
Content-Type: text/html

<html>...
</code>```0
```<code>200 OK
Content-Type: text/html

<html>...
</code>```1

The server would use the payload of the POST requests to resolve any ambiguity that might be introduced by having multiple "not worth standardizing" actions.

Body:
I'm working on a server developing REST API.

The structure by now (at least what is needed to know for this question) is that I have a products collection retrievable via GET /products, GET /products/:id. I want to be able to edit these products, but I want to be able also to make drafts. This will be useful for save the edits but apply them only when done and make a history of the edits.

I thought that a possible way could be develop this endpoints:

GET /products/:id/drafts
 this will retrieve all the drafts made for this product

GET /products/:id/draft
 this will retrieve the last non applied draft, if any

POST /products/:id/draft/apply
 this will apply the last non applied draft, if any

To this point, all seems fine, but I am struggling finding a good way for handling the creation of the drafts. I thought that it could be POST /products/:id/drafts but, because of there can be only one draft a time, should this response with 409 Conflict if is there any non applied draft yet?

So I thought that it could be PATCH /products/:id, so if there is yet a non applied draft, then it will be edited else it will be created. Could it be done?

Can the PATCH /products/:id return a representation of the draft (created or edited)?

Is it better the POST approach described before?

Is there another way that I can't think of?

Body:
You seem to be trying to change the semantics of PATCH, which is not a good idea.

HTTP includes methods that support remote authoring use cases; for instance, if I wanted to change the title of the home page on my web site, the sequence of steps might look like

GET /home.html

200 OK
Content-Type: text/html

<html>...

(make local changes)

PUT /home.html
Content-Type: text/html

<html>...

200 OK

Now, if home.html were very big (relative to the size of the standard HTTP headers) and the changes we were making were very small, then we might instead want to send a patch document instead of sending the entire mostly unchanged file.

PATCH /home.html
Content-Type: text/prs.patch

????

200 OK

If we wanted to create a draft, using the general purpose remote authoring interface, then our sequence of requests would look something like

GET /documents/123
PUT /drafts/456

and publish would look something like

GET /drafts/456
PUT /documents/123

What it sounds like you want is to achieve this without sending the documents over the wire, allowing the server to manage the process.  The usual way to do that is with POST

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.”

POST /documents/123

???

201 Created
Location: /drafts/456

POST /drafts/456

???

200 OK

The server would use the payload of the POST requests to resolve any ambiguity that might be introduced by having multiple "not worth standardizing" actions.


问:
How to create a React app directly in the current folder
I know I've done it before but I can't seem to find the answer anywhere. I want to run create-react-app without creating a whole other folder within the folder I'm already in. I believe it is just an additional flag appended to the command. </p>

答:
When you use create-react-app app-name, the part that comes after create-react-app tells CRA where to create a react app. So create-react-app app-name is actually telling CRA to create a react app in a new directory called 'my-app'. This can cause lots of issues with deployment for the inexperienced developer.

By using npx create-react-app . we can tell CRA to create a react app here or in the current directory. This will help prevent any issues which may come from not having your react app directly in the root directory of your project or repo.


问:
R ggplot2: custom y-axis tick labels for log-transformed data?
Most tutorials I've seen for dealing with transforming log-based data involve using a log-based y-axis or x-axis scale. If I wanted to plot the log10  -based values of my data and indicate their relative actual exponent-based real values:

```<code>library(ggplot2)
library(scales)

a <- c(5,10,15,20)
b <- c(100,210,350,750)
d <- log10(b)

test_df <- data.frame(xval = a,yval = d)
test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
  geom_point() +
  scale_y_continuous(breaks = seq(1,3,by = 1),limits = c(1,3),labels = trans_format("log10",
math_format(10^.x)))

print(test_plt)
</code>```

Based on the code, I get the following results:

Obviously, R is trying to convert the already log10-transformed values into log10 based values again, is there a way indicate that I want my y-axis tick values to be 101, 102, 103, etc. (ie: the the plotted values are log10 transformed, but the y-ticks indicate the actual values before the log10 transformation? Or am I approaching this problem incorrectly?

答:
You can just use math_format() with its default arguments:

```<code>test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
    geom_point() +
    scale_y_continuous(breaks = seq(1,3,by = 1),
                       limits = c(1,3),
                       labels = math_format())

print(test_plt)
</code>```

From help("math_format"):

```<code>Usage
... [Some content omitted]...

math_format(expr = 10^.x, format = force)
</code>```

This is exactly the formatting you want, 10^.x, rather than 10^.x after a log10 transformation, which is what you get when you call it within trans_format("log10",
math_format(10^.x))

Body:
Most tutorials I've seen for dealing with transforming log-based data involve using a log-based y-axis or x-axis scale. If I wanted to plot the log10  -based values of my data and indicate their relative actual exponent-based real values:

library(ggplot2)
library(scales)

a <- c(5,10,15,20)
b <- c(100,210,350,750)
d <- log10(b)

test_df <- data.frame(xval = a,yval = d)
test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
  geom_point() +
  scale_y_continuous(breaks = seq(1,3,by = 1),limits = c(1,3),labels = trans_format("log10",
math_format(10^.x)))

print(test_plt)

Based on the code, I get the following results:

Obviously, R is trying to convert the already log10-transformed values into log10 based values again, is there a way indicate that I want my y-axis tick values to be 101, 102, 103, etc. (ie: the the plotted values are log10 transformed, but the y-ticks indicate the actual values before the log10 transformation? Or am I approaching this problem incorrectly?

Body:
You can just use math_format() with its default arguments:

test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
    geom_point() +
    scale_y_continuous(breaks = seq(1,3,by = 1),
                       limits = c(1,3),
                       labels = math_format())

print(test_plt)

From help("math_format"):

Usage
... [Some content omitted]...

math_format(expr = 10^.x, format = force)

This is exactly the formatting you want, 10^.x, rather than 10^.x after a log10 transformation, which is what you get when you call it within trans_format("log10",
math_format(10^.x))


问:
Is there a pandas functionality to get an None instead of an index error?
I have a pandas (version 0.25) DataFrame with some indexes. When I'm looking for an index not present in the DataFrame, I (of course) get an KeyError.

```<code>import pandas as pd
df = pd.DataFrame({'age': [50, 40]}, index = ['alice', 'bob'])
# works, returns age 50:
df.loc['alice']
# does not work, gives KeyError
</code>```

What I would like to have is something like get for dictionaries ({'alice': 50}.get('charlie')) for DataFrames. The best I could find was

```<code>df.loc['charlie'] if 'charlie' in df.index else None
</code>```

答:
You can use DataFrame.get which behaves same as the vanilla Python dict.get method. So it will return None when the key does not exist. We use Transpose because its an column index method.

```<code>df.T.get('charlie')

# returns None
</code>```

```<code>df.T.get('alice')

age    50
Name: alice, dtype: int64
</code>```

Body:
I have a pandas (version 0.25) DataFrame with some indexes. When I'm looking for an index not present in the DataFrame, I (of course) get an KeyError.

import pandas as pd
df = pd.DataFrame({'age': [50, 40]}, index = ['alice', 'bob'])
# works, returns age 50:
df.loc['alice']
# does not work, gives KeyError

What I would like to have is something like get for dictionaries ({'alice': 50}.get('charlie')) for DataFrames. The best I could find was

df.loc['charlie'] if 'charlie' in df.index else None

Body:
You can use DataFrame.get which behaves same as the vanilla Python dict.get method. So it will return None when the key does not exist. We use Transpose because its an column index method.

df.T.get('charlie')

# returns None

df.T.get('alice')

age    50
Name: alice, dtype: int64


问:
GA Management API - Custom Dimensions list() - Error 403: Insufficient Permission
I'm using Management API (using PY Client Library) to get list of Custom Dimensions as described here -  Custom Dimensions: list

```<code>link = analytics.management().customDimensions().list(accountId = ACCOUNT_ID,
                                                     webPropertyId = PROPERTY_ID)
dimensions = link.execute()
</code>```

but the API keeps returning Error Code: 403, Insufficient Permission

I'm pretty sure the service account email address I'm using to build credentials object has sufficient Edit, Read & Analyse level access at the GA Account Level!.

I confirm - get() and patch() verbs execute properly using same credentials, same account, property ID. Even the API Explorer works fine.

Any clue what I might be missing, or potential bug in API ?

Thanks for any clue

答:
I have had a similar problem, notice that listing custom dimensions can only be done using those scopes:

['https://www.googleapis.com/auth/analytics.readonly',
'https://www.googleapis.com/auth/analytics']

get() and patch() can be done using https://www.googleapis.com/auth/analytics.edit scope, I am assuming this is the one that you are using.

It is annoying as edit scope can list most of the assets such as goals but not custom dimensions and metrics.

Hope that resolves your problem

Body:
I'm using Management API (using PY Client Library) to get list of Custom Dimensions as described here -  Custom Dimensions: list

link = analytics.management().customDimensions().list(accountId = ACCOUNT_ID,
                                                     webPropertyId = PROPERTY_ID)
dimensions = link.execute()

but the API keeps returning Error Code: 403, Insufficient Permission

I'm pretty sure the service account email address I'm using to build credentials object has sufficient Edit, Read & Analyse level access at the GA Account Level!.

I confirm - get() and patch() verbs execute properly using same credentials, same account, property ID. Even the API Explorer works fine.

Any clue what I might be missing, or potential bug in API ?

Thanks for any clue


问:
Determine place values for any base
I'm looking for a function that will determine the value of a place given a number and a base.  For example,

Given:

```<code>Whole Value: 1120
Base: 10
Place: Tens place
</code>```

Should return: 2

Does anybody know the math for this?

Edit: The function is also expected to pass the whole value numerically, not as a string like "e328fa" or something.  Also the return value should be numeric as well, so a FindInPlace(60 (whole value), 16 (base), 2 (place, 1-based index)) should return 3.

答:
With 1-based place indexing the formula is:

placeval = floor(number / (base^(place-1))) mod base

In Python:

```<code>def FindInPlace(number, base, place):
    return number//base**(place-1) % base
</code>```

ContentLicense: CC BY-SA 2.5

Title: Determine place values for any base

Body:
I'm looking for a function that will determine the value of a place given a number and a base.  For example,

Given:

Whole Value: 1120
Base: 10
Place: Tens place

Should return: 2

Does anybody know the math for this?

Edit: The function is also expected to pass the whole value numerically, not as a string like "e328fa" or something.  Also the return value should be numeric as well, so a FindInPlace(60 (whole value), 16 (base), 2 (place, 1-based index)) should return 3.

Body:
With 1-based place indexing the formula is:

placeval = floor(number / (base^(place-1))) mod base

In Python:

def FindInPlace(number, base, place):
    return number//base**(place-1) % base

OwnerDisplayName: Theran


问:
PHP Header location in IF statement
Im trying to write this script to say if email is valied insert into DB and redirect, else redirect with error message only my redirect isn't working, im not terribly great with php and still reading up on the subject so id appreciate any advice, thanks in advance!

```<code><?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
{
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=invalid');
}
else
{
mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=success');
}

?>
</code>```

Sorry for not describing what goes wrong, what's happening is my page isnt redirecting back to the page in the header(location)

I've now enabled Error reporting and im still only seeing a white page, heres my entire page code.

```<code><?php

error_reporting(E_ALL);
require 'config.inc.php';

?>

<?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
    {
    header('Location: http://www..co.uk/mytwitter.php?msg=invalid');
    }
else
    {
    mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
    header('Location: http://www..co.uk/mytwitter.php?msg=success');
    }

?>
</code>```

答:
I managed to get it working using the following code, I've rewritten it based upon what I've read regarding SQL injections and it works fine, I'd appreciate any advice on this, thanks!</p>

```<code><?php

require 'config.inc.php';

$userid = $usersClass->userID();
$user_email=mysql_real_escape_string($_POST['email_upd']);

if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $user_email))
{
    mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=/mytwitter.php?msg=email updated\">";
}
else
{
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=/mytwitter.php?msg=email error\">";
}

?>
</code>```

Title: PHP Header location in IF statement

Body:
Im trying to write this script to say if email is valied insert into DB and redirect, else redirect with error message only my redirect isn't working, im not terribly great with php and still reading up on the subject so id appreciate any advice, thanks in advance!

<?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
{
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=invalid');
}
else
{
mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=success');
}

?>

Sorry for not describing what goes wrong, what's happening is my page isnt redirecting back to the page in the header(location)

I've now enabled Error reporting and im still only seeing a white page, heres my entire page code.

<?php

error_reporting(E_ALL);
require 'config.inc.php';

?>

<?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
    {
    header('Location: http://www..co.uk/mytwitter.php?msg=invalid');
    }
else
    {
    mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
    header('Location: http://www..co.uk/mytwitter.php?msg=success');
    }

?>

Body:
I managed to get it working using the following code, I've rewritten it based upon what I've read regarding SQL injections and it works fine, I'd appreciate any advice on this, thanks!

<?php

require 'config.inc.php';

$userid = $usersClass->userID();
$user_email=mysql_real_escape_string($_POST['email_upd']);

if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $user_email))
{
    mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=/mytwitter.php?msg=email updated\">";
}
else
{
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=/mytwitter.php?msg=email error\">";
}

?>


问:
binomial regression with group effects
I am trying to build a binomial regression model with rstan.

The aim is to get the effect size bt between two conditions X in a group t in total and the effect size btg for subgroups g.

```<code>library(rstan)

df <- data.frame(hits=c(36,1261,36,1261,49,1248,17,7670,25,759,29,755),trials=c(118,53850,184,53784,209,53759,118,53850,184,53784,209,53759)
                ,X=rep(c(1,0),6),g=rep(rep(1:3, each=2),2),t=rep(1:2,each=6),tg=rep(1:6,each=2) )

stanIn <- list(Nt=length(unique(df$t)), #number of groups t
            Nc=length(df$t), #number of rows
            Ng=length(unique(df$g)), #number of subgroups g
            Ntg=length(unique(df$tg)), #number of t and g combinations
            N=df$trials,
            n=df$hits,
            X=df$X, #condition 1 or 0
            t=df$t, #index of groups
            g=df$g, #index of subgroups
            tg=df$tg) #index of combinations between t and g

model <- stan(data=stanIn, file="minimal.stan", chains = 4)
</code>```

with minimal.stan as below.

```<code>data {
  int<lower=1> Nt;
  int<lower=1> Nc;
  int<lower=1> Ng;
  int<lower=1> Ntg;
  int<lower=1> N[Nc];
  int<lower=0> n[Nc];
  int<lower=0,upper=1> X[Nc];
  int<lower=1> t[Nc];
  int<lower=0> g[Nc];
  int<lower=1> tg[Nc];
}

parameters {
  real at[Nt]; // group intercepts
  real bt[Nt]; // group slopes
  real btg[Ntg]; // subgroup slopes
  real atg[Ntg]; // subgroup intercept
}

transformed parameters {
  vector[Nc] theta; // binomial probabilities

  for (i in 1:Nc) { // linear model
    theta[i] = inv_logit( (atg[tg[i]]+at[t[i]] ) + (bt[t[i]]+btg[tg[i]]) * X[i]);
    //theta[i] = inv_logit(at[t[i]] + bt[t[i]] * X[i]); //group effect
    //theta[i] = inv_logit(atg[tg[i]] + btg[tg[i]] * X[i]); //subgroup effects
  }
}

model {
  at ~ normal(0.0, 20.0);
  bt ~ normal(0.0, 20.0);
  atg ~ normal(0.0, 20.0);
  btg ~ normal(0.0, 20.0);
  n ~ binomial(N, theta);
}
</code>```

I can model the overall group effect with the first commented line (in
transformed parameters) and the subgroup effects with the second commented line. The idea was to combine both to get a group effect and the deviation from it for the individual group (first line).

However, this gives really weird results for bt and btg (A), and I was expecting something more like (B) (I can not recreate the behavior seen in A with a minimal example, this only occurs in the full dataset.)

If its not apparent from the type of question, I am completely new to statistic modeling and suspect that I have a conceptional error. So I would be grateful for any hint on this issue or a source to read up on those things (Feels like a common thing but I did not find anything).

答:
I see several issues. Most directly, the model is not identified as the parameters atg and btg includes at and bt. I've changed those to ag and bg as they are your subgroup parameters, and indexed them as such, below:

```<code>library(rstan)

df <- data.frame(hits   = c(36, 1261, 36, 1261, 49, 1248,
                            17, 7670, 25, 759, 29, 755),
                 trials = c(118, 53850, 184, 53784, 209, 53759,
                            118, 53850, 184, 53784, 209, 53759),
                 X  = rep(c(1,0), 6),
                 g  = rep(rep(1:3, each=2), 2),
                 t  = rep(1:2, each=6),
                 tg = rep(1:6, each=2) )

stanIn <- list(Nt = length(unique(df$t)), #number of groups t
               Nc = length(df$t),         #number of rows
               Ng = length(unique(df$g)), #number of subgroups g
               N  = df$trials,
               n  = df$hits,
               X  = df$X,                 #condition 1 or 0
               t  = df$t,                 #index of groups
               g  = df$g)                 #index of subgroups

model <- stan(data = stanIn, file = "minimal.stan",
              cores = 4, chains = 4,
              control = list(max_treedepth = 14))
</code>```

with this modified Stan model samples without issues:

```<code>data {
  int<lower=1> Nt;
  int<lower=1> Nc;
  int<lower=1> Ng;
  int<lower=1> N[Nc];
  int<lower=0> n[Nc];
  vector<lower=0,upper=1>[Nc] X;
  int<lower=1> t[Nc];
  int<lower=0> g[Nc];
}

parameters {
  vector<offset=0, multiplier=20>[Nt] at; // group intercepts
  vector<offset=0, multiplier=20>[Nt] bt; // group slopes
  vector<offset=0, multiplier=20>[Ng] ag; // subgroup intercepts
  vector<offset=0, multiplier=20>[Ng] bg; // subgroup slopes
}

model {
  at ~ normal(0.0, 20.0);
  bt ~ normal(0.0, 20.0);
  ag ~ normal(0.0, 20.0);
  bg ~ normal(0.0, 20.0);
  n  ~ binomial_logit(N, ag[g] + at[t] + (bt[t] + bg[g]) .* X);
}

generated quantities {
  vector[Nc] theta = inv_logit(ag[g] + at[t] + (bt[t] + bg[g]) .* X);
}
</code>```

Of note, I had to use a high max_treedepth to fit the model, but it's hard for me to comment on that without understanding the data. I've also moved theta to generated quantities in case you want those calculations, but the binomial_logit handles this directly.

I've also setup noncentered parameters using offset and multiplier so that the Stan sampler has a better parameter space to sample from. Finally, I've re-coded the loops as vectors.

Title: binomial regression with group effects

Body:
I am trying to build a binomial regression model with rstan.

The aim is to get the effect size bt between two conditions X in a group t in total and the effect size btg for subgroups g.

library(rstan)

df <- data.frame(hits=c(36,1261,36,1261,49,1248,17,7670,25,759,29,755),trials=c(118,53850,184,53784,209,53759,118,53850,184,53784,209,53759)
                ,X=rep(c(1,0),6),g=rep(rep(1:3, each=2),2),t=rep(1:2,each=6),tg=rep(1:6,each=2) )

stanIn <- list(Nt=length(unique(df$t)), #number of groups t
            Nc=length(df$t), #number of rows
            Ng=length(unique(df$g)), #number of subgroups g
            Ntg=length(unique(df$tg)), #number of t and g combinations
            N=df$trials,
            n=df$hits,
            X=df$X, #condition 1 or 0
            t=df$t, #index of groups
            g=df$g, #index of subgroups
            tg=df$tg) #index of combinations between t and g

model <- stan(data=stanIn, file="minimal.stan", chains = 4)

with minimal.stan as below.

data {
  int<lower=1> Nt;
  int<lower=1> Nc;
  int<lower=1> Ng;
  int<lower=1> Ntg;
  int<lower=1> N[Nc];
  int<lower=0> n[Nc];
  int<lower=0,upper=1> X[Nc];
  int<lower=1> t[Nc];
  int<lower=0> g[Nc];
  int<lower=1> tg[Nc];
}

parameters {
  real at[Nt]; // group intercepts
  real bt[Nt]; // group slopes
  real btg[Ntg]; // subgroup slopes
  real atg[Ntg]; // subgroup intercept
}

transformed parameters {
  vector[Nc] theta; // binomial probabilities

  for (i in 1:Nc) { // linear model
    theta[i] = inv_logit( (atg[tg[i]]+at[t[i]] ) + (bt[t[i]]+btg[tg[i]]) * X[i]);
    //theta[i] = inv_logit(at[t[i]] + bt[t[i]] * X[i]); //group effect
    //theta[i] = inv_logit(atg[tg[i]] + btg[tg[i]] * X[i]); //subgroup effects
  }
}

model {
  at ~ normal(0.0, 20.0);
  bt ~ normal(0.0, 20.0);
  atg ~ normal(0.0, 20.0);
  btg ~ normal(0.0, 20.0);
  n ~ binomial(N, theta);
}

I can model the overall group effect with the first commented line (in
transformed parameters) and the subgroup effects with the second commented line. The idea was to combine both to get a group effect and the deviation from it for the individual group (first line).

However, this gives really weird results for bt and btg (A), and I was expecting something more like (B) (I can not recreate the behavior seen in A with a minimal example, this only occurs in the full dataset.)

If its not apparent from the type of question, I am completely new to statistic modeling and suspect that I have a conceptional error. So I would be grateful for any hint on this issue or a source to read up on those things (Feels like a common thing but I did not find anything).

Body:
I see several issues. Most directly, the model is not identified as the parameters atg and btg includes at and bt. I've changed those to ag and bg as they are your subgroup parameters, and indexed them as such, below:

library(rstan)

df <- data.frame(hits   = c(36, 1261, 36, 1261, 49, 1248,
                            17, 7670, 25, 759, 29, 755),
                 trials = c(118, 53850, 184, 53784, 209, 53759,
                            118, 53850, 184, 53784, 209, 53759),
                 X  = rep(c(1,0), 6),
                 g  = rep(rep(1:3, each=2), 2),
                 t  = rep(1:2, each=6),
                 tg = rep(1:6, each=2) )

stanIn <- list(Nt = length(unique(df$t)), #number of groups t
               Nc = length(df$t),         #number of rows
               Ng = length(unique(df$g)), #number of subgroups g
               N  = df$trials,
               n  = df$hits,
               X  = df$X,                 #condition 1 or 0
               t  = df$t,                 #index of groups
               g  = df$g)                 #index of subgroups

model <- stan(data = stanIn, file = "minimal.stan",
              cores = 4, chains = 4,
              control = list(max_treedepth = 14))

with this modified Stan model samples without issues:

data {
  int<lower=1> Nt;
  int<lower=1> Nc;
  int<lower=1> Ng;
  int<lower=1> N[Nc];
  int<lower=0> n[Nc];
  vector<lower=0,upper=1>[Nc] X;
  int<lower=1> t[Nc];
  int<lower=0> g[Nc];
}

parameters {
  vector<offset=0, multiplier=20>[Nt] at; // group intercepts
  vector<offset=0, multiplier=20>[Nt] bt; // group slopes
  vector<offset=0, multiplier=20>[Ng] ag; // subgroup intercepts
  vector<offset=0, multiplier=20>[Ng] bg; // subgroup slopes
}

model {
  at ~ normal(0.0, 20.0);
  bt ~ normal(0.0, 20.0);
  ag ~ normal(0.0, 20.0);
  bg ~ normal(0.0, 20.0);
  n  ~ binomial_logit(N, ag[g] + at[t] + (bt[t] + bg[g]) .* X);
}

generated quantities {
  vector[Nc] theta = inv_logit(ag[g] + at[t] + (bt[t] + bg[g]) .* X);
}

Of note, I had to use a high max_treedepth to fit the model, but it's hard for me to comment on that without understanding the data. I've also moved theta to generated quantities in case you want those calculations, but the binomial_logit handles this directly.

I've also setup noncentered parameters using offset and multiplier so that the Stan sampler has a better parameter space to sample from. Finally, I've re-coded the loops as vectors.


问:
Access locally served files within an R session

Context

In order to test the web capabilities of an R package I am writing, I'm attempting to serve a file locally use the httpuv package so that I can run tests using an offline copy of the page.

Issue

However, curl doesn't seem to want to play nice with httpuv - specifically, when trying to read the hosted file using curl (for example, with curl::curl() or curl::curl_fetch_memory()), the request hangs, and eventually times out if not manually interrupted.

Minimal example

```<code># Serve a small page
server <- httpuv::startServer("0.0.0.0", port = 9359, app = list(
  call = function(req) {
    list(
      status = 200L,
      headers = list("Content-Type" = "text/html"),
      body = "Some content..."
    )
  }
))

# Attempt to retrieve content (this hangs)
page <- curl::curl_fetch_memory(url = "http://127.0.0.1:9359")

httpuv::stopServer(server)
</code>```

Current progress

Once the server has been started, running curl -v 127.0.0.1:9359 at the terminal returns content as expected. Additionally, if I open a new instance of RStudio and try to curl::curl_fetch_memory() in that new R session (while the old one is still open), it works perfectly.

Encouraged by that, I've been playing around with callr for a while, thinking maybe it's possible to launch the server in some background process, and then continue as usual. Unfortunately I haven't had any success so far with this approach.

Any insight or suggestions very much appreciated!

答:
Isn't it a great feeling when you can come back and answer a question you asked!

From the httpuv::startServer() documentation:

startServer binds the specified port and listens for connections on an thread running in the background. This background thread handles the I/O, and when it receives a HTTP request, it will schedule a call to the user-defined R functions in app to handle the request. This scheduling is done with later(). When the R call stack is empty – in other words, when an interactive R session is sitting idle at the command prompt – R will automatically run the scheduled calls. However, if the call stack is not empty – if R is evaluating other R code – then the callbacks will not execute until either the call stack is empty, or the run_now() function is called. This function tells R to execute any callbacks that have been scheduled by later(). The service() function is essentially a wrapper for run_now().

In other words, if we want to respond to requests as soon as they are received, we have to explicitly do so using httpuv::service(). Something like the following does the trick!

s <- callr::r_session$new()
on.exit(s$close())

s$call(function() {
  httpuv::startServer("0.0.0.0", port = 9359, app = list(
    call = function(req) {
      list(
        status = 200L,
        headers = list("Content-Type" = "text/html"),
        body = "Some content...")
      )
    }
  ))

  while (TRUE) httpuv::service()
})

# Give the server a chance to start
Sys.sleep(3)
page <- curl_fetch_memory(url = "http://127.0.0.1:9359")
```

Body:
Context

In order to test the web capabilities of an R package I am writing, I'm attempting to serve a file locally use the httpuv package so that I can run tests using an offline copy of the page.

Issue

However, curl doesn't seem to want to play nice with httpuv - specifically, when trying to read the hosted file using curl (for example, with curl::curl() or curl::curl_fetch_memory()), the request hangs, and eventually times out if not manually interrupted.

Minimal example

# Serve a small page
server <- httpuv::startServer("0.0.0.0", port = 9359, app = list(
  call = function(req) {
    list(
      status = 200L,
      headers = list("Content-Type" = "text/html"),
      body = "Some content..."
    )
  }
))

# Attempt to retrieve content (this hangs)
page <- curl::curl_fetch_memory(url = "http://127.0.0.1:9359")

httpuv::stopServer(server)

Current progress

Once the server has been started, running curl -v 127.0.0.1:9359 at the terminal returns content as expected. Additionally, if I open a new instance of RStudio and try to curl::curl_fetch_memory() in that new R session (while the old one is still open), it works perfectly.

Encouraged by that, I've been playing around with callr for a while, thinking maybe it's possible to launch the server in some background process, and then continue as usual. Unfortunately I haven't had any success so far with this approach.

Any insight or suggestions very much appreciated!


答:
You can use a CTE and check if the group by returns no rows:

```<code>with g as (
      select . . .
      from . . .
      group by . . .
     )
select g.*
from g
union all
select g.*
from (select 1 as n from dual) n left join
     g
     on 1 = 0  -- never true
where not exists (select 1 from g)
</code>```

Title: Force Oracle SQL query to return at least one row when using GROUP BY

Body:
Using an empty grouping set, Oracle will not return any rows even when using aggregate functions.

For example, this query without a GROUP BY clause:

select count(*)
from dual
where 1 = 0;

yields:

  COUNT(*)
----------
         0

whereas this query with GROUP BY ():

select count(*)
from dual
where 1 = 0
group by ();

doesn't return any rows.

How can I force Oracle to return at least one row, even when the query contains a GROUP BY clause?

Can it be done with GROUPING SETS, ROLLUP, CUBE or some other GROUP BY clause?

I would like to avoid using UNION ALL.

Body:
You can use a CTE and check if the group by returns no rows:

with g as (
      select . . .
      from . . .
      group by . . .
     )
select g.*
from g
union all
select g.*
from (select 1 as n from dual) n left join
     g
     on 1 = 0  -- never true
where not exists (select 1 from g)


问:
How can I obtain the registry repositories and tags associated with a specific gitlab project
I'd like to grab the associated registry repositories and tags for a gitlab project. Right now my code attempts to do this for a single project but later I'll have to scale this for multiple projects and update as the tags are updated.

Here's my code but I don't get the registries out as expected, instead a 404 error.

```<code># private token authentication
parser = argparse.ArgumentParser()
parser.add_argument("--token","-t",help="Gitlab token used to login")
args = parser.parse_args()
if not args.token:
    raise ValueError("No gitlab token specified")
gl = gitlab.Gitlab('https://gitlab.abcdef.com', private_token=args.token)

project = gl.projects.get('https://gitlab.abcdef.com/xyz/reflection')
repositories = project.repositories.list()
repository = repositories.pop()
tags = repository.tags.list()

print(tags)

</code>```

I tried it out by looking at the examples here: https://python-gitlab.readthedocs.io/en/stable/gl_objects/repository_tags.html

What am I doing incorrect? How can I get a list out. Thanks so much for any help!

答:
Update: I got this to work using project_id , however I'd ideally like it to work using project name or url as I need to loop through and grab registries and tags for a number of gitlab projects.

```<code># private token authentication
parser = argparse.ArgumentParser()
parser.add_argument("--token","-t",help="Gitlab token used to login")
args = parser.parse_args()
if not args.token:
    raise ValueError("No gitlab token specified")
gl = gitlab.Gitlab('https://gitlab.abcdef.com', private_token=args.token)

project_id = 85
project = gl.projects.get(project_id)

repositories = project.repositories.list()
repository = repositories.pop()
tags = repository.tags.list()
print(repositories)
print(tags)
</code>```

I get a list of tags and registry repositories.

Body:
I'd like to grab the associated registry repositories and tags for a gitlab project. Right now my code attempts to do this for a single project but later I'll have to scale this for multiple projects and update as the tags are updated.

Here's my code but I don't get the registries out as expected, instead a 404 error.

# private token authentication
parser = argparse.ArgumentParser()
parser.add_argument("--token","-t",help="Gitlab token used to login")
args = parser.parse_args()
if not args.token:
    raise ValueError("No gitlab token specified")
gl = gitlab.Gitlab('https://gitlab.abcdef.com', private_token=args.token)

project = gl.projects.get('https://gitlab.abcdef.com/xyz/reflection')
repositories = project.repositories.list()
repository = repositories.pop()
tags = repository.tags.list()

print(tags)

I tried it out by looking at the examples here: https://python-gitlab.readthedocs.io/en/stable/gl_objects/repository_tags.html

What am I doing incorrect? How can I get a list out. Thanks so much for any help!

Body:
Update: I got this to work using project_id , however I'd ideally like it to work using project name or url as I need to loop through and grab registries and tags for a number of gitlab projects.

# private token authentication
parser = argparse.ArgumentParser()
parser.add_argument("--token","-t",help="Gitlab token used to login")
args = parser.parse_args()
if not args.token:
    raise ValueError("No gitlab token specified")
gl = gitlab.Gitlab('https://gitlab.abcdef.com', private_token=args.token)

project_id = 85
project = gl.projects.get(project_id)

repositories = project.repositories.list()
repository = repositories.pop()
tags = repository.tags.list()
print(repositories)
print(tags)

I get a list of tags and registry repositories.


问:
How to get timestamp in nanoseconds in Python 3?
```<code>import time
print(time.time())
</code>```

This gives me output:

```<code>1590683242.8507078
</code>```

Desired output is 19-digit long nanosecond Unix timestamp.

答:
You can use time.time_ns() method of Time module.

```<code>import time
print(time.time_ns())
</code>```

time.time() -- retrieves time in seconds.

time.time_ns() -- retrieves time in nano seconds.

Body:
import time
print(time.time())

This gives me output:

1590683242.8507078

Desired output is 19-digit long nanosecond Unix timestamp.

Body:
You can use time.time_ns() method of Time module.

import time
print(time.time_ns())

time.time() -- retrieves time in seconds.

time.time_ns() -- retrieves time in nano seconds.


问:
Error when trying to install puppeteer in Docker container
I have a docker container specifically for Ruby on Rails that is basically built from a Ruby docker container. After it runs bundle install and everything else successfully, it then tries to run npm install which tries to install puppeteer. This is the error I'm receiving below:

```<code>sudo docker exec -ti app_1 npm install

> puppeteer@3.1.0 install /myapp/node_modules/puppeteer
> node install.js

/myapp/node_modules/puppeteer/install.js:175
            } catch {
                    ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
npm WARN ws@7.3.0 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN ws@7.3.0 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.

npm ERR! code ELIFECYCLE
npm ERR! errno 1                                                                                npm ERR! puppeteer@3.1.0 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the puppeteer@3.1.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-05-21T18_12_14_082Z-debug.log
</code>```

If I look into the log file printed at the bottom of that output, here's what I see towards the very bottom:

```<code>1284 info lifecycle ws@7.3.0~install: ws@7.3.0
1285 silly install yauzl@2.10.0
1286 info lifecycle yauzl@2.10.0~install: yauzl@2.10.0
1287 silly install extract-zip@2.0.0
1288 info lifecycle extract-zip@2.0.0~install: extract-zip@2.0.0
1289 silly install puppeteer@3.1.0
1290 info lifecycle puppeteer@3.1.0~install: puppeteer@3.1.0
1291 verbose lifecycle puppeteer@3.1.0~install: unsafe-perm in lifecycle false
1292 verbose lifecycle puppeteer@3.1.0~install: PATH: /usr/lib/node_modules/npm/bin/node-gyp-bin:/myapp/node_modules/puppeteer/node_modules/.bin:/myapp/node_modules/.bin:/usr/local/bundle/bin:/usr/local/bundle/gems/bin:/usr/local/sbin:/usr/local/bin:/usr
/sbin:/usr/bin:/sbin:/bin
1293 verbose lifecycle puppeteer@3.1.0~install: CWD: /myapp/node_modules/puppeteer
1294 silly lifecycle puppeteer@3.1.0~install: Args: [ '-c', 'node install.js' ]
1295 silly lifecycle puppeteer@3.1.0~install: Returned: code: 1  signal: null
1296 info lifecycle puppeteer@3.1.0~install: Failed to exec install script
1297 verbose unlock done using /root/.npm/_locks/staging-bcb8ce459d19ee76.lock for /myapp/node_modules/.staging
1298 warn ws@7.3.0 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
1299 warn ws@7.3.0 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.
1300 verbose stack Error: puppeteer@3.1.0 install: `node install.js`
1300 verbose stack Exit status 1
1300 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
1300 verbose stack     at emitTwo (events.js:126:13)
1300 verbose stack     at EventEmitter.emit (events.js:214:7)
1300 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)                                                                                1300 verbose stack     at emitTwo (events.js:126:13)
1300 verbose stack     at ChildProcess.emit (events.js:214:7)
1300 verbose stack     at maybeClose (internal/child_process.js:925:16)
1300 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
1301 verbose pkgid puppeteer@3.1.0
1302 verbose cwd /myapp
1303 verbose Linux 5.4.0-31-generic
1304 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
1305 verbose node v8.9.3
1306 verbose npm  v5.5.1
1307 error code ELIFECYCLE
1308 error errno 1
1309 error puppeteer@3.1.0 install: `node install.js`
1309 error Exit status 1
1310 error Failed at the puppeteer@3.1.0 install script.
1310 error This is probably not a problem with npm. There is likely additional logging output above.
1311 verbose exit [ 1, true ]
</code>```

According to this GitHub issue, the suggestion was to just simply run npm install puppeteer --unsafe-perm=true. However, when I ran that, I receive the same exact error.

Still learning Docker, so I'm not quite sure if there is something else that I need to include into the Dockerfile as part of the build. Here's what my Dockerfile looks like:

```<code>FROM ruby:2.5.1-alpine
ENV BUNDLER_VERSION=2.0.2

RUN apk add --update --no-cache \
        binutils-gold \
        build-base \
        curl \
        file \
        g++ \
        gcc \
        git \
        less \
        libstdc++ \
        libffi-dev \
        libc-dev \
        linux-headers \
        libxml2-dev \
        libxslt-dev \
        libgcrypt-dev \
        make \
        netcat-openbsd \
        nodejs \
        openssl \
        pkgconfig \
        postgresql-dev \
        python \
        tzdata \
        yarn

RUN gem install bundler -v 2.0.2
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle check || bundle install

COPY . /myapp
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]%
</code>```

I noticed two warnings about bufferutil and utf-8-validate peers being required, and so I installed those successfully, but still ran into the same error

Any suggestions on resolving this npm install puppeteer issue would be greatly appreciated.

答:
Updating node and npm to these versions solved the problem for me:</p>

```<code>$ node -v
v12.17.0
$ npm -v
6.14.4
</code>```

Body:
I have a docker container specifically for Ruby on Rails that is basically built from a Ruby docker container. After it runs bundle install and everything else successfully, it then tries to run npm install which tries to install puppeteer. This is the error I'm receiving below:

sudo docker exec -ti app_1 npm install

> puppeteer@3.1.0 install /myapp/node_modules/puppeteer
> node install.js

/myapp/node_modules/puppeteer/install.js:175
            } catch {
                    ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
npm WARN ws@7.3.0 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN ws@7.3.0 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.

npm ERR! code ELIFECYCLE
npm ERR! errno 1                                                                                npm ERR! puppeteer@3.1.0 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the puppeteer@3.1.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-05-21T18_12_14_082Z-debug.log

If I look into the log file printed at the bottom of that output, here's what I see towards the very bottom:

1284 info lifecycle ws@7.3.0~install: ws@7.3.0
1285 silly install yauzl@2.10.0
1286 info lifecycle yauzl@2.10.0~install: yauzl@2.10.0
1287 silly install extract-zip@2.0.0
1288 info lifecycle extract-zip@2.0.0~install: extract-zip@2.0.0
1289 silly install puppeteer@3.1.0
1290 info lifecycle puppeteer@3.1.0~install: puppeteer@3.1.0
1291 verbose lifecycle puppeteer@3.1.0~install: unsafe-perm in lifecycle false
1292 verbose lifecycle puppeteer@3.1.0~install: PATH: /usr/lib/node_modules/npm/bin/node-gyp-bin:/myapp/node_modules/puppeteer/node_modules/.bin:/myapp/node_modules/.bin:/usr/local/bundle/bin:/usr/local/bundle/gems/bin:/usr/local/sbin:/usr/local/bin:/usr
/sbin:/usr/bin:/sbin:/bin
1293 verbose lifecycle puppeteer@3.1.0~install: CWD: /myapp/node_modules/puppeteer
1294 silly lifecycle puppeteer@3.1.0~install: Args: [ '-c', 'node install.js' ]
1295 silly lifecycle puppeteer@3.1.0~install: Returned: code: 1  signal: null
1296 info lifecycle puppeteer@3.1.0~install: Failed to exec install script
1297 verbose unlock done using /root/.npm/_locks/staging-bcb8ce459d19ee76.lock for /myapp/node_modules/.staging
1298 warn ws@7.3.0 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
1299 warn ws@7.3.0 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.
1300 verbose stack Error: puppeteer@3.1.0 install: `node install.js`
1300 verbose stack Exit status 1
1300 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
1300 verbose stack     at emitTwo (events.js:126:13)
1300 verbose stack     at EventEmitter.emit (events.js:214:7)
1300 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)                                                                                1300 verbose stack     at emitTwo (events.js:126:13)
1300 verbose stack     at ChildProcess.emit (events.js:214:7)
1300 verbose stack     at maybeClose (internal/child_process.js:925:16)
1300 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
1301 verbose pkgid puppeteer@3.1.0
1302 verbose cwd /myapp
1303 verbose Linux 5.4.0-31-generic
1304 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
1305 verbose node v8.9.3
1306 verbose npm  v5.5.1
1307 error code ELIFECYCLE
1308 error errno 1
1309 error puppeteer@3.1.0 install: `node install.js`
1309 error Exit status 1
1310 error Failed at the puppeteer@3.1.0 install script.
1310 error This is probably not a problem with npm. There is likely additional logging output above.
1311 verbose exit [ 1, true ]

According to this GitHub issue, the suggestion was to just simply run npm install puppeteer --unsafe-perm=true. However, when I ran that, I receive the same exact error.

Still learning Docker, so I'm not quite sure if there is something else that I need to include into the Dockerfile as part of the build. Here's what my Dockerfile looks like:

FROM ruby:2.5.1-alpine
ENV BUNDLER_VERSION=2.0.2

RUN apk add --update --no-cache \
        binutils-gold \
        build-base \
        curl \
        file \
        g++ \
        gcc \
        git \
        less \
        libstdc++ \
        libffi-dev \
        libc-dev \
        linux-headers \
        libxml2-dev \
        libxslt-dev \
        libgcrypt-dev \
        make \
        netcat-openbsd \
        nodejs \
        openssl \
        pkgconfig \
        postgresql-dev \
        python \
        tzdata \
        yarn

RUN gem install bundler -v 2.0.2
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle check || bundle install

COPY . /myapp
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]%

I noticed two warnings about bufferutil and utf-8-validate peers being required, and so I installed those successfully, but still ran into the same error

Any suggestions on resolving this npm install puppeteer issue would be greatly appreciated.

Body:
Updating node and npm to these versions solved the problem for me:

$ node -v
v12.17.0
$ npm -v
6.14.4


答:
You can't do this because argv[1] and argv[2] are NULL pointers (if they even exist in the array), so you can't access them.

You need to approach the problem from a different way.

Instead of trying to change members of argv, assign them to other variables that hold the file names.

```<code>int main (int argc, char **argv)
{
    char file1[100], file2[100];
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", file1);
        printf("file 2: ");
        scanf("%s ", file2);
    } else {
        strcpy(file1, argv[1]);
        strcpy(file2, argv[2]);
    }

    printf("%s\n", file1);
    printf("%s\n", file2);

    FILE *file1 = fopen(file1, "r");
    FILE *file2 = fopen(file2, "r");
}
</code>```

Note that I made some assumptions about the length of a filename.  Adjust as necessary.

Title: How can I have access into *argv[ ] in C?

Body:
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!

int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}

Body:
You can't do this because argv[1] and argv[2] are NULL pointers (if they even exist in the array), so you can't access them.

You need to approach the problem from a different way.

Instead of trying to change members of argv, assign them to other variables that hold the file names.

int main (int argc, char **argv)
{
    char file1[100], file2[100];
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", file1);
        printf("file 2: ");
        scanf("%s ", file2);
    } else {
        strcpy(file1, argv[1]);
        strcpy(file2, argv[2]);
    }

    printf("%s\n", file1);
    printf("%s\n", file2);

    FILE *file1 = fopen(file1, "r");
    FILE *file2 = fopen(file2, "r");
}

Note that I made some assumptions about the length of a filename.  Adjust as necessary.


问:
ANTLR v4 : How to implement deactivation of rule alternatives in listener like embedded semantic predicate in grammar file?
I have a java target v4 ANTLR grammar. I want to implement the same functionality of embedded semantic predicate using a listener to free my grammar from language specific embedded actions. The propose is to deactivate an alternate sub rule matching. I know how to write an extend BaseListener and overide that but really do not know how to do this since I am a beginner.

```<code>grammar MyParserGrammar;
@parser::members {
    public static boolean singularSub, pluralSub;
    }
sentence: (subject beVerb)+
            {
            singularSub=false;
            pluralSub=false;
            }
            ;
subject: singularSub {singularSub=true;}|
         pluralSub {pluralSub=true;};
singularSub : 'He';
pluralSub : 'They';
beVerb: {singularSub}? 'is'|
        {pluralSub}? 'are';
 WS: [ \t\r\n]->skip;
</code>```

The exact part I want to sift and very hard for me is:

```<code>beVerb: {singularSub}? 'is'|
        {pluralSub}? 'are';
</code>```

My Listener

```<code>public MyGListener extends MyParserGrammarBaseListener{
        @Override
        public void exitBeVerb(MyParserGrammarParser.BeVerbContext ctx) {

        }
}
</code>```

答:
You could do something like this:

```<code>sentences
 : sentence+ EOF
 ;

sentence
 : subject beVerb
 ;
</code>```

and then override the enterSentence(...) method and inspect the subject and beVerb from it:

class MyGListener extends MyParserGrammarBaseListener {

    @Override
    public void enterSentence(MyParserGrammarParser.SentenceContext ctx) {

        boolean isPluralSubject = ctx.subject().getText().equals("They");
        boolean isPluralVerb = ctx.beVerb().getText().equals("are");

        if (isPluralSubject != isPluralVerb) {
            // throw an exception?
        }
    }
}
```

Note that for parsing real human languages, ANTLR is not a good fit. In such cases, look into using something like Stanford's Natural Language Processing tools: https://nlp.stanford.edu/software

Body:
I have a java target v4 ANTLR grammar. I want to implement the same functionality of embedded semantic predicate using a listener to free my grammar from language specific embedded actions. The propose is to deactivate an alternate sub rule matching. I know how to write an extend BaseListener and overide that but really do not know how to do this since I am a beginner.

grammar MyParserGrammar;
@parser::members {
    public static boolean singularSub, pluralSub;
    }
sentence: (subject beVerb)+
            {
            singularSub=false;
            pluralSub=false;
            }
            ;
subject: singularSub {singularSub=true;}|
         pluralSub {pluralSub=true;};
singularSub : 'He';
pluralSub : 'They';
beVerb: {singularSub}? 'is'|
        {pluralSub}? 'are';
 WS: [ \t\r\n]->skip;

The exact part I want to sift and very hard for me is:

beVerb: {singularSub}? 'is'|
        {pluralSub}? 'are';

My Listener

public MyGListener extends MyParserGrammarBaseListener{
        @Override
        public void exitBeVerb(MyParserGrammarParser.BeVerbContext ctx) {

        }
}

Body:
You could do something like this:

sentences
 : sentence+ EOF
 ;

sentence
 : subject beVerb
 ;

and then override the enterSentence(...) method and inspect the subject and beVerb from it:

class MyGListener extends MyParserGrammarBaseListener {

    @Override
    public void enterSentence(MyParserGrammarParser.SentenceContext ctx) {

        boolean isPluralSubject = ctx.subject().getText().equals("They");
        boolean isPluralVerb = ctx.beVerb().getText().equals("are");

        if (isPluralSubject != isPluralVerb) {
            // throw an exception?
        }
    }
}

Note that for parsing real human languages, ANTLR is not a good fit. In such cases, look into using something like Stanford's Natural Language Processing tools: https://nlp.stanford.edu/software