问:
generate days from date range
I would like to run a query like

```<code>select ... as days where `date` is between '2010-01-20' and '2010-01-24'
</code>```

And return data like:

```
days
----------
2010-01-20
2010-01-21
2010-01-22
2010-01-23
2010-01-24
```

答:
For anyone who wants this as a saved view (MySQL doesn't support nested select statements in views):

```<code>create view zero_to_nine as
    select 0 as n union all
    select 1 union all
    select 2 union all
    select 3 union all
    select 4 union all
    select 5 union all
    select 6 union all
    select 7 union all
    select 8 union all
    select 9;

create view date_range as
    select curdate() - INTERVAL (a.n + (10 * b.n) + (100 * c.n)) DAY as date
    from zero_to_nine as a
    cross join zero_to_nine as b
    cross join zero_to_nine as c;
</code>```

You can then do

```<code>select * from date_range
</code>```

to get

```<code>date
---
2017-06-06
2017-06-05
2017-06-04
2017-06-03
2017-06-02
...
</code>```

Title: generate days from date range

Body:
I would like to run a query like

select ... as days where `date` is between '2010-01-20' and '2010-01-24'

And return data like:

days
----------
2010-01-20
2010-01-21
2010-01-22
2010-01-23
2010-01-24

Body:
For anyone who wants this as a saved view (MySQL doesn't support nested select statements in views):

create view zero_to_nine as
    select 0 as n union all
    select 1 union all
    select 2 union all
    select 3 union all
    select 4 union all
    select 5 union all
    select 6 union all
    select 7 union all
    select 8 union all
    select 9;

create view date_range as
    select curdate() - INTERVAL (a.n + (10 * b.n) + (100 * c.n)) DAY as date
    from zero_to_nine as a
    cross join zero_to_nine as b
    cross join zero_to_nine as c;

You can then do

select * from date_range

to get

date
---
2017-06-06
2017-06-05
2017-06-04
2017-06-03
2017-06-02
...


来源: stackexchange

问:
Docker Container works locally but fails on server
I'm fairly new to docker and I'm kind of experimenting with Angular CLI app. I managed to run it locally through my docker container. It works great, but when I try running it from my server it fails.

Server is hosted on DigitalOcean:

```<code>512 MB Memory / 20 GB Disk / FRA1 - Ubuntu Docker 17.03.0-ce on 14.04
</code>```

I used dockerhub to transfer my container to the server.

When logging the container it gives me this:

```<code>** NG Live Development Server is running on http://0.0.0.0:4200. **
 63% building modules 469/527 modules 58 active ...s/@angular/compiler/src/assertions.jsKilled

npm info lifecycle angular-test@0.0.0~start: Failed to exec start script
npm ERR! Linux 4.4.0-64-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! angular-test@0.0.0 start: `ng serve --host 0.0.0.0`
npm ERR! Exit status 137
npm ERR!
npm ERR! Failed at the angular-test@0.0.0 start script 'ng serve --host 0.0.0.0'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular-test package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ng serve --host 0.0.0.0
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs angular-test
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls angular-test
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /usr/src/app/npm-debug.log
</code>```

Here is my Dockerfile:

```<code># Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]
</code>```

How come it runs locally and fails on server? Am I missing some dependencies?

答:
ng serve is an angular-cli command. I'm guessing you need to install it globally in your docker file if you want to start your server like that on digital ocean:

```<code>RUN npm i -g angular-cli
</code>```

I think it would be more typical to simply run the app using the naked node server in production.  So your CMD would look more like this:

```<code>CMD ["node", "app.js"]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm fairly new to docker and I'm kind of experimenting with Angular CLI app. I managed to run it locally through my docker container. It works great, but when I try running it from my server it fails.

Server is hosted on DigitalOcean:

512 MB Memory / 20 GB Disk / FRA1 - Ubuntu Docker 17.03.0-ce on 14.04

I used dockerhub to transfer my container to the server.

When logging the container it gives me this:

** NG Live Development Server is running on http://0.0.0.0:4200. **
 63% building modules 469/527 modules 58 active ...s/@angular/compiler/src/assertions.jsKilled

npm info lifecycle angular-test@0.0.0~start: Failed to exec start script
npm ERR! Linux 4.4.0-64-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! angular-test@0.0.0 start: `ng serve --host 0.0.0.0`
npm ERR! Exit status 137
npm ERR!
npm ERR! Failed at the angular-test@0.0.0 start script 'ng serve --host 0.0.0.0'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular-test package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ng serve --host 0.0.0.0
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs angular-test
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls angular-test
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /usr/src/app/npm-debug.log

Here is my Dockerfile:

# Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]

How come it runs locally and fails on server? Am I missing some dependencies?

Body:
ng serve is an angular-cli command. I'm guessing you need to install it globally in your docker file if you want to start your server like that on digital ocean:

RUN npm i -g angular-cli

I think it would be more typical to simply run the app using the naked node server in production.  So your CMD would look more like this:

CMD ["node", "app.js"]


问:
Using a Version Control System on a Shared Network Drive at Work
I am trying to set up a version control system at work to manage python code among multiple collaborators (ideally, the VCS would be integrated into IntelliJ PyCharm).

I am familiar with GitHub, which I have played around with. But I am leery of putting the intellectual property (code) of the company on GitHub servers (even if it is a paid, private repository). I would like to basically take advantage of Git VCS, but instead of storing repositories on GitHub online servers, I would instead like these repositories to be on our the Shared Windows Drive @ work. Is it possible to do this with Git?

Here is the set up:
Each user has a local drive and access to the shared drive
I want each user to have a local repository on their local drives, which they can push to the 'master' repository on the shared drive (pending checking the code differences and approvals, which I currently do on the GitHub website via 'pull request').

Does that make sense?  I can't seem to find any tutorials / documentation on how to achieve this!

Thank you!

答:
You can certainly use git without github.

Placing the origin repo on a shared drive is one option, but it has some disadvantages.  (To avoid confusion, by the way, its a good idea to refer to the source repository as origin; in git terminology, master is the default branch.)

You will still need each developer to clone the repo, and they should use file:// URL's to clone it.  (Just using the path will work, but may cause additional issues.)  So for example

```<code>git clone file://server/share/path/to/repo
</code>```

Another option is to internally host a server that supports git.  You could use something like GitLab.  Or you could host it in TFS.  Or there are others...  (You also can just put it on a web server, but again this won't get you advanced workflow features etc.)

Body:
You can certainly use git without github.

Placing the origin repo on a shared drive is one option, but it has some disadvantages.  (To avoid confusion, by the way, its a good idea to refer to the source repository as origin; in git terminology, master is the default branch.)

You will still need each developer to clone the repo, and they should use file:// URL's to clone it.  (Just using the path will work, but may cause additional issues.)  So for example

git clone file://server/share/path/to/repo

Another option is to internally host a server that supports git.  You could use something like GitLab.  Or you could host it in TFS.  Or there are others...  (You also can just put it on a web server, but again this won't get you advanced workflow features etc.)


问:
OpenGL C++: Struct wrapper for VBO won't initialize members
I am pretty new to OpenGL, and have been going through some online tutorials to get used to the API. I understand that the creation of a VBO goes as such:

```<code>GLuint vboID;
glGenBuffers(1, &vboID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(verticesArray), verticesArray, GL_STATIC DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
</code>```

And, prior to declaring any given VBO, I create a VAO and bind it. At this point in time, I'm working by making one VBO per one VAO.

I want to make some wrapper tools on top of the API, just so that the things like creating VBOs and VAOs become more convenient.

I've began to create a struct that will, in its constructor, take an array of vertices and create a VBO from them. I've named it "triVBO", just because I'm creating only "GL_TRIANGLES" objects right now.

A "triVBO" struct is defined as follows:

```<code>struct triVBO {
GLuint ID = 0;
const void* data = (void*)0;
GLsizeiptr verticeCount = 0;
GLsizeiptr triCount = 0;

triVBO(const void* _data) {
    //VBO generation
    GLuint vboID;
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(_data), _data, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    //do our assigning
    data = _data;
    ID = vboID;
    verticeCount = (sizeof(data) / sizeof(GLfloat)) / 3;
    triCount = verticeCount / 3;
}
};
</code>```

Everything runs and compiles fine. However, the problem lies in the assignment of the "verticeCount" and "triCount" members.

As you can see in the constructor, the parameter is a "const void*", which I used because, upon checking the type of the third parameter for "glBufferData()", the third parameter being the array you pass in to the macro and thus the array that I would be trying to pass in to my constructor, I saw it was a "const void*", and I figured that I should use the same type that works for the macro.

I've laced some DEBUG macros that I made throughout the constructor and in the main program, which I've removed from that sample so that it's easier to read. When I run the program with those DEBUG macros in it, this is what I get.

When I call this:

```<code>triVBO tv_pyrVBO(pyramidVerts);
DEBUG("pyramidVerts: ", pyramidVerts);
DEBUG("tv_pyrVBO.data: ", tv_pyrVBO.data);
DEBUG("tv_pyrVBO.ID: ", tv_pyrVBO.ID);
DEBUG("tv_pyrVBO.verticeCount: ", tv_pyrVBO.verticeCount);
DEBUG("tv_pyrVBO.triCount: ", tv_pyrVBO.triCount);
</code>```

The console prints this:

```<code>pyramidVerts: 00007FF603EFC4C0
tv_pyrVBO.data: 00007FF603EFC4C0
tv_pyrVBO.ID: 2
tv_pyrVBO.verticeCount: 0
tv_pyrVBO.triCount: 0
</code>```

From what I can tell, the "data" member, which, in the constructor, I have attempted to assign the array "pyramidVerts", is being assigned properly, because the addresses are the same. Also, the code for the buffer generation and binding works because "ID" is correctly assigned a value of 2 (I have some other VBOs in the program already, that's why it isn't 1). It's just that the "verticeCount" and "triCount" members, whose calculations you can see in the constructor, aren't being assigned properly, as both of them have a value of 0, but with this specific array they should have values of 18 and 6, respectively.

What is the error? Am I using the wrong types to pass around the arrays or hold the information for the "verticeCount" and "triCount"? Is there something in the OpenGL API that I'm missing or using incorrectly that's causing it to not be assigned? Am I making a super obvious mistake of C++ or programming in general? I have searched for hours and I could not come across a stackoverflow or quora or cplusplus answer that really answered my specific question.

Any help or direction would be greatly appreciated, and any extra GL tips you would like to throw in are welcome as well. Thanks!

答:
It's just that the "verticeCount" and "triCount" members, whose calculations you can see in the constructor, aren't being assigned properly

Am I making a super obvious mistake of C++ or programming in general?

Yes. sizeof doesn't work that way. Take another parameter defining the size of the input and use that instead or, better, take in an std::vector or some other standard container that knows its size.

I'd recommend getting familiar with basic C++ concepts before you dive into wrapping OpenGL API, as doing that properly will require a certain knowledge of both the language and the API you're using.

Body:
I am pretty new to OpenGL, and have been going through some online tutorials to get used to the API. I understand that the creation of a VBO goes as such:

GLuint vboID;
glGenBuffers(1, &vboID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(verticesArray), verticesArray, GL_STATIC DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

And, prior to declaring any given VBO, I create a VAO and bind it. At this point in time, I'm working by making one VBO per one VAO.

I want to make some wrapper tools on top of the API, just so that the things like creating VBOs and VAOs become more convenient.

I've began to create a struct that will, in its constructor, take an array of vertices and create a VBO from them. I've named it "triVBO", just because I'm creating only "GL_TRIANGLES" objects right now.

A "triVBO" struct is defined as follows:

struct triVBO {
GLuint ID = 0;
const void* data = (void*)0;
GLsizeiptr verticeCount = 0;
GLsizeiptr triCount = 0;

triVBO(const void* _data) {
    //VBO generation
    GLuint vboID;
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(_data), _data, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    //do our assigning
    data = _data;
    ID = vboID;
    verticeCount = (sizeof(data) / sizeof(GLfloat)) / 3;
    triCount = verticeCount / 3;
}
};

Everything runs and compiles fine. However, the problem lies in the assignment of the "verticeCount" and "triCount" members.

As you can see in the constructor, the parameter is a "const void*", which I used because, upon checking the type of the third parameter for "glBufferData()", the third parameter being the array you pass in to the macro and thus the array that I would be trying to pass in to my constructor, I saw it was a "const void*", and I figured that I should use the same type that works for the macro.

I've laced some DEBUG macros that I made throughout the constructor and in the main program, which I've removed from that sample so that it's easier to read. When I run the program with those DEBUG macros in it, this is what I get.

When I call this:

triVBO tv_pyrVBO(pyramidVerts);
DEBUG("pyramidVerts: ", pyramidVerts);
DEBUG("tv_pyrVBO.data: ", tv_pyrVBO.data);
DEBUG("tv_pyrVBO.ID: ", tv_pyrVBO.ID);
DEBUG("tv_pyrVBO.verticeCount: ", tv_pyrVBO.verticeCount);
DEBUG("tv_pyrVBO.triCount: ", tv_pyrVBO.triCount);

The console prints this:

pyramidVerts: 00007FF603EFC4C0
tv_pyrVBO.data: 00007FF603EFC4C0
tv_pyrVBO.ID: 2
tv_pyrVBO.verticeCount: 0
tv_pyrVBO.triCount: 0

From what I can tell, the "data" member, which, in the constructor, I have attempted to assign the array "pyramidVerts", is being assigned properly, because the addresses are the same. Also, the code for the buffer generation and binding works because "ID" is correctly assigned a value of 2 (I have some other VBOs in the program already, that's why it isn't 1). It's just that the "verticeCount" and "triCount" members, whose calculations you can see in the constructor, aren't being assigned properly, as both of them have a value of 0, but with this specific array they should have values of 18 and 6, respectively.

What is the error? Am I using the wrong types to pass around the arrays or hold the information for the "verticeCount" and "triCount"? Is there something in the OpenGL API that I'm missing or using incorrectly that's causing it to not be assigned? Am I making a super obvious mistake of C++ or programming in general? I have searched for hours and I could not come across a stackoverflow or quora or cplusplus answer that really answered my specific question.

Any help or direction would be greatly appreciated, and any extra GL tips you would like to throw in are welcome as well. Thanks!


问:
How to enable/disable a button while validating a button?
here I try this code.......enter image description here I try this code...I want to disable a button while validating a username and password.
if my username and password is correct then my button will enable...But I didn't get correct answer.</p>

答:
```<code>-(void)checkValidation
{
    NSString *strUserName = [_txtUsername.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *strPassword = [_txtPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    if([strUserName isEqualToString:@"YOURSTRING"] && [strPassword isEqualToString:@"YOURSTRING"])
    {
        // make your button enable
    }
    else
    {
        // make it disable
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    [self performSelector:@selector(checkValidation) withObject:nil afterDelay:0.3];

    return TRUE;
    }
</code>```


问:
Embed vimeo player in Rails?
I want to allow users to submit a vimeo url and embed that in a player. Is there a plugin or gem that does that?

Thanks

答:
Old question but I found myself in the same situation.

If you wan't to retrieve Vimeo iframe for your video you can use the following code. No need to add a gem.

Add helper

Just create a file app/helpers/videos_helper.rb and the following lines.

module VideosHelper

  require 'net/http'

  VIMEO_REGEX = %r(^https?:\/\/(?:.*?)\.?(vimeo)\.com\/(\d+).*$)

  # Finds Vimeo's video ID from given URL or [nil] if URL is invalid
  def find_vimeo_id url
    url     = sanitize url
    matches = VIMEO_REGEX.match url.to_str
    matches[2] if matches
  end

  # Get Vimeo video iframe from given URL
  def get_vimeo_iframe url, width, height
    vimeo_id = find_vimeo_id url
    uri      = "https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/#{ vimeo_id }&width=#{ width }&height=#{ height }"
    response = Net::HTTP.get( URI.parse( uri ))
    json     = JSON.parse response
    json['html'].html_safe
  end

end
```

<h3>Get iframe in view</h3>

<p>In your view just call <code>get_vimeo_iframe()</code> to print the iframe.</p>

```<%= get_vimeo_iframe('http://your.vimeo.url') %>
```

<p>Or if you want you can add width and height</p>

```<%= get_vimeo_iframe('http://your.vimeo.url', '800px', '450px') %>
```

If you want I created this gist which lets you ask also for YouTube iframe (not just Vimeo).

ContentLicense: CC BY-SA 2.5

Title: Embed vimeo player in Rails?

Body:
Old question but I found myself in the same situation.

If you wan't to retrieve Vimeo iframe for your video you can use the following code. No need to add a gem.

Add helper

Just create a file app/helpers/videos_helper.rb and the following lines.

module VideosHelper

  require 'net/http'

  VIMEO_REGEX = %r(^https?:\/\/(?:.*?)\.?(vimeo)\.com\/(\d+).*$)

  # Finds Vimeo's video ID from given URL or [nil] if URL is invalid
  def find_vimeo_id url
    url     = sanitize url
    matches = VIMEO_REGEX.match url.to_str
    matches[2] if matches
  end

  # Get Vimeo video iframe from given URL
  def get_vimeo_iframe url, width, height
    vimeo_id = find_vimeo_id url
    uri      = "https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/#{ vimeo_id }&width=#{ width }&height=#{ height }"
    response = Net::HTTP.get( URI.parse( uri ))
    json     = JSON.parse response
    json['html'].html_safe
  end

end

Get iframe in view

In your view just call get_vimeo_iframe() to print the iframe.

<%= get_vimeo_iframe('http://your.vimeo.url') %>

Or if you want you can add width and height

<%= get_vimeo_iframe('http://your.vimeo.url', '800px', '450px') %>

If you want I created this gist which lets you ask also for YouTube iframe (not just Vimeo).


问:
Python text file append error
So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)

```<code>    'Application1': ['Username1', 'Password1']
    'Application2': ['Username2', 'Password2']
</code>```

So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)

```<code>    hp = open("Passwords.txt","a") #open the file

    key = raw_input("Which app: ")
    usr = raw_input("Username: ")
    psw = raw_input("Password: ") #make variables to add

    hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file

    hp.close() #close the file
</code>```

I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?

答:
Your problem is when you try to write to the file. Change it to</p>

```<code>hp.write('\n\'' + key + '\': ''[\'' + usr + '\', ' '\'' + psw +'\']')
</code>```

Title: Python text file append error

Body:
So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)

    'Application1': ['Username1', 'Password1']
    'Application2': ['Username2', 'Password2']

So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)

    hp = open("Passwords.txt","a") #open the file

    key = raw_input("Which app: ")
    usr = raw_input("Username: ")
    psw = raw_input("Password: ") #make variables to add

    hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file

    hp.close() #close the file

I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?

Body:
Your problem is when you try to write to the file. Change it to

hp.write('\n\'' + key + '\': ''[\'' + usr + '\', ' '\'' + psw +'\']')


问:
Simple Encryption/Decryption method for encrypting an image file
My requirement is that I need simple encryption/decryption methods in C# to encrypt and
decrypt an image (maybe gif/jpeg).Simple cause I have to store it in the database in a BLOB field andsome other developers in some other programming language(like java) may need to extract and display this image.I don't need much security cause its just a matter of "security by obscuring"(life).

Gulp..can someone help...

答:
Since you "don't need much security" you can probably manage to get by with something like AES (Rijndael).  It uses a symmetric-key and there is plenty of help in the .NET framework to make is easy to implement.  There is plenty of info in MSDN on the Rijndael class that you might find helpful.

Here is a very stripped down example of encrypt / decrypt methods which can be used for working with byte arrays (binary contents)...

```<code>using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class RijndaelHelper
{
    // Example usage: EncryptBytes(someFileBytes, "SensitivePhrase", "SodiumChloride");
    public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        RijndaelCipher.Mode = CipherMode.CBC;
        byte[] salt = Encoding.ASCII.GetBytes(saltValue);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);

        ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(inputBytes, 0, inputBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] CipherBytes = memoryStream.ToArray();

        memoryStream.Close();
        cryptoStream.Close();

        return CipherBytes;
    }

    // Example usage: DecryptBytes(encryptedBytes, "SensitivePhrase", "SodiumChloride");
    public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        RijndaelCipher.Mode = CipherMode.CBC;
        byte[] salt = Encoding.ASCII.GetBytes(saltValue);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);

        ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream(encryptedBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
        byte[] plainBytes = new byte[encryptedBytes.Length];

        int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);

        memoryStream.Close();
        cryptoStream.Close();

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

Body:
Since you "don't need much security" you can probably manage to get by with something like AES (Rijndael).  It uses a symmetric-key and there is plenty of help in the .NET framework to make is easy to implement.  There is plenty of info in MSDN on the Rijndael class that you might find helpful.

Here is a very stripped down example of encrypt / decrypt methods which can be used for working with byte arrays (binary contents)...

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class RijndaelHelper
{
    // Example usage: EncryptBytes(someFileBytes, "SensitivePhrase", "SodiumChloride");
    public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        RijndaelCipher.Mode = CipherMode.CBC;
        byte[] salt = Encoding.ASCII.GetBytes(saltValue);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);

        ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(inputBytes, 0, inputBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] CipherBytes = memoryStream.ToArray();

        memoryStream.Close();
        cryptoStream.Close();

        return CipherBytes;
    }

    // Example usage: DecryptBytes(encryptedBytes, "SensitivePhrase", "SodiumChloride");
    public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        RijndaelCipher.Mode = CipherMode.CBC;
        byte[] salt = Encoding.ASCII.GetBytes(saltValue);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);

        ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream(encryptedBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
        byte[] plainBytes = new byte[encryptedBytes.Length];

        int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);

        memoryStream.Close();
        cryptoStream.Close();

        return plainBytes;
    }
}


问:
Django not inserting data into database when I execute subprocess.Popen
I am using django and inserting data into database and downloading images. When I call the function it works fine but it blocks the main thread. To execute the process in the background  I'm using :

views.py:

class get_all_data(View):
    def post(self, request, *args, **kwargs):

```<code>subprocess.Popen(
            ['python get_images.py --data=data'],
            close_fds=True,
            shell = True
        )
</code>```

But when I call:

python get_images.py(data="data")

it works fine but it runs on the main thread.

How can I fix it ? BTW I'm using python 2.7.

Note: Please don't suggest Celery . I'm looking for something which runs the task async or any other alternative.

I'm using the following code to insert into my db:

get_images.py:

```<code>from models import Test

        def get_image_all():

            #get data from server
            insert_to_Test(data="data")

        if __name__ == "__main__":
            import argparse
            from  .models import Test
            import django
            django.setup()

            parser = argparse.ArgumentParser()
            parser.add_argument('--from_date')
            parser.add_argument('--data')
            parser.add_argument('--execute', type=bool, default=False)
            args = parser.parse_args()
            print "args", args
            get_image_all(**vars(args))
</code>```

When I call subprocess.Popen then it does not insert data into my db but If I execute it by call the function then it inserts the data to db. Why does that happen?

答:
First, import and use Django models after django.setup()

Second, make sure the environment the spawn process runs in is correct, mainly make sure you use the right Python interpreter in the right virtualenv (if you use it), and make sure the process runs in the correct working directory

Sample code:

```<code>if __name__ == "__main__":

    import argparse
    import django
    django.setup()

    from  .models import Test

    # Parse args
    # Use Django models
</code>```

Next you need to make sure subprocess runs in the correct working directory, and activates your Python virtualenv (if any), roughly something like below:

```<code>subprocess.Popen(
    '/path/to/virtualenv/bin/python get_images.py --data=data',
    cwd='/path/to/project/working_directory/',
    shell=True
)
</code>```

Body:
I am using django and inserting data into database and downloading images. When I call the function it works fine but it blocks the main thread. To execute the process in the background  I'm using :

views.py:

class get_all_data(View):
    def post(self, request, *args, **kwargs):

subprocess.Popen(
            ['python get_images.py --data=data'],
            close_fds=True,
            shell = True
        )

But when I call:

python get_images.py(data="data")

it works fine but it runs on the main thread.

How can I fix it ? BTW I'm using python 2.7.

Note: Please don't suggest Celery . I'm looking for something which runs the task async or any other alternative.

I'm using the following code to insert into my db:

get_images.py:

from models import Test

        def get_image_all():

            #get data from server
            insert_to_Test(data="data")

        if __name__ == "__main__":
            import argparse
            from  .models import Test
            import django
            django.setup()

            parser = argparse.ArgumentParser()
            parser.add_argument('--from_date')
            parser.add_argument('--data')
            parser.add_argument('--execute', type=bool, default=False)
            args = parser.parse_args()
            print "args", args
            get_image_all(**vars(args))

When I call subprocess.Popen then it does not insert data into my db but If I execute it by call the function then it inserts the data to db. Why does that happen?

Body:
First, import and use Django models after django.setup()

Second, make sure the environment the spawn process runs in is correct, mainly make sure you use the right Python interpreter in the right virtualenv (if you use it), and make sure the process runs in the correct working directory

Sample code:

if __name__ == "__main__":

    import argparse
    import django
    django.setup()

    from  .models import Test

    # Parse args
    # Use Django models

Next you need to make sure subprocess runs in the correct working directory, and activates your Python virtualenv (if any), roughly something like below:

subprocess.Popen(
    '/path/to/virtualenv/bin/python get_images.py --data=data',
    cwd='/path/to/project/working_directory/',
    shell=True
)


问:
Fiori launchpad fails to load UI5 app because it cannot find registered custom module
I've a custom control in my app. It runs as a standalone web application fine. But when I'm launching it from the Fiori Launchpad (FLP), it logs an error in the console. I've registered my control in my index.html file:

```

The structure of file directory is:

If I remove my custom control, then I can run my app in the launchpad. Do I need to add some settings in my manifest file? What could be the reason for this error?

答:
The common configuration for a Fiori tile is to point to the Component file. So the index.html file is not deployed together with the app. If it's absolutely necessary to register additional module paths, do it in manifest.json instead.

{
  "sap.ui5": {
    "resourceRoots": {
      "sap.ui.codetools": "sap/ui/codetools"
    }
  }
}
```

Documentation: Descriptor for Applications, Components, and Libraries (See resourceRoots).

ContentLicense: CC BY-SA 4.0

Body:
I've a custom control in my app. It runs as a standalone web application fine. But when I'm launching it from the Fiori Launchpad (FLP), it logs an error in the console. I've registered my control in my index.html file:

The structure of file directory is:

If I remove my custom control, then I can run my app in the launchpad. Do I need to add some settings in my manifest file? What could be the reason for this error?

Body:
The common configuration for a Fiori tile is to point to the Component file. So the index.html file is not deployed together with the app. If it's absolutely necessary to register additional module paths, do it in manifest.json instead.

{
  "sap.ui5": {
    "resourceRoots": {
      "sap.ui.codetools": "sap/ui/codetools"
    }
  }
}

Documentation: Descriptor for Applications, Components, and Libraries (See resourceRoots).


答: The csvread() function might be helpful here: https://uk.mathworks.com/help/matlab/ref/csvread.html

Title: read formatted data with coma delimiter in matlab

Body:
Good day

I have a problem in reading a formatted data file using Matlab

Data include integers and real numbers as well characters. Data are separated with a coma (,) and they are split in different lines. See below :

10732, 10711, 10730,'A1',1,1,1, 0.00000E+0,-1.23000E-3,2,'N. SANTA_A1 ',1, 999,1.0000,   0,1.0000,   0,1.0000,   0,1.0000,'            ' (end of first line)
1.25000E-3, 8.11400E-2,   100.00, 3.59000E-3, 4.61720E-1,   100.00, 3.70000E-3, 8.90580E-1,   100.00,1.03918, -75.6446 (end of second line)
1.05000,   0.000,   0.000,   280.00,   280.00,   280.00, 0,      0, 1.10000, 0.90000, 1.10000, 0.90000, 999, 0, 0.00000, 0.00000,  0.000 (end of third line)
1.00000,   0.000,   0.000,   280.00,   280.00,   280.00, 0,      0, 1.10000, 0.90000, 1.10000, 0.90000, 999, 0, 0.00000, 0.00000,  0.000 (end of fourth line)
1.00000,   0.000,   0.000,    60.00,    60.00,    60.00, 0,      0, 1.10000, 0.90000, 1.10000, 0.90000, 999, 0, 0.00000, 0.00000,  0.000 (end of fifth line)

Any idea on that ?


问:
Select element by class name AND text content?
I'm trying to select a div with class mstrmojo-ListBox-item selected nAll and content Market Risk. I tried this:

```<code>$("[class^='mstrmojo-ListBox-item']","div:contains('Market Risk')")
</code>```

However it returns all the nodes with this class, like it omits the second argument.

```<code>var a = $("[nm='Sel_Team_ListB']")
$(a).filter(function() {
  return $(this).text() === 'Market Risk';
})
</code>```

It returns an empty string.

```<code>var a = $("[nm='Sel_Team_ListB']")
$(a).find("div:contains('Market Risk')", "[class^='mstrmojo-ListBox-item']")
</code>```

This one is the closest, yet it returns all the parent nodes of the one I'm after as well.

How to do this properly? Thanks.

答:
As of now, you are setting second argument as context

Where as you need to combine the selectors.

```<code>$("div:contains('Market Risk')[class^='mstrmojo-ListBox-item']")
</code>```

Body:
I'm trying to select a div with class mstrmojo-ListBox-item selected nAll and content Market Risk. I tried this:

$("[class^='mstrmojo-ListBox-item']","div:contains('Market Risk')")

However it returns all the nodes with this class, like it omits the second argument.

var a = $("[nm='Sel_Team_ListB']")
$(a).filter(function() {
  return $(this).text() === 'Market Risk';
})

It returns an empty string.

var a = $("[nm='Sel_Team_ListB']")
$(a).find("div:contains('Market Risk')", "[class^='mstrmojo-ListBox-item']")

This one is the closest, yet it returns all the parent nodes of the one I'm after as well.

How to do this properly? Thanks.

Body:
As of now, you are setting second argument as context

Where as you need to combine the selectors.

$("div:contains('Market Risk')[class^='mstrmojo-ListBox-item']")


问:
How to do multifield validation in MVC?
I'm able to validate each textbox separately by using data-val true but how can I do multi-field validation? I want to validate first name and last name together. Both fields are required. I'm using guid to generate an unique id so the values can be passed to the controller.</p>

```<code><input type="text" data-val="true" data-val-required="This field is required." name="FormResponse.NameResponse[@guid].FirstName" />
<span data-valmsg-for="FormResponse.NameResponse[@guid].FirstName" data-valmsg-replace="true"></span>

<input type="text" data-val="true" data-val-required="This field is required." name="FormResponse.NameResponse[@guid].LastName" />
<span data-valmsg-for="FormResponse.NameResponse[@guid].LastName" data-valmsg-replace="true"></span>
</code>```

答: Use a ViewModel , and validate on submit/focusOut.</p>

Title: How to do multifield validation in MVC?

Body:
I'm able to validate each textbox separately by using data-val true but how can I do multi-field validation? I want to validate first name and last name together. Both fields are required. I'm using guid to generate an unique id so the values can be passed to the controller.

<input type="text" data-val="true" data-val-required="This field is required." name="FormResponse.NameResponse[@guid].FirstName" />

<input type="text" data-val="true" data-val-required="This field is required." name="FormResponse.NameResponse[@guid].LastName" />


问:
uncheck selected checkbox when one of the checkbox option has been selected
I have 2 groups of checkbox options on same page. below is the code.

```<code><div class="col-xs-12">
<label class="checkbox-inline">
<input type="checkbox" th:field="*{borrowerRace1}"  th:value="1"  th:text="borrower1" />
 </label>
 </div>
 <div class="col-xs-12">
 <label class="checkbox-inline">
 <input type="checkbox" th:field="*{borrowerRace1}"  th:value="2"  th:text="borrower2" />
  </label>
  </div>
  <div class="col-xs-12">
  <label class="checkbox-inline">
   <input type="checkbox" th:field="*{borrowerRace1}"  th:value="3"  th:text="borrower3" />
       </label>
   </div>
     <div class="col-xs-12">
        <label class="checkbox-inline">
          <input type="checkbox" th:field="*{borrowerRace1}"  th:value="4" th:text="borrower4" />
        </label>
        </div>

        <div class="col-xs-12">
              <label class="checkbox-inline">
  <input type="checkbox" th:field="*{borrowerEthnicity1}"  th:value="1" th:text="Ethnicity1" />
           </label>
        </div>
           <div class="col-xs-12">
         <label class="checkbox-inline">
         <input type="checkbox" th:field="*{borrowerEthnicity2}"  th:value="2" th:text="Ethnicity2" />
      </label>
          </div>
     <div class="col-xs-12">
      <label class="checkbox-inline">
 <input type="checkbox" th:field="*{borrowerEthnicity3}"  th:value="3"  th:text="Ethnicity3" />
</label>
</div>
<div class="col-xs-12">
<label class="checkbox-inline">
 <input type="checkbox" th:field="*{borrowerEthnicity4}"  th:value="4" th:text="Ethnicity4" />
   </label>
    </div>
</code>```

Now,

User can select first 3 check boxes but clicking the 4th (last) one should
select the 4th (last) one and deselect all other of the set. Same should
happen for all checkbox sets.

Example : User can select A,B,C checkbox at a same time but when he checks D
all the above selected checkboxes should get unselected. Similarly for E,F,G
and H. I hope I am clear now.

Please help me on this. I hope I am clear, if not please do let me know

答:
The below code section should work according to your requirement

$(document).ready(function() {
  $('.checkbox1').on('click', function() {
   var last_chekbox1 = $('.checkbox1:last');
   if (last_chekbox1.is(':checked')) {
     $('.checkbox1').prop('checked', false);
      $(this).prop('checked', true);
    }
  });
  $('.checkbox2').on('click', function(e) {
   var last_chekbox2 = $('.checkbox2:last');
   if (last_chekbox2.is(':checked')) {
      $('.checkbox2').prop('checked', false);
      $(this).prop('checked', true);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="1" th:text="borrower1" class="checkbox1" /> A
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="2" th:text="borrower2" class="checkbox1" /> B
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="3" th:text="borrower3" class="checkbox1" /> C
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="4" th:text="borrower4" class="checkbox1" /> D
  </label>
</div>

<hr>

<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity1}" th:value="1" th:text="Ethnicity1" class="checkbox2" /> E
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity2}" th:value="2" th:text="Ethnicity2" class="checkbox2" /> F
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity3}" th:value="3" th:text="Ethnicity3" class="checkbox2" /> G
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity4}" th:value="4" th:text="Ethnicity4" class="checkbox2" /> H
  </label>
</div></code>```

Body:
I have 2 groups of checkbox options on same page. below is the code.

<input type="checkbox" th:field="*{borrowerRace1}"  th:value="1"  th:text="borrower1" />

 <input type="checkbox" th:field="*{borrowerRace1}"  th:value="2"  th:text="borrower2" />

   <input type="checkbox" th:field="*{borrowerRace1}"  th:value="3"  th:text="borrower3" />

          <input type="checkbox" th:field="*{borrowerRace1}"  th:value="4" th:text="borrower4" />

  <input type="checkbox" th:field="*{borrowerEthnicity1}"  th:value="1" th:text="Ethnicity1" />

         <input type="checkbox" th:field="*{borrowerEthnicity2}"  th:value="2" th:text="Ethnicity2" />

 <input type="checkbox" th:field="*{borrowerEthnicity3}"  th:value="3"  th:text="Ethnicity3" />

 <input type="checkbox" th:field="*{borrowerEthnicity4}"  th:value="4" th:text="Ethnicity4" />

Now,

User can select first 3 check boxes but clicking the 4th (last) one should
select the 4th (last) one and deselect all other of the set. Same should
happen for all checkbox sets.

Example : User can select A,B,C checkbox at a same time but when he checks D
all the above selected checkboxes should get unselected. Similarly for E,F,G
and H. I hope I am clear now.

Please help me on this. I hope I am clear, if not please do let me know

Body:
The below code section should work according to your requirement

$(document).ready(function() {
  $('.checkbox1').on('click', function() {
   var last_chekbox1 = $('.checkbox1:last');
   if (last_chekbox1.is(':checked')) {
     $('.checkbox1').prop('checked', false);
      $(this).prop('checked', true);
    }
  });
  $('.checkbox2').on('click', function(e) {
   var last_chekbox2 = $('.checkbox2:last');
   if (last_chekbox2.is(':checked')) {
      $('.checkbox2').prop('checked', false);
      $(this).prop('checked', true);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="1" th:text="borrower1" class="checkbox1" /> A
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="2" th:text="borrower2" class="checkbox1" /> B
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="3" th:text="borrower3" class="checkbox1" /> C
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerRace1}" th:value="4" th:text="borrower4" class="checkbox1" /> D
  </label>
</div>

<hr>

<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity1}" th:value="1" th:text="Ethnicity1" class="checkbox2" /> E
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity2}" th:value="2" th:text="Ethnicity2" class="checkbox2" /> F
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity3}" th:value="3" th:text="Ethnicity3" class="checkbox2" /> G
  </label>
</div>
<div class="col-xs-12">
  <label class="checkbox-inline">
    <input type="checkbox" th:field="*{borrowerEthnicity4}" th:value="4" th:text="Ethnicity4" class="checkbox2" /> H
  </label>
</div>


答:
To validate on the server side (at the time when the request is bound to the ViewModel), implement IValidatableObject:

```<code>using System.ComponentModel.DataAnnotations;

public class MyViewModel : IValidatableObject {

    // note that we do not have a [Required] attribute here,
    // or we would show two validation messages if one property is not set
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (string.IsNullOrWhiteSpace(FirstName) ||
            string.IsNullOrWhiteSpace(LastName)) {
                yield return new ValidationResult(
                  "Both first and last name are required!",
                   new[] { "FirstName", "LastName" }
               );
        }
    }
}
</code>```

The messages generated by this validation method can be rendered using @Html.ValidationSummary(). It will be shown after a round trip to the server on which validation failed.

You can test whether the model is valid in the controller by calling ModelState.IsValid.

ASP.NET MVC: Self Validating Model objects

Title: How to do multifield validation in MVC?

Body:
To validate on the server side (at the time when the request is bound to the ViewModel), implement IValidatableObject:

using System.ComponentModel.DataAnnotations;

public class MyViewModel : IValidatableObject {

    // note that we do not have a [Required] attribute here,
    // or we would show two validation messages if one property is not set
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (string.IsNullOrWhiteSpace(FirstName) ||
            string.IsNullOrWhiteSpace(LastName)) {
                yield return new ValidationResult(
                  "Both first and last name are required!",
                   new[] { "FirstName", "LastName" }
               );
        }
    }
}

The messages generated by this validation method can be rendered using @Html.ValidationSummary(). It will be shown after a round trip to the server on which validation failed.

You can test whether the model is valid in the controller by calling ModelState.IsValid.

ASP.NET MVC: Self Validating Model objects


问:
Angular - ExpressionChangedAfterItHasBeenCheckedError on binding
I have one <input> field and one component which have a common model binded. I'm using ngOnChanges() in the component to check the value of that input, and also I'm changing the model binded to that input somewhere in this component.

Let say we binded date variable to the <input> and the component. The error occurs in that situation:

```<code>input field changed (also date changed)
--> ngOnChanges
--> new value of date doesn't fit requirements
--> change the date to something else
--> <input> emits the new date
--> ngOnChanges() triggered again
--> ExpressionChangedAfterItHasBeenCheckedError
</code>```

Here are parts of my code:

app.component.html:

```<code>...
<input [(ngModel)]="date">
<app-date-picker [date]="date" (dateUpdated)="setDate($event)"></app-date-picker>
...
</code>```

app.component.ts:

```<code>setDate(newDate: Date): void {
  this.date = newDate.toISOString().split('T')[0];
}
</code>```

date-picker.component.ts:

```<code>  ngOnChanges(changes: SimpleChanges): void {
    if (changes.date) ... // Do some checks
    if (invalidDate) {
       ...
       this.select(newDay);
    }
  }

  select(d: number): void {
    this.selectedYear = this.year;
    this.selectedMonth = this.month;
    this.selectedDay = this.day = d;
    this.dateUpdated.emit(new Date(this.year, this.month, this.day + 1));
  }
</code>```

答:
I solved it by changing the date with a timeout:</p>

```<code>ngOnChanges(changes: SimpleChanges): void {
  if (changes.date) ... // Do some checks
  if (invalidDate) {
     ...
     setTimeout(() => { select(newDay); }, 50);
  }
}
</code>```

Body:
I have one <input> field and one component which have a common model binded. I'm using ngOnChanges() in the component to check the value of that input, and also I'm changing the model binded to that input somewhere in this component.

Let say we binded date variable to the <input> and the component. The error occurs in that situation:

input field changed (also date changed)
--> ngOnChanges
--> new value of date doesn't fit requirements
--> change the date to something else
--> <input> emits the new date
--> ngOnChanges() triggered again
--> ExpressionChangedAfterItHasBeenCheckedError

Here are parts of my code:

app.component.html:

...
<input [(ngModel)]="date">
<app-date-picker [date]="date" (dateUpdated)="setDate($event)"></app-date-picker>
...

app.component.ts:

setDate(newDate: Date): void {
  this.date = newDate.toISOString().split('T')[0];
}

date-picker.component.ts:

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.date) ... // Do some checks
    if (invalidDate) {
       ...
       this.select(newDay);
    }
  }

  select(d: number): void {
    this.selectedYear = this.year;
    this.selectedMonth = this.month;
    this.selectedDay = this.day = d;
    this.dateUpdated.emit(new Date(this.year, this.month, this.day + 1));
  }

