问:
Problem applying texture to square in OpenGL
I'm stuck at not being able to map texture to a square in openGLES. I'm trying to display a jpg image on the screen, and in order for me to do that, I draw a square that I want to then map image onto. However all I get as an output is a white square. I don't know what am I doing wrong. And this problem is preventing me from moving forward with my project. I'm using Managed OpenGL ES wrapper for Windows Mobile.
I verified that the texture is loading correctly, but I can't apply it to my object. I uploaded sample project that shows my problem here. You would need VS2008 with Windows Mobile 6 SDK to be able to run it. I'm also posting the code of the Form that renders and textures an object here. Any suggestions would be much appreciated, since I've been stuck on this problem for a while, and I can't figure out what am I doing wrong.</p>

```<code>    public partial class Form1 : Form
{
    [DllImport("coredll")]
    extern static IntPtr GetDC(IntPtr hwnd);

    EGLDisplay myDisplay;
    EGLSurface mySurface;
    EGLContext myContext;

    public Form1()
    {
        InitializeComponent();
        myDisplay = egl.GetDisplay(new EGLNativeDisplayType(this));

        int major, minor;
        egl.Initialize(myDisplay, out major, out minor);

        EGLConfig[] configs = new EGLConfig[10];
        int[] attribList = new int[]
        {
            egl.EGL_RED_SIZE, 5,
            egl.EGL_GREEN_SIZE, 6,
            egl.EGL_BLUE_SIZE, 5,
            egl.EGL_DEPTH_SIZE, 16 ,
            egl.EGL_SURFACE_TYPE, egl.EGL_WINDOW_BIT,
            egl.EGL_STENCIL_SIZE, egl.EGL_DONT_CARE,
            egl.EGL_NONE, egl.EGL_NONE
        };

        int numConfig;
        if (!egl.ChooseConfig(myDisplay, attribList, configs, configs.Length, out numConfig) || numConfig < 1)
            throw new InvalidOperationException("Unable to choose config.");

        EGLConfig config = configs[0];
        mySurface = egl.CreateWindowSurface(myDisplay, config, Handle, null);
        myContext = egl.CreateContext(myDisplay, config, EGLContext.None, null);

        egl.MakeCurrent(myDisplay, mySurface, mySurface, myContext);
        gl.ClearColor(0, 0, 0, 0);
        InitGL();
    }

    void InitGL()
    {
        gl.ShadeModel(gl.GL_SMOOTH);
        gl.ClearColor(0.0f, 0.0f, 0.0f, 0.5f);
        gl.BlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA);
        gl.Hint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
    }

    public unsafe void DrawGLScene()
    {
        gl.MatrixMode(gl.GL_PROJECTION);
        gl.LoadIdentity();
        gl.Orthof(0, ClientSize.Width, ClientSize.Height, 0, 0, 1);
        gl.Disable(gl.GL_DEPTH_TEST);

        gl.MatrixMode(gl.GL_MODELVIEW);
        gl.LoadIdentity();

        Texture myImage;
        Bitmap Image = new Bitmap(@"\Storage Card\Texture.jpg");
        using (MemoryStream ms = new MemoryStream())
        {
            Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            myImage = Texture.LoadStream(ms, false);
        }

        float[] rectangle = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        float[] texturePosition = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        //Bind texture
        gl.BindTexture(gl.GL_TEXTURE_2D, myImage.Name);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
        gl.EnableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.EnableClientState(gl.GL_VERTEX_ARRAY);

        //draw square and texture it.
        fixed (float* rectanglePointer = &rectangle[0], positionPointer = &texturePosition[0])
        {
            gl.TexCoordPointer(2, gl.GL_FLOAT, 0, (IntPtr)positionPointer);
            gl.VertexPointer(2, gl.GL_FLOAT, 0, (IntPtr)rectanglePointer);
            gl.DrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4);
        }

        gl.DisableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.DisableClientState(gl.GL_VERTEX_ARRAY);

    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);

        DrawGLScene();
        egl.SwapBuffers(myDisplay, mySurface);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);
    }

    protected override void OnClosing(CancelEventArgs e)
    {
        if (!egl.DestroySurface(myDisplay, mySurface))
            throw new Exception("Error while destroying surface.");
        if (!egl.DestroyContext(myDisplay, myContext))
            throw new Exception("Error while destroying context.");
        if (!egl.Terminate(myDisplay))
            throw new Exception("Error while terminating display.");
        base.OnClosing(e);
    }
}
</code>```

答:
If you work with OpenGL|ES also take a look if the glDrawTexImage-Extension is supported (well - it should, it's a core-extension and required, but you never know...)

It won't help you with your problem directly (e.g. you have to enable texturing as well), but glDrawTexImage is a hell lot more efficient than polygon rendering. And it needs less code to write as well.

OwnerDisplayName: Ilya Volodin

Body:
I'm stuck at not being able to map texture to a square in openGLES. I'm trying to display a jpg image on the screen, and in order for me to do that, I draw a square that I want to then map image onto. However all I get as an output is a white square. I don't know what am I doing wrong. And this problem is preventing me from moving forward with my project. I'm using Managed OpenGL ES wrapper for Windows Mobile.
I verified that the texture is loading correctly, but I can't apply it to my object. I uploaded sample project that shows my problem here. You would need VS2008 with Windows Mobile 6 SDK to be able to run it. I'm also posting the code of the Form that renders and textures an object here. Any suggestions would be much appreciated, since I've been stuck on this problem for a while, and I can't figure out what am I doing wrong.

    public partial class Form1 : Form
{
    [DllImport("coredll")]
    extern static IntPtr GetDC(IntPtr hwnd);

    EGLDisplay myDisplay;
    EGLSurface mySurface;
    EGLContext myContext;

    public Form1()
    {
        InitializeComponent();
        myDisplay = egl.GetDisplay(new EGLNativeDisplayType(this));

        int major, minor;
        egl.Initialize(myDisplay, out major, out minor);

        EGLConfig[] configs = new EGLConfig[10];
        int[] attribList = new int[]
        {
            egl.EGL_RED_SIZE, 5,
            egl.EGL_GREEN_SIZE, 6,
            egl.EGL_BLUE_SIZE, 5,
            egl.EGL_DEPTH_SIZE, 16 ,
            egl.EGL_SURFACE_TYPE, egl.EGL_WINDOW_BIT,
            egl.EGL_STENCIL_SIZE, egl.EGL_DONT_CARE,
            egl.EGL_NONE, egl.EGL_NONE
        };

        int numConfig;
        if (!egl.ChooseConfig(myDisplay, attribList, configs, configs.Length, out numConfig) || numConfig < 1)
            throw new InvalidOperationException("Unable to choose config.");

        EGLConfig config = configs[0];
        mySurface = egl.CreateWindowSurface(myDisplay, config, Handle, null);
        myContext = egl.CreateContext(myDisplay, config, EGLContext.None, null);

        egl.MakeCurrent(myDisplay, mySurface, mySurface, myContext);
        gl.ClearColor(0, 0, 0, 0);
        InitGL();
    }

    void InitGL()
    {
        gl.ShadeModel(gl.GL_SMOOTH);
        gl.ClearColor(0.0f, 0.0f, 0.0f, 0.5f);
        gl.BlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA);
        gl.Hint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
    }

    public unsafe void DrawGLScene()
    {
        gl.MatrixMode(gl.GL_PROJECTION);
        gl.LoadIdentity();
        gl.Orthof(0, ClientSize.Width, ClientSize.Height, 0, 0, 1);
        gl.Disable(gl.GL_DEPTH_TEST);

        gl.MatrixMode(gl.GL_MODELVIEW);
        gl.LoadIdentity();

        Texture myImage;
        Bitmap Image = new Bitmap(@"\Storage Card\Texture.jpg");
        using (MemoryStream ms = new MemoryStream())
        {
            Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            myImage = Texture.LoadStream(ms, false);
        }

        float[] rectangle = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        float[] texturePosition = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        //Bind texture
        gl.BindTexture(gl.GL_TEXTURE_2D, myImage.Name);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
        gl.EnableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.EnableClientState(gl.GL_VERTEX_ARRAY);

        //draw square and texture it.
        fixed (float* rectanglePointer = &rectangle[0], positionPointer = &texturePosition[0])
        {
            gl.TexCoordPointer(2, gl.GL_FLOAT, 0, (IntPtr)positionPointer);
            gl.VertexPointer(2, gl.GL_FLOAT, 0, (IntPtr)rectanglePointer);
            gl.DrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4);
        }

        gl.DisableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.DisableClientState(gl.GL_VERTEX_ARRAY);

    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);

        DrawGLScene();
        egl.SwapBuffers(myDisplay, mySurface);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);
    }

    protected override void OnClosing(CancelEventArgs e)
    {
        if (!egl.DestroySurface(myDisplay, mySurface))
            throw new Exception("Error while destroying surface.");
        if (!egl.DestroyContext(myDisplay, myContext))
            throw new Exception("Error while destroying context.");
        if (!egl.Terminate(myDisplay))
            throw new Exception("Error while terminating display.");
        base.OnClosing(e);
    }
}

LastEditorDisplayName: aib

OwnerDisplayName: Nils


来源: stackexchange

问:
Rails 3 - link_to to call partial using jquery ajax
I am trying to get a link_to to display a partial via jquery ajax, but can't seem to get it to work (edit: returning blank screen) and I'm not sure what I'm missing. Any help would be appreciated.

I would like to click the link "Preview Widget" and have it display _widget.html.erb in the div preview.

From my understanding the link "Preview Widget" should call the action def preview_widget which calls preview_widget.js.erb which then renders the partial _widget.html.erb in the div.

EDIT: updates link as per Ignatius Reza suggestions

show.html.erb

```<code><%= link_to "Preview Widget", :action => 'preview_widget' , :id => @widget.id, :remote => true %> %>
<div id="preview"></div>
</code>```

widget_controller.rb

```<code>def preview_widget
    respond_to do | format |
        format.js {render :layout => false}
    end
end
</code>```

preview_widget.js.erb

