问:
Gathering credit card information, security?
We have created a portal for users to pay online via our website.

We have created an option for user to check a "checkbox" to save their details to their account so they can pay easily next time.

What is the best way to save credit card details to a mySQL database? I want it to be secure, I don't want to purely save their details to a field as "XXXXXXXXXXXXXXXX".

What is the most secure way to save credit card details? We will have SSL on our server when the site goes live.

Regards

答:
Review the pci requirements as linked to by Mark B.

In one of my recent contracts I worked with a government department, although I didn't have anything to do with the pci compliance I do know it cost in excess of $1M. You certainly won't need to spend that much. but take it as a warning.

If you are operating on a shared platform I can only re-iterate what others have said and say don't store it for re-use. In fact on a shared platform it may not be wise to collect payments at all, regardless of the storing of card details.

At the very least you need a VM, if not a dedicated box behind a firewall, the database should be on a separate server which is firewalled and only used for the database.

Never forget your hosting provider can get access to the box, one bad staff member and you are in trouble. or at least your cardholders are and if they can trace it back to you and you should always admit to a breach then you are in trouble.

If you must. Then store everything else but get the user to enter the credit card each time. don't forget that expiry dates change. so you will need to let the user update that anyway so why not get the whole number again.

Your customers would probably look on you more kindly if you stipulated "Card Details Not Stored"

DC


来源: stackexchange

问:
How to return an empty list in python
I am trying to call a function that will empty two lists that i send as arguments.
How do i go about emptying the lists within the function and making sure they are empty once the code comes to reuse them in the original function in Python? Below is the code i am using as a test run for a larger system.</p>

```<code>def Input():
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        ErrorInput(1, nextRound, maleNames )
        # I want the below to print two empty strings
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):

    if error == 1:
        print('ERROR: You have entered a number above what is impossible to
        score')
        namelist = []
        round = []
    elif error == 2:
        print('ERROR: You Have entered a score meaning both players win')
        namelist = []
        round = []
    elif error == 3:
        print('ERROR: You have entered a score meaning neither of the two
        players win')
        namelist = []
        round = []
    elif error == 4:
        print('EEROR: You have entered a negative number, this is
        impossible')
        namelist = []
        round = []

    return(namelist, round)

Input()
</code>```

答:
Here, I took the liberty to tidy up the code.

```<code>def start():  # don't use the name input()
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        nextRound, maleNames = ErrorInput(1, nextRound, maleNames)  # if you want nextRound, maleNames to be [] you have to assign it to them
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):
    error_codes = {1: 'ERROR: You have entered a number above what is impossible to score', 2: 'ERROR: You Have entered a score meaning both players win',3: 'ERROR: You have entered a score meaning neither of the two players win', 4: 'ERROR: You have entered a negative number, this is impossible'}  # too many ifs makes one wonder if a dictionary is the way to go
    print(error_codes.get(error, 'Unknown Error'))
    return([], [])  # return the empty lists.

start()
</code>```

Not sure why you go to such lengths to just get [], [] but whatever floats your boat.

Take a look at the notes on the code to get a better feeling of why I made the changes.

ContentLicense: CC BY-SA 3.0

Title: How to return an empty list in python

Body:
I am trying to call a function that will empty two lists that i send as arguments.
How do i go about emptying the lists within the function and making sure they are empty once the code comes to reuse them in the original function in Python? Below is the code i am using as a test run for a larger system.

def Input():
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        ErrorInput(1, nextRound, maleNames )
        # I want the below to print two empty strings
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):

    if error == 1:
        print('ERROR: You have entered a number above what is impossible to
        score')
        namelist = []
        round = []
    elif error == 2:
        print('ERROR: You Have entered a score meaning both players win')
        namelist = []
        round = []
    elif error == 3:
        print('ERROR: You have entered a score meaning neither of the two
        players win')
        namelist = []
        round = []
    elif error == 4:
        print('EEROR: You have entered a negative number, this is
        impossible')
        namelist = []
        round = []

    return(namelist, round)

Input()

Body:
Here, I took the liberty to tidy up the code.

def start():  # don't use the name input()
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        nextRound, maleNames = ErrorInput(1, nextRound, maleNames)  # if you want nextRound, maleNames to be [] you have to assign it to them
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):
    error_codes = {1: 'ERROR: You have entered a number above what is impossible to score', 2: 'ERROR: You Have entered a score meaning both players win',3: 'ERROR: You have entered a score meaning neither of the two players win', 4: 'ERROR: You have entered a negative number, this is impossible'}  # too many ifs makes one wonder if a dictionary is the way to go
    print(error_codes.get(error, 'Unknown Error'))
    return([], [])  # return the empty lists.

start()

Not sure why you go to such lengths to just get [], [] but whatever floats your boat.

Take a look at the notes on the code to get a better feeling of why I made the changes.


问:
Pushing onto Mongo SubDoc of SubDoc array
I'm going around in circles with this one so hoping someone can help. I'm building a nodejs application that receives sensor values from nodes. There can be multiple sensors on a node.

Using NodeJS, Mongod DB and Mongoose, all running on a raspberry pi, 3 I've built the following Schemas & Model:

```<code>var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var valueSchema = new Schema ({
  timestamp: {type: Date},
  value: {}
});

var sensorSchema = new Schema ({
  id: {type: Number},
  type: {type: String},
  description: {type: String},
  ack: {type: Boolean},
  values: [valueSchema]
});

var SensorNode = mongoose.model('SensorNode', {
  id: {type: Number, required: true},
  protocol: {},
  sensors: [sensorSchema]
});
</code>```

I can add in the node, and push sensors onto the sensors array, but I seem unable to push values onto the values array.

I've looked over a few other examples and questions on similar issues, and looked at using populate, but cant seem to get them to work.

Here is my code:

```<code>function saveValue(rsender, rsensor, payload) {

  var value = {
    values: {
      timestamp: new Date().getTime(),
      value: payload
    }
  }

  SensorNode.findOneAndUpdate({

    "id": rsender,
    "sensors.id": rsensor
  }, {
    "$push": {
      "sensors.$": value
    }
  }, function(err, result) {

    if (err) {
      console.log(err);
    }
    console.log(result);
  });

}
</code>```

This is returning undefined for the result and this error:

```<code>MongoError: exception: Cannot apply $push/$pushAll modifier to non-array
</code>```

Values is definitely an array in the sensor schema.

I'm using readable ids rather than the auto assigned Mongo DB IDs for the sake of the UI, but I could use the MongoDB _id if that makes any difference, I don't see why it would?

Where am I going wrong ?

答:
You're using positional operator $ so let's check the docs

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array. To project, or return, an array element from a read operation, see the $ projection operator.

So sensors.$ will return one particular document from your sensors array. That's why you're getting an error. On this level of your document you can only replace this item by using $set. I bet you wanted to do something like this:

```<code>SensorNode.findOneAndUpdate({

    "id": rsender,
    "sensors.id": rsensor
  }, {
    "$push": {
      "sensors.$.values": payload
    }
  });
</code>```

This operation will just append payload to values array in one particular sensor with id equal to rsensor.

Body:
I'm going around in circles with this one so hoping someone can help. I'm building a nodejs application that receives sensor values from nodes. There can be multiple sensors on a node.

Using NodeJS, Mongod DB and Mongoose, all running on a raspberry pi, 3 I've built the following Schemas & Model:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var valueSchema = new Schema ({
  timestamp: {type: Date},
  value: {}
});

var sensorSchema = new Schema ({
  id: {type: Number},
  type: {type: String},
  description: {type: String},
  ack: {type: Boolean},
  values: [valueSchema]
});

var SensorNode = mongoose.model('SensorNode', {
  id: {type: Number, required: true},
  protocol: {},
  sensors: [sensorSchema]
});

I can add in the node, and push sensors onto the sensors array, but I seem unable to push values onto the values array.

I've looked over a few other examples and questions on similar issues, and looked at using populate, but cant seem to get them to work.

Here is my code:

function saveValue(rsender, rsensor, payload) {

  var value = {
    values: {
      timestamp: new Date().getTime(),
      value: payload
    }
  }

  SensorNode.findOneAndUpdate({

    "id": rsender,
    "sensors.id": rsensor
  }, {
    "$push": {
      "sensors.$": value
    }
  }, function(err, result) {

    if (err) {
      console.log(err);
    }
    console.log(result);
  });

}

This is returning undefined for the result and this error:

MongoError: exception: Cannot apply $push/$pushAll modifier to non-array

Values is definitely an array in the sensor schema.

I'm using readable ids rather than the auto assigned Mongo DB IDs for the sake of the UI, but I could use the MongoDB _id if that makes any difference, I don't see why it would?

Where am I going wrong ?

Body:
You're using positional operator $ so let's check the docs

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array. To project, or return, an array element from a read operation, see the $ projection operator.

So sensors.$ will return one particular document from your sensors array. That's why you're getting an error. On this level of your document you can only replace this item by using $set. I bet you wanted to do something like this:

SensorNode.findOneAndUpdate({

    "id": rsender,
    "sensors.id": rsensor
  }, {
    "$push": {
      "sensors.$.values": payload
    }
  });

This operation will just append payload to values array in one particular sensor with id equal to rsensor.


问:
Double click to edit node before rename with jstree
I have a jstree set up (on div id ="surveyManager"). And i have bound the dbclick and rename function to it as under:

```<code> .bind("rename.jstree", function (node, data) {
            edit_node(node,data);
}),

.bind("dblclick.jstree", function (event) {
            //Double Click to Rename
                    jQuery("#surveyManager").jstree("rename");
    })
</code>```

over here edit_node is a function that have to implement to pass all the node information thru an ajax call.

Is it possible to setup the tree, such that on dbclick, instead of renaming the node, i can just trigger the edit_node(node,data). Maybe another jstree function , or somewhereelse i could define it. Please help

答:
To anyone reading this answer.  I don't know if this answer worked on the old jstree or something but it didn't work for me.  I implemented click to Edit on this jsfiddle.

Here is the code that worked:

$('#jstree_demo_div2')
  // listen for event
  .on('select_node.jstree', function (e, data) {
    var node = data.instance.get_node(data.selected[0]);
    data.instance.edit(node);
});```

Body:
I have a jstree set up (on div id ="surveyManager"). And i have bound the dbclick and rename function to it as under:

 .bind("rename.jstree", function (node, data) {
            edit_node(node,data);
}),

.bind("dblclick.jstree", function (event) {
            //Double Click to Rename
                    jQuery("#surveyManager").jstree("rename");
    })

over here edit_node is a function that have to implement to pass all the node information thru an ajax call.

Is it possible to setup the tree, such that on dbclick, instead of renaming the node, i can just trigger the edit_node(node,data). Maybe another jstree function , or somewhereelse i could define it. Please help


问:
Most computationally efficient method to perform sumproduct for a very large dataframe in R
I have a very large dataframe (hundreds of columns and tens of thousands of rows) for which I would like to do the following:

on each row calculate weighted combinations of the elements on the column using given vector(s) of weights (some of the weights may be zero)

create a new dataframe with each of the columns containing the weighted combinations for the corresponding vector of weights

What would be the most computationally efficient way to do that?

Replicating simple example:

```<code>require(tidyverse)

theDatesTibble <-c(lubridate::mdy("3/15/2017"), lubridate::mdy("4/15/2017"), lubridate::mdy("5/15/2017"), lubridate::mdy("6/15/2017"))

theValuesTibble_A <- c(123.45, 201.29, 337.78, 275.98)
theValuesTibble_B <- c(113.45, 221.29, 327.78, 255.98)
theValuesTibble_C <- c(143.45, 251.29, 307.78, 235.98)
theValuesTibble_D <- c(153.45, 231.29, 347.78, 225.98)
theValuesTibble_E <- c(163.45, 291.29, 323.78, 215.98)

theTibble <- tibble(Dates= theDatesTibble, A = theValuesTibble_A, B = theValuesTibble_B,
                    C = theValuesTibble_C, D = theValuesTibble_D, E = theValuesTibble_E)

weights_1 <- c(2.3, 0.0, 3.6, 12.7, 8.9)
weights_2 <- c(0.0, 0.0, 13.6, 4.7, 0.0)
weights_3 <- c(6.3, 4.4, 8.6, 12.3, 18.9)
</code>```

答:
As @BenoitLondon mentioned, a matrix product would be the fastest way to do what you want.</p>

```<code>cbind.data.frame(
  theTibble[1],
  as.matrix(theTibble[-1]) %*% cbind(weights_1, weights_2, weights_3)
)
</code>```

Body:
I have a very large dataframe (hundreds of columns and tens of thousands of rows) for which I would like to do the following:

on each row calculate weighted combinations of the elements on the column using given vector(s) of weights (some of the weights may be zero)

create a new dataframe with each of the columns containing the weighted combinations for the corresponding vector of weights

What would be the most computationally efficient way to do that?

Replicating simple example:

require(tidyverse)

theDatesTibble <-c(lubridate::mdy("3/15/2017"), lubridate::mdy("4/15/2017"), lubridate::mdy("5/15/2017"), lubridate::mdy("6/15/2017"))

theValuesTibble_A <- c(123.45, 201.29, 337.78, 275.98)
theValuesTibble_B <- c(113.45, 221.29, 327.78, 255.98)
theValuesTibble_C <- c(143.45, 251.29, 307.78, 235.98)
theValuesTibble_D <- c(153.45, 231.29, 347.78, 225.98)
theValuesTibble_E <- c(163.45, 291.29, 323.78, 215.98)

theTibble <- tibble(Dates= theDatesTibble, A = theValuesTibble_A, B = theValuesTibble_B,
                    C = theValuesTibble_C, D = theValuesTibble_D, E = theValuesTibble_E)

weights_1 <- c(2.3, 0.0, 3.6, 12.7, 8.9)
weights_2 <- c(0.0, 0.0, 13.6, 4.7, 0.0)
weights_3 <- c(6.3, 4.4, 8.6, 12.3, 18.9)

Body:
As @BenoitLondon mentioned, a matrix product would be the fastest way to do what you want.

cbind.data.frame(
  theTibble[1],
  as.matrix(theTibble[-1]) %*% cbind(weights_1, weights_2, weights_3)
)


答: Use namelist.clear() to clear a list

Title: How to return an empty list in python

Body: Use namelist.clear() to clear a list


问:
How can I dynamically generate DOM elements using ReactJS?
I have array with thee values:

```<code>let elements = ["div", "span", "button"]
</code>```

How can I dynamically generate these elements in DOM using forEach or map  iterator in ReactJS?

So as output I want to have:

 Value1

 Value 2
<button> Click me! </button>
```

答:
Use createElement directly, rather than writing JSX (which does that under the hood):

const Test = (props) => {
    let elements = ["div", "span", "button"];
    return (

            {
                elements.map((el, index) =>
                    React.createElement(el, { key: index }, "hello"))
            }

    );
};

ReactDOM.render(<Test />, document.getElementById("app"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

From the docs:

```<code>React.createElement(type, [props], [...children])
</code>```

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), or a React component type (a class or a function).

ContentLicense: CC BY-SA 4.0

Body:
I have array with thee values:

let elements = ["div", "span", "button"]

How can I dynamically generate these elements in DOM using forEach or map  iterator in ReactJS?

So as output I want to have:

 Value1

 Value 2
<button> Click me! </button>

Body:
Use createElement directly, rather than writing JSX (which does that under the hood):

const Test = (props) => {
    let elements = ["div", "span", "button"];
    return (
        <div>
            {
                elements.map((el, index) =>
                    React.createElement(el, { key: index }, "hello"))
            }
        </div>
    );
};

ReactDOM.render(<Test />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

From the docs:

React.createElement(type, [props], [...children])

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), or a React component type (a class or a function).


问:
How to avoid duplicate file upload but keep the uploader unaware of it?
First of all, I apologize if the question is not clear, I'm explaining it below.

For every file uploaded, I'm renaming the file and recording the hash values (using sha1_files function, please suggest if there are some better or faster hashing techniques for the file in php) in a separate DB table and checking the hash of every new file to avoid duplicate files.

In this manner, the one uploading a duplicate file will get an error msg and the file won't be uploaded.

My question is, is there any techniques or algorithm by which I can prevent duplicate file upload but the duplicate file uploader will be unaware of it and will find the file in his/her account with a different name than the one already present. However, users won't be able to upload banned files by any means.

答:
Use an example like this to generate your sha1 hash client side before upload.

Save all your uploaded files with their hash as the filename, or have a database table which contains the hash and your local filename for each file, also save file size and content type.

Before upload submit hash from client side to your server and check for hash in database. If its not present then commence file upload. If present then fake the upload client side or whatever you want to do so the user thinks they have uploaded their file.

Create a column in your users table for files uploaded. Store a serialised associative array in this column with hash => users_file_name as key=>value pairs. Unserialize and display to each user to maintain their own file names then use readfile to serve them the file with the correct name, selecting it server side using the hash

As for your URL question. Create a page for the downloads but include the user in the url as well, so mysite.com/image.php?user=NewBee&image=filename.jpg

Query the database for files uploaded by NewBee and unserialize the array. Then:

```<code>$upload = $_GET['image'];
foreach($array as $hash => $filename){
        if($filename == $upload)
              $file = $hash;
    }
</code>```

Seach database for the path to your copy of that file, then using readfile you can output the same file with whatever namme you want.

```<code>header("Content-Description: File Transfer");
header("Content-type: {$contenttype}");
header("Content-Disposition: attachment; filename=\"{$filename}\"");
header("Content-Length: " . filesize($file));
header('Pragma: public');
header("Expires: 0");
readfile($file);
</code>```

Body:
Use an example like this to generate your sha1 hash client side before upload.

Save all your uploaded files with their hash as the filename, or have a database table which contains the hash and your local filename for each file, also save file size and content type.

Before upload submit hash from client side to your server and check for hash in database. If its not present then commence file upload. If present then fake the upload client side or whatever you want to do so the user thinks they have uploaded their file.

Create a column in your users table for files uploaded. Store a serialised associative array in this column with hash => users_file_name as key=>value pairs. Unserialize and display to each user to maintain their own file names then use readfile to serve them the file with the correct name, selecting it server side using the hash

As for your URL question. Create a page for the downloads but include the user in the url as well, so mysite.com/image.php?user=NewBee&image=filename.jpg

Query the database for files uploaded by NewBee and unserialize the array. Then:

$upload = $_GET['image'];
foreach($array as $hash => $filename){
        if($filename == $upload)
              $file = $hash;
    }

Seach database for the path to your copy of that file, then using readfile you can output the same file with whatever namme you want.

header("Content-Description: File Transfer");
header("Content-type: {$contenttype}");
header("Content-Disposition: attachment; filename=\"{$filename}\"");
header("Content-Length: " . filesize($file));
header('Pragma: public');
header("Expires: 0");
readfile($file);


问:
Virtual directory inside of ASP.NET Core app in IIS
We have an application using ASP.NET Core 1.0 RC1 and hosted on IIS. It works fine. Now we have static content, that is available on a file share and should be accessible from the application.

Before ASP.NET 5, we added a virtual directory in IIS and could access the shared content easily. With our hosted ASP.NET 5 application, this unfortunately doesn't seem to work. We just get a 404 back when trying to access the static content.

Our application is using app.UseIISPlatformHandler() and app.UseStaticFiles(), but this doesn't work. We discovered that we could use app.UseFileServer() with custom FileServerOptions to get the desired behavior, but we are curious if it's also possible with the normal "old" way of adding a virtual directory in IIS.

答:
I know its a question with 1,8 year, but if someone needs to resolve the same problem, try to use this:

```<code>public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}
</code>```

Is perfectly possible to change parameters of PhysicalFileProvider to any local or shared folder, and with this serve a file.

Doing that in this way is not SECURITY recommended. But, for study propose, its acceptable.

The static file module provides no
  authorization checks. Any files served by it, including those under
  wwwroot are publicly available. To serve files based on
  authorization: Store them outside of wwwroot and any directory
  accessible to the static file middleware and Serve them through a
  controller action, returning a FileResult where authorization is
  applied.

In Microsoft's Asp.Net documentations we can find more complete information to help with this issue.

Check this link: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files

Body:
I know its a question with 1,8 year, but if someone needs to resolve the same problem, try to use this:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}

Is perfectly possible to change parameters of PhysicalFileProvider to any local or shared folder, and with this serve a file.

Doing that in this way is not SECURITY recommended. But, for study propose, its acceptable.