Body:
I solved it by changing the date with a timeout:

ngOnChanges(changes: SimpleChanges): void {
  if (changes.date) ... // Do some checks
  if (invalidDate) {
     ...
     setTimeout(() => { select(newDay); }, 50);
  }
}


问:
SQL Server Index Dependency
I'm considering dropping an index from a table in a SQL Server 2005 instance.  Is there a way that I can see which stored procedures might have statements that are dependent on that index?</p>

答:
First check if the indexes are being used at all, you can use the sys.dm_db_index_usage_stats DMV for that, check the user_scans and the user_seeks column

read this Use the sys.dm db index usage stats dmv to check if indexes are being used

OwnerDisplayName: Al Wild

Title: SQL Server Index Dependency

LastEditorDisplayName: kristof

OwnerDisplayName: SQLMenace


问:
Can't overwrite file in docker compose
I'm using docker compose to set up a payara server and need to overwrite the domain.xml file. I'm currently doing it through

volumes:
   - './domain.xml:/opt/payara41/glassfish/domains/domain1/config/domain.xml'

but when i compose it with docker-compose up it keeps saying that it could not rename domain.xml to domain.xml.bak. Is there any way i can get permissions to overwrite it or make sure the rename works ?

答:
Something like this should work:

```<code>command: sh -c 'cp /tmp/domain.xml /opt/payara41/glassfish/domains/domain1/config/domain.xml && YOUR_PREVIOUS_COMMAND'
volumes:
   - ./domain.xml:/tmp/domain.xml
</code>```