```<code>$( "#preview" ).html( "<%= escape_javascript( render( :partial => "widget", :locals => { :widget => @widget} ) ) %>" );
</code>```

_widget.html.erb

```<code><% @widget.videos.each do |video| %>
      <h3><a href='#'><%= video.name %></a></h3>
      <div>
        <object height='316' width='540'>
          <embed  style='border: 1px solid #333333;' height='316' width='540' allowfullscreen='true' allowscriptaccess='always' type='application/x-shockwave-flash' src='<%= video.url %>'>
        </object>
      </div>
  <% end %>
</code>```

routes.rb

```<code>match 'preview_widget' => 'widgets#preview_widget'
</code>```

答:
It's not cleared on your question, what you "can't seem to get it to work".. but from what i see in the code you gave.. all seems right, but you miss the actual ajax call..

it could be added by adding :remote => true to the "Preview Widget" link such as :

```<code><%= link_to "Preview Widget", :action => 'preview_widget' , :id => @widget, :remote => true %>
</code>```

if the default behaviour is enough.. or you could add your own custom ajax call on application.js..

as a note, i don't think setting the :id attribute of "Preview Widget" link to @widget is wise.. as it will put the string representation of widget, which usually will looks like "<Widget:0x12412 ..>" perhaps it would be better to change it to "widget-link-#{@widget.id}"

ContentLicense: CC BY-SA 2.5

Body:
I am trying to get a link_to to display a partial via jquery ajax, but can't seem to get it to work (edit: returning blank screen) and I'm not sure what I'm missing. Any help would be appreciated.

I would like to click the link "Preview Widget" and have it display _widget.html.erb in the div preview.

From my understanding the link "Preview Widget" should call the action def preview_widget which calls preview_widget.js.erb which then renders the partial _widget.html.erb in the div.

EDIT: updates link as per Ignatius Reza suggestions

show.html.erb

<%= link_to "Preview Widget", :action => 'preview_widget' , :id => @widget.id, :remote => true %> %>

widget_controller.rb

def preview_widget
    respond_to do | format |
        format.js {render :layout => false}
    end
end

preview_widget.js.erb

$( "#preview" ).html( "<%= escape_javascript( render( :partial => "widget", :locals => { :widget => @widget} ) ) %>" );

_widget.html.erb

<% @widget.videos.each do |video| %>

<%= video.name %>

        <object height='316' width='540'>
          <embed  style='border: 1px solid #333333;' height='316' width='540' allowfullscreen='true' allowscriptaccess='always' type='application/x-shockwave-flash' src='<%= video.url %>'>
        </object>

  <% end %>

routes.rb

match 'preview_widget' => 'widgets#preview_widget'

Body:
It's not cleared on your question, what you "can't seem to get it to work".. but from what i see in the code you gave.. all seems right, but you miss the actual ajax call..

it could be added by adding :remote => true to the "Preview Widget" link such as :

<%= link_to "Preview Widget", :action => 'preview_widget' , :id => @widget, :remote => true %>

if the default behaviour is enough.. or you could add your own custom ajax call on application.js..

as a note, i don't think setting the :id attribute of "Preview Widget" link to @widget is wise.. as it will put the string representation of widget, which usually will looks like "<Widget:0x12412 ..>" perhaps it would be better to change it to "widget-link-#{@widget.id}"


问:
Send PDF to google API via axios on server(NodeJs)
I have problems trying to send a PDF to Google API via Axios.

Code I tried:

const express = require('express');
const axios = require('axios');
const router = express.Router();
const PDFDocument = require('pdfkit');

const ticketProperties = {
  'version': '1.0',
  'print': {}
};

router.post('/print/sale', async (req, res) => {

    // Generate test PDF
    let doc = new PDFDocument;
    doc.pipe(fs.createWriteStream('output.pdf'));
    doc.fontSize(8)
      .text('Some text example for pdf', 1, 1);
    doc.end();

    // Once the pdf is generated, read it and send it via axios
    axios.post(
      'https://www.google.com/cloudprint/submit',
      {
        printerid : 'PRINTER_ID_REMOVED_INTENTIONALLY',
        title: 'pdf print',
        ticket: ticketProperties,
        content : doc,
        contentType: 'application/pdf'
      },
      {
        headers: {
        'Authorization': 'Bearer ACCESS_TOKEN_REMOVED_INTENTIONALLY',
        'Content-Type': 'application/pdf'
        }
      }
    )
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });

});
```

The error I got in console.log(error) when I call that API:

TypeError: Converting circular structure to JSON
      at JSON.stringify ()
      at transformRequest (G:\projects\pos-web\pos-backend\node_modules\axios\lib\defaults.js:51:19)
      at transform (G:\projects\pos-web\pos-backend\node_modules\axios\lib\core\transformData.js:16:12)
      at Object.forEach (G:\projects\pos-web\pos-backend\node_modules\axios\lib\utils.js:224:12)
      at transformData (G:\projects\pos-web\pos-backend\node_modules\axios\lib\core\transformData.js:15:9)
      at dispatchRequest (G:\projects\pos-web\pos-backend\node_modules\axios\lib\core\dispatchRequest.js:37:17)
      at

I think that error is because I'm writing the file doc inside the body of post. Do I need to process it before?

Notes:

The pdf is generated successfully inside of my project.

My first test was sending a text instead of pdf and was OK.

I've tried a lot of possible solutions, but give me different errors, maybe I'm understanding wrong how to send a pdf from the server.
Please If you have another library instead of axios or you know the flow of how to send a pdf from the server, don't hesitate in write it, I'll take it as a good answer.

More information:

about endpoint https://www.google.com/cloudprint/submit : Link

答:
Ok, I solved my problem, the error was because ticketProperties need to be as string: JSON.stringify(ticketProperties), because it is an object.

Despite I solved this problem, I had others problems with Axios package and I decided change axios by request package to make my request API and It worked. This solution helped me: Stackoverflow link

code:

var formData = {
  printerid : 'PRINTER_ID_REMOVED_INTENTIONALLY',
  title: 'pdf print',
  ticket: JSON.stringify(ticketProperties),
  content: fs.createReadStream('output.pdf'),
  contentType: 'application/pdf'
};

request.post(
  {
    url:'https://www.google.com/cloudprint/submit',
    formData: formData,
    headers: {
      'Authorization': 'Bearer ACCESS_TOKEN_REMOVED_INTENTIONALLY'
    }
  },
  function optionalCallback(err, httpResponse, body) {
    if (err) {
      console.error('upload failed:', err);
    } else {
      console.log('Upload successful!  Server responded with:', body);
    }
  }
);
```

But After It worked, I had more problems with pdf:

I need to wait that pdf will be generated with async function doc.end() before calling to fs.createReadStream('output.pdf'), otherwise I'll have the error could not convert to pdf

Great upper margin in printing, impossible to reduce it.

After spending hours trying to solve this, I read that is possible send HTML data and I think that is better because it consumes fewer resources and solves the problems described.

Only I changed:

content: '<MY_STRING_HTML>'

contentType: 'text/html'

ContentLicense: CC BY-SA 3.0

Body:
I have problems trying to send a PDF to Google API via Axios.

Code I tried:

const express = require('express');
const axios = require('axios');
const router = express.Router();
const PDFDocument = require('pdfkit');

const ticketProperties = {
  'version': '1.0',
  'print': {}
};

router.post('/print/sale', async (req, res) => {

    // Generate test PDF
    let doc = new PDFDocument;
    doc.pipe(fs.createWriteStream('output.pdf'));
    doc.fontSize(8)
      .text('Some text example for pdf', 1, 1);
    doc.end();

    // Once the pdf is generated, read it and send it via axios
    axios.post(
      'https://www.google.com/cloudprint/submit',
      {
        printerid : 'PRINTER_ID_REMOVED_INTENTIONALLY',
        title: 'pdf print',
        ticket: ticketProperties,
        content : doc,
        contentType: 'application/pdf'
      },
      {
        headers: {
        'Authorization': 'Bearer ACCESS_TOKEN_REMOVED_INTENTIONALLY',
        'Content-Type': 'application/pdf'
        }
      }
    )
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });

});

The error I got in console.log(error) when I call that API:

TypeError: Converting circular structure to JSON
      at JSON.stringify ()
      at transformRequest (G:\projects\pos-web\pos-backend\node_modules\axios\lib\defaults.js:51:19)
      at transform (G:\projects\pos-web\pos-backend\node_modules\axios\lib\core\transformData.js:16:12)
      at Object.forEach (G:\projects\pos-web\pos-backend\node_modules\axios\lib\utils.js:224:12)
      at transformData (G:\projects\pos-web\pos-backend\node_modules\axios\lib\core\transformData.js:15:9)
      at dispatchRequest (G:\projects\pos-web\pos-backend\node_modules\axios\lib\core\dispatchRequest.js:37:17)
      at

I think that error is because I'm writing the file doc inside the body of post. Do I need to process it before?

Notes:

The pdf is generated successfully inside of my project.

My first test was sending a text instead of pdf and was OK.

I've tried a lot of possible solutions, but give me different errors, maybe I'm understanding wrong how to send a pdf from the server.
Please If you have another library instead of axios or you know the flow of how to send a pdf from the server, don't hesitate in write it, I'll take it as a good answer.

More information:

about endpoint https://www.google.com/cloudprint/submit : Link

Body:
Ok, I solved my problem, the error was because ticketProperties need to be as string: JSON.stringify(ticketProperties), because it is an object.

Despite I solved this problem, I had others problems with Axios package and I decided change axios by request package to make my request API and It worked. This solution helped me: Stackoverflow link

code:

var formData = {
  printerid : 'PRINTER_ID_REMOVED_INTENTIONALLY',
  title: 'pdf print',
  ticket: JSON.stringify(ticketProperties),
  content: fs.createReadStream('output.pdf'),
  contentType: 'application/pdf'
};

request.post(
  {
    url:'https://www.google.com/cloudprint/submit',
    formData: formData,
    headers: {
      'Authorization': 'Bearer ACCESS_TOKEN_REMOVED_INTENTIONALLY'
    }
  },
  function optionalCallback(err, httpResponse, body) {
    if (err) {
      console.error('upload failed:', err);
    } else {
      console.log('Upload successful!  Server responded with:', body);
    }
  }
);