The static file module provides no
  authorization checks. Any files served by it, including those under
  wwwroot are publicly available. To serve files based on
  authorization: Store them outside of wwwroot and any directory
  accessible to the static file middleware and Serve them through a
  controller action, returning a FileResult where authorization is
  applied.

In Microsoft's Asp.Net documentations we can find more complete information to help with this issue.

Check this link: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files


答:
As per the comment above, i don't follow your code.  But to iteratively empty a list try:</p>

```<code>while len(maleNames) !=0:
    popped = maleNames.pop()
    print('Popped value: ', popped, '\tNew list: ', maleNames)
</code>```

Title: How to return an empty list in python

Body:
As per the comment above, i don't follow your code.  But to iteratively empty a list try:

while len(maleNames) !=0:
    popped = maleNames.pop()
    print('Popped value: ', popped, '\tNew list: ', maleNames)


问:
How to add all of the migrations/ to git .gitignore file in django?
In my Django project, I have many migrations directory, I want to add to my .gitignore file:

Because they are under each app directory, I do not want to add every one.

How can I add all the migrations directories in it?

Now in it only like this:

```<code>.idea/
</code>```

答: You must not do this. Migrations are part of your code base, and must be committed and deployed with it.</p>

Body:
In my Django project, I have many migrations directory, I want to add to my .gitignore file:

Because they are under each app directory, I do not want to add every one.

How can I add all the migrations directories in it?

Now in it only like this:

.idea/


问:
Trouble with ASC
Hey I wanted to make it so that whenever I click button if textbox1  contains anything other than a number it will show me in the message box "You can only enter numbers"
I am having trouble figuring out how to properly use the Asc function</p>

```<code>   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    If Asc(TextBox1.Text) < 48 Or Asc(TextBox1.Text) > 57 Then
        TextBox1.Text = True
        MessageBox.Show("You can only enter numbers")

    End If
</code>```

答:
Even if you must use a TextBox, there's no need for the Asc function. Use Integer/Double.TryParse

```<code>' if you want to accept doubles
Dim numberDouble As Double
If Not Double.TryParse(TextBox1.Text, numberDouble) Then
    TextBox1.Text = True
    MessageBox.Show("You can only enter doubles")
End If

' if you want to accept integers
Dim numberInteger As Integer
If Not Integer.TryParse(TextBox1.Text, numberInteger) Then
    TextBox1.Text = True
    MessageBox.Show("You can only enter integers")
End If
</code>```

Better yet, use a NumericUpDown, which has all the validation built in.

```<code>Dim numberDecimal As Decimal = NumericUpDown1.Value
Dim numberDouble = Convert.ToDouble(NumericUpDown1.Value)
Dim numberInteger = Convert.ToInt32(NumericUpDown1.Value)
</code>```

Just set NumericUpDown.Maximum and NumericUpDown.Minumum, and NumericUpDown.DecimalPlaces before it's used (i.e. in the designer) and all the validation is taken care of.

Title: Trouble with ASC

Body:
Hey I wanted to make it so that whenever I click button if textbox1  contains anything other than a number it will show me in the message box "You can only enter numbers"
I am having trouble figuring out how to properly use the Asc function

   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    If Asc(TextBox1.Text) < 48 Or Asc(TextBox1.Text) > 57 Then
        TextBox1.Text = True
        MessageBox.Show("You can only enter numbers")

    End If

Body:
Even if you must use a TextBox, there's no need for the Asc function. Use Integer/Double.TryParse

' if you want to accept doubles
Dim numberDouble As Double
If Not Double.TryParse(TextBox1.Text, numberDouble) Then
    TextBox1.Text = True
    MessageBox.Show("You can only enter doubles")
End If

' if you want to accept integers
Dim numberInteger As Integer
If Not Integer.TryParse(TextBox1.Text, numberInteger) Then
    TextBox1.Text = True
    MessageBox.Show("You can only enter integers")
End If

Better yet, use a NumericUpDown, which has all the validation built in.

Dim numberDecimal As Decimal = NumericUpDown1.Value
Dim numberDouble = Convert.ToDouble(NumericUpDown1.Value)
Dim numberInteger = Convert.ToInt32(NumericUpDown1.Value)

Just set NumericUpDown.Maximum and NumericUpDown.Minumum, and NumericUpDown.DecimalPlaces before it's used (i.e. in the designer) and all the validation is taken care of.


问:
Selenium with Python -- finding element without proper identifiers
I am using selenium with python to write the code. I am looking to pull the information from a text box. The box auto fills as other information is being filled out. Inspecting the box gives the following code:

```<code><input type="tel" autocomplete="off" name="amount" step="any" class="form-
control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-not-empty"
placeholder="" tw-focusable="" show-decimals="$ctrl.showDecimals" tw-number-
input-formatter="" ng-change="$ctrl.changedAmount()" ng-
model="$ctrl.ngModel" ng-disabled="$ctrl.ngDisabled" disabled="disabled"
style="">
</code>```

The issue is that there is already another input box that has the name "amount", so I can't do a simple selection by name. I am thinking this would require me to use a CSS selector but everything I have tried so far has not worked. Please let me know what I can try.

答:
Looks like you need to use CSS or XPath locators.
Its hard to tell how exactly you can find that element since you haven't provided a source of the entire page but here are some tips.
In the worst case when you cant find any combination of attributes that will uniquely identify the element you need to rely on dom nodes hierarchy, i.e. in order to find first input on the following page:

```<code><!DOCTYPE html>
<html>

<head>
    <title>Dummy page</title>
</head>

<body>
    <div>
        <div>
            <input type="text">
        </div>
        <p>
            <input type="text">
        </p>
        <input type="text">
    </div>
</body>

</html>
</code>```

You can use XPath locator that might look similar to this one:

```<code>//div/div/input
</code>```

But that's the worst case, usually you can use more flexible locators based on element attributes that less likely to be affected by page structure modifications. Let's say each of our inputs from the page above has "name" and "disabled" attributes.

```<code><div>
    <div>
        <input name="input1" disabled="" type="text">
    </div>
    <p>
        <input name="input1" disabled="disabled" type="text">
    </p>
    <input name="input2" disabled="" type="text">
</div>
</code>```

Then we can find first input using the following locator:

```<code>//input[@name="input1" and @disabled=""]
</code>```

Hope that helps.

Body:
I am using selenium with python to write the code. I am looking to pull the information from a text box. The box auto fills as other information is being filled out. Inspecting the box gives the following code:

<input type="tel" autocomplete="off" name="amount" step="any" class="form-
control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-not-empty"
placeholder="" tw-focusable="" show-decimals="$ctrl.showDecimals" tw-number-
input-formatter="" ng-change="$ctrl.changedAmount()" ng-
model="$ctrl.ngModel" ng-disabled="$ctrl.ngDisabled" disabled="disabled"
style="">

The issue is that there is already another input box that has the name "amount", so I can't do a simple selection by name. I am thinking this would require me to use a CSS selector but everything I have tried so far has not worked. Please let me know what I can try.

Body:
Looks like you need to use CSS or XPath locators.
Its hard to tell how exactly you can find that element since you haven't provided a source of the entire page but here are some tips.
In the worst case when you cant find any combination of attributes that will uniquely identify the element you need to rely on dom nodes hierarchy, i.e. in order to find first input on the following page:

<!DOCTYPE html>
<html>

<head>
    <title>Dummy page</title>
</head>

<body>
    <div>
        <div>
            <input type="text">
        </div>
        <p>
            <input type="text">
        </p>
        <input type="text">
    </div>
</body>

</html>

You can use XPath locator that might look similar to this one:

//div/div/input

But that's the worst case, usually you can use more flexible locators based on element attributes that less likely to be affected by page structure modifications. Let's say each of our inputs from the page above has "name" and "disabled" attributes.

<div>
    <div>
        <input name="input1" disabled="" type="text">
    </div>
    <p>
        <input name="input1" disabled="disabled" type="text">
    </p>
    <input name="input2" disabled="" type="text">
</div>

Then we can find first input using the following locator:

//input[@name="input1" and @disabled=""]

Hope that helps.


问:
Change color of a word in html
I have a .html document that looks like this:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Change color</title>
  <style>
   .colortext {
     color: red;
   }
  </style>
 </head>
 <body>
  <p>bla bla lbla <span class="colortext">the</span>,
 the balfds of .</p>
 </body>
</html>
</code>```

In this document I give to the a red color. But how should I go in order to change color of every thein my huge text? Is there a way to change color in order not to write

for every word, I need?

答: Yes with only HTML and CSS that is the only way.</p>

Title: Change color of a word in html

Body:
I have a .html document that looks like this:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Change color</title>

bla bla lbla the,
 the balfds of .

In this document I give to the a red color. But how should I go in order to change color of every thein my huge text? Is there a way to change color in order not to write

for every word, I need?


问:
Get list of databases, tables, columns, and column datatypes
I would like to get a collection of all user databases, all the tables within each database, and columns and their datatypes for each of the tables. I have a SQL script that gets the database names I am looking for (and excludes those I am not, like system databases)...

```<code>DECLARE @DatabaseIgnoreList AS VARCHAR(500);
SET @DatabaseIgnoreList = 'DatabaseNotToInclude';

SELECT name, database_id
FROM sys.databases
WHERE HAS_DBACCESS(name) = 1
AND name NOT IN ('msdb')
AND database_id > 4
AND name NOT LIKE '%$%'
AND name NOT IN (@DatabaseIgnoreList)
ORDER BY name ASC
</code>```

I also have a separate SQL script that gets all the tables and columns from a specific database. I found this from this SO question/answer.

```<code>USE DatabaseName;
SELECT TABLE_SCHEMA ,
   TABLE_NAME ,
   COLUMN_NAME ,
   ORDINAL_POSITION ,
   COLUMN_DEFAULT ,
   DATA_TYPE ,
   CHARACTER_MAXIMUM_LENGTH ,
   NUMERIC_PRECISION ,
   NUMERIC_PRECISION_RADIX ,
   NUMERIC_SCALE ,
   DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS;