Or edit your current command (or CMD) if it's a script, prepending the copy.

Edit: This alternative is very handy and elegant.

```<code>command: sh /run-from-compose.sh
volumes:
   - ./domain.xml:/tmp/domain.xml
   - ./run-from-compose.sh:/run-from-compose.sh
</code>```

run-from-compose.sh:

```<code>#!/bin/sh
cp /tmp/domain.xml /opt/payara41/glassfish/domains/domain1/config/domain.xml

YOUR_PREVIOUS_COMMAND
</code>```

You don't need to modify the image, just mount a custom script that acts as command.

Title: Can't overwrite file in docker compose

Body:
Something like this should work:

command: sh -c 'cp /tmp/domain.xml /opt/payara41/glassfish/domains/domain1/config/domain.xml && YOUR_PREVIOUS_COMMAND'
volumes:
   - ./domain.xml:/tmp/domain.xml

Or edit your current command (or CMD) if it's a script, prepending the copy.

Edit: This alternative is very handy and elegant.

command: sh /run-from-compose.sh
volumes:
   - ./domain.xml:/tmp/domain.xml
   - ./run-from-compose.sh:/run-from-compose.sh

run-from-compose.sh:

#!/bin/sh
cp /tmp/domain.xml /opt/payara41/glassfish/domains/domain1/config/domain.xml