But After It worked, I had more problems with pdf:

I need to wait that pdf will be generated with async function doc.end() before calling to fs.createReadStream('output.pdf'), otherwise I'll have the error could not convert to pdf

Great upper margin in printing, impossible to reduce it.

After spending hours trying to solve this, I read that is possible send HTML data and I think that is better because it consumes fewer resources and solves the problems described.

Only I changed:

content: '<MY_STRING_HTML>'

contentType: 'text/html'


问:
Error when installing Pygame (1.9.3) on Windows
This question has been asked a lot around the Internet but until now I haven't found someone who's getting the same error as I am (maybe I'm not looking hard enough, who knows).

I'm using a Windows 10 64-bit Acer laptop (I don't know any other specs, it isn't mine) and trying to install pygame‑1.9.3‑cp36‑cp36m‑win32.whl (I've been told it's better to get the 32-bit versions of both Python and Pygame). I receive this error when I go into PowerShell:

```<code>PS C:\Program Files (x86)\Python36-32\Scripts> pip3 install pygame-1.9.3-cp36-cp36m-win32.whl
Processing c:\program files (x86)\python36-32\scripts\pygame-1.9.3-cp36-cp36m-win32.whl
Installing collected packages: pygame
Exception:
Traceback (most recent call last):
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "c:\program files (x86)\python36-32\lib\os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\Lib\\site-packages\\pygame'
</code>```

Not too sure what's going on. If anyone does, thanks so much in advance.

答:
In your case it seems like a permission issue so try to run it as admin. In case it doesn't work this is my advise:

I have always had issues installing python libs in windows until I found this repo, it has never let me down. I have installed pygame from here like 20 times and always works. Try it and let me know:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

Body:
This question has been asked a lot around the Internet but until now I haven't found someone who's getting the same error as I am (maybe I'm not looking hard enough, who knows).

I'm using a Windows 10 64-bit Acer laptop (I don't know any other specs, it isn't mine) and trying to install pygame‑1.9.3‑cp36‑cp36m‑win32.whl (I've been told it's better to get the 32-bit versions of both Python and Pygame). I receive this error when I go into PowerShell:

PS C:\Program Files (x86)\Python36-32\Scripts> pip3 install pygame-1.9.3-cp36-cp36m-win32.whl
Processing c:\program files (x86)\python36-32\scripts\pygame-1.9.3-cp36-cp36m-win32.whl
Installing collected packages: pygame
Exception:
Traceback (most recent call last):
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "c:\program files (x86)\python36-32\lib\os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\Lib\\site-packages\\pygame'

Not too sure what's going on. If anyone does, thanks so much in advance.


问:
Abstract class as attribute in Interface which will be overwritten to child class
Given that Bean is an abstract class and Venue class extends Bean. ControllerInterface is an interface and VenueController implements this interface.

interface

```<code>public interface ControllerInterface {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List getAll();

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Bean getOneById(@PathVariable(value = "id", required = true) String id);

    @RequestMapping(value = "/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public @ResponseBody Bean updateOne(@PathVariable("id") String id,Bean beanData);

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String addOne();
}
</code>```

normal class

```<code>public class VenueController implements ControllerInterface{

    @Autowired
    VenueDAO venueDAO;

    @Override
    public List<Venue> getAll() {
        return venueDAO.findAll();
    }

    @Override
    public Bean getOneById(@PathVariable(value = "id", required = true) String id) {
        return venueDAO.findBy(id);
    }

    @Override
    public String addOne() {
        // TODO : add a new venue and return its id
        return null;
    }

    @Override
    @RequestMapping(value = "/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public @ResponseBody Bean updateOne(@PathVariable("id") String id, Bean data) {
        Venue venueData = (Venue) data;
        Venue venue = venueDAO.findBy(id);
        Util.copyNonNullProperties(venueData, venue);
        venueDAO.update(venue);
        return null;
    }

}
</code>```

obviously this code will lead to InstantiationException in public @ResponseBody Bean updateOne(@PathVariable("id") String id, Bean data)
because the Bean is an abstract class and no way to initialise it.

So my question is how to make this possible ?
I thought of changing Bean data to Venue data but it's not working since this changes the method signature and wont be overwritten then.

Any idea ?

答:
Just some advice be careful with your annotated methods being inherited, I have found many times that my annotations did not carry through and these errors become very difficult to trace.

You will need to use generics ControllerInterface<SOME extends Bean>, and then use SOME instead of Bean.

Regards

Body:
Given that Bean is an abstract class and Venue class extends Bean. ControllerInterface is an interface and VenueController implements this interface.

interface

public interface ControllerInterface {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List getAll();

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Bean getOneById(@PathVariable(value = "id", required = true) String id);

    @RequestMapping(value = "/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public @ResponseBody Bean updateOne(@PathVariable("id") String id,Bean beanData);

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String addOne();
}

normal class

public class VenueController implements ControllerInterface{

    @Autowired
    VenueDAO venueDAO;

    @Override
    public List<Venue> getAll() {
        return venueDAO.findAll();
    }

    @Override
    public Bean getOneById(@PathVariable(value = "id", required = true) String id) {
        return venueDAO.findBy(id);
    }

    @Override
    public String addOne() {
        // TODO : add a new venue and return its id
        return null;
    }

    @Override
    @RequestMapping(value = "/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public @ResponseBody Bean updateOne(@PathVariable("id") String id, Bean data) {
        Venue venueData = (Venue) data;
        Venue venue = venueDAO.findBy(id);
        Util.copyNonNullProperties(venueData, venue);
        venueDAO.update(venue);
        return null;
    }

}

obviously this code will lead to InstantiationException in public @ResponseBody Bean updateOne(@PathVariable("id") String id, Bean data)
because the Bean is an abstract class and no way to initialise it.

So my question is how to make this possible ?
I thought of changing Bean data to Venue data but it's not working since this changes the method signature and wont be overwritten then.

Any idea ?


问:
How to automate moving data from one google sheet to another
I am trying to send values from Google sheets to Firebase so that the data table updates automatically. To do this I used Google Drive CMS which exported the data to Firebase perfectly. The problem is that I scrape data off of websites. For example, I get a list of data through the use of importXML:

```<code>=IMPORTXML("https://www.congress.gov/search?q=%7B%22source%22%3A%22legislation%22%7D", "//li[@class='expanded']/span[@class='result-heading']/a[1]")
</code>```

CMS doesn't seem to get the values that this formula results in but the actual formula which causes errors. The way I adressed this is to make a new tab that has the formulas and keep the CMS tab with the value only. I've been copying and pasting this manually but want to make that process automatic. I cannot find any help to make a script that takes the values of the formulas from one tab and place those values in a different sheet.

Here are some pictures for reference:

*I put the blue highlight on the cell I am referring to for the google sheets and the data from the firebase is showing the first row of data that was exported.

答:
How about this sample script? Please think of this as one of several answers. The flow of this script is as follows. When you use this script, please copy and paste it and run sample().

Flow :

Input a source range of active sheet.

Retrieve the source range.

Input a destination range of a destination spreadsheet.

Retrieve the destination range of the destination sheet.

Copy data from the source range to the destination range.

Data which included values, formulas and formats is copied.

Sample script :

```<code>function sample() {
  // Source
  var range = "a1:b5"; // Source range
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcrange = ss.getActiveSheet().getRange(range);

  // Destination
  var range = "c1:d5"; // Destination range,
  var dstid = "### file id ###"; // Destination spreadsheet ID
  var dst = "### sheet name ###"; // Destination sheet name
  var dstrange = SpreadsheetApp.openById(dstid).getSheetByName(dst).getRange(range);

  var dstSS = dstrange.getSheet().getParent();
  var copiedsheet = srcrange.getSheet().copyTo(dstSS);
  copiedsheet.getRange(srcrange.getA1Notation()).copyTo(dstrange);
  dstSS.deleteSheet(copiedsheet);
}
</code>```

If I misunderstand your question, I'm sorry.

Edit :

This sample script copies from values of source spreadsheet to destination spreadsheet.

```<code>function sample() {
  // Source
  var range = "a1:b5"; // Source range
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcrange = ss.getActiveSheet().getRange(range);

  // Destination
  var range = "c1:d5"; // Destination range,
  var dstid = "### file id ###"; // Destination spreadsheet ID
  var dst = "### sheet name ###"; // Destination sheet name
  var dstrange = SpreadsheetApp.openById(dstid).getSheetByName(dst).getRange(range);

  var dstSS = dstrange.getSheet().getParent();
  var sourceValues = srcrange.getValues();
  dstrange.setValues(sourceValues);
}
</code>```

Body:
I am trying to send values from Google sheets to Firebase so that the data table updates automatically. To do this I used Google Drive CMS which exported the data to Firebase perfectly. The problem is that I scrape data off of websites. For example, I get a list of data through the use of importXML:

=IMPORTXML("https://www.congress.gov/search?q=%7B%22source%22%3A%22legislation%22%7D", "//li[@class='expanded']/span[@class='result-heading']/a[1]")

CMS doesn't seem to get the values that this formula results in but the actual formula which causes errors. The way I adressed this is to make a new tab that has the formulas and keep the CMS tab with the value only. I've been copying and pasting this manually but want to make that process automatic. I cannot find any help to make a script that takes the values of the formulas from one tab and place those values in a different sheet.

Here are some pictures for reference:

*I put the blue highlight on the cell I am referring to for the google sheets and the data from the firebase is showing the first row of data that was exported.

Body:
How about this sample script? Please think of this as one of several answers. The flow of this script is as follows. When you use this script, please copy and paste it and run sample().

Flow :

Input a source range of active sheet.

Retrieve the source range.

Input a destination range of a destination spreadsheet.

Retrieve the destination range of the destination sheet.

Copy data from the source range to the destination range.

Data which included values, formulas and formats is copied.

Sample script :

function sample() {
  // Source
  var range = "a1:b5"; // Source range
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcrange = ss.getActiveSheet().getRange(range);

  // Destination
  var range = "c1:d5"; // Destination range,
  var dstid = "### file id ###"; // Destination spreadsheet ID
  var dst = "### sheet name ###"; // Destination sheet name
  var dstrange = SpreadsheetApp.openById(dstid).getSheetByName(dst).getRange(range);

  var dstSS = dstrange.getSheet().getParent();
  var copiedsheet = srcrange.getSheet().copyTo(dstSS);
  copiedsheet.getRange(srcrange.getA1Notation()).copyTo(dstrange);
  dstSS.deleteSheet(copiedsheet);
}

If I misunderstand your question, I'm sorry.

Edit :

This sample script copies from values of source spreadsheet to destination spreadsheet.

function sample() {
  // Source
  var range = "a1:b5"; // Source range
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcrange = ss.getActiveSheet().getRange(range);

  // Destination
  var range = "c1:d5"; // Destination range,
  var dstid = "### file id ###"; // Destination spreadsheet ID
  var dst = "### sheet name ###"; // Destination sheet name
  var dstrange = SpreadsheetApp.openById(dstid).getSheetByName(dst).getRange(range);

  var dstSS = dstrange.getSheet().getParent();
  var sourceValues = srcrange.getValues();
  dstrange.setValues(sourceValues);
}


问:
How can I disable this pop-up that appears during hover in the Visual Studio editor?
I've already turned off many options in Visual Studio 2017, but I can't suppress this annoying pop-up.  (Not this specific one, but all of them, for all the API's)

Can someone please show me the setting I need?

答:
Check this old post How do I turn off code tooltips in Visual Studio 2010. In it a workaround is provided but you will probably make a new extension from the source for it to work in Visual Studio 2017.
Looks like there is no setting for this except for the C/C++ language.</p>


问:
Parsing #regions within Code Files
I'm trying to create a C# program that extracts the code contained within #region tags in *.cs files.  I more or less just want to be able to anotate the code I'm working on and have it be accessible to this other program as just text.

Is there something that already exists that accomplishes this?

Say I have code like this:

```<code>#region ClassName.Test()
public static void Test()
{
     //Some method that does stuff
}
#endregion
</code>```

I'd like to be able to extract

```<code>public static void Test()
{
     //Some method that does stuff
}
</code>```

from the *.cs as a string when I specify that I'm looking for Class.Test().

答:
If you don't mind potential troublesome issues then you can simply open the file and search for the keywords you are looking for.

The problem comes from that fact that strings may contain the information you are looking for but are not meant to be searched. You can attempt to ignore strings but this can get a little complicated because of all the ways " is used (\", "", etc...).

If you can safely ignore strings in C# then simply open the text file, search line by line what you are looking for(string.Find).

If your looking to do it right then using CodeDOM is the way to go!

Title: Parsing #regions within Code Files

Body:
I'm trying to create a C# program that extracts the code contained within #region tags in *.cs files.  I more or less just want to be able to anotate the code I'm working on and have it be accessible to this other program as just text.

Is there something that already exists that accomplishes this?

Say I have code like this:

#region ClassName.Test()
public static void Test()
{
     //Some method that does stuff
}
#endregion

I'd like to be able to extract

public static void Test()
{
     //Some method that does stuff
}

from the *.cs as a string when I specify that I'm looking for Class.Test().


问:
JSON parsing - Memory Dependent?
I'm trying to pass very large arrays to JavaScipt to be manipulated client-side, and it's not working. These arrays typically have about 12,000 elements each, and this snippet of code is functioning correctly when I only plug in 2,000 elements.

```<code>    <script type="text/javascript">

        var getLenders = JSON.parse('<?php echo json_encode($getlenders); ?>');
        var discountArray = JSON.parse('<?php echo json_encode($discountArray); ?>');
        var getData = JSON.parse('<?php echo json_encode($sortedArray); ?>');

    </script>
</code>```

I increased the memory requirements of the server to 512MB (4 time as much as before) thinking that'd be more than enough, however it is still not working. Before I crank up the memory to 1024MB, I would like to know if there is any other reason this is not working. Could it be an issue with client-side memory?

Any input is appreciated.

答:
Don't.

Handling such a big amount of elements is not profitable. It's bad for your server, which generates somehow the array, and it's bad for your clients that have to deal with the huge amount, and sincerely, I dont think the client need to display all that data in a single run. Why you don't think about an ajax implementation which load the data only when it needs?

Title: JSON parsing - Memory Dependent?

Body:
I'm trying to pass very large arrays to JavaScipt to be manipulated client-side, and it's not working. These arrays typically have about 12,000 elements each, and this snippet of code is functioning correctly when I only plug in 2,000 elements.

I increased the memory requirements of the server to 512MB (4 time as much as before) thinking that'd be more than enough, however it is still not working. Before I crank up the memory to 1024MB, I would like to know if there is any other reason this is not working. Could it be an issue with client-side memory?

Any input is appreciated.


问:
Too many values to unpack (expected 4)
I have this piece of basic code just trying to split a file into 4 lists. The .txt file is formatted as shown underneath the code, with spaces delimiting each number. The error appearing is 'ValueError: too many values to unpack (expected 4)'.

```<code>file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y= line.split(' ')

#v  a  t  y
-0.10 -9.81 0.01 5500.00
-0.20 -9.81 0.02 5500.00
-0.29 -9.81 0.03 5500.00
-0.39 -9.81 0.04 5499.99
-0.49 -9.81 0.05 5499.99
-0.59 -9.81 0.06 5499.99
-0.69 -9.81 0.07 5499.98
-0.78 -9.81 0.08 5499.97
...
</code>```

However I changed the code to be as shown below to test how many variables it was expecting, and the error changed to 'not enough values to unpack (expected 5, got 4)'. This doesn't make sense as now the code is unpacking the four variables I wanted! Any solutions/pointers would be much appreciated.

```<code>file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y,test= line.split(' ')
</code>```

答:
As commenters have suggested, try printing the line to see the line that's actually causing a problem (but be sure to insert the print before the line.split).

The most likely problem is a blank line at the end, which is read as a newline character. If so the easiest solution is probably to tack on another condition to the if statement:

```<code>file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#') and line != '\n':
     # or, more robust:
     if not line.startswith('#') and len(line) == 4:
         v,a,t,y= line.split(' ')
</code>```

Or with a try/except:

```<code>file = open("myfreefall.txt","r")
for line in file:
    try:
       v,a,t,y= line.split(' ')
    except ValueError:
       continue
       # Skip over this line if the extraction fails
</code>```

The second if-statement is more robust because it will only try to extract your four variables if there are exactly four list entries to work with. Any other case (more or fewer entries to extract from) will be ignored. You can tailor it a bit more to your needs, e.g. by changing it to 'len(line) >= 4' if you wanted to allow longer lines to be read as well.

To be honest, I can't think of a particular advantage for the try/except variant, but since I just wrote it out I might as well leave it in. It might be a bit too robust, in fact, because it would also skip lines that cause ValueErrors for reasons other than there being too few entries to work with.

Your second attempt failing as you describe makes perfect sense.
You're telling python to split a list of four entries into five variables, v, a, t, y and test. That's what the error is referring to when it says, 'expected 5, got 4'. The behaviour of your error probably changed because the code fails a lot sooner now. Before it was working for all lines except the last one, where there's only one list entry to use. With your change to five variables it's causing an error with the very first line, where there are four entries but now you're asking for five.

Title: Too many values to unpack (expected 4)

Body:
I have this piece of basic code just trying to split a file into 4 lists. The .txt file is formatted as shown underneath the code, with spaces delimiting each number. The error appearing is 'ValueError: too many values to unpack (expected 4)'.

file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y= line.split(' ')

#v  a  t  y
-0.10 -9.81 0.01 5500.00
-0.20 -9.81 0.02 5500.00
-0.29 -9.81 0.03 5500.00
-0.39 -9.81 0.04 5499.99
-0.49 -9.81 0.05 5499.99
-0.59 -9.81 0.06 5499.99
-0.69 -9.81 0.07 5499.98
-0.78 -9.81 0.08 5499.97
...

However I changed the code to be as shown below to test how many variables it was expecting, and the error changed to 'not enough values to unpack (expected 5, got 4)'. This doesn't make sense as now the code is unpacking the four variables I wanted! Any solutions/pointers would be much appreciated.

file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y,test= line.split(' ')

Body:
As commenters have suggested, try printing the line to see the line that's actually causing a problem (but be sure to insert the print before the line.split).

The most likely problem is a blank line at the end, which is read as a newline character. If so the easiest solution is probably to tack on another condition to the if statement:

file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#') and line != '\n':
     # or, more robust:
     if not line.startswith('#') and len(line) == 4:
         v,a,t,y= line.split(' ')

Or with a try/except:

file = open("myfreefall.txt","r")
for line in file:
    try:
       v,a,t,y= line.split(' ')
    except ValueError:
       continue
       # Skip over this line if the extraction fails

The second if-statement is more robust because it will only try to extract your four variables if there are exactly four list entries to work with. Any other case (more or fewer entries to extract from) will be ignored. You can tailor it a bit more to your needs, e.g. by changing it to 'len(line) >= 4' if you wanted to allow longer lines to be read as well.

To be honest, I can't think of a particular advantage for the try/except variant, but since I just wrote it out I might as well leave it in. It might be a bit too robust, in fact, because it would also skip lines that cause ValueErrors for reasons other than there being too few entries to work with.

Your second attempt failing as you describe makes perfect sense.
You're telling python to split a list of four entries into five variables, v, a, t, y and test. That's what the error is referring to when it says, 'expected 5, got 4'. The behaviour of your error probably changed because the code fails a lot sooner now. Before it was working for all lines except the last one, where there's only one list entry to use. With your change to five variables it's causing an error with the very first line, where there are four entries but now you're asking for five.


问:
Media query min-width not considering devices below a certain width
Why is some devices NOT listening to my media query when the device width is smaller than "375" which is my smallest breakpoint. I use @media (min-width: 375px) { // Rules here }... I get that it "requires" that the device has to be at least "375px" wide, but I can't figure out what's wrong here. It works when I change the 375-breakpoint to 0px... But is that even a correct approach?

In my "media.scss" file, I've it all set up like this:

```<code>@media (min-width: 375px) {}
@media (min-width: 768px) {}
@media (min-width: 992px) {}
@media (min-width: 1280px) {}
</code>```

Everything works fine, but when testing on a device that is smaller than 375 pixels, it doesn't consider the rules. I hope you get what I mean. I've looked how bootstrap has their media queries, and I can't really tell if there is any difference.

答:
No matter if you use the mobile-first or desktop-first approach, you need some styles that apply when none of the media queries apply. In your example, there are no styles which apply for widths below 375px. Most likely it would be okay if you simply take the CSS rules you have inside the first query (<375) out of that query and put it at the very beginning of the stylesheet.

Or said differenty: Just erase the @media (min-width: 375px) { at the beginning and its closing } bracket, then those styles will apply to all widths below 768px  (also to those narrower than 375px)

Body:
Why is some devices NOT listening to my media query when the device width is smaller than "375" which is my smallest breakpoint. I use @media (min-width: 375px) { // Rules here }... I get that it "requires" that the device has to be at least "375px" wide, but I can't figure out what's wrong here. It works when I change the 375-breakpoint to 0px... But is that even a correct approach?

In my "media.scss" file, I've it all set up like this:

@media (min-width: 375px) {}
@media (min-width: 768px) {}
@media (min-width: 992px) {}
@media (min-width: 1280px) {}

Everything works fine, but when testing on a device that is smaller than 375 pixels, it doesn't consider the rules. I hope you get what I mean. I've looked how bootstrap has their media queries, and I can't really tell if there is any difference.


问:
Why does my hand created deb package fails at install with "unable to create" on files?
I made a perl script that creates a deb binary package from scratch.
I created the data, control, etc.
But when I run dpkg -i on my deb package it complains that it is unable to files from data.
Example:
unable to create '.dpkg-new'(while processing ''): No such file or directory.

I have downloaded some .deb packages to look at and they do not use the preinst script to create the directory structure.

I am thinking I am doing something wrong, I consider having to create my own directories in preinst but it does not seem right... perhaps I am missing something?

Do I have to create directories where my files from data will be copied in the preinst sh, or should dpkg do it and I am doing something wrong?

答:
You should not attempt to manually create a .deb binary package by hand. The Debian New Maintainers' Guide covers how to get started creating a Debian package using the correct tools.

Your hand created package may look correct to you but because it is not installing it is obviously flawed in either a minor way that you have not noticed or in a more serious way that is not visible to you (for example most people don't realize a .deb is actually an ar archive).


问:
What's a RegEx to match any numeric OR question mark?
I'm using this Regular Expression "\d+" to match any numeric (0-9)
in my code, but how can I alter it to also include question marks?

For example, I want 04/??/1992 to return 04??1992, and I want -123?6 to return 123?6, and I want just 123 to return 123. Basically, I want to match any number (0-9) and question marks only.

Any help would be greatly appreciated! Thank you.

答: This should cover your needs: string result = Regex.Replace(input, @"[^\d?]", "");.


问:
Having issues with simple VB script
I am having issues running the following VB script to create a new directory in my SSIS package. It should create the following new path D:\customers\documents\orders\20171205.

Public Sub Main()
    'set dir path
    Dts.Variables("var_DirPath").Value =
        "D:\customers\documents\orders\" + Date.Today.Year.ToString +
        Date.Today.Month.ToString + Date.Today.Day.ToString
    Dts.TaskResult = ScriptResults.Success
End Sub
```

<p>The ReadWriteVariables of the script task editor is configured to User:var_DirPath. The value of the variable is “D:\customers\documents\orders\" </p>

<p>The file task is configured for</p>

```UseDirector/Exists = True
Operation = Create directory
IsSourcePathAvailable = True
Source variable = User:var_DirPath
```

It resolves in the package during debugging, but I do not know why this simple script does not work.

Any assistance is appreciated.

答:
I'm not sure why you wouldn't see any date subfolder but that code has other issues.  For instance, January 11 and November 1 would produce the same folder name for the same year.  Try this:

```<code>Dts.Variables("var_DirPath").Value = String.Format("D:\customers\documents\orders\{0:yyyyMMdd}", Date.Now)
</code>```

That is better than concatenation and the format ensures unique folder names for all dates.

Title: Having issues with simple VB script

Body:
I am having issues running the following VB script to create a new directory in my SSIS package. It should create the following new path D:\customers\documents\orders\20171205.

Public Sub Main()
    'set dir path
    Dts.Variables("var_DirPath").Value =
        "D:\customers\documents\orders\" + Date.Today.Year.ToString +
        Date.Today.Month.ToString + Date.Today.Day.ToString
    Dts.TaskResult = ScriptResults.Success
End Sub

The ReadWriteVariables of the script task editor is configured to User:var_DirPath. The value of the variable is “D:\customers\documents\orders\"

The file task is configured for

UseDirector/Exists = True
Operation = Create directory
IsSourcePathAvailable = True
Source variable = User:var_DirPath

It resolves in the package during debugging, but I do not know why this simple script does not work.

Any assistance is appreciated.

Body:
I'm not sure why you wouldn't see any date subfolder but that code has other issues.  For instance, January 11 and November 1 would produce the same folder name for the same year.  Try this:

Dts.Variables("var_DirPath").Value = String.Format("D:\customers\documents\orders\{0:yyyyMMdd}", Date.Now)

That is better than concatenation and the format ensures unique folder names for all dates.


问:
Box-Model for inline vs. block elements within a table td
I'm using a table to display tabular data, but I need to get the sizing pixel-perfect so that the contents don't end up taking more vertical space than I have available.  Also, layout using css alone isn't feasible because I have dozens of elements.

Here is my simple test code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<style>
table, td, tr, thead, tfoot, tbody, th, tf {
    border-collapse: collapse;
    margin: 0px;
    padding: 0px;
    border:0;
    line-height:16px;
}
</style>
</head>
<body>
    <table border="0" cellspacing="0" cellpadding="0">
        <tr style="height:16px">
        <td>
            <span style="font-size:10pt;">Here is some text</span>
        </td>
        </tr>
    </table>
</body>
</html>
</code>```

Basically I want the row of the table to take up only 16px, however, in this configuration it ends up taking 17px.

Inspecting the elements in FireBug it shows the span at 15px but the td and tr at 17, yet no padding, no border, etc...

In IE I get the same behavior, however there is a little more information about my mysterious extra pixel or two, seems there is an offset on the span element:

Finally, I can fix the problem by turning my span element into a div, (or by making the span element display:block, or even display: table-cell which I don't really understand). So I don't really need help solving my problem, but I want to understand why inline elements within table cells end up taking more space then they should.  I tried google and the w3c spec but couldn't find anything useful.

答:
Could it be something like the line-height of the span?

Edit: I realized that I didn't really answer the question.  I did some poking around in Firebug (I'm on a Mac, so no access to IE at the moment), and it looks like it's not the span itself that's pushing the cell's height, but that the line-height of the td does end up controlling the height of the td.  The height of the span is only 14px.  I suspect that it's the empty text node (show's in IE's dev tools) that's pushing the height.  One way to see this is to move the font-size specification up a node or two so that it will apply to the empty text node as well.  At least in FB that seems to fix it and demonstrate that the span isn't the issue. (Maybe the empty text node doesn't exist if you use a div instead? Do you even need a span or a div, or could you have your text right in the td?)

Body:
I'm using a table to display tabular data, but I need to get the sizing pixel-perfect so that the contents don't end up taking more vertical space than I have available.  Also, layout using css alone isn't feasible because I have dozens of elements.

Here is my simple test code:

<!DOCTYPE html>

            Here is some text

Basically I want the row of the table to take up only 16px, however, in this configuration it ends up taking 17px.

Inspecting the elements in FireBug it shows the span at 15px but the td and tr at 17, yet no padding, no border, etc...

In IE I get the same behavior, however there is a little more information about my mysterious extra pixel or two, seems there is an offset on the span element:

Finally, I can fix the problem by turning my span element into a div, (or by making the span element display:block, or even display: table-cell which I don't really understand). So I don't really need help solving my problem, but I want to understand why inline elements within table cells end up taking more space then they should.  I tried google and the w3c spec but couldn't find anything useful.


问:
How can I add a footnote without any numbering in a *.docx file using ReporteRs?
When using the ReporteRs package, it seems that the only way to get text into the footer of a page involves placing a numbered footnote in the body of the text, and having that footnote appear with the same number in the footer.  I'd like to be able to put text in the footer of a page without any numbering in front.

```<code>library(ReporteRs)

doc1 <- docx()
doc1 <- addFlexTable(doc1,vanilla.table(head(iris)))
Foot <- Footnote()
Foot <- addParagraph(Foot,"This should not have a number in front of it")
doc <- addParagraph(doc,pot("There should be no number after this",footnote=Foot))
writeDoc(doc1, file = "footnote1.docx")
</code>```

Alternatively, if it's possible to just put a paragraph at the bottom of the page, that would also solve my problem. This could be done by figuring out how many more lines will fit on the page, but if there was some way to make the vertical alignment the bottom of the page for the last paragraph, that would be ideal.

```<code>doc2 <- docx()
doc2 <- addFlexTable(doc2,vanilla.table(head(iris)))
doc2 <- addParagraph(doc2,c(rep("",33),"Text placed by dynamically finding bottom of the page"))
writeDoc(doc2, file = "footnote2.docx")
</code>```

答:
What you are trying to do doesn't match ReporteRs::Footnote as it was written, as shown in the help:

If in a docx object, footnote will be flagged by a number immediately following the portion of the text the note is in reference to.

However, what you are after is achievable if I understand your question correctly. The note in your table and the text in the footer will not be connected in any way, such as a hyperlink provided by Footnote.

There is also the issue that ReporteRs does not provide a method to place text in the footer without using bookmarks (except Footnote, which we have now discounted). That means we need to use a docx template instead of the empty document generated by the package.

Template creation

Steps:

From MS Word I have opened an empty document

Placed the cursor in the footer area

Insert => Bookmark

Enter Bookmark name, I just used FOOTER, and click Add

Save the document

Document generation with ReporteRs

With our new template, the next steps will seem more familiar.

```<code>library(ReporteRs)

doc <- docx(template = "Doc1.docx")

# do the flextable, note that I add your table footer here
ftable <- vanilla.table(head(iris))

ftable <- addFooterRow(
  ftable,
  value = c("There should be no number after this"),
  colspan = 5
)

doc <- addFlexTable(doc, ftable)

# check for the presence of our bookmark
list_bookmarks(doc)
# [1] "FOOTER"

# now add the footer text using the bookmark
doc <- addParagraph(
  doc, stylename = "footer", bookmark = "FOOTER",
  pot("This should not have a number in front of it")
)

# and finally write the document
writeDoc(doc, file = "doc.docx")
</code>```

End product

The table, which you can better format to suit, I have not removed the border on the added row.

The footer, in the standard footer style, which again you can modify to suit.

Body:
When using the ReporteRs package, it seems that the only way to get text into the footer of a page involves placing a numbered footnote in the body of the text, and having that footnote appear with the same number in the footer.  I'd like to be able to put text in the footer of a page without any numbering in front.

library(ReporteRs)

doc1 <- docx()
doc1 <- addFlexTable(doc1,vanilla.table(head(iris)))
Foot <- Footnote()
Foot <- addParagraph(Foot,"This should not have a number in front of it")
doc <- addParagraph(doc,pot("There should be no number after this",footnote=Foot))
writeDoc(doc1, file = "footnote1.docx")

Alternatively, if it's possible to just put a paragraph at the bottom of the page, that would also solve my problem. This could be done by figuring out how many more lines will fit on the page, but if there was some way to make the vertical alignment the bottom of the page for the last paragraph, that would be ideal.

doc2 <- docx()
doc2 <- addFlexTable(doc2,vanilla.table(head(iris)))
doc2 <- addParagraph(doc2,c(rep("",33),"Text placed by dynamically finding bottom of the page"))
writeDoc(doc2, file = "footnote2.docx")

Body:
What you are trying to do doesn't match ReporteRs::Footnote as it was written, as shown in the help:

If in a docx object, footnote will be flagged by a number immediately following the portion of the text the note is in reference to.

However, what you are after is achievable if I understand your question correctly. The note in your table and the text in the footer will not be connected in any way, such as a hyperlink provided by Footnote.

There is also the issue that ReporteRs does not provide a method to place text in the footer without using bookmarks (except Footnote, which we have now discounted). That means we need to use a docx template instead of the empty document generated by the package.

Template creation

Steps:

From MS Word I have opened an empty document

Placed the cursor in the footer area

Insert => Bookmark

Enter Bookmark name, I just used FOOTER, and click Add

Save the document

Document generation with ReporteRs

With our new template, the next steps will seem more familiar.

library(ReporteRs)

doc <- docx(template = "Doc1.docx")

# do the flextable, note that I add your table footer here
ftable <- vanilla.table(head(iris))

ftable <- addFooterRow(
  ftable,
  value = c("There should be no number after this"),
  colspan = 5
)

doc <- addFlexTable(doc, ftable)

# check for the presence of our bookmark
list_bookmarks(doc)
# [1] "FOOTER"

# now add the footer text using the bookmark
doc <- addParagraph(
  doc, stylename = "footer", bookmark = "FOOTER",
  pot("This should not have a number in front of it")
)

# and finally write the document
writeDoc(doc, file = "doc.docx")

End product

The table, which you can better format to suit, I have not removed the border on the added row.

The footer, in the standard footer style, which again you can modify to suit.


问:
Is it possible to programmatically embed Reddit posts in a page?
Reddit now offers the possibility to embed reddit posts and comments on your page. For posts, the way to do it manually is to click the "share" button, then select "embed" in the pop-up window. This creates a snippet that you can include in your page. However I would like to this automatically with posts I get and select from the reddit API.

Is there an API to generate the snippet? Should I just figure out the format and generate it myself?

答: Yh. You can even use IFTTT.COM. Remove the data card created part and replace url with {{PostURL}} and Title work {{title}}. Hope it helps.</p>


问:
SQL Query: Grouping the latest messages using SQL JOIN
I am trying to retrieve the latest messages about each post from different users using SQL. I have 3 tables:

The Users Table (To collect user Information)

The Post Table (To Collect post information)

The Messages Table (Table containing messages)

However, I am getting an error with my SQL Syntax, Here is the code

```<code>SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username,
   receipient,
   message,
   datestamp
FROM
   messages
   JOIN
      users
      ON messages.username = users.username
   JOIN
      posts
      ON posts.postid = messages.messageid
WHERE
   messages.receipient = 'try-2a'
GROUP BY
   messages.messageid
ORDER BY
   messages.sequence DESC
</code>```

Error: Column 'username' in field list is ambiguous

Link to Fiddle with Schema

答:
The username column in the SELECT list needs to have the table alias prefixed, since username exists in both messages and users

```<code>SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username, --This column needs to have the alias prefix
   receipient,
   message,
   datestamp
</code>```

Body:
I am trying to retrieve the latest messages about each post from different users using SQL. I have 3 tables:

The Users Table (To collect user Information)

The Post Table (To Collect post information)

The Messages Table (Table containing messages)

However, I am getting an error with my SQL Syntax, Here is the code

SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username,
   receipient,
   message,
   datestamp
FROM
   messages
   JOIN
      users
      ON messages.username = users.username
   JOIN
      posts
      ON posts.postid = messages.messageid
WHERE
   messages.receipient = 'try-2a'
GROUP BY
   messages.messageid
ORDER BY
   messages.sequence DESC

Error: Column 'username' in field list is ambiguous

Link to Fiddle with Schema

Body:
The username column in the SELECT list needs to have the table alias prefixed, since username exists in both messages and users

SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username, --This column needs to have the alias prefix
   receipient,
   message,
   datestamp


问:
relational prolog and bit mask manipulations
I am trying my hand at relational prolog. Part of my program needs to deal with bitmasks. It however seems that prolog code handles bit makes, such as to set a bit or clear a bit doesn't work relationally -- i.e. it only works in setting a bit, but not in the other direction, identifying what bit is set.

For example:

```<code>setbit(X, N, V) :-
    N1 #= 1<< N,
    V #= X \/ N1.
</code>```

this code only work in one direction, where X and N are given and V is calculated. If one provides V and N, then X is not derived, but rather its left as an uninstantiated expression.

Does this mean that calculating with bit maps and masks is out of scope of relational prolog.

```<code>?- setbit(0,1,X).
X = 2.

?- setbit(X, 1, 2).
2#=X\/2.
</code>```

the latter doesn't bind X to 0.

thank you,

Daniel

Edit: based on the comments below, the following code works very well:

```<code>setbit(X, N, V) :-
    X in 0..1,
    label([X]),
    N1 #= 1<< N,
    V #= X \/ N1.

clearbit(X, N, V) :-
    X in 0..1,
    label([X]),
    current_prolog_flag(max_tagged_integer, MTI),
    N1 #= MTI /\ \(1<<N),
%   N1 #= 0xffffffffffffff /\ \(1<<N),
    V #= X /\ N1
</code>```

Note, the current_prolog_flag -- it retrieves the maximum integer fitting into one word on the current machine architecture -- on 64 bit its 54 bits, the rest of the bits are used for housekeeping.

答:
I am not great at clpfd, but I think the problem here is that you haven't given X a finite domain or asked for its values to be enumerated. This works:

```<code>?- setbit(X, 1, 2), X in 0..1, label([X]).
X = 0 ;
false.
</code>```

The second expression there, X in 0..1 says you want X to be zero or one, and the third says, "give me the values X can obtain."

Body:
I am trying my hand at relational prolog. Part of my program needs to deal with bitmasks. It however seems that prolog code handles bit makes, such as to set a bit or clear a bit doesn't work relationally -- i.e. it only works in setting a bit, but not in the other direction, identifying what bit is set.

For example:

setbit(X, N, V) :-
    N1 #= 1<< N,
    V #= X \/ N1.

this code only work in one direction, where X and N are given and V is calculated. If one provides V and N, then X is not derived, but rather its left as an uninstantiated expression.

Does this mean that calculating with bit maps and masks is out of scope of relational prolog.

?- setbit(0,1,X).
X = 2.

?- setbit(X, 1, 2).
2#=X\/2.

the latter doesn't bind X to 0.

thank you,

Daniel

Edit: based on the comments below, the following code works very well:

setbit(X, N, V) :-
    X in 0..1,
    label([X]),
    N1 #= 1<< N,
    V #= X \/ N1.

clearbit(X, N, V) :-
    X in 0..1,
    label([X]),
    current_prolog_flag(max_tagged_integer, MTI),
    N1 #= MTI /\ \(1<<N),
%   N1 #= 0xffffffffffffff /\ \(1<<N),
    V #= X /\ N1

Note, the current_prolog_flag -- it retrieves the maximum integer fitting into one word on the current machine architecture -- on 64 bit its 54 bits, the rest of the bits are used for housekeeping.

Body:
I am not great at clpfd, but I think the problem here is that you haven't given X a finite domain or asked for its values to be enumerated. This works:

?- setbit(X, 1, 2), X in 0..1, label([X]).
X = 0 ;
false.

The second expression there, X in 0..1 says you want X to be zero or one, and the third says, "give me the values X can obtain."


问:
Node.js, express, and object instantiation inside/outside route endpoints
I have a question regarding object instantiation.  Right now I have a fairly large application set up, with RESTful endpoints implemented on the back-end.

I was wondering what is the "best" way of object instantiation, and how the garbage collector is affected by what I do.

Take for example the following:

```<code>const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    const myClass = new MyClass();
    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});
</code>```

Here, an object is instantiated INSIDE the route path implementation.

Now, takes this for example:

```<code>const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

const myClass = new MyClass();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});
</code>```

Here, the object is instantiated OUTSIDE the route path implementation.  Seems to me as though this would persist indefinitely for the life of the application, whereas the first example, the variable myClass would get cleaned up.

So really I'm wondering:

Am I thinking about this the right way?

Is there a reason why I should do one method vs the other?  It seems as though if I chose option 2, I might as well just make static methods on the class itself...

What are some general pros/cons of each approach?

I feel like in my head I'm fighting the battle that things aren't being correctly cleaned up, one way is better than the other in terms of how much traffic there is, race condition avoidance, etc!

答:
Yes, your thoughts are legitimate. Even though stuff like object instantion is probably a micro optimization.

As Bergi already mentioned in the comments you shouldn't reconstruct or process anything again inside of your routes if you don't need to. You always need to keep in mind that the code inside of your route handler is executed on every single requests which reaches this route.

So what you are literally asking is: Should I do const myClass = new MyClass(); once per application lifecycle or potentially up to thousands times a second. Only you could answer if you really need to create a new instance of your class every time a request for this route has to be processed. Probably you don't need to create an instance every time. So in order to avoid unnecessary work put it outside of your route handler.

As of #3 there is no real pro/con list for above reasons. If you can avoid the instanation inside of your route handler, then avoid it!

Body:
I have a question regarding object instantiation.  Right now I have a fairly large application set up, with RESTful endpoints implemented on the back-end.

I was wondering what is the "best" way of object instantiation, and how the garbage collector is affected by what I do.

Take for example the following:

const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    const myClass = new MyClass();
    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});

Here, an object is instantiated INSIDE the route path implementation.

Now, takes this for example:

const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

const myClass = new MyClass();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});

Here, the object is instantiated OUTSIDE the route path implementation.  Seems to me as though this would persist indefinitely for the life of the application, whereas the first example, the variable myClass would get cleaned up.

So really I'm wondering:

Am I thinking about this the right way?

Is there a reason why I should do one method vs the other?  It seems as though if I chose option 2, I might as well just make static methods on the class itself...

What are some general pros/cons of each approach?

I feel like in my head I'm fighting the battle that things aren't being correctly cleaned up, one way is better than the other in terms of how much traffic there is, race condition avoidance, etc!


问:
nvcc fatal : Value 'sm_20' is not defined for option 'gpu-architecture'
I've looked at many pages and either could not follow what they were saying because they were unclear and/or my knowledge is just not sufficient enough.

I am trying to run:

luarocks install https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec

So that I may run DenseCap over some images using GPU Acceleration. When I run it, I get this error:

```<code>$ luarocks install https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec
Using https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec... switching to 'build' mode
Cloning into 'stnbhwd'...
remote: Counting objects: 24, done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 24 (delta 0), reused 14 (delta 0), pack-reused 0
Receiving objects: 100% (24/24), 19.42 KiB | 0 bytes/s, done.
Checking connectivity... done.
cmake -E make_directory build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="/home/tex/torch/install/bin/.." -DCMAKE_INSTALL_PREFIX="/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1" && make

-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Torch7 in /home/tex/torch/install
-- Try OpenMP C flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Try OpenMP CXX flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Found OpenMP: -fopenmp
-- Compiling with OpenMP support
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Found CUDA: /usr/local/cuda (found suitable version "9.0", minimum required is "5.5")
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/luarocks_stnbhwd-scm-1-4197/stnbhwd/build
Scanning dependencies of target stn
[ 25%] Building C object CMakeFiles/stn.dir/init.c.o
[ 50%] Linking C shared module libstn.so
[ 50%] Built target stn
[ 75%] Building NVCC (Device) object CMakeFiles/custn.dir/custn_generated_init.cu.o
nvcc fatal   : Value 'sm_20' is not defined for option 'gpu-architecture'
CMake Error at custn_generated_init.cu.o.cmake:207 (message):
  Error generating
  /tmp/luarocks_stnbhwd-scm-1-4197/stnbhwd/build/CMakeFiles/custn.dir//./custn_generated_init.cu.o

CMakeFiles/custn.dir/build.make:63: recipe for target 'CMakeFiles/custn.dir/custn_generated_init.cu.o' failed
make[2]: *** [CMakeFiles/custn.dir/custn_generated_init.cu.o] Error 1
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/custn.dir/all' failed
make[1]: *** [CMakeFiles/custn.dir/all] Error 2
Makefile:127: recipe for target 'all' failed
make: *** [all] Error 2

Error: Build error: Failed building.
</code>```

I was able to luarocks install cutorch, luarocks install cunn, and luarocks install cudnn just fine.

I am running Ubuntu 16.04 on a GTX 1080ti.

```<code>$ nvidia-smi
Tue Dec  5 16:25:42 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.90                 Driver Version: 384.90                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:29:00.0  On |                  N/A |
|  0%   47C    P8    16W / 250W |    716MiB / 11169MiB |      1%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1128      G   /usr/lib/xorg/Xorg                           479MiB |
|    0      1782      G   compiz                                       234MiB |
+-----------------------------------------------------------------------------+
</code>```

For some reason, when I run $ nvcc -V, I get:

```<code>    The program 'nvcc' is currently not installed. You can install it by typing:
sudo apt install nvidia-cuda-toolkit
</code>```

..and this is another big problem I am facing. When I install nvcc, it installs the toolkit for Cuda 7.5, but I have Cuda 9.0. I installed it using the .deb file that comes from Cuda's website.

```<code>$ sudo apt-get install cuda
Reading package lists... Done
Building dependency tree
Reading state information... Done
cuda is already the newest version (9.0.176-1).
The following packages were automatically installed and are no longer required:
  libcublas7.5 libcudart7.5 libcufft7.5 libcufftw7.5 libcuinj64-7.5
  libcurand7.5 libcusolver7.5 libcusparse7.5 libnppc7.5 libnppi7.5 libnpps7.5
  libnvblas7.5 libnvrtc7.5 libnvtoolsext1 libnvvm3 libthrust-dev libvdpau-dev
  nvidia-cuda-dev nvidia-cuda-doc nvidia-cuda-gdb nvidia-opencl-dev
  nvidia-profiler nvidia-visual-profiler opencl-headers
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 222 not upgraded.
</code>```

I honestly expect that I need to install nvcc, but like I said, it installs for the wrong version, and I cannot for the life of me figure out how to install it for the right version, and Im really confused as to why I am getting this error now even though I already installed cutorch, cudnn, and cunn just fine. Any help is appreciated...

Thanks

答:
Try to change the code architecture (such as sm_20) to some higher version in CMakeLists.txt of stnbhwd that you are trying to install.

From:

```<code>IF (CUDA_FOUND)
   LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_20")
</code>```

to:

```<code>IF (CUDA_FOUND)
   LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_30")
</code>```

Body:
I've looked at many pages and either could not follow what they were saying because they were unclear and/or my knowledge is just not sufficient enough.

I am trying to run:

luarocks install https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec

So that I may run DenseCap over some images using GPU Acceleration. When I run it, I get this error:

$ luarocks install https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec
Using https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec... switching to 'build' mode
Cloning into 'stnbhwd'...
remote: Counting objects: 24, done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 24 (delta 0), reused 14 (delta 0), pack-reused 0
Receiving objects: 100% (24/24), 19.42 KiB | 0 bytes/s, done.
Checking connectivity... done.
cmake -E make_directory build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="/home/tex/torch/install/bin/.." -DCMAKE_INSTALL_PREFIX="/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1" && make

-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Torch7 in /home/tex/torch/install
-- Try OpenMP C flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Try OpenMP CXX flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Found OpenMP: -fopenmp
-- Compiling with OpenMP support
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Found CUDA: /usr/local/cuda (found suitable version "9.0", minimum required is "5.5")
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/luarocks_stnbhwd-scm-1-4197/stnbhwd/build
Scanning dependencies of target stn
[ 25%] Building C object CMakeFiles/stn.dir/init.c.o
[ 50%] Linking C shared module libstn.so
[ 50%] Built target stn
[ 75%] Building NVCC (Device) object CMakeFiles/custn.dir/custn_generated_init.cu.o
nvcc fatal   : Value 'sm_20' is not defined for option 'gpu-architecture'
CMake Error at custn_generated_init.cu.o.cmake:207 (message):
  Error generating
  /tmp/luarocks_stnbhwd-scm-1-4197/stnbhwd/build/CMakeFiles/custn.dir//./custn_generated_init.cu.o

CMakeFiles/custn.dir/build.make:63: recipe for target 'CMakeFiles/custn.dir/custn_generated_init.cu.o' failed
make[2]: *** [CMakeFiles/custn.dir/custn_generated_init.cu.o] Error 1
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/custn.dir/all' failed
make[1]: *** [CMakeFiles/custn.dir/all] Error 2
Makefile:127: recipe for target 'all' failed
make: *** [all] Error 2

Error: Build error: Failed building.

I was able to luarocks install cutorch, luarocks install cunn, and luarocks install cudnn just fine.

I am running Ubuntu 16.04 on a GTX 1080ti.

$ nvidia-smi
Tue Dec  5 16:25:42 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.90                 Driver Version: 384.90                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:29:00.0  On |                  N/A |
|  0%   47C    P8    16W / 250W |    716MiB / 11169MiB |      1%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1128      G   /usr/lib/xorg/Xorg                           479MiB |
|    0      1782      G   compiz                                       234MiB |
+-----------------------------------------------------------------------------+

For some reason, when I run $ nvcc -V, I get:

    The program 'nvcc' is currently not installed. You can install it by typing:
sudo apt install nvidia-cuda-toolkit

..and this is another big problem I am facing. When I install nvcc, it installs the toolkit for Cuda 7.5, but I have Cuda 9.0. I installed it using the .deb file that comes from Cuda's website.

$ sudo apt-get install cuda
Reading package lists... Done
Building dependency tree
Reading state information... Done
cuda is already the newest version (9.0.176-1).
The following packages were automatically installed and are no longer required:
  libcublas7.5 libcudart7.5 libcufft7.5 libcufftw7.5 libcuinj64-7.5
  libcurand7.5 libcusolver7.5 libcusparse7.5 libnppc7.5 libnppi7.5 libnpps7.5
  libnvblas7.5 libnvrtc7.5 libnvtoolsext1 libnvvm3 libthrust-dev libvdpau-dev
  nvidia-cuda-dev nvidia-cuda-doc nvidia-cuda-gdb nvidia-opencl-dev
  nvidia-profiler nvidia-visual-profiler opencl-headers
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 222 not upgraded.

I honestly expect that I need to install nvcc, but like I said, it installs for the wrong version, and I cannot for the life of me figure out how to install it for the right version, and Im really confused as to why I am getting this error now even though I already installed cutorch, cudnn, and cunn just fine. Any help is appreciated...

Thanks

Body:
Try to change the code architecture (such as sm_20) to some higher version in CMakeLists.txt of stnbhwd that you are trying to install.

From:

IF (CUDA_FOUND)
   LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_20")

to:

IF (CUDA_FOUND)
   LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_30")


问:
How to apply Polynomial Transformation to subset of features in scikitlearn
Scikitlearn's PolynomialFeatures facilitates polynomial feature generation.

Here is a simple example:

```<code>import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures

# Example data:
X = np.arange(6).reshape(3, 2)

# Works fine
poly = PolynomialFeatures(2)
pd.DataFrame(poly.fit_transform(X))

   0  1  2   3   4   5
0  1  0  1   0   0   1
1  1  2  3   4   6   9
2  1  4  5  16  20  25
</code>```

Question: Is there any capability to only have the polynomial transformation apply to a specified list of features?

e.g.

```<code># Use previous dataframe
X2 = X.copy()

# Categorical feature will be handled
# by a one hot encoder in another feature generation step
X2['animal'] = ['dog', 'dog', 'cat']

# Don't try to poly transform the animal column
poly2 = PolynomialFeatures(2, cols=[1,2]) # <-- ("cols" not an actual param)

# desired outcome:
pd.DataFrame(poly2.fit_transform(X))
   0  1  2   3   4   5   'animal'
0  1  0  1   0   0   1   'dog'
1  1  2  3   4   6   9   'dog'
2  1  4  5  16  20  25   'cat'
</code>```

This would be particularly useful when using the Pipeline feature to combine a long series of feature generation and model training code.

One option would be to roll-your-own transformer (great example by Michelle Fullwood), but I figured someone else would have stumbled across this use case before.

答:
PolynomialFeatures, like many other transformers in sklearn, does not have a parameter that specifies which column(s) of the data to apply, so it is not straightforward to put it in a Pipeline and expect to work.

A more general way to do this, you can use FeatureUnion and specify transformer(s) for each feature you have in your dataframe using another pipeline.

A simple example could be:

from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import PolynomialFeatures, OneHotEncoder, LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

X = pd.DataFrame({'cat_var': ['a', 'b', 'c'], 'num_var': [1, 2, 3]})

class ColumnExtractor(object):
    def __init__(self, columns=None):
        self.columns = columns

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        X_cols = X[self.columns]

    return X_cols

pipeline = Pipeline([
    ('features', FeatureUnion([
        ('num_var', Pipeline([
            ('extract', ColumnExtractor(columns=['num_var'])),
            ('poly', PolynomialFeatures(degree=2))
        ])),
        ('cat_var', Pipeline([
            ('extract', ColumnExtractor(columns=['cat_var'])),
            ('le', LabelEncoder()),
            ('ohe', OneHotEncoder()),
        ]))
    ])),
    ('estimator', LogisticRegression())
])
```

Body:
Scikitlearn's PolynomialFeatures facilitates polynomial feature generation.

Here is a simple example:

import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures

# Example data:
X = np.arange(6).reshape(3, 2)

# Works fine
poly = PolynomialFeatures(2)
pd.DataFrame(poly.fit_transform(X))

   0  1  2   3   4   5
0  1  0  1   0   0   1
1  1  2  3   4   6   9
2  1  4  5  16  20  25

Question: Is there any capability to only have the polynomial transformation apply to a specified list of features?

e.g.

# Use previous dataframe
X2 = X.copy()

# Categorical feature will be handled
# by a one hot encoder in another feature generation step
X2['animal'] = ['dog', 'dog', 'cat']

# Don't try to poly transform the animal column
poly2 = PolynomialFeatures(2, cols=[1,2]) # <-- ("cols" not an actual param)

# desired outcome:
pd.DataFrame(poly2.fit_transform(X))
   0  1  2   3   4   5   'animal'
0  1  0  1   0   0   1   'dog'
1  1  2  3   4   6   9   'dog'
2  1  4  5  16  20  25   'cat'

This would be particularly useful when using the Pipeline feature to combine a long series of feature generation and model training code.

One option would be to roll-your-own transformer (great example by Michelle Fullwood), but I figured someone else would have stumbled across this use case before.


问:
Can we access the objects outside the method?
I created two Classes A and B.

I created an object in B outside any method like below, but I can't access variables and methods from A. Why? I can't understand this

```<code>Class B {
    int a, b;
    A Obja = new(); // this does not work

    public void method1() {
        A Obja1 = new A(); // from here I am able to access the members from A
    }
}
</code>```

答:
You forgot to specify the classname for the new keyword.

```<code>A Obja = new A();
</code>```

See also:

Java tutorial - Creating objects

This would however have resulted in a compilation error, not a runtime error. So if your code actually compiled, then your concrete problem might rather be a scoping or visibility issue. But the code example given as far doesn't indicate any.

Body:
I created two Classes A and B.

I created an object in B outside any method like below, but I can't access variables and methods from A. Why? I can't understand this

Class B {
    int a, b;
    A Obja = new(); // this does not work

    public void method1() {
        A Obja1 = new A(); // from here I am able to access the members from A
    }
}

Body:
You forgot to specify the classname for the new keyword.

A Obja = new A();

See also:

Java tutorial - Creating objects

This would however have resulted in a compilation error, not a runtime error. So if your code actually compiled, then your concrete problem might rather be a scoping or visibility issue. But the code example given as far doesn't indicate any.


问:
How to extract paragraphs separated by a comma?
This is a piece of code from which I am trying to obtain data.

```<code><p>ul. Niecała 10</p>
<p>05-800 Pruszków</p>

</div>
</code>```

I did it this way:

```<code>address = result.find('div', attrs={'class': 'section address'}).get_text()
</code>```

Unfortunately, the result does not satisfy me. The texts from the paragraphs are stuck together. I would like these paragraphs to be separated by a comma.

Now:

```<code>ul. Niecała 1005-800 Pruszków
</code>```

I would like it to be:

```<code>ul. Niecała 10, 05-800 Pruszków
</code>```

How do I do that? Do you have any suggestions?

答:
There is an even easier way than .stripped_strings - just use .get_text() directly with a comma as a separator:

```<code>address = soup.find('div', attrs={'class': 'section address'})
print(address.get_text(", ", strip=True))
</code>```

Prints:

```<code>ul. Niecała 10, 05-800 Pruszków
</code>```

Body:
This is a piece of code from which I am trying to obtain data.

ul. Niecała 10

05-800 Pruszków

I did it this way:

address = result.find('div', attrs={'class': 'section address'}).get_text()

Unfortunately, the result does not satisfy me. The texts from the paragraphs are stuck together. I would like these paragraphs to be separated by a comma.

Now:

ul. Niecała 1005-800 Pruszków

I would like it to be:

ul. Niecała 10, 05-800 Pruszków

How do I do that? Do you have any suggestions?

Body:
There is an even easier way than .stripped_strings - just use .get_text() directly with a comma as a separator:

address = soup.find('div', attrs={'class': 'section address'})
print(address.get_text(", ", strip=True))

Prints:

ul. Niecała 10, 05-800 Pruszków


答:
```<code>SELECT
       MAX(sequence) AS latestmsg,
       COUNT(*) AS msgcount,
       sequence,
       messageid,
       users.username,
       receipient,
       message,
       datestamp
    FROM
       messages
       JOIN
          users
          ON messages.username = users.username
       JOIN
          posts
          ON posts.postid = messages.messageid
    WHERE
       messages.receipient = 'try-2a'
    GROUP BY
       messages.messageid
    ORDER BY
       messages.sequence DESC
</code>```

Try the modified query below:

```<code>SELECT sequence AS latestmsg,
    msgcount,
    sequence,
    messages.messageid,
    users.username,
    receipient,
    message,
    messages.datestamp
FROM messages
JOIN users ON messages.username = users.username
JOIN posts ON posts.postid = messages.messageid
JOIN (
    SELECT messageid, MAX(sequence) AS max_seq, COUNT(*) AS msgcount
    FROM messages
    GROUP BY messageid
) m ON m.messageid = messages.messageid AND m.max_seq = messages.sequence
WHERE messages.receipient = 'try-2a'
ORDER BY messages.sequence DESC
</code>```

Title: SQL Query: Grouping the latest messages using SQL JOIN

Body:
SELECT
       MAX(sequence) AS latestmsg,
       COUNT(*) AS msgcount,
       sequence,
       messageid,
       users.username,
       receipient,
       message,
       datestamp
    FROM
       messages
       JOIN
          users
          ON messages.username = users.username
       JOIN
          posts
          ON posts.postid = messages.messageid
    WHERE
       messages.receipient = 'try-2a'
    GROUP BY
       messages.messageid
    ORDER BY
       messages.sequence DESC

Try the modified query below:

SELECT sequence AS latestmsg,
    msgcount,
    sequence,
    messages.messageid,
    users.username,
    receipient,
    message,
    messages.datestamp
FROM messages
JOIN users ON messages.username = users.username
JOIN posts ON posts.postid = messages.messageid
JOIN (
    SELECT messageid, MAX(sequence) AS max_seq, COUNT(*) AS msgcount
    FROM messages
    GROUP BY messageid
) m ON m.messageid = messages.messageid AND m.max_seq = messages.sequence
WHERE messages.receipient = 'try-2a'
ORDER BY messages.sequence DESC