</code>```

What I am not sure how to do is to link the two. For each database I would like to run the table/column discover script and end up with one single table that has the database name, table name, column name, and column datatype.

Is this a situation for a cursor? I am using SQL Server 2008+.

答:
This is not the best way but it works</p>

```<code>  DECLARE @DatabaseIgnoreList AS VARCHAR(500);
  SET @DatabaseIgnoreList = 'DatabaseNotToInclude';

  SELECT name, database_id
  into #temporaltable
  FROM sys.databases
  WHERE HAS_DBACCESS(name) = 1
  AND name NOT IN ('msdb')
  AND database_id > 4
  AND name NOT LIKE '%$%'
  AND name NOT IN (@DatabaseIgnoreList)
  ORDER BY name ASC

declare
        @target varchar(250),
        @statement varchar(max)

declare @schemas as CURSOR;

set @schemas = CURSOR FOR

select name from #temporaltable;

open @schemas;

fetch next from @schemas INTO @target

while @@FETCH_STATUS = 0

begin

    set @statement = '
    use '+@target+'

   SELECT TABLE_SCHEMA ,
   TABLE_NAME ,
   COLUMN_NAME ,
   ORDINAL_POSITION ,
   COLUMN_DEFAULT ,
   DATA_TYPE ,
   CHARACTER_MAXIMUM_LENGTH ,
   NUMERIC_PRECISION ,
   NUMERIC_PRECISION_RADIX ,
   NUMERIC_SCALE ,
   DATETIME_PRECISION,
   TABLE_CATALOG
   FROM INFORMATION_SCHEMA.COLUMNS'

    EXEC (@statement)

fetch next from @schemas INTO @target
end

close @schemas;
deallocate @schemas

drop table #temporaltable
</code>```

Body:
I would like to get a collection of all user databases, all the tables within each database, and columns and their datatypes for each of the tables. I have a SQL script that gets the database names I am looking for (and excludes those I am not, like system databases)...

DECLARE @DatabaseIgnoreList AS VARCHAR(500);
SET @DatabaseIgnoreList = 'DatabaseNotToInclude';

SELECT name, database_id
FROM sys.databases
WHERE HAS_DBACCESS(name) = 1
AND name NOT IN ('msdb')
AND database_id > 4
AND name NOT LIKE '%$%'
AND name NOT IN (@DatabaseIgnoreList)
ORDER BY name ASC

I also have a separate SQL script that gets all the tables and columns from a specific database. I found this from this SO question/answer.

USE DatabaseName;
SELECT TABLE_SCHEMA ,
   TABLE_NAME ,
   COLUMN_NAME ,
   ORDINAL_POSITION ,
   COLUMN_DEFAULT ,
   DATA_TYPE ,
   CHARACTER_MAXIMUM_LENGTH ,
   NUMERIC_PRECISION ,
   NUMERIC_PRECISION_RADIX ,
   NUMERIC_SCALE ,
   DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS;

What I am not sure how to do is to link the two. For each database I would like to run the table/column discover script and end up with one single table that has the database name, table name, column name, and column datatype.

Is this a situation for a cursor? I am using SQL Server 2008+.

Body:
This is not the best way but it works

  DECLARE @DatabaseIgnoreList AS VARCHAR(500);
  SET @DatabaseIgnoreList = 'DatabaseNotToInclude';

  SELECT name, database_id
  into #temporaltable
  FROM sys.databases
  WHERE HAS_DBACCESS(name) = 1
  AND name NOT IN ('msdb')
  AND database_id > 4
  AND name NOT LIKE '%$%'
  AND name NOT IN (@DatabaseIgnoreList)
  ORDER BY name ASC

declare
        @target varchar(250),
        @statement varchar(max)

declare @schemas as CURSOR;

set @schemas = CURSOR FOR

select name from #temporaltable;

open @schemas;

fetch next from @schemas INTO @target

while @@FETCH_STATUS = 0

begin

    set @statement = '
    use '+@target+'

   SELECT TABLE_SCHEMA ,
   TABLE_NAME ,
   COLUMN_NAME ,
   ORDINAL_POSITION ,
   COLUMN_DEFAULT ,
   DATA_TYPE ,
   CHARACTER_MAXIMUM_LENGTH ,
   NUMERIC_PRECISION ,
   NUMERIC_PRECISION_RADIX ,
   NUMERIC_SCALE ,
   DATETIME_PRECISION,
   TABLE_CATALOG
   FROM INFORMATION_SCHEMA.COLUMNS'

    EXEC (@statement)

fetch next from @schemas INTO @target
end

close @schemas;
deallocate @schemas

drop table #temporaltable


问:
Responsive images in CKEditor?
Is there a way to set an image width to 100% of its parent?

At the minute I'm using Enhanced Image with a nicely styled figure tag for captions, but until the image fits the width of the figure it's pretty much useless!

Thanks!

答:
Thank you for providing details and sorry for late reply.

In order to make the image 100% width of the figure please open ckeditor\contents.css file, find the selector for figure element and remove the padding: 10px; declaration. Next refresh your page and you should be good to go.

Title: Responsive images in CKEditor?


问:
Python argparse - mandatory argument - either positional or optional
I want the user to be able to pass a mandatory argument to 'argparse', with either positional, or optional argument.

I.e.,
both following forms are valid:

```<code>my_prog arg
my_prog -m arg
</code>```

I've seen Argparse optional positional arguments?

But the suggestions there make both form optional. I want that one of them will be mandatory.

Of course, I can add a manual checking after parsing that at least one of them has been set. But I got a hunch that there must be a better solution.

(And even with my manual approach, the 'help' section shows both of them as optional)

答:
The mutually exclusive group mechanism can take a required parameter.  It also works with one ? positional along with the optionals (flagged arguments).  (more than one '?' positional doesn't make sense).

As for the help display there are 2 default groups, positonal and optional.  So even if an optional (flagged) is set to required it is, by default, displayed in the optional group.  The usage line is a better guide as to whether an argument is required or not.  If you don't like the group labels in the help section, define your own argument groups.

```<code>In [146]: import argparse
In [147]: parser = argparse.ArgumentParser()
In [148]: gp = parser.add_mutually_exclusive_group(required=True)
In [149]: gp.add_argument('pos', nargs='?', default='foo');
In [150]: gp.add_argument('-f','--foo', default='bar');

In [151]: parser.parse_args('arg'.split())
Out[151]: Namespace(foo='bar', pos='arg')

In [152]: parser.parse_args('-f arg'.split())
Out[152]: Namespace(foo='arg', pos='foo')

In [153]: parser.parse_args('arg -f arg'.split())
usage: ipython3 [-h] [-f FOO] [pos]
ipython3: error: argument -f/--foo: not allowed with argument pos

In [154]: parser.parse_args(''.split())
usage: ipython3 [-h] [-f FOO] [pos]
ipython3: error: one of the arguments pos -f/--foo is required

In [155]: parser.parse_args('-h'.split())
usage: ipython3 [-h] [-f FOO] [pos]

positional arguments:
  pos

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO
</code>```

Oops, usage isn't showing the -f and pos in a mutually exlusive group.  Sometimes that usage formatting is brittle.

Switching the order in which the arguments are defined gives a better usage

```<code>In [156]: parser = argparse.ArgumentParser()
In [157]: gp = parser.add_mutually_exclusive_group(required=True)
In [158]: gp.add_argument('-f','--foo', default='bar');
In [159]: gp.add_argument('pos', nargs='?', default='foo');
In [160]:
In [160]: parser.parse_args('-h'.split())
usage: ipython3 [-h] (-f FOO | pos)

positional arguments:
  pos

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO
</code>```

With a user defined argument group:

```<code>In [165]: parser = argparse.ArgumentParser()
In [166]: gp = parser.add_argument_group('Mutually exclusive')
In [167]: gpm = gp.add_mutually_exclusive_group(required=True)
In [168]: gpm.add_argument('-f','--foo', default='bar');
In [169]: gpm.add_argument('pos', nargs='?', default='foo');
In [170]:
In [170]: parser.parse_args('-h'.split())
usage: ipython3 [-h] (-f FOO | pos)

optional arguments:
  -h, --help         show this help message and exit

Mutually exclusive:
  -f FOO, --foo FOO
  pos