YOUR_PREVIOUS_COMMAND

You don't need to modify the image, just mount a custom script that acts as command.


问:
Giving border to
 of table in a table
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

```<code><table>

    <tr>
        <td>A</td>
    </tr>

    <tr>
        <td>
           <table class="t_border">
              <tr>
                 <td>B</td>
              </tr>
        </td>
    </tr>
</tbody>
</code>```

答:
You can try as per my code:

```<code><style>
    table{
         border-collapse: collapse;
    }
    table.t_border tr{
         border:solid 1px red;
    }
</style>

  <table>
        <tr>
            <td>A</td>
        </tr>
        <tr>
            <td>
               <table class="t_border">
                  <tr>
                     <td>B</td><td>B</td><td>B</td>
                  </tr>
                  </table>
            </td>
        </tr>
    </table>
</code>```

Hope it might help you!

Title: Giving border to <tr> of table in a table

Body:
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

        A

                 B

Body:
You can try as per my code:

<style>
    table{
         border-collapse: collapse;
    }
    table.t_border tr{
         border:solid 1px red;
    }
</style>

  <table>
        <tr>
            <td>A</td>
        </tr>
        <tr>
            <td>
               <table class="t_border">
                  <tr>
                     <td>B</td><td>B</td><td>B</td>
                  </tr>
                  </table>
            </td>
        </tr>
    </table>

Hope it might help you!


问:
Using Selenium on https web application that runs over vpn
First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.

My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.

My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.

If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!

```<code>public static void main(String[] args) {
    System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
    // I tried also with this code bellow in comment, but it did not work, it did not even get to login page
    //WebDriverWait wait = new WebDriverWait(driver, 10);
    //Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    //alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
    driver.get("https://Application_login_page.com");
    driver.findElement(By.xpath(".//*[@id='login']")).click();
    driver.findElement(By.xpath("[@id='login']")).sendKeys("Username");
</code>```

}

答:
There is no way to open already authorised page, you have to have to pass username and password through selenium script.

You may use below code to do the authentication

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));
</code>```

Body:
First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.

My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.

My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.

If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!

public static void main(String[] args) {
    System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
    // I tried also with this code bellow in comment, but it did not work, it did not even get to login page
    //WebDriverWait wait = new WebDriverWait(driver, 10);
    //Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    //alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
    driver.get("https://Application_login_page.com");
    driver.findElement(By.xpath(".//*[@id='login']")).click();
    driver.findElement(By.xpath("[@id='login']")).sendKeys("Username");

}

Body:
There is no way to open already authorised page, you have to have to pass username and password through selenium script.

You may use below code to do the authentication

WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));


问:
Creating an extension method in C#
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}
</code>```