</code>```

This is the one exception to the general rule argument_groups and mutually_exclusive_groups aren't designed for nesting.

The m-x-group was not required, usage would use []

```<code>usage: ipython3 [-h] [-f FOO | pos]
</code>```

Body:
I want the user to be able to pass a mandatory argument to 'argparse', with either positional, or optional argument.

I.e.,
both following forms are valid:

my_prog arg
my_prog -m arg

I've seen Argparse optional positional arguments?

But the suggestions there make both form optional. I want that one of them will be mandatory.

Of course, I can add a manual checking after parsing that at least one of them has been set. But I got a hunch that there must be a better solution.

(And even with my manual approach, the 'help' section shows both of them as optional)

Body:
The mutually exclusive group mechanism can take a required parameter.  It also works with one ? positional along with the optionals (flagged arguments).  (more than one '?' positional doesn't make sense).

As for the help display there are 2 default groups, positonal and optional.  So even if an optional (flagged) is set to required it is, by default, displayed in the optional group.  The usage line is a better guide as to whether an argument is required or not.  If you don't like the group labels in the help section, define your own argument groups.

In [146]: import argparse
In [147]: parser = argparse.ArgumentParser()
In [148]: gp = parser.add_mutually_exclusive_group(required=True)
In [149]: gp.add_argument('pos', nargs='?', default='foo');
In [150]: gp.add_argument('-f','--foo', default='bar');

In [151]: parser.parse_args('arg'.split())
Out[151]: Namespace(foo='bar', pos='arg')

In [152]: parser.parse_args('-f arg'.split())
Out[152]: Namespace(foo='arg', pos='foo')

In [153]: parser.parse_args('arg -f arg'.split())
usage: ipython3 [-h] [-f FOO] [pos]
ipython3: error: argument -f/--foo: not allowed with argument pos

In [154]: parser.parse_args(''.split())
usage: ipython3 [-h] [-f FOO] [pos]
ipython3: error: one of the arguments pos -f/--foo is required

In [155]: parser.parse_args('-h'.split())
usage: ipython3 [-h] [-f FOO] [pos]

positional arguments:
  pos

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO

Oops, usage isn't showing the -f and pos in a mutually exlusive group.  Sometimes that usage formatting is brittle.

Switching the order in which the arguments are defined gives a better usage

In [156]: parser = argparse.ArgumentParser()
In [157]: gp = parser.add_mutually_exclusive_group(required=True)
In [158]: gp.add_argument('-f','--foo', default='bar');
In [159]: gp.add_argument('pos', nargs='?', default='foo');
In [160]:
In [160]: parser.parse_args('-h'.split())
usage: ipython3 [-h] (-f FOO | pos)

positional arguments:
  pos

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO

With a user defined argument group:

In [165]: parser = argparse.ArgumentParser()
In [166]: gp = parser.add_argument_group('Mutually exclusive')
In [167]: gpm = gp.add_mutually_exclusive_group(required=True)
In [168]: gpm.add_argument('-f','--foo', default='bar');
In [169]: gpm.add_argument('pos', nargs='?', default='foo');
In [170]:
In [170]: parser.parse_args('-h'.split())
usage: ipython3 [-h] (-f FOO | pos)

optional arguments:
  -h, --help         show this help message and exit

Mutually exclusive:
  -f FOO, --foo FOO
  pos

This is the one exception to the general rule argument_groups and mutually_exclusive_groups aren't designed for nesting.

The m-x-group was not required, usage would use []

usage: ipython3 [-h] [-f FOO | pos]


问:
hadoop current leaseholder is trying to recreate file
My MapReduce job processes data by dates and needs to write output to a certain folder structure. Current expectation is to generate out put in following structure:

days => days/months/file

Reducer Class:

```<code>public static class Reducerclass  extends Reducer<Text,Text,Text,Text> {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        private MultipleOutputs<Text, Text> multipleOutputs;
        public void reduce(Text rkey, Iterable<Text> rvalue, Context context) throws IOException, InterruptedException {
            multipleOutputs = new MultipleOutputs<Text, Text>(context);
            for(Text value : rvalue) {

                Date date = new Date(Long.parseLong(value.toString()));
                String datestring = dateFormat.format(date);
                //              context.write(new Text(rkey + ", "),new Text(", "+value +", "+datestring));

                String[] parts = datestring.split(" ");
                String[] dateparts = parts[0].split("-");

                String day = dateparts[2];
                String month = dateparts[1];
                String year = dateparts[0];

                String baseFileName ="Days";
                String dayFolderpath = baseFileName + day + "/" + month + "/" + year;

                String outputFileName = baseFileName + "/" + month + "/" + day;
                if(datestring.equals("2017-10-26 20:30:42") || datestring.equals("2017-10-26 20:29:32")){

                    multipleOutputs.write(new Text(rkey + ", "), new Text(", "+value +", "+datestring),outputFileName) ;
                }
                else{

                multipleOutputs.write(new Text(rkey + ", "), new Text(", "+value +", "+datestring),generateFileName(new Text(rkey),new Text(value) )) ;
                }

            }
        }
        String generateFileName(Text key, Text value){
            return key.toString() + "_" + value.toString();
        }

        @Override
        public void setup(Context context){
            multipleOutputs = new MultipleOutputs<Text, Text>(context);
        }

        @Override
        public void cleanup(final Context context) throws IOException, InterruptedException{
            multipleOutputs.close();
        }
    }
</code>```

When i ran the jar am getting following error message

```<code>17/11/14 18:30:17 INFO mapreduce.Job: Task Id : attempt_1510547616164_0054_r_000000_0, Status : FAILED
Error: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException): failed to create file /user/hdfs/OutputFile/_temporary/1/_temporary/attempt_1510547616164_0054_r_000000_0/Days/10/26-r-00000 for DFSClient_attempt_1510547616164_0054_r_000000_0_757297700_1 for client 10.0.2.15 because current leaseholder is trying to recreate file.
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.recoverLeaseInternal(FSNamesystem.java:3171)
</code>```

答:
I believe what you have missed is:

```<code>job.setReducerClass(ReducerFormatMultiOutput.class);
</code>```

Please post the driver code to find the exact reason.

Body:
My MapReduce job processes data by dates and needs to write output to a certain folder structure. Current expectation is to generate out put in following structure:

days => days/months/file

Reducer Class:

public static class Reducerclass  extends Reducer<Text,Text,Text,Text> {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        private MultipleOutputs<Text, Text> multipleOutputs;
        public void reduce(Text rkey, Iterable<Text> rvalue, Context context) throws IOException, InterruptedException {
            multipleOutputs = new MultipleOutputs<Text, Text>(context);
            for(Text value : rvalue) {

                Date date = new Date(Long.parseLong(value.toString()));
                String datestring = dateFormat.format(date);
                //              context.write(new Text(rkey + ", "),new Text(", "+value +", "+datestring));

                String[] parts = datestring.split(" ");
                String[] dateparts = parts[0].split("-");

                String day = dateparts[2];
                String month = dateparts[1];
                String year = dateparts[0];

                String baseFileName ="Days";
                String dayFolderpath = baseFileName + day + "/" + month + "/" + year;

                String outputFileName = baseFileName + "/" + month + "/" + day;
                if(datestring.equals("2017-10-26 20:30:42") || datestring.equals("2017-10-26 20:29:32")){

                    multipleOutputs.write(new Text(rkey + ", "), new Text(", "+value +", "+datestring),outputFileName) ;
                }
                else{

                multipleOutputs.write(new Text(rkey + ", "), new Text(", "+value +", "+datestring),generateFileName(new Text(rkey),new Text(value) )) ;
                }

            }
        }
        String generateFileName(Text key, Text value){
            return key.toString() + "_" + value.toString();
        }

        @Override
        public void setup(Context context){
            multipleOutputs = new MultipleOutputs<Text, Text>(context);
        }

        @Override
        public void cleanup(final Context context) throws IOException, InterruptedException{
            multipleOutputs.close();
        }
    }

When i ran the jar am getting following error message

17/11/14 18:30:17 INFO mapreduce.Job: Task Id : attempt_1510547616164_0054_r_000000_0, Status : FAILED
Error: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException): failed to create file /user/hdfs/OutputFile/_temporary/1/_temporary/attempt_1510547616164_0054_r_000000_0/Days/10/26-r-00000 for DFSClient_attempt_1510547616164_0054_r_000000_0_757297700_1 for client 10.0.2.15 because current leaseholder is trying to recreate file.
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.recoverLeaseInternal(FSNamesystem.java:3171)

Body:
I believe what you have missed is:

job.setReducerClass(ReducerFormatMultiOutput.class);

Please post the driver code to find the exact reason.


问:
Convert byte array to time_t
I have a linux time clock, that sending me the clock with bytes, I have no idea how to get the clock out of it, I do know that it's a type of "time_t" (which is probably the total seconds since 1/1/1970), See below a few examples what I'm receiving from the clock
(I'm not sure if it's sending local or GMT time)

This bytes represents 11/09/2017 16:52(Local time) or 11/09/2017 21:52(GMT)

```<code>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,66,120,53,34,0,0,0
</code>```

This bytes represents 11/10/2017 10:27(Local time) or 11/10/2017 15:27(GMT)

```<code>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,162,111,54,34,0,0,0
</code>```

This bytes represents 11/13/2017 14:20(Local time) or 11/13/2017 19:20(GMT)

```<code>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,160,154,58,34,0,0,0
</code>```

答:
WOW!!!, that helped me a lot, Here is the code what I used, Thanks @ASMackay </p>

```<code>private DateTime convertTime(byte[] bytes)
        {
              ulong localEpoch = 936316800;   // local epoch Sept 1999
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            ulong total = 0;
            for (int i = 0; i < bytes.Count(); ++i)
            {
                total += (ulong)bytes[i] << (8 * i);
            }
            return epoch.AddSeconds(total + localEpoch);
        }
</code>```

Title: Convert byte array to time_t

Body:
I have a linux time clock, that sending me the clock with bytes, I have no idea how to get the clock out of it, I do know that it's a type of "time_t" (which is probably the total seconds since 1/1/1970), See below a few examples what I'm receiving from the clock
(I'm not sure if it's sending local or GMT time)

This bytes represents 11/09/2017 16:52(Local time) or 11/09/2017 21:52(GMT)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,66,120,53,34,0,0,0

This bytes represents 11/10/2017 10:27(Local time) or 11/10/2017 15:27(GMT)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,162,111,54,34,0,0,0

This bytes represents 11/13/2017 14:20(Local time) or 11/13/2017 19:20(GMT)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,160,154,58,34,0,0,0

Body:
WOW!!!, that helped me a lot, Here is the code what I used, Thanks @ASMackay

private DateTime convertTime(byte[] bytes)
        {
              ulong localEpoch = 936316800;   // local epoch Sept 1999
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            ulong total = 0;
            for (int i = 0; i < bytes.Count(); ++i)
            {
                total += (ulong)bytes[i] << (8 * i);
            }
            return epoch.AddSeconds(total + localEpoch);
        }


问:
React router v4 route onchange event
Is there any way to fire an event when route changes with react router v4. I need to fire a function on every route change. I use BrowserRouter and Switch from react-router-dom on client side in universal react-redux application.

答:
React: v15.x, React Router: v4.x

components/core/App.js:

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';

class LocationListener extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  componentDidMount() {
    this.handleLocationChange(this.context.router.history.location);
    this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  handleLocationChange(location) {
    // your staff here
    console.log(`- - - location: '${location.pathname}'`);
  }

  render() {
    return this.props.children;
  }
}

export class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        <LocationListener>
         ...
        </LocationListener>
      </BrowserRouter>
    );
  }
}
</code>```

index.js:

```<code>import App from 'components/core/App';

render(<App />, document.querySelector('#root'));
</code>```

Title: React router v4 route onchange event

Body:
React: v15.x, React Router: v4.x

components/core/App.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';

class LocationListener extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  componentDidMount() {
    this.handleLocationChange(this.context.router.history.location);
    this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  handleLocationChange(location) {
    // your staff here
    console.log(`- - - location: '${location.pathname}'`);
  }

  render() {
    return this.props.children;
  }
}

export class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        <LocationListener>
         ...
        </LocationListener>
      </BrowserRouter>
    );
  }
}

index.js:

import App from 'components/core/App';

render(<App />, document.querySelector('#root'));


问:
Classification using Multiple CSV files with filename as label
I am dealing with Sensor Data which has numerical observations for different variables. I want to classify them into three labels A, B, C.

But, here the situation is different.

I have 30 Instances for training (or labelled data) and 20 instances for testing (unlabelled data).

Now, these instances are time series recordings for variables and parameters recorded by the sensor. Each instance (or a single observation) is a CSV as shown in the screenshot file.