First time that this happens to me when programming in C#. Anyone else encounter this problem?

答:
According to MSDN:

Extensions to the HtmlHelper class are
  located in the System.Web.Mvc.Html
  namespace. These extensions add helper
  methods for creating forms, rendering
  HTML controls, rendering partial
  views, input validation, and more.

Trying including the System.Web.Mvc.Html namespace. LinkExtensions.RouteLink gives its namespace as that (it says it's in System.Web.Mvc.dll, just in a different namespace).

OwnerDisplayName: delete

Title: Creating an extension method in C#

Body:
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}

First time that this happens to me when programming in C#. Anyone else encounter this problem?


问:
Send Messages without reload page using ajax in laravel
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

```<code><form action="{{action('MessageController@sendmessagereply')}}" method="post">
            <div class="panel-footer">
                <div class="input-group">
                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />
                    <span class="input-group-btn">
                       <button class="btn btn-info" type="submit">SEND</button>
                    </span>
                </div>
            </div>
          </form>
</code>```

Controller file

```<code> public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }
</code>```

Route file

```<code>Route::any('messageschat/{id}','MessageController@messageschat');
</code>```

Javascript file

```<code><script>
$("#add").click(function() {

    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});
    </script>
</code>```

答:
You need to make sure your form is not submitted. This can be one by using preventDefault() or returning false. Also I prefer to use submit() as callback on submitting a form.

```<code>$('form').submit(function (e) {
    e.preventDefault(); // prevent default behaviour

    ...

    return false; // return false to be sure
});
</code>```

Also I should enable "preserve log" in your console to see all errors before the page refreshes.

Body:
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

<form action="{{action('MessageController@sendmessagereply')}}" method="post">

                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />

                       <button class="btn btn-info" type="submit">SEND</button>

          </form>

Controller file

 public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }

Route file

Route::any('messageschat/{id}','MessageController@messageschat');

Javascript file

Body:
You need to make sure your form is not submitted. This can be one by using preventDefault() or returning false. Also I prefer to use submit() as callback on submitting a form.

$('form').submit(function (e) {
    e.preventDefault(); // prevent default behaviour

    ...

    return false; // return false to be sure
});

Also I should enable "preserve log" in your console to see all errors before the page refreshes.


问:
Dynamiclly append different class with increment numereic value by click event
I have a span tag and a button tag

```<code><span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
</code>```

I want to append more span tag with new class from  this array with increment value by clicking button.
Like this output:

```<code><span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
</code>```

i  try `
this JsFiddle

But i can not add class name to new append tag from array.

Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here

value increaseesenter code here this snippet

    <button onclick="buttonClick();">Click Me</button>    <input type="text" id="inc" value="0"></input>```
</div>
</div>
</p>

<p>another attempt...anyone can help.. to get desire output</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;

$("#add").click( function() {
(i < elements.length){

  $(".new-field").append('<span class="myspan">1</span><script');
    var value = parseInt($(".myspan").text(), 10) + 1;
    elements[i].className += ' ' + backgrounds[i%len];
    i++;
    $(".background").text(i);
    }
});</code>```

*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="myspan">1</span>

<button id="add">Add +1</button>
<div class="new-field">

</div></code>```

Body:
I have a span tag and a button tag

1
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}

I want to append more span tag with new class from  this array with increment value by clicking button.
Like this output:

1
2
3
4

i  try `
this JsFiddle

But i can not add class name to new append tag from array.

Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here

value increaseesenter code here this snippet

    <button onclick="buttonClick();">Click Me</button>    <input type="text" id="inc" value="0"></input>

another attempt...anyone can help.. to get desire output

var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;

$("#add").click( function() {
(i < elements.length){

  $(".new-field").append('1

Body: <script>    var i = 0;    function buttonClick()    {i++;     document.getElementById('inc').value = i;    }    </script>    <button onclick="buttonClick();">Click Me</button>    <input type="text" id="inc" value="0"></input>


问:
getScript Local Load Instead of Global?
From what I have read JQuery's getScript function loads the script file in a global context using a function called 'global eval'. Is there a particular setting or method to change this so it will instead load within the function I am calling it from?

If I do the following code name returns undefined as its not loading the script in the local context.

```<code>    function callscript(){
        var name='fred';
    getScript(abc.js);
    }

//abc.js:
alert(name);
</code>```

答:
Ok i know this is 2017, 4 years later, but it seems jQuery team never bothered to address this issue, well sort of. I had the same problem and i think this is the solution, the actual intended way of using getScript in a local context. What I noticed was that there is no way that code could be easily eval'd in a local context against your code, which jQuery has no idea how it is going. I haven't gone deeper, but if you look at the jQuery source, how it is injecting the script into the document, it's genius, it avoids eval altogether. The script it therefore ran as if it's a file that was imported through script tag. Without further ado...

I have decided to do the vice-versa of the situation, it better explains what's going on. You can then reverse it to that example in question.

If you noticed getScript actually sends a unique ID to the server in the query string. I don't know why they didn't mention this in documentation. Use that to identify returned scripts. But you have to do something in the backend...

```<code>let imports;

$.getScript("scripts.php?file=abc.js", (data, textStatus, jqXHR) => {
    window[jqXHR.getResponseHeader('X-scriptID')](imports);
    alert (imports.name);
});
</code>```

abc.js:

```<code>imports.name = 'fred';
</code>```

backend wraps whatever script we are getting scripts.php:

```<code>// code that gets the file from  file system into var $output
$output = file_get_contents($_REQUEST['file']);

// generate a unique script function name, sort of a namespace
$scriptID = "__script" . $_REQUEST['_'];

// wrap the script in a function a pass the imports variable
// (remember it was defined in js before this request) we will attach
// things we want to become local on to this object in script file
$output = "window.".$scriptID."=function(imports) { ".$output." };";

// set the script id so we can find this script in js
header ("X-scriptID: " . $scriptID);

// return the output
echo $output;
</code>```

What going is that the js requests a script through getScript, but it doesn't request directly to the file it uses a php script to fetch the contents of the file. I am doing this so that i can modify the returned data and attach headers that are used to id the returned script (this is large app in mind here where a lot of scripts are requested this way).

When getScript runs the returned script in the browser as usual, the actual content of the script are not ran, just a declaration of the wrapper function with a unique name __script1237863498 or something like (the number was given by getScript upon requisition of that script earlier), attached to the global window object.
Then js uses that response to run the wrapper function and inject properties into the imports object... which become local to the requesting whatever's scope.

Title: getScript Local Load Instead of Global?

Body:
From what I have read JQuery's getScript function loads the script file in a global context using a function called 'global eval'. Is there a particular setting or method to change this so it will instead load within the function I am calling it from?

If I do the following code name returns undefined as its not loading the script in the local context.

    function callscript(){
        var name='fred';
    getScript(abc.js);
    }

//abc.js:
alert(name);

Body:
Ok i know this is 2017, 4 years later, but it seems jQuery team never bothered to address this issue, well sort of. I had the same problem and i think this is the solution, the actual intended way of using getScript in a local context. What I noticed was that there is no way that code could be easily eval'd in a local context against your code, which jQuery has no idea how it is going. I haven't gone deeper, but if you look at the jQuery source, how it is injecting the script into the document, it's genius, it avoids eval altogether. The script it therefore ran as if it's a file that was imported through script tag. Without further ado...

I have decided to do the vice-versa of the situation, it better explains what's going on. You can then reverse it to that example in question.

If you noticed getScript actually sends a unique ID to the server in the query string. I don't know why they didn't mention this in documentation. Use that to identify returned scripts. But you have to do something in the backend...

let imports;

$.getScript("scripts.php?file=abc.js", (data, textStatus, jqXHR) => {
    window[jqXHR.getResponseHeader('X-scriptID')](imports);
    alert (imports.name);
});

abc.js:

imports.name = 'fred';

backend wraps whatever script we are getting scripts.php:

// code that gets the file from  file system into var $output
$output = file_get_contents($_REQUEST['file']);

// generate a unique script function name, sort of a namespace
$scriptID = "__script" . $_REQUEST['_'];

// wrap the script in a function a pass the imports variable
// (remember it was defined in js before this request) we will attach
// things we want to become local on to this object in script file
$output = "window.".$scriptID."=function(imports) { ".$output." };";

// set the script id so we can find this script in js
header ("X-scriptID: " . $scriptID);

// return the output
echo $output;

What going is that the js requests a script through getScript, but it doesn't request directly to the file it uses a php script to fetch the contents of the file. I am doing this so that i can modify the returned data and attach headers that are used to id the returned script (this is large app in mind here where a lot of scripts are requested this way).

When getScript runs the returned script in the browser as usual, the actual content of the script are not ran, just a declaration of the wrapper function with a unique name __script1237863498 or something like (the number was given by getScript upon requisition of that script earlier), attached to the global window object.
Then js uses that response to run the wrapper function and inject properties into the imports object... which become local to the requesting whatever's scope.


问:
Issue with attempting to replace odd characters with 'é'
Is there any problem with this update I am trying to run? When I run it, it says the relevant amount of rows have been updated but nothing actually changes:

```<code>BEGIN TRAN
UPDATE a
SET a.name = REPLACE(a.name, 'Ã©', 'é')
FROM table1 a
JOIN table2 b
ON a.userID = b.userID