The name of the CSV file is the label, this label I need to classify. So, I have 30 CSV files or instances (or thirty labels) and 20 instances or CSV files for testing.

All the CSV files have same data structure. there is no label in any file, since they are itself a single observation(of shape 5000, 12) and represent a single observation altogether, and the filename for example classA.csv , where Class A is target variable

I want to figure out, how can I put these data (each observation (or class) of training data is a csv file and each file contains 5000 observations).

Please Suggest.

Thanks in Advance.

答:
I recommend reading this link to understand Python's CSV interface:
https://docs.python.org/2/library/csv.html

Your basic steps will be:

Point Python to the directory where your data is stored

Iterate through the files in this directory

For each file:
Use Python's CSV interface to pull out the data and place it in your data structure. When you parse the CSV, you will have an array of rows you can iterate through to pull data. I recommend looking under the "short usage example" to see how you can access the data.


问:
Splitting a 2D array into smaller equally sized 2D subarrays
Basically what I am asking is given a square 2D array and a valid patch size (the size of the 2D subarrays) how would I go about doing this.
Ultimately I don't need to store the subarrays in any way, I just need to find the median of each subarray and store them in a 1D array. The median and storing to new array are simple for me, I just can't figure out how to go about the original 2D array and splitting it properly.
I've attempted this several times and keep getting out of bounds errors.
I have a 4x4:

[1,2,3,4]
 [2,3,4,1]
 [3,4,1,2]
 [4,1,2,3]

I need to split it like so

[1,2] [3,4]
[2,3] [4,1]

[3,4] [1,2]
[4,1] [2,3]

And then take the median of each and store them into a new 1D array.

EDIT: Solved, thanks for the help!

答:
You can use Arrays.copyOfRange(Object[] src, int from, int to) for this where:

src is the source 1D array

from is the initial index of the range to be copied, inclusive.

to is the final index of the range to be copied, exclusive.

I don't prefer your code because it seems that it's time complexity is too high.

Try below code:

```<code>public class Temp {
    public static void main(String[] args) {
        int[][] arr = { { 1,2,3,4 },
                        { 2,3,4,1 },
                        { 3,4,1,2 },
                        { 4,1,2,3 } };

        int patch = 2;

        splitToSubArrays(arr, patch);

    }

    static void splitToSubArrays(int arr[][], int patch) {
        for (int i = 0; i < arr[0].length; i++) {
            int to = patch;
            for (int from = 0; to <= arr.length;) {
                int a[] = Arrays.copyOfRange(arr[i], from, to);
                // instead of printing you can store in a separate array for later usage
                System.out.println(Arrays.toString(a));
                to += patch;
                from += patch;
            }
        }
    }

}
</code>```

EDIT: N.B.: For n*n array if n%patch is not 0 i.e. dimension is not divisible by  patch value then you would need to use proper if condition here int a[] = Arrays.copyOfRange(arr[i], from, to); to control the index bound. Hope you are aware of this.

Output

```<code>[1, 2]
[3, 4]
[2, 3]
[4, 1]
[3, 4]
[1, 2]
[4, 1]
[2, 3]
</code>```

Body:
You can use Arrays.copyOfRange(Object[] src, int from, int to) for this where:

src is the source 1D array

from is the initial index of the range to be copied, inclusive.

to is the final index of the range to be copied, exclusive.

I don't prefer your code because it seems that it's time complexity is too high.

Try below code:

public class Temp {
    public static void main(String[] args) {
        int[][] arr = { { 1,2,3,4 },
                        { 2,3,4,1 },
                        { 3,4,1,2 },
                        { 4,1,2,3 } };

        int patch = 2;

        splitToSubArrays(arr, patch);

    }

    static void splitToSubArrays(int arr[][], int patch) {
        for (int i = 0; i < arr[0].length; i++) {
            int to = patch;
            for (int from = 0; to <= arr.length;) {
                int a[] = Arrays.copyOfRange(arr[i], from, to);
                // instead of printing you can store in a separate array for later usage
                System.out.println(Arrays.toString(a));
                to += patch;
                from += patch;
            }
        }
    }

}

EDIT: N.B.: For n*n array if n%patch is not 0 i.e. dimension is not divisible by  patch value then you would need to use proper if condition here int a[] = Arrays.copyOfRange(arr[i], from, to); to control the index bound. Hope you are aware of this.

Output

[1, 2]
[3, 4]
[2, 3]
[4, 1]
[3, 4]
[1, 2]
[4, 1]
[2, 3]


问:
Amazon S3 Bucket Policy Referer
I'm trying to edit my S3 bucket configuration such that 3rd party sites can not link to content in it. Also an added benefit is that they can only access content from my domain rather than the supplementary s3bucket.amazon-east.amazonaws.com or something to that effect.

The documentation has an example exactly for this but when I copied/pasted/modified for my website below it does not work? I still get 403 errors. When I take out only the conditional section it allows full access so there is only an issue with the referer section.

It's such a short piece of code I'm beating my head against the wall on...hoping a second set of eyes could enlighten me on something that's probably obvious that I'm missing?

Alternatively there might not be anything wrong with this and there might be additional configurations elsewhere that I haven't set/considered?

Thanks for reading.

```<code>{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "fml",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::www.mysite.com/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": [
                        "http://mysite.com/*",
                        "http://www.mysite.com/*"
                    ]
                }
            }
        }
    ]
}
</code>```