--ROLLBACK
--COMMIT
</code>```

I am wondering if SQL Management Studio is not able to read the characters perhaps? I have seen nothing online to confirm this however.

答:
```<code>SELECT REPLACE(a.name, 'Ã©', 'é') AS name
INTO temp_new
FROM table1 a
JOIN table2 b ON a.userID = b.userID
</code>```

I then just ran this update which has resolved

```<code>BEGIN TRAN
UPDATE a
SET a.name = tmp.name
FROM table1 a
JOIN temp_new tmp
ON a.userID = tmp.userID

--ROLLBACK
--COMMIT
</code>```

Body:
Is there any problem with this update I am trying to run? When I run it, it says the relevant amount of rows have been updated but nothing actually changes:

BEGIN TRAN
UPDATE a
SET a.name = REPLACE(a.name, 'Ã©', 'é')
FROM table1 a
JOIN table2 b
ON a.userID = b.userID

--ROLLBACK
--COMMIT

I am wondering if SQL Management Studio is not able to read the characters perhaps? I have seen nothing online to confirm this however.

Body:
SELECT REPLACE(a.name, 'Ã©', 'é') AS name
INTO temp_new
FROM table1 a
JOIN table2 b ON a.userID = b.userID

I then just ran this update which has resolved

BEGIN TRAN
UPDATE a
SET a.name = tmp.name
FROM table1 a
JOIN temp_new tmp
ON a.userID = tmp.userID

--ROLLBACK
--COMMIT


问:
How the last line of following recursive program is working?
I was studying Linked List and then I found a code for reversing the Linked List recursively. Here is the C++ code.

```<code>void recursiveReverse(node*& head)
{
  node* first;
  node* rest;

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

  recursiveReverse(rest);
  first->next->next  = first;
  first->next  = NULL;

/* fix the head pointer */
  head = rest;
}
</code>```

I understood the whole code except the last line. Because according to me, the rest pointer is also updated similarly as the first pointer during unwinding of the recursion and therefore, at the end of this code, the head will not point to the last node.

Here's my interpretation of the following code.

Let's take a Linked List 1 -> 2 -> 3.

Initially, first will store the address of the head node and rest
will contain the address of the node 2.

Now, since rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 2 and rest will point to node 3.

Again, rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 3 and rest will contain NULL.

After that, the recursion will start unwinding and first will be back to node 2 and the rest will be back to node 3.

Now, the statement first -> next -> next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL and since head = rest, therefore, head will also point to last node as the rest pointer.

After that, first will point to node 1 and the statement first -> next -> next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2.

Can anyone please explain where I am wrong in interpreting this code?

答:
Maybe there are other misinterpretations, but I assume that the basic one concerns your interpretation "the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2".

At the end, head will point to the last node of the initial list. Let's consider a simplified/shortened portion of your code:

```<code>rest  = head->next;

if (rest == NULL)  // end of list reached; head points tho the last node
   return;

recursiveReverse(rest);  // if the end is not reached, go forward with the next node (i.e. the value of head->next

head = rest;    // reset head to the (shared) value of rest.
</code>```

This is because statement recursiveReverse(rest) will be called again and again until head->next will be NULL, i.e. the end of the list is reached. The very last run of recursiveReverse returns because head->next == NULL, and in the caller, variable rest points to the last node.
Now note that "rest" is shared among all the calls to recursiveReverse, as it is passed by reference. So statement head = rest will be called for every instance of recursiveReverse called so far, but - as rest is shared among all the calls and is not changed after the recursive calls - statement head = rest will assign the head always to the same value of rest, which remains the one pointing to the last node.

Puh - hope this is comprehensive.

Anyway, doing recursive functions with parameters passed by reference is usually hard to understand; Typically things become easier when recursive functions manage their private states but use the return value to coordinate the results. If you arrange the code such that you have node* reverseRecursive(node *current), your code will become easier to understand.

Body:
I was studying Linked List and then I found a code for reversing the Linked List recursively. Here is the C++ code.

void recursiveReverse(node*& head)
{
  node* first;
  node* rest;

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

  recursiveReverse(rest);
  first->next->next  = first;
  first->next  = NULL;

/* fix the head pointer */
  head = rest;
}

I understood the whole code except the last line. Because according to me, the rest pointer is also updated similarly as the first pointer during unwinding of the recursion and therefore, at the end of this code, the head will not point to the last node.

Here's my interpretation of the following code.

Let's take a Linked List 1 -> 2 -> 3.

Initially, first will store the address of the head node and rest
will contain the address of the node 2.

Now, since rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 2 and rest will point to node 3.

Again, rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 3 and rest will contain NULL.

After that, the recursion will start unwinding and first will be back to node 2 and the rest will be back to node 3.

Now, the statement first -> next -> next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL and since head = rest, therefore, head will also point to last node as the rest pointer.

After that, first will point to node 1 and the statement first -> next -> next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2.

Can anyone please explain where I am wrong in interpreting this code?

Body:
Maybe there are other misinterpretations, but I assume that the basic one concerns your interpretation "the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2".

At the end, head will point to the last node of the initial list. Let's consider a simplified/shortened portion of your code:

rest  = head->next;

if (rest == NULL)  // end of list reached; head points tho the last node
   return;

recursiveReverse(rest);  // if the end is not reached, go forward with the next node (i.e. the value of head->next

head = rest;    // reset head to the (shared) value of rest.

This is because statement recursiveReverse(rest) will be called again and again until head->next will be NULL, i.e. the end of the list is reached. The very last run of recursiveReverse returns because head->next == NULL, and in the caller, variable rest points to the last node.
Now note that "rest" is shared among all the calls to recursiveReverse, as it is passed by reference. So statement head = rest will be called for every instance of recursiveReverse called so far, but - as rest is shared among all the calls and is not changed after the recursive calls - statement head = rest will assign the head always to the same value of rest, which remains the one pointing to the last node.

Puh - hope this is comprehensive.

Anyway, doing recursive functions with parameters passed by reference is usually hard to understand; Typically things become easier when recursive functions manage their private states but use the return value to coordinate the results. If you arrange the code such that you have node* reverseRecursive(node *current), your code will become easier to understand.


问:
XPATH - Find element where child items h3 text has a specific value

I need to find the selected DIV using a 'Employment' text for h3 tag.

I can find it using the following XPATH:

```<code>.//div[table[tbody[tr[td[h3[text() = 'Employment']]]]]]/following-sibling::div[@class = 'pbBody']
</code>```

But this is too big and ugly, what is the good way? something like:

parent::div[h3]following-sibling::div, so without this [table[tbody[tr[td[

HTML text:

Employment

```

答:
The most simple locator:

```<code>//div[@class="pbBody"][.//h3[text()='Employment']
</code>```

but better to use "contains", as usually classes could be added to element

```<code>//div[contains(@class, "pbBody")][.//h3[text()='Employment']
</code>```

And last one is similar to @Andersson 's, but corrected (as you need not following element, but ancestor):

```<code>//h3[.="Employment"]/ancestor::div[@class="pbBody"]
</code>```

Body:
I need to find the selected DIV using a 'Employment' text for h3 tag.

I can find it using the following XPATH:

.//div[table[tbody[tr[td[h3[text() = 'Employment']]]]]]/following-sibling::div[@class = 'pbBody']

But this is too big and ugly, what is the good way? something like:

parent::div[h3]following-sibling::div, so without this [table[tbody[tr[td[

HTML text:

Employment

Body:
The most simple locator:

//div[@class="pbBody"][.//h3[text()='Employment']

but better to use "contains", as usually classes could be added to element

//div[contains(@class, "pbBody")][.//h3[text()='Employment']

And last one is similar to @Andersson 's, but corrected (as you need not following element, but ancestor):

//h3[.="Employment"]/ancestor::div[@class="pbBody"]