答:
Its important to note that if your referer includes /* on the end then it will only allow content from children of that referer, but not from that referer itself.

So if you want to include your main domain as well, then you would need to do it like this:

```<code>                "aws:Referer": [
                    "http://example.com",
                    "http://example.com/*",
                    "http://www.example.com",
                    "http://www.example.com/*"
                ]
</code>```

Title: Amazon S3 Bucket Policy Referer

Body:
I'm trying to edit my S3 bucket configuration such that 3rd party sites can not link to content in it. Also an added benefit is that they can only access content from my domain rather than the supplementary s3bucket.amazon-east.amazonaws.com or something to that effect.

The documentation has an example exactly for this but when I copied/pasted/modified for my website below it does not work? I still get 403 errors. When I take out only the conditional section it allows full access so there is only an issue with the referer section.

It's such a short piece of code I'm beating my head against the wall on...hoping a second set of eyes could enlighten me on something that's probably obvious that I'm missing?

Alternatively there might not be anything wrong with this and there might be additional configurations elsewhere that I haven't set/considered?

Thanks for reading.

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "fml",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::www.mysite.com/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": [
                        "http://mysite.com/*",
                        "http://www.mysite.com/*"
                    ]
                }
            }
        }
    ]
}

Body:
Its important to note that if your referer includes /* on the end then it will only allow content from children of that referer, but not from that referer itself.

So if you want to include your main domain as well, then you would need to do it like this:

                "aws:Referer": [
                    "http://example.com",
                    "http://example.com/*",
                    "http://www.example.com",
                    "http://www.example.com/*"
                ]


问:
can you access soap xml's in SQL and parse it in XQuery without the use of CLR?
as the title suggests, is this possible?</p>

答:
At a superficial level yes, it is possible. But would you want to re-implement in SQL the entire SOAP stack to validate the message for ws-security, ws-metadatexchange, ws-addressing, ws-reliablemessaging and what else?

Is this a good job for sqlclr? Absolutely not. Why would sqlclr have to handle the transport and enveloping of a message? This should be handled close to where the message is accepted, way before it gets written into the database.

So let WCF handle the SOAP layer, that's one thing is actually good at. There is no reason why the database layer should end up with the entire SOAP package.

ContentLicense: CC BY-SA 2.5


问:
ValueError: Cannot feed value of shape (200,) for Tensor 'Placeholder_32:0', which has shape '(?, 1)'
I am new to tensorflow. This code is just for a simple neural network.
I think the problem maybe is from:

```<code>x_data = np.linspace(-0.5,0.5,200)[:np..newaxis]
</code>```

I tried to write without [:np.newaxis], but it looks like the same.

```<code>import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

x_data = np.linspace(-0.5,0.5,200)[:np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise

x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])

Weights_L1 = tf.Variable(tf.random_normal([1,10]))
biases_L1 = tf.Variable(tf.zeros([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)

Weights_L2 = tf.Variable(tf.random_normal([10,1]))
biases_L2 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

loss = tf.reduce_mean(tf.square(y-prediction))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step,feed_dict={x:x_data,y:y_data})

    prediction_value = sess.run(prediction,feed_dict={x:x_data})
    plt.figure()
    plt.scatter(x_data,y_data)
    plt.plot(x_data,prediction_value,'r-',lw=5)
    plt.show()
</code>```

答:
The defined placeholders (both x and y) are 2-dimensional, so you should reshape the input arrays to rank 2. Try to add this:

x_data = x_data.reshape([-1,1])
y_data = y_data.reshape([-1,1])
```

Body:
I am new to tensorflow. This code is just for a simple neural network.
I think the problem maybe is from:

x_data = np.linspace(-0.5,0.5,200)[:np..newaxis]

I tried to write without [:np.newaxis], but it looks like the same.

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

x_data = np.linspace(-0.5,0.5,200)[:np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise

x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])

Weights_L1 = tf.Variable(tf.random_normal([1,10]))
biases_L1 = tf.Variable(tf.zeros([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)

Weights_L2 = tf.Variable(tf.random_normal([10,1]))
biases_L2 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

loss = tf.reduce_mean(tf.square(y-prediction))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step,feed_dict={x:x_data,y:y_data})

    prediction_value = sess.run(prediction,feed_dict={x:x_data})
    plt.figure()
    plt.scatter(x_data,y_data)
    plt.plot(x_data,prediction_value,'r-',lw=5)
    plt.show()


问:
JavaScript - How to get current date, and store previous dates, for use in a list?
I would like to make a UL with previous dates, the current date, and have
these listed items nested within it. An example is this:

```<code>•   Monday November 13, 2017
   o    List item
   o    List item
   o    List item
•   Tuesday November 14, 2017
   o    List item
   o    List item
   o    List item
•   Wednesday November 15, 2017
   o    List item
   o    List item
   o    List item
</code>```

I would be getting the current date via JavaScript.

How would I be able to do the following?

Get the current date via JavaScript?

Store the previous dates (i.e. yesterday's date, the day before's date, etc.)?;

note: every time a new list item is added (like a to do app), the current date will be saved. If i were to come back to my app the next day, yesterday's date is saved, and the current date is added. Hope that makes sense!

Thanks in advance!

答:
Apply following code. </p>

```<code>var todayDate = new Date();
var yesterdayDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
var beforeDate = new Date(new Date().getTime() - 2 * ( 24 * 60 * 60 * 1000));
 console.log("Today Date: " + todayDate );
 console.log("yesterday Date: " + yesterdayDate );
 console.log("before Date: " + beforeDate );
</code>```

Body:
I would like to make a UL with previous dates, the current date, and have
these listed items nested within it. An example is this:

•   Monday November 13, 2017
   o    List item
   o    List item
   o    List item
•   Tuesday November 14, 2017
   o    List item
   o    List item
   o    List item
•   Wednesday November 15, 2017
   o    List item
   o    List item
   o    List item

I would be getting the current date via JavaScript.

How would I be able to do the following?

Get the current date via JavaScript?

Store the previous dates (i.e. yesterday's date, the day before's date, etc.)?;

note: every time a new list item is added (like a to do app), the current date will be saved. If i were to come back to my app the next day, yesterday's date is saved, and the current date is added. Hope that makes sense!

Thanks in advance!

Body:
Apply following code.

var todayDate = new Date();
var yesterdayDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
var beforeDate = new Date(new Date().getTime() - 2 * ( 24 * 60 * 60 * 1000));
 console.log("Today Date: " + todayDate );
 console.log("yesterday Date: " + yesterdayDate );
 console.log("before Date: " + beforeDate );


问:
I want to aggregate the information on two different tables
I have two tables as below and I want to get a result like

first table ->

```<code>name    properties  piece
A            X       50
B            Y       40
A            Z       20
B            Y       10
A            X       15
</code>```

Second table ->

```<code>name    properties  piece
A            X       10
B            Y       10
A            Z       10
B            Y       15
</code>```

The result I want to have

```<code>name    properties  piece
A            X       55
A            Z       10
B            Y       40
</code>```

Calc for A-X (50+15-10=5)

答:
```<code>select name, properties, sum(piece) from (
  select name, properties, piece from first_table
  union all
  select name, properties, -1 * piece from second_table
) a
group by name, properties
</code>```

This would do

Body:
I have two tables as below and I want to get a result like

first table ->

name    properties  piece
A            X       50
B            Y       40
A            Z       20
B            Y       10
A            X       15

Second table ->

name    properties  piece
A            X       10
B            Y       10
A            Z       10
B            Y       15

The result I want to have

name    properties  piece
A            X       55
A            Z       10
B            Y       40

Calc for A-X (50+15-10=5)

Body:
select name, properties, sum(piece) from (
  select name, properties, piece from first_table
  union all
  select name, properties, -1 * piece from second_table
) a
group by name, properties

This would do


问:
Updating Primary Key value Cassandra
I have table with node_id, node_name and data. My requirement is to getByID and getByName. So I have made id and name as the primary keys. But I also need to sometimes update the name as well.

I know Cassandra does not allow updating primary keys and having non primary key in the WHERE clause.

How can I achieve this?

I did consider deleting the record first, and then inserting again with the same id and new name. But I read that this would create tombstones and affect the performance.

答: Use only node_id as the primary key. To implement getByName create a materialized view. materialized views in cassandra</p>

Title: Updating Primary Key value Cassandra


问:
SQL Server: Get data for only the past year
I am writing a query in which I have to get the data for only the last year. What is the best way to do this?</p>

```<code>SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
</code>```

答:
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):</p>

```<code>SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >=  DATEADD(year,-1,GETDATE())
</code>```

OwnerDisplayName: jmein

Body:
I am writing a query in which I have to get the data for only the last year. What is the best way to do this?

SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'

LastEditorDisplayName: jmein

Body:
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):

SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >=  DATEADD(year,-1,GETDATE())


问:
how to define the Console.WriteLine behavior for a class in C#?
I have a class:

```<code>class Rect{
    int x;
    int y;
    public Rect(int x, int y){
        this.x = x;
        this.y = y;
    }

}
</code>```

I want this happen:

```<code>Console.WriteLine(new Rect(12,12));
>>> <Rect with x=12, y=12>
</code>```

How could I do it?

答:
Console.WriteLine Method (Object)

You need to override the ToString() method from Object.

Body:
I have a class:

class Rect{
    int x;
    int y;
    public Rect(int x, int y){
        this.x = x;
        this.y = y;
    }

}

I want this happen:

Console.WriteLine(new Rect(12,12));
>>> <Rect with x=12, y=12>

How could I do it?


问:
Acumatica pivot tables not loading
I am trying to build a pivot table in acumatica Build 17.201.0043 sandbox to do some testing.
When I View Pivot it keeps loading and the request times out as below

The GI for the pivot table is

The Pivot table is...

答: Are you using the SalesDemo database? Can you include screenshots from your Pivot Table definition?</p>

Title: Acumatica pivot tables not loading


问:
C++ - Object slicing even after using pointers
I have a base class Shape, and a derived class Circle which inherits Shape publically:

```<code>class Circle : public Shape
</code>```

I made a C++ vector of Shape pointers, and I assigned Circle pointers to them. I'd read up a lot on object slicing so expected the code to treat the Circle in the vector as a Circle, not a Shape.

Can anyone point out what's wrong with this, given the output?

```<code>int main(void) {
vector<Shape*> shapes;

Circle* ncl = new Circle(-8, -8, 0.2f);
shapes.push_back(ncl);

cout << "Expected: " << *ncl << endl;
cout << "Reality: " << *shapes[0] << endl;
}
</code>```

outputs:

```<code>Expected: Circle is at: -8,-8 and has a radius of: 0.2
Reality: Shape centered at point: -8,-8
</code>```

I have overridden the << operator for both classes out of scope, so I think that's not the problem, but still - here's the code context of my overrides:

```<code>inline std::ostream& operator<< (std::ostream& stream, const Shape& shape) {
    std::cout << "Shape centered at point: " << shape.getX() << "," << shape.getY();
    return stream;
}

inline std::ostream& operator<< (std::ostream& stream, const Circle& circle) {
    std::cout << "Circle is at: " << circle.getX() << "," << circle.getY() <<
        " and has a radius of: " << circle.getR();
    return stream;
}
</code>```

All in all - I want to be able to access my Circle variables properly while they're stored in the Shape vector (with pointers or otherwise).

答:
overload resolution is done with static type.

You may use:

```<code>std::ostream& operator<< (std::ostream& stream, const Shape& shape) {
    shape.print(stream);
    return stream;
}
</code>```

with virtual void Shape::print(std::ostream&) const; to solve your issue.

Body:
I have a base class Shape, and a derived class Circle which inherits Shape publically:

class Circle : public Shape

I made a C++ vector of Shape pointers, and I assigned Circle pointers to them. I'd read up a lot on object slicing so expected the code to treat the Circle in the vector as a Circle, not a Shape.

Can anyone point out what's wrong with this, given the output?

int main(void) {
vector<Shape*> shapes;

Circle* ncl = new Circle(-8, -8, 0.2f);
shapes.push_back(ncl);

cout << "Expected: " << *ncl << endl;
cout << "Reality: " << *shapes[0] << endl;
}

outputs:

Expected: Circle is at: -8,-8 and has a radius of: 0.2
Reality: Shape centered at point: -8,-8

I have overridden the << operator for both classes out of scope, so I think that's not the problem, but still - here's the code context of my overrides:

inline std::ostream& operator<< (std::ostream& stream, const Shape& shape) {
    std::cout << "Shape centered at point: " << shape.getX() << "," << shape.getY();
    return stream;
}

inline std::ostream& operator<< (std::ostream& stream, const Circle& circle) {
    std::cout << "Circle is at: " << circle.getX() << "," << circle.getY() <<
        " and has a radius of: " << circle.getR();
    return stream;
}

All in all - I want to be able to access my Circle variables properly while they're stored in the Shape vector (with pointers or otherwise).

Body:
overload resolution is done with static type.

You may use:

std::ostream& operator<< (std::ostream& stream, const Shape& shape) {
    shape.print(stream);
    return stream;
}

with virtual void Shape::print(std::ostream&) const; to solve your issue.


问:
How to pass a function in Puppeteers .evaluate() method
Whenever I try to pass a function, like this:

```<code>var myFunc = function() { console.log("lol"); };

await page.evaluate(func => {
 func();
 return true;
}, myFunc);
</code>```

I get:

```<code>(node:13108) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: TypeError: func is not a function
at func (<anonymous>:9:9)
(node:13108) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Why? How to do it correctly?

Thank you!

€: let me clarify: I am doing it this way because I want to find some DOM elements first and use them inside of that function, more like this (simplified):

```<code>var myFunc = function(element) { element.innerHTML = "baz" };

await page.evaluate(func => {
  var foo = document.querySelector('.bar');
  func(foo);
  return true;
}, myFunc);
</code>```

答:
Similar problems have been discussed in a puppeteer issue.

There are several way to deal with your problem. First rule is to keep it simple.

Evaluate the function

This is the fastest way to do things, you can just pass the function and execute it.

```<code>await page.evaluate(() => {
  var myFunc = function(element) { element.innerHTML = "baz" };
  var foo = document.querySelector('.bar');
  myFunc(foo);
  return true;
});
</code>```

Expose the function beforehand

You can expose the function beforehand using a page.evaluate, or a page.addScriptTag

```<code>// add it manually and expose to window
await page.evaluate(() => {
  window.myFunc = function(element) { element.innerHTML = "baz" };
});

// add some scripts
await page.addScriptTag({path: "myFunc.js"});

// Now I can evaluate as many times as I want
await page.evaluate(() => {
  var foo = document.querySelector('.bar');
  myFunc(foo);
  return true;
});
</code>```

Use ElementHandle

page.$(selector)

You can pass an element handle to .evaluate and make changes as you seem fit.

```<code>const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
</code>```

page.$eval

You can target one element and make changes as you want.

```<code>const html = await page.$eval('.awesomeSelector', e => {
e.outerHTML = "whatever"
});
</code>```

The trick is to read the docs and keep it simple.

Body:
Whenever I try to pass a function, like this:

var myFunc = function() { console.log("lol"); };

await page.evaluate(func => {
 func();
 return true;
}, myFunc);

I get:

(node:13108) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: TypeError: func is not a function
at func (<anonymous>:9:9)
(node:13108) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Why? How to do it correctly?

Thank you!

€: let me clarify: I am doing it this way because I want to find some DOM elements first and use them inside of that function, more like this (simplified):

var myFunc = function(element) { element.innerHTML = "baz" };

await page.evaluate(func => {
  var foo = document.querySelector('.bar');
  func(foo);
  return true;
}, myFunc);

Body:
Similar problems have been discussed in a puppeteer issue.

There are several way to deal with your problem. First rule is to keep it simple.

Evaluate the function

This is the fastest way to do things, you can just pass the function and execute it.

await page.evaluate(() => {
  var myFunc = function(element) { element.innerHTML = "baz" };
  var foo = document.querySelector('.bar');
  myFunc(foo);
  return true;
});

Expose the function beforehand

You can expose the function beforehand using a page.evaluate, or a page.addScriptTag

// add it manually and expose to window
await page.evaluate(() => {
  window.myFunc = function(element) { element.innerHTML = "baz" };
});

// add some scripts
await page.addScriptTag({path: "myFunc.js"});

// Now I can evaluate as many times as I want
await page.evaluate(() => {
  var foo = document.querySelector('.bar');
  myFunc(foo);
  return true;
});

Use ElementHandle

page.$(selector)

You can pass an element handle to .evaluate and make changes as you seem fit.

const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);

page.$eval

You can target one element and make changes as you want.

const html = await page.$eval('.awesomeSelector', e => {
e.outerHTML = "whatever"
});

The trick is to read the docs and keep it simple.


问:
Sidebar hide and show with Bootstrap and Jquery?
Guys I want to create a sidebar hiding and showing using bootstrap, but my code isn't working..

Please help me...

My code HTML is:

```<code><nav role="nav" class="navbar">
    <a href="" class="menu">button</a>
</nav>

<nav role="nav" class="sidebar">
    sidebar menu
</nav>

<main role="main" class="main-page">
    main content
</main>
</code>```

This is my CSS code:

```<code>.menu {
    display: block !important;
}

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
}

.main-page {
    color: #000;
    margin-left: 240px;
    position :relative;
}
</code>```

And this is my jquery code:

```<code><script>
    $(function () {
        $('.menu').on('click', function () {
            if ($('.sidebar').is(':visible')) {
                $('.sidebar').animate({'width': '0px'}, 'slow', function () {
                    $('.sidebar').hide();
                });
                $('.main-page').animate({'padding-left': '0px'}, 'slow');
            } else {
                $('.sidebar').show();
                $('.sidebar').animate({'width': '240px'}, 'slow');
                $('.main-page').animate({'padding-left': '240px'}, 'slow');
            }
        });
    });
</script>
</code>```

I'm using bootstrp CDN: jquery-3.2.1.slim.min.js / popper.min.js / bootstrap.min.js

答:
Im not sure why is not working. Try this one.

Change/Add the following CSS:

```<code>.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
    left:0px;
    transition:0.3s all ease-in-out;
}

.sidebar.close {
    left: -240px;
    transition:0.3s all ease-in-out;
}
</code>```

In your script Change/Add the following:

```<code>$('.menu').on('click', function () {
  $('.sidebar').toggleClass('close');
});
</code>```

Body:
Guys I want to create a sidebar hiding and showing using bootstrap, but my code isn't working..

Please help me...

My code HTML is:

    button

    sidebar menu

    main content

This is my CSS code:

.menu {
    display: block !important;
}

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
}

.main-page {
    color: #000;
    margin-left: 240px;
    position :relative;
}

And this is my jquery code:

I'm using bootstrp CDN: jquery-3.2.1.slim.min.js / popper.min.js / bootstrap.min.js

Body:
Im not sure why is not working. Try this one.

Change/Add the following CSS:

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
    left:0px;
    transition:0.3s all ease-in-out;
}

.sidebar.close {
    left: -240px;
    transition:0.3s all ease-in-out;
}

In your script Change/Add the following:

$('.menu').on('click', function () {
  $('.sidebar').toggleClass('close');
});


问:
How can I use gettext in jupyter-notebook/python interactive mode?
I use the following code, which I got from this question, to get country codes from their russian names.

```<code>def get_country_code(russian_name):
    gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['RU']).install()
    country_code = ''.join([country.alpha_2 for country in pycountry.countries if _(country.name) == russian_name])
    return country_code
</code>```

But as I try to use this function in my jupyter-notebook, it gives me the following error:

```<code>TypeError: 'str' object is not callable
</code>```

Is seems like this is because in jupyter as well as in interactive mode _ means the result of the previous calculation, but gettext define it as its function.

How can I execute this code in Jupyter?

答:
I've found the solution to the problem. The install() function sets variable _ in builtins like this:

```<code>builtins.__dict__['_'] = self.gettext
</code>```

So we can use this function instead.

```<code>def get_country_code(russian_name):
    rus = gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['RU'])
    rus.install()
    country_code = ''.join([country.alpha_2 for country in pycountry.countries if rus.gettext(country.name) == russian_name]) # u'FR'
    return country_code
</code>```

Body:
I use the following code, which I got from this question, to get country codes from their russian names.

def get_country_code(russian_name):
    gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['RU']).install()
    country_code = ''.join([country.alpha_2 for country in pycountry.countries if _(country.name) == russian_name])
    return country_code

But as I try to use this function in my jupyter-notebook, it gives me the following error:

TypeError: 'str' object is not callable

Is seems like this is because in jupyter as well as in interactive mode _ means the result of the previous calculation, but gettext define it as its function.

How can I execute this code in Jupyter?

Body:
I've found the solution to the problem. The install() function sets variable _ in builtins like this:

builtins.__dict__['_'] = self.gettext

So we can use this function instead.

def get_country_code(russian_name):
    rus = gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['RU'])
    rus.install()
    country_code = ''.join([country.alpha_2 for country in pycountry.countries if rus.gettext(country.name) == russian_name]) # u'FR'
    return country_code


问:
Right-align CSS sprite list
Please look at the Facebook/YouTube/Twitter icons at the top of http://live-fenfast.pantheonsite.io/. I'm trying to align them to the right like they are on http://fenfast.com. The difference on the "live-fenfast.pantheonsite.io" site is that I've converted plain img a hrefs with a styled list that uses CSS to reveal parts of a single image for clicking in the list (CSS sprites).

How do I right-align this list? I've tried a bunch of obvious CSS properties but none of them work.

答:
Why you don't use simply:

```<code>#socialnavlist {
    position: relative;
    float: right;
}
</code>```

In my opinion you has a problems because you use:

```<code>#socialnavlist li {
    margin: 0;
    padding: 0;
    list-style: none;
    position: absolute;
    top: 0;
}
</code>```

This is a main reason of all your problems. If you use position: absolute you can't use normal align/float attributes, and you can't get what you need.

Title: Right-align CSS sprite list

Body:
Why you don't use simply:

#socialnavlist {
    position: relative;
    float: right;
}

In my opinion you has a problems because you use:

#socialnavlist li {
    margin: 0;
    padding: 0;
    list-style: none;
    position: absolute;
    top: 0;
}

This is a main reason of all your problems. If you use position: absolute you can't use normal align/float attributes, and you can't get what you need.


问:
How to upsample one layer to any size in keras?
I'd like to upsample one layer with size of (w,h,channels) to size of (w',h',channels), but the Upsample2D layer just can upsample to the double size.

Anybody could tell me how do any size upsampling?

答:
The Keras UpSample2D can upsample to different sizes, not just double size. From the Keras docs we can see this is indicated for such layer:

keras.layers.UpSampling2D(size=(2, 2), data_format=None)

Upsampling layer for 2D inputs.

Repeats the rows and columns of the data by size[0] and size[1] respectively.

The default size value is indeed (2,2), so in that case your upsampling will be double. By specifying the size you desire you can manage to upsample to different sizes according to your needs. So, if you want an upsample factor of say, 3 then you should use size=(3,3), etc.

As alternatives, you can also define your own custom layers if you want something really specific to your case. For example, here is a Github issue about creating custom pooling function (opposite of upsampling layers, so easily comparable), which could help you in case you needed such custom layer.


答:
I think something like this could do, altough i didn't test it, but It should give you a good idea of how to do this scan</p>

```<code>public int[] patchArray(int[][] img, int patch)
{
    int size = img.length * (img[0].length / patch) ;
    int[] pArray = new int[size];
    int[] tmp = new int[patch];

    for (int row_i = 0; row_i < img.length; row_i++)
    {
        for (int patch_start = 0; patch_start < img[i].length; patch_start += patch)
        {
            int x = 0;
            for (int patch_i = patch_start; patch_i < (patch_start + patch); patch_i++)
            {
                tmp[patch_i - patch_start] = img[row_i][patch_i];
            }

            calculateMedian(tmp);
        }
    }

    return pArray;
}
</code>```

Title: Splitting a 2D array into smaller equally sized 2D subarrays

Body:
Basically what I am asking is given a square 2D array and a valid patch size (the size of the 2D subarrays) how would I go about doing this.
Ultimately I don't need to store the subarrays in any way, I just need to find the median of each subarray and store them in a 1D array. The median and storing to new array are simple for me, I just can't figure out how to go about the original 2D array and splitting it properly.
I've attempted this several times and keep getting out of bounds errors.
I have a 4x4:

[1,2,3,4]
 [2,3,4,1]
 [3,4,1,2]
 [4,1,2,3]

I need to split it like so

[1,2] [3,4]
[2,3] [4,1]

[3,4] [1,2]
[4,1] [2,3]

And then take the median of each and store them into a new 1D array.

EDIT: Solved, thanks for the help!

Body:
I think something like this could do, altough i didn't test it, but It should give you a good idea of how to do this scan

public int[] patchArray(int[][] img, int patch)
{
    int size = img.length * (img[0].length / patch) ;
    int[] pArray = new int[size];
    int[] tmp = new int[patch];

    for (int row_i = 0; row_i < img.length; row_i++)
    {
        for (int patch_start = 0; patch_start < img[i].length; patch_start += patch)
        {
            int x = 0;
            for (int patch_i = patch_start; patch_i < (patch_start + patch); patch_i++)
            {
                tmp[patch_i - patch_start] = img[row_i][patch_i];
            }

            calculateMedian(tmp);
        }
    }

    return pArray;
}