问:
Split string every nth character from the right?
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

```<code>import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))
</code>```

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

```<code>'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])
</code>```

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

```<code>ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))
</code>```

Body:
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))

Body:
Try this:

>>> line = '1234567890'
>>> n = 3
>>> rev_line = line[::-1]
>>> out = [rev_line[i:i+n][::-1] for i in range(0, len(line), n)]
>>> ['890', '567', '234', '1']
>>> "/".join(reversed(out))
>>> '1/234/567/890'


来源: stackexchange

问:
memcpy vs for loop - What's the proper way to copy an array from a pointer?
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums).  Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo.  I understand the following is invalid:

```<code>void foo (int[] nums)
{
    myGlobalArray = *nums
}
</code>```

What is the proper way to copy the array?  Should I use memcpy like so:

```<code>void foo (int[] nums)
{
    memcpy(&myGlobalArray, nums, 10);
}
</code>```

or should I use a for loop?

```<code>void foo(int[] nums)
{
    for(int i =0; i < 10; i++)
    {
        myGlobalArray[i] = nums[i];
    }
}
</code>```

Is there a third option that I'm missing?

答:
Memcpy will probably be faster, but it's more likely you will make a mistake using it.
It may depend on how smart your optimizing compiler is.

Your code is incorrect though. It should be:

```<code>memcpy(myGlobalArray, nums, 10 * sizeof(int) );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums).  Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo.  I understand the following is invalid:

void foo (int[] nums)
{
    myGlobalArray = *nums
}

What is the proper way to copy the array?  Should I use memcpy like so:

void foo (int[] nums)
{
    memcpy(&myGlobalArray, nums, 10);
}

or should I use a for loop?

void foo(int[] nums)
{
    for(int i =0; i < 10; i++)
    {
        myGlobalArray[i] = nums[i];
    }
}

Is there a third option that I'm missing?

Body:
Memcpy will probably be faster, but it's more likely you will make a mistake using it.
It may depend on how smart your optimizing compiler is.

Your code is incorrect though. It should be:

memcpy(myGlobalArray, nums, 10 * sizeof(int) );

ContentLicense: CC BY-SA 4.0


问:
Change of the background color in minimized MenuStrip
I have a Windows Forms application with a MenuStrip. BackColor is blue, but when the window is resized (in the image you see only left corner of the menu) and I want to display other hidden items, the background is not blue.

How can I change the background color?

答:
Check out this : ToolStripProfessionalRenderer

```<code>public class MyToolStripRenderer : ToolStripProfessionalRenderer
{
    /* override styling/drawing here */
}

MenuStrip strip = new MenuStrip();

strip.Renderer = new MyToolStripRenderer();

//this will set RenderMode to "Custom"
</code>```

Exemple :

```<code>public  class TestColorTable : ProfessionalColorTable
{
    public override Color MenuItemSelected
    {
        get { return Color.Red; }
    }

    public override Color MenuBorder  //added for changing the menu border
    {
        get { return Color.Green; }
    }
</code>```

You would use it like this:

```<code>private void Form1_Load(object sender, EventArgs e)
{
    menuStrip1.Renderer = new ToolStripProfessionalRenderer(new TestColorTable());
}
</code>```

Body:
Check out this : ToolStripProfessionalRenderer

public class MyToolStripRenderer : ToolStripProfessionalRenderer
{
    /* override styling/drawing here */
}

MenuStrip strip = new MenuStrip();

strip.Renderer = new MyToolStripRenderer();

//this will set RenderMode to "Custom"

Exemple :

public  class TestColorTable : ProfessionalColorTable
{
    public override Color MenuItemSelected
    {
        get { return Color.Red; }
    }

    public override Color MenuBorder  //added for changing the menu border
    {
        get { return Color.Green; }
    }

You would use it like this:

private void Form1_Load(object sender, EventArgs e)
{
    menuStrip1.Renderer = new ToolStripProfessionalRenderer(new TestColorTable());
}


问:
How to read Media from Attachment using REST API
I have created an Attachment with image:

```<code>{
"_rid": "xD4vALTE7QBAAwAAAAAAAA==",
"Attachments": [
    {
        "contentType": "image/jpeg",
        "id": "10b91d7d-2e5e-466e-a896-3ee54baff4dc",
        "media": "/media/xD4vALTE7QBAAwAAAAAAALobDgYB",
        "_rid": "xD4vALTE7QBAAwAAAAAAALobDgY=",
        "_self": "dbs/xD4vAA==/colls/xD4vALTE7QA=/docs/xD4vALTE7QBAAwAAAAAAAA==/attachments/xD4vALTE7QBAAwAAAAAAALobDgY=",
        "_etag": "\"00000d37-0000-0000-0000-5a09602a0000\"",
        "_ts": 1510563882
    }
],
"_count": 1
</code>```

}

What is the url to the Media object?

When I use the Cosmos .NET SDK method DocumentClient.ReadMediaAsync(string mediaLink) where mediaLink is /media/xD4vALTE7QBAAwAAAAAAALobDgY= then I can get the Media stream and display the image. But this only works when connecting to Cosmos Db Emulator, when doing the same on the Azure Cosmos DB instance, then I get this error:

Unknown server error occurred when processing this request. ActivityId: 53508de6-2456-4213-947e-4361a8118574, Microsoft.Azure.Documents.Common/1.17.99.1, documentdb-dotnet-sdk/1.19.0 Host/32-bit MicrosoftWindowsNT/6.2.9200.0

The Attachment creation with Medial upload works.

I was thinking to try to query the CosmosDB using the Postman, but I cannot figure out the url to get the Media object.

答:
The url to the Media object is: https://[YOUR-DOCDB-HOST]/media/xD4vALTE7QBAAwAAAAAAALobDgYB

I call this as a GET request in Postman with the following Pre-Request Script:

```<code>// store our master key for documentdb
var mastKey = [YOUR-DOCUMENTDB-KEY-HERE];
console.log("mastKey = " + mastKey);

// store our date as RFC1123 format for the request
var today = new Date();
var UTCstring = today.toUTCString();
postman.setEnvironmentVariable("RFC1123time", UTCstring);

// define resourceId/Type now so we can assign based on the amount of levels
var resourceId = "[YOUR-RID-HERE]"; // _rid in attachment document
var resType = "media";

// assign our verb
var verb = request.method.toLowerCase();

// assign our RFC 1123 date
var date = UTCstring.toLowerCase();

// parse our master key out as base64 encoding
var key = CryptoJS.enc.Base64.parse(mastKey);
console.log("key = " + key);

// build up the request text for the signature so can sign it along with the key
var text = (verb || "").toLowerCase() + "\n" +
               (resType || "").toLowerCase() + "\n" +
               (resourceId || "").toLowerCase() + "\n" +
               (date || "").toLowerCase() + "\n" +
               "" + "\n";
console.log("text = " + text);

// create the signature from build up request text
var signature = CryptoJS.HmacSHA256(text, key);
console.log("sig = " + signature);

// back to base 64 bits
var base64Bits = CryptoJS.enc.Base64.stringify(signature);
console.log("base64bits = " + base64Bits);

// format our authentication token and URI encode it.
var MasterToken = "master";
var TokenVersion = "1.0";
auth = encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + base64Bits);
console.log("auth = " + auth);

// set our auth token enviornmental variable.
postman.setEnvironmentVariable("authToken", auth);
</code>```

There are two variables: [YOUR-DOCUMENTDB-KEY-HERE] and [YOUR-RID-HERE]. The kicker is, you need to query attachment meta data first to get the _rid value to use in the token when requesting the media.

The authToken and RFC1123time postman variables are used in the Authorization header:

Body:
I have created an Attachment with image:

{
"_rid": "xD4vALTE7QBAAwAAAAAAAA==",
"Attachments": [
    {
        "contentType": "image/jpeg",
        "id": "10b91d7d-2e5e-466e-a896-3ee54baff4dc",
        "media": "/media/xD4vALTE7QBAAwAAAAAAALobDgYB",
        "_rid": "xD4vALTE7QBAAwAAAAAAALobDgY=",
        "_self": "dbs/xD4vAA==/colls/xD4vALTE7QA=/docs/xD4vALTE7QBAAwAAAAAAAA==/attachments/xD4vALTE7QBAAwAAAAAAALobDgY=",
        "_etag": "\"00000d37-0000-0000-0000-5a09602a0000\"",
        "_ts": 1510563882
    }
],
"_count": 1

}

What is the url to the Media object?

When I use the Cosmos .NET SDK method DocumentClient.ReadMediaAsync(string mediaLink) where mediaLink is /media/xD4vALTE7QBAAwAAAAAAALobDgY= then I can get the Media stream and display the image. But this only works when connecting to Cosmos Db Emulator, when doing the same on the Azure Cosmos DB instance, then I get this error:

Unknown server error occurred when processing this request. ActivityId: 53508de6-2456-4213-947e-4361a8118574, Microsoft.Azure.Documents.Common/1.17.99.1, documentdb-dotnet-sdk/1.19.0 Host/32-bit MicrosoftWindowsNT/6.2.9200.0

The Attachment creation with Medial upload works.

I was thinking to try to query the CosmosDB using the Postman, but I cannot figure out the url to get the Media object.

Body:
The url to the Media object is: https://[YOUR-DOCDB-HOST]/media/xD4vALTE7QBAAwAAAAAAALobDgYB

I call this as a GET request in Postman with the following Pre-Request Script:

// store our master key for documentdb
var mastKey = [YOUR-DOCUMENTDB-KEY-HERE];
console.log("mastKey = " + mastKey);

// store our date as RFC1123 format for the request
var today = new Date();
var UTCstring = today.toUTCString();
postman.setEnvironmentVariable("RFC1123time", UTCstring);

// define resourceId/Type now so we can assign based on the amount of levels
var resourceId = "[YOUR-RID-HERE]"; // _rid in attachment document
var resType = "media";

// assign our verb
var verb = request.method.toLowerCase();

// assign our RFC 1123 date
var date = UTCstring.toLowerCase();

// parse our master key out as base64 encoding
var key = CryptoJS.enc.Base64.parse(mastKey);
console.log("key = " + key);

// build up the request text for the signature so can sign it along with the key
var text = (verb || "").toLowerCase() + "\n" +
               (resType || "").toLowerCase() + "\n" +
               (resourceId || "").toLowerCase() + "\n" +
               (date || "").toLowerCase() + "\n" +
               "" + "\n";
console.log("text = " + text);

// create the signature from build up request text
var signature = CryptoJS.HmacSHA256(text, key);
console.log("sig = " + signature);

// back to base 64 bits
var base64Bits = CryptoJS.enc.Base64.stringify(signature);
console.log("base64bits = " + base64Bits);

// format our authentication token and URI encode it.
var MasterToken = "master";
var TokenVersion = "1.0";
auth = encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + base64Bits);
console.log("auth = " + auth);

// set our auth token enviornmental variable.
postman.setEnvironmentVariable("authToken", auth);

There are two variables: [YOUR-DOCUMENTDB-KEY-HERE] and [YOUR-RID-HERE]. The kicker is, you need to query attachment meta data first to get the _rid value to use in the token when requesting the media.

The authToken and RFC1123time postman variables are used in the Authorization header:


问:
Adding Font To A CSS Page
I have a font I downloaded and I'm trying to apply that font to my site.

so I simply used font-family but my font isn't there(obviously) any idea on how to add it?

答:
You have to embed the font via CSS before you can use it (since most computers probably don't have the font installed locally). Check out:

CSS Cross Browser Fonts using CSS3 @font-face

The cross-browser compatible code ends up looking something like:

```<code>@font-face
{
    font-family: "Your Font Name";
    src: url(~/Fonts/SomeFontName.eot); /* IE */
    src: local("The Real Font Name"),
         url(~/Fonts/FontFileName.ttf) format("truetype"); /* non-IE */
}

body
{
    font-family:"Your Font Name", verdana, helvetica, sans-serif;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Adding Font To A CSS Page

Body:
You have to embed the font via CSS before you can use it (since most computers probably don't have the font installed locally). Check out:

CSS Cross Browser Fonts using CSS3 @font-face

The cross-browser compatible code ends up looking something like:

@font-face
{
    font-family: "Your Font Name";
    src: url(~/Fonts/SomeFontName.eot); /* IE */
    src: local("The Real Font Name"),
         url(~/Fonts/FontFileName.ttf) format("truetype"); /* non-IE */
}

body
{
    font-family:"Your Font Name", verdana, helvetica, sans-serif;
}


问:
Seaborn does not show legend with %matplotlib notebook
When I use %matplotlib notebook, the legend is not displayed.

```<code>%matplotlib notebook
...
fg = seaborn.FacetGrid(data=df, hue='Scenario', hue_order=df.Scenario.unique().tolist(), aspect=1.61)
fg.map(plt.scatter, 'Yaw', 'posNoseEye').add_legend()
</code>```

While when I use %matplotlib inline, the legend is correctly shown.

```<code>%matplotlib inline
...
fg = seaborn.FacetGrid(data=df, hue='Scenario', hue_order=df.Scenario.unique().tolist(), aspect=1.61)
fg.map(plt.scatter, 'Yaw', 'posNoseEye').add_legend()
</code>```

How to manage it in %matplotlib notebook ?
Thanks

As I can't put image in the comment, I tried the answer below and it still does not work.
I have the last version of matplotlib and  seaborn.

答:
The figure does not have any space for the legend. There are several ways to overcome this, as shown in this answer.

An option is to manually create some space for the legend, e.g.

```<code>%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.random.rand(20,2), columns=['Yaw', 'posNoseEye'])
df["Scenario"] = np.random.choice(["Scenario A","Scenario B"], size=20)

fg = sns.FacetGrid(data=df, hue='Scenario', hue_order=df.Scenario.unique().tolist(), aspect=1.61)
fg.map(plt.scatter, 'Yaw', 'posNoseEye')

fg.fig.legend()

fg.fig.subplots_adjust(right=0.7)
plt.show()
</code>```

Body:
When I use %matplotlib notebook, the legend is not displayed.

%matplotlib notebook
...
fg = seaborn.FacetGrid(data=df, hue='Scenario', hue_order=df.Scenario.unique().tolist(), aspect=1.61)
fg.map(plt.scatter, 'Yaw', 'posNoseEye').add_legend()

While when I use %matplotlib inline, the legend is correctly shown.

%matplotlib inline
...
fg = seaborn.FacetGrid(data=df, hue='Scenario', hue_order=df.Scenario.unique().tolist(), aspect=1.61)
fg.map(plt.scatter, 'Yaw', 'posNoseEye').add_legend()

How to manage it in %matplotlib notebook ?
Thanks

As I can't put image in the comment, I tried the answer below and it still does not work.
I have the last version of matplotlib and  seaborn.

Body:
The figure does not have any space for the legend. There are several ways to overcome this, as shown in this answer.

An option is to manually create some space for the legend, e.g.

%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.random.rand(20,2), columns=['Yaw', 'posNoseEye'])
df["Scenario"] = np.random.choice(["Scenario A","Scenario B"], size=20)

fg = sns.FacetGrid(data=df, hue='Scenario', hue_order=df.Scenario.unique().tolist(), aspect=1.61)
fg.map(plt.scatter, 'Yaw', 'posNoseEye')

fg.fig.legend()

fg.fig.subplots_adjust(right=0.7)
plt.show()


问:
Function that takes string as Input, evaluate it like a calculator and return the Integer answer
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

```<code>d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i
</code>```

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

答:
You have the right idea in your code, but are trying to effectively add to the sum by referencing the next character in the string which limits you to a string of form:

```<code>.a.b
</code>```

where . is a + or -.

What you want to do is iterate through each character in the string and if that character is a plus or minus (i.e. not a digit) then change the multiplication variable to a 1 or -1 respectively. Then, whenever you reach an actual digit to add or subtract, you just add that digit times by the multiplication value.

So here is the code for the logic outlined above:

```<code>s = "1+2-3"
m = 1
sm = 0
for c in s:
    is c.isdigit():
        sm += m * int(c)
    else:
         m = -1 if c == "-" else 1
</code>```

which outputs sm as:

```<code>0
</code>```

Bare in mind that this only works when the string alternates between an operation and a digit.

Body:
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

Body:
You have the right idea in your code, but are trying to effectively add to the sum by referencing the next character in the string which limits you to a string of form:

.a.b

where . is a + or -.

What you want to do is iterate through each character in the string and if that character is a plus or minus (i.e. not a digit) then change the multiplication variable to a 1 or -1 respectively. Then, whenever you reach an actual digit to add or subtract, you just add that digit times by the multiplication value.

So here is the code for the logic outlined above:

s = "1+2-3"
m = 1
sm = 0
for c in s:
    is c.isdigit():
        sm += m * int(c)
    else:
         m = -1 if c == "-" else 1

which outputs sm as:

0

Bare in mind that this only works when the string alternates between an operation and a digit.


问:
JavaScript textarea calculate
The point is that you create a table of your own size. Is there any possible way that when I press "Calc" button it calculates number in this table? Imagine all the rows and columns are filled with random numbers. I want to calculate numbers in same row. First you create a table, then you fill it with values and than you calculate all values between each other.
This is my code:

function createTable() {
  var num_rows = document.getElementById('rows').value;
  var num_cols = document.getElementById('cols').value;
  var theader = '
\n';
  var tbody = '';

  for (var i = 0; i < num_rows; i++) {
    tbody += '
';
    for (var j = 0; j < num_cols; j++) {
      tbody += '';
      tbody += '<input type="text" name="something">';
      tbody += '	'
    }
    tbody += '
\n';
  }
  var tfooter = '
';
  document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="tablegen">
  <label>col: <input type="text" name="rows" id="rows"/></label><br />
  <label>row: <input type="text" name="cols" id="cols"/></label><br/>
  <input name="generate" type="button" value="Make table!" onclick='createTable();' />
</form>

<div id="wrapper"></div>
<input name="calculate" type="button" value="Calc" /></code>```

答:
function createTable() {
  let num_rows = document.getElementById('rows').value;
  let num_cols = document.getElementById('cols').value;
  let table = '
';

  for (var i = 0; i < num_rows; i++) {
    table += '
';
    for (var j = 0; j < num_cols; j++) {
      table += '<textarea style="width:95%;"></textarea>	';
    }
    table += '
';
  }
  table += '
';
  document.getElementById('wrapper').innerHTML = table;
}

function calcValues() {
  let result = 0;
  let table = document.getElementById('my-table');
  if (table) {
    let textareas = table.getElementsByTagName('textarea');
    if (textareas.length > 0) {
      for (let i = 0; i < textareas.length; i++) {
        let textarea = textareas[i];
        let value = textarea.value;
        if (!isNaN(parseInt(value))) {
          result *= parseInt(value);
        } else {
          textarea.value = 'That was not a number!';
        }
      }
      if (result != 0) document.getElementById('calcResult').innerHTML = '
The result is: ' + result.toString() + '
';
    }
  } else alert('Make a table!');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="tablegen">
  <input type="text" name="rows" id="rows" placeholder="Columns" />
  <input type="text" name="cols" id="cols" placeholder="Rows" />
  <input name="generate" type="button" value="Make table!" onclick="createTable()" />
</form>
<div id="wrapper" style="margin:5px 0;border:1px solid black;min-height:10px;">Create a table first!</div>
<input name="calculate" type="button" value="Calculate Values!" onClick="calcValues()" />
<p id="calcResult"></p></code>```

Title: JavaScript textarea calculate

Body:
The point is that you create a table of your own size. Is there any possible way that when I press "Calc" button it calculates number in this table? Imagine all the rows and columns are filled with random numbers. I want to calculate numbers in same row. First you create a table, then you fill it with values and than you calculate all values between each other.
This is my code:

function createTable() {
  var num_rows = document.getElementById('rows').value;
  var num_cols = document.getElementById('cols').value;
  var theader = '
\n';
  var tbody = '';

  for (var i = 0; i < num_rows; i++) {
    tbody += '
';
    for (var j = 0; j < num_cols; j++) {
      tbody += '';
      tbody += '<input type="text" name="something">';
      tbody += '	'
    }
    tbody += '
\n';
  }
  var tfooter = '
';
  document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

<form name="tablegen">
  col: <input type="text" name="rows" id="rows"/>

  row: <input type="text" name="cols" id="cols"/>

  <input name="generate" type="button" value="Make table!" onclick='createTable();' />
</form>

<input name="calculate" type="button" value="Calc" />

Body:
function createTable() {
  let num_rows = document.getElementById('rows').value;
  let num_cols = document.getElementById('cols').value;
  let table = '<table id="my-table" border="1" style="width:100%;">';

  for (var i = 0; i < num_rows; i++) {
    table += '<tr>';
    for (var j = 0; j < num_cols; j++) {
      table += '<td><textarea style="width:95%;"></textarea></td>';
    }
    table += '</tr>';
  }
  table += '</table>';
  document.getElementById('wrapper').innerHTML = table;
}

function calcValues() {
  let result = 0;
  let table = document.getElementById('my-table');
  if (table) {
    let textareas = table.getElementsByTagName('textarea');
    if (textareas.length > 0) {
      for (let i = 0; i < textareas.length; i++) {
        let textarea = textareas[i];
        let value = textarea.value;
        if (!isNaN(parseInt(value))) {
          result *= parseInt(value);
        } else {
          textarea.value = 'That was not a number!';
        }
      }
      if (result != 0) document.getElementById('calcResult').innerHTML = '<p>The result is: ' + result.toString() + '</p>';
    }
  } else alert('Make a table!');
}

<form name="tablegen">
  <input type="text" name="rows" id="rows" placeholder="Columns" />
  <input type="text" name="cols" id="cols" placeholder="Rows" />
  <input name="generate" type="button" value="Make table!" onclick="createTable()" />
</form>
<div id="wrapper" style="margin:5px 0;border:1px solid black;min-height:10px;">Create a table first!</div>
<input name="calculate" type="button" value="Calculate Values!" onClick="calcValues()" />
<p id="calcResult"></p>


问:
How to import machine certificate into the Personal certificate store associated with a Windows service?
I am reposting my question from the MSDN forums here.

This problem has to do with importing a certificate into the personal certificate store associated with a windows service.

The name of my machine is il-mark-lap (the machine is pingable by this name).

The process:

1. There is a self signed authority certificate, let us call it NCCA. Its private key lives on another machine, let us refer it by dev-profiler.

```<code>dev-profiler> makecert -n "CN=NCCA" -sr localmachine -ss root -a sha1 -cy authority -r -sv NCCA.pvk NCCA.cer
</code>```

2. The il-mark-lap machine certificate is created on dev-profiler and imported to the LocalComputer\My certificate store on il-mark-lap. Note, that the authority certificate (NCCA) has to be moved to LocalComputer\Root certificate store, but since I do not know how to move, I use the export-delete-import sequence.

```<code>dev-profiler> makecert -n "CN=il-mark-lap" -sr CurrentUser -ss My -cy end -pe -sky exchange -a sha1 -is Root -ir LocalMachine -in NCCA
dev-profiler> certutil -user -exportpfx -p 123 il-mark-lap il-mark-lap.pfx
dev-profiler> certutil -user -delstore My il-mark-lap

il-mark-lap> cscript CStore.vbs import -l LM -s My -e il-mark-lap.pfx 123
il-mark-lap> cscript CStore.vbs export -l LM -s My -subject NCCA NCCA.cer
il-mark-lap> cscript CStore.vbs delete -noprompt -l LM -subject NCCA My
il-mark-lap> cscript CStore.vbs import -l LM -s Root NCCA.cer
</code>```

3. The il-mark-lap machine certificate is copied from LocalComputer\My certificate store into MSMQ\My certificate store (Message Queuing service Personal certificate store). Again, I do not know how to copy, so I use the export-import sequence.

```<code>il-mark-lap> cscript CStore.vbs export -l LM -s My -subject il-mark-lap tmp.pfx
il-mark-lap> ImportPfxIntoSrvCertStore MSMQ tmp.pfx 123
</code>```

Where ImportPfxIntoSrvCertStore is my program written in C++ to import the given PFX into the Personal certificate store of the given service, MSMQ in my case.

Omitting all the error handling, the relevant  C++ code is this:

```<code>CSafeHandle pfxFileHandle(::CreateFile(wszPfxFilePath, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0));
CSafeHandle pfxFileMapping(::CreateFileMapping(pfxFileHandle, 0, PAGE_READONLY, 0, 0, 0));
CSafeMapViewOfFile pfxFileBuffer(::MapViewOfFile(pfxFileMapping, FILE_MAP_READ, 0, 0, 0));

CRYPT_DATA_BLOB blob;
blob.cbData = ::GetFileSize(pfxFileHandle, 0);
blob.pbData = LPBYTE(LPVOID(pfxFileBuffer));

CSafeCertStoreHandle pfxStore(::PFXImportCertStore(&blob, wszPassword, CRYPT_MACHINE_KEYSET | CRYPT_EXPORTABLE));
CSafeCertStoreHandle serviceStore(::CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_SERVICES, wszCertificateStoreName));

PCCERT_CONTEXT pctx = NULL;
while (NULL != (pctx = ::CertEnumCertificatesInStore(pfxStore, pctx)))
{
 ::CertAddCertificateContextToStore(serviceStore, pctx, CERT_STORE_ADD_REPLACE_EXISTING, NULL);
}
</code>```

Ignore the CSafeXXXHandle and CSafeMapViewOfFile classes, these are simple handle/buffer holders, releasing the respective handle/buffer in the destructor ("resource acquisition is initialization" design pattern).

Anyway, the PFXImportCertStore API fails with the message An error occurred during encode or decode operation. If I call the PFXIsPFXBlob API, it returns FALSE.

Here is the Locals debugger view at the start of the code:

```<code>+        wszPfxFilePath    0x00774e0c "tmp.pfx"    const wchar_t *
+        wszCertificateStoreName    0x002cf7f4 "MSMQ\My"    const wchar_t *
+        wszPassword    0x00774e1c "123"    const wchar_t *
</code>```

So, all the parameters seem to be correct.

I have no idea what is wrong. The PFX file being imported is absolutely correct, because it is imported flawlessly using the MMC console.

Incidentally, I have based my code on the example found in this article - http://www.codeguru.com/Cpp/I-N/internet/security/article.php/c6211

Edit

I would like to emphasize that I need a non interactive procedure to copy the machine certificate from LocalComputer\My to MSMQ\My.

答:
Instead of using a program I would try to use the certificate store mmc plugin:

Start mmc.exe, this will give you the MMC in authoring mode.

Click File -> Add/remove Snap-in

Find and double-click "Certificates". This will pop up a dialog where you can select which certificate storage you want to administer.

I think "Service Account" is the appropriate selection for you here

Click next

Select local if you are on il-mark-lap already, otherwise select "Another computer". AFAIK, you will have to be logged in with a domain administrator account for this to work though.

Click next

Select your service

click finish.

At this point you should already be able to access the certificate storage for your service. If you want to do this more often then I suggest you do this as well:

Right-click "Certificates" in the tree and select "New Window from Here"

Switch back to the console root window and close it

Save your work of art to a .msc file

Edit

Before you save, select "Certificates" from the tree, and then View -> Options. Here you can select to see the "Physical Certificate stores" if you like.

Body:
I am reposting my question from the MSDN forums here.

This problem has to do with importing a certificate into the personal certificate store associated with a windows service.

The name of my machine is il-mark-lap (the machine is pingable by this name).

The process:

1. There is a self signed authority certificate, let us call it NCCA. Its private key lives on another machine, let us refer it by dev-profiler.

dev-profiler> makecert -n "CN=NCCA" -sr localmachine -ss root -a sha1 -cy authority -r -sv NCCA.pvk NCCA.cer

2. The il-mark-lap machine certificate is created on dev-profiler and imported to the LocalComputer\My certificate store on il-mark-lap. Note, that the authority certificate (NCCA) has to be moved to LocalComputer\Root certificate store, but since I do not know how to move, I use the export-delete-import sequence.

dev-profiler> makecert -n "CN=il-mark-lap" -sr CurrentUser -ss My -cy end -pe -sky exchange -a sha1 -is Root -ir LocalMachine -in NCCA
dev-profiler> certutil -user -exportpfx -p 123 il-mark-lap il-mark-lap.pfx
dev-profiler> certutil -user -delstore My il-mark-lap

il-mark-lap> cscript CStore.vbs import -l LM -s My -e il-mark-lap.pfx 123
il-mark-lap> cscript CStore.vbs export -l LM -s My -subject NCCA NCCA.cer
il-mark-lap> cscript CStore.vbs delete -noprompt -l LM -subject NCCA My
il-mark-lap> cscript CStore.vbs import -l LM -s Root NCCA.cer

3. The il-mark-lap machine certificate is copied from LocalComputer\My certificate store into MSMQ\My certificate store (Message Queuing service Personal certificate store). Again, I do not know how to copy, so I use the export-import sequence.

il-mark-lap> cscript CStore.vbs export -l LM -s My -subject il-mark-lap tmp.pfx
il-mark-lap> ImportPfxIntoSrvCertStore MSMQ tmp.pfx 123

Where ImportPfxIntoSrvCertStore is my program written in C++ to import the given PFX into the Personal certificate store of the given service, MSMQ in my case.

Omitting all the error handling, the relevant  C++ code is this:

CSafeHandle pfxFileHandle(::CreateFile(wszPfxFilePath, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0));
CSafeHandle pfxFileMapping(::CreateFileMapping(pfxFileHandle, 0, PAGE_READONLY, 0, 0, 0));
CSafeMapViewOfFile pfxFileBuffer(::MapViewOfFile(pfxFileMapping, FILE_MAP_READ, 0, 0, 0));

CRYPT_DATA_BLOB blob;
blob.cbData = ::GetFileSize(pfxFileHandle, 0);
blob.pbData = LPBYTE(LPVOID(pfxFileBuffer));

CSafeCertStoreHandle pfxStore(::PFXImportCertStore(&blob, wszPassword, CRYPT_MACHINE_KEYSET | CRYPT_EXPORTABLE));
CSafeCertStoreHandle serviceStore(::CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_SERVICES, wszCertificateStoreName));

PCCERT_CONTEXT pctx = NULL;
while (NULL != (pctx = ::CertEnumCertificatesInStore(pfxStore, pctx)))
{
 ::CertAddCertificateContextToStore(serviceStore, pctx, CERT_STORE_ADD_REPLACE_EXISTING, NULL);
}

Ignore the CSafeXXXHandle and CSafeMapViewOfFile classes, these are simple handle/buffer holders, releasing the respective handle/buffer in the destructor ("resource acquisition is initialization" design pattern).

Anyway, the PFXImportCertStore API fails with the message An error occurred during encode or decode operation. If I call the PFXIsPFXBlob API, it returns FALSE.

Here is the Locals debugger view at the start of the code:

+        wszPfxFilePath    0x00774e0c "tmp.pfx"    const wchar_t *
+        wszCertificateStoreName    0x002cf7f4 "MSMQ\My"    const wchar_t *
+        wszPassword    0x00774e1c "123"    const wchar_t *

So, all the parameters seem to be correct.

I have no idea what is wrong. The PFX file being imported is absolutely correct, because it is imported flawlessly using the MMC console.

Incidentally, I have based my code on the example found in this article - http://www.codeguru.com/Cpp/I-N/internet/security/article.php/c6211

Edit

I would like to emphasize that I need a non interactive procedure to copy the machine certificate from LocalComputer\My to MSMQ\My.


问:
changing notebook page title to bold in Wxpython
I have the following code:

```<code>self.NB = wx.Notebook(self.panel_1, -1, style=0)
self.NB_Partsnote= NB_Parts(self.NB,None,userId)
self.NB_Parts2note = NB_Parts2(self.NB,None,userId)
self.NB.AddPage(self.NB_Partsnote,_("Parts"))
self.NB.AddPage(self.NB_Parts2note ,_("Parts2"))
</code>```

This create the notebook and add 2 tabs.

in Parts2 I have a textctrl with readonly data:

```<code>self.cellPhone = wx.TextCtrl(self, -1, "", style=wx.TE_READONLY)
</code>```

What I want is when self.cellPhone has value then the Parts2 title of the notebook to be BOLD

I tried to do:

```<code>class NB_Parts2(GeneralPanel):
    def __init__(self,parent,poId,userId, toolbar=None):
    more code...
    if self.cellPhone.GetValue() <> '':
        SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT,
                             wx.FONTWEIGHT_BOLD,
                             wx.FONTSTYLE_NORMAL))
</code>```

But this doesn't work. nothing happens. I tried also to remove the condition so it will always be BOLD but still nothing happens.

How can I do that?

答:
When using the native notebook widget a font can be set for all tabs, but not for individual tab.  Calling notebook.SetFont would result in all tabs being bold.

One possible solution is using Images to customize what gets displayed in each tab.

```<code>import wx

app = wx.App()

frame = wx.Frame(None, size=(600, 600))

# Draw a bitmap image with normal text
notBold = wx.Bitmap(150, 40, depth=32)
dc = wx.MemoryDC()
dc.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT,
                   wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,))

dc.SelectObject(notBold)
dc.Clear()
dc.DrawText("Text not bold", 5, 5)
dc.SelectObject(wx.NullBitmap)

# Draw a bitmap image with bold text
withBold = wx.Bitmap(150, 40)
dc = wx.MemoryDC()
dc.SetFont(wx.Font(12,  wx.FONTFAMILY_DEFAULT,
                   wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD,))
dc.SelectObject(withBold)
dc.Clear()
dc.DrawText("Text BOLD", 5, 5)
dc.SelectObject(wx.NullBitmap)

# wx.Notebook needs a wx.ImageList to set images from
# Notice images must be at least the size set by wx.ImageList.__init__
imgList = wx.ImageList(150, 40)
imgList.Add(notBold)
imgList.Add(withBold)

panel = wx.Panel(frame)
notebook = wx.Notebook(panel)
notebook.SetImageList(imgList)

notebook.AddPage(wx.Panel(notebook), "")
notebook.SetPageImage(0, 0)  # notBold
notebook.AddPage(wx.Panel(notebook), "")
notebook.SetPageImage(1, 1)  # withBold

notebook.AddPage(wx.Panel(notebook), "Image not required")

sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(notebook, proportion=1, flag=wx.EXPAND)
panel.SetSizerAndFit(sizer)

frame.Show()
app.MainLoop()
</code>```

Body:
I have the following code:

self.NB = wx.Notebook(self.panel_1, -1, style=0)
self.NB_Partsnote= NB_Parts(self.NB,None,userId)
self.NB_Parts2note = NB_Parts2(self.NB,None,userId)
self.NB.AddPage(self.NB_Partsnote,_("Parts"))
self.NB.AddPage(self.NB_Parts2note ,_("Parts2"))

This create the notebook and add 2 tabs.

in Parts2 I have a textctrl with readonly data:

self.cellPhone = wx.TextCtrl(self, -1, "", style=wx.TE_READONLY)

What I want is when self.cellPhone has value then the Parts2 title of the notebook to be BOLD

I tried to do:

class NB_Parts2(GeneralPanel):
    def __init__(self,parent,poId,userId, toolbar=None):
    more code...
    if self.cellPhone.GetValue() <> '':
        SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT,
                             wx.FONTWEIGHT_BOLD,
                             wx.FONTSTYLE_NORMAL))

But this doesn't work. nothing happens. I tried also to remove the condition so it will always be BOLD but still nothing happens.

How can I do that?

Body:
When using the native notebook widget a font can be set for all tabs, but not for individual tab.  Calling notebook.SetFont would result in all tabs being bold.

One possible solution is using Images to customize what gets displayed in each tab.

import wx

app = wx.App()

frame = wx.Frame(None, size=(600, 600))

# Draw a bitmap image with normal text
notBold = wx.Bitmap(150, 40, depth=32)
dc = wx.MemoryDC()
dc.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT,
                   wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,))

dc.SelectObject(notBold)
dc.Clear()
dc.DrawText("Text not bold", 5, 5)
dc.SelectObject(wx.NullBitmap)

# Draw a bitmap image with bold text
withBold = wx.Bitmap(150, 40)
dc = wx.MemoryDC()
dc.SetFont(wx.Font(12,  wx.FONTFAMILY_DEFAULT,
                   wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD,))
dc.SelectObject(withBold)
dc.Clear()
dc.DrawText("Text BOLD", 5, 5)
dc.SelectObject(wx.NullBitmap)

# wx.Notebook needs a wx.ImageList to set images from
# Notice images must be at least the size set by wx.ImageList.__init__
imgList = wx.ImageList(150, 40)
imgList.Add(notBold)
imgList.Add(withBold)

panel = wx.Panel(frame)
notebook = wx.Notebook(panel)
notebook.SetImageList(imgList)

notebook.AddPage(wx.Panel(notebook), "")
notebook.SetPageImage(0, 0)  # notBold
notebook.AddPage(wx.Panel(notebook), "")
notebook.SetPageImage(1, 1)  # withBold

notebook.AddPage(wx.Panel(notebook), "Image not required")

sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(notebook, proportion=1, flag=wx.EXPAND)
panel.SetSizerAndFit(sizer)

frame.Show()
app.MainLoop()


问:
Google Analytics Measurement Protocol Sale Not Showing
I'm trying to use the google analytics measurement protocol (https://developers.google.com/analytics/devguides/collection/protocol/v1/reference) to send enhanced e-commerce data, but the hits are not showing up and I don't really know how else to ask for help. I'm using the python requests library to send the data like so:

HTTP POST

Url:

```<code>https://www.google-analytics.com/collect
</code>```

Headers:

```<code>'User-Agent': 'python-requests/2.18.4'
</code>```

payload:

```<code>{
'cid': 'e60da0b9e312442fb1fe3e30c0f2d679',
'ea': 'Confirmed Booking',
'ec': 'Booking',
'el': 'SpeediShuttle-Shared Ride Van-oneway-from-HNL',
'ev': 18,
'pa': 'purchase',
'pr1br': 'SpeediShuttle',
'pr1ca': 'Shared Ride Van',
'pr1nm': 'SpeediShuttle-Shared Ride Van-oneway-from-HNL',
'pr1pr': 18.16,
'pr1qt': 1,
'pr1va': 'oneway-from-HNL',
't': 'event',
'ta': 'Airportshuttles.com',
'ti': '2IIMVM.GO',
'tid': 'UA-10350251-1',
'tr': 18.16,
'ts': 0.77,
'tt': '1.17',
'v': 1,
'z': 707523808
}
</code>```

Is there anything obvious that I'm doing wrong?

答: If you take a look at the documentation, you see that the payload is supposed to be in FormData format, and not json. I don't think it will accept json, but to be sure your request is okay, you could verify your request by changing the endpoint to '/debug/collect' (see the docs)</p>

Body:
I'm trying to use the google analytics measurement protocol (https://developers.google.com/analytics/devguides/collection/protocol/v1/reference) to send enhanced e-commerce data, but the hits are not showing up and I don't really know how else to ask for help. I'm using the python requests library to send the data like so:

HTTP POST

Url:

https://www.google-analytics.com/collect

Headers:

'User-Agent': 'python-requests/2.18.4'

payload:

{
'cid': 'e60da0b9e312442fb1fe3e30c0f2d679',
'ea': 'Confirmed Booking',
'ec': 'Booking',
'el': 'SpeediShuttle-Shared Ride Van-oneway-from-HNL',
'ev': 18,
'pa': 'purchase',
'pr1br': 'SpeediShuttle',
'pr1ca': 'Shared Ride Van',
'pr1nm': 'SpeediShuttle-Shared Ride Van-oneway-from-HNL',
'pr1pr': 18.16,
'pr1qt': 1,
'pr1va': 'oneway-from-HNL',
't': 'event',
'ta': 'Airportshuttles.com',
'ti': '2IIMVM.GO',
'tid': 'UA-10350251-1',
'tr': 18.16,
'ts': 0.77,
'tt': '1.17',
'v': 1,
'z': 707523808
}

Is there anything obvious that I'm doing wrong?


问:
awk to convert unix time without strftime or date command(-d & -r option isn't supported in AIX)
I have current output as

```<code>file | awk '$1=="IMAGE" {print $2","$7","$14","$17","$19/1000}'

ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5
</code>```

Expected output should have these unix time converted into human readable format, I can't use strftime or date -d option as they are not supported in AIX.
I do have a user defined command which i can use to convert but i can't use it in awk.I tried creating function and then use it in awk which didn't help

With Ed's Code I am getting this output as the user defined command gives output like this, However I want it to give me only day/Mon/Year. I can use awk to print this in user command, But i do i use it in this function?

```<code>ABC POL1 1510009167 = Mon Nov  6 17:59:27 EST 2017 1510009677 = Tue Nov  7 04:37:57 IST 2017 20.5
DEF POL2 1510009667 = Mon Nov  6 18:07:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
XYZ POL3 1510007867 = Mon Nov  6 17:37:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
PQR POL4 1510009267 = Mon Nov  6 18:01:07 EST 2017 1510009997 = Tue Nov  7 04:43:17 IST 2017 20.5
</code>```

答:
if you already have a date conversion routine, wrap it in a command and call from awk

using your data

```<code>$ awk -F, '{"./todate.sh " $3 | getline $3}1' file

ABC POL1 Mon Nov  6 17:59:27 EST 2017 1510009677 20.5
DEF POL2 Mon Nov  6 18:07:47 EST 2017 1510009887 20.5
XYZ POL3 Mon Nov  6 17:37:47 EST 2017 1510009887 20.5
PQR POL4 Mon Nov  6 18:01:07 EST 2017 1510009997 20.5
</code>```

where the date conversion I used is

```<code>==> todate.sh <==

#!/bin/bash
date -d "@$1"
</code>```

Body:
I have current output as

file | awk '$1=="IMAGE" {print $2","$7","$14","$17","$19/1000}'

ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5

Expected output should have these unix time converted into human readable format, I can't use strftime or date -d option as they are not supported in AIX.
I do have a user defined command which i can use to convert but i can't use it in awk.I tried creating function and then use it in awk which didn't help

With Ed's Code I am getting this output as the user defined command gives output like this, However I want it to give me only day/Mon/Year. I can use awk to print this in user command, But i do i use it in this function?

ABC POL1 1510009167 = Mon Nov  6 17:59:27 EST 2017 1510009677 = Tue Nov  7 04:37:57 IST 2017 20.5
DEF POL2 1510009667 = Mon Nov  6 18:07:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
XYZ POL3 1510007867 = Mon Nov  6 17:37:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
PQR POL4 1510009267 = Mon Nov  6 18:01:07 EST 2017 1510009997 = Tue Nov  7 04:43:17 IST 2017 20.5

Body:
if you already have a date conversion routine, wrap it in a command and call from awk

using your data

$ awk -F, '{"./todate.sh " $3 | getline $3}1' file

ABC POL1 Mon Nov  6 17:59:27 EST 2017 1510009677 20.5
DEF POL2 Mon Nov  6 18:07:47 EST 2017 1510009887 20.5
XYZ POL3 Mon Nov  6 17:37:47 EST 2017 1510009887 20.5
PQR POL4 Mon Nov  6 18:01:07 EST 2017 1510009997 20.5

where the date conversion I used is

==> todate.sh <==

#!/bin/bash
date -d "@$1"


问:
Spark DataFrame/Dataset Find most common value for each key Efficient way
Problem:
I have a problem to map most common value of a key in spark(using scala). I have done it with RDD but don't know how to do efficiently with DF/DS(sparksql)

dataset is like

```<code>key1 = value_a
key1 = value_b
key1 = value_b
key2 = value_a
key2 = value_c
key2 = value_c
key3 = value_a
</code>```

After spark transformation and access output should be each key with its common value

Output

```<code>key1 = valueb
key2 = valuec
key3 = valuea
</code>```

Tried until now:

RDD

I have tried to map and reduce by group of (key,value),count in RDD and it makes logic but I cant translate this into sparksql(DataFrame/Dataset) (as I want minimum shuffle across network)

Here is my code for RDD

```<code> val data = List(

"key1,value_a",
"key1,value_b",
"key1,value_b",
"key2,value_a",
"key2,value_c",
"key2,value_c",
"key3,value_a"

)

val sparkConf = new SparkConf().setMaster("local").setAppName("example")
val sc = new SparkContext(sparkConf)

val lineRDD = sc.parallelize(data)

val pairedRDD = lineRDD.map { line =>
val fields = line.split(",")
(fields(0), fields(2))
}

val flatPairsRDD = pairedRDD.flatMap {
  (key, val) => ((key, val), 1)
}

val SumRDD = flatPairsRDD.reduceByKey((a, b) => a + b)

val resultsRDD = SumRDD.map{
  case ((key, val), count) => (key, (val,count))
 }.groupByKey.map{
  case (key, valList) => (name, valList.toList.sortBy(_._2).reverse.head)
}

resultsRDD.collect().foreach(println)
</code>```

DataFrame , Using Windowing: I am trying with Window.partitionBy("key", "value") to aggregate the count over the window. and thn sorting and agg() respectively

答:
According to what I understood from your question here's what you can do

First you have to read the data and convert it to dataframe

```<code>val df = sc.textFile("path to the data file")   //reading file line by line
  .map(line => line.split("="))                 // splitting each line by =
  .map(array => (array(0).trim, array(1).trim)) //tuple2(key, value) created
  .toDF("key", "value")                        //rdd converted to dataframe which required import sqlContext.implicits._
</code>```

which would be

```<code>+----+-------+
|key |value  |
+----+-------+
|key1|value_a|
|key1|value_b|
|key1|value_b|
|key2|value_a|
|key2|value_c|
|key2|value_c|
|key3|value_a|
+----+-------+
</code>```

Next step would be to count the repetition of identical values for each key and select the value that repeated the most for each key which can be done by using Window function, and aggregations as below

```<code>import org.apache.spark.sql.expressions._                   //import Window library
def windowSpec = Window.partitionBy("key", "value")         //defining a window frame for the aggregation
import org.apache.spark.sql.functions._                     //importing inbuilt functions
df.withColumn("count", count("value").over(windowSpec))     // counting repeatition of value for each group of key, value and assigning that value to new column called as count
  .orderBy($"count".desc)                                   // order dataframe with count in descending order
  .groupBy("key")                                           // group by key
  .agg(first("value").as("value"))                          //taking the first row of each key with count column as the highest
</code>```

thus the final output should be equal to

```<code>+----+-------+
|key |value  |
+----+-------+
|key3|value_a|
|key1|value_b|
|key2|value_c|
+----+-------+
</code>```

Body:
Problem:
I have a problem to map most common value of a key in spark(using scala). I have done it with RDD but don't know how to do efficiently with DF/DS(sparksql)

dataset is like

key1 = value_a
key1 = value_b
key1 = value_b
key2 = value_a
key2 = value_c
key2 = value_c
key3 = value_a

After spark transformation and access output should be each key with its common value

Output

key1 = valueb
key2 = valuec
key3 = valuea

Tried until now:

RDD

I have tried to map and reduce by group of (key,value),count in RDD and it makes logic but I cant translate this into sparksql(DataFrame/Dataset) (as I want minimum shuffle across network)

Here is my code for RDD

 val data = List(

"key1,value_a",
"key1,value_b",
"key1,value_b",
"key2,value_a",
"key2,value_c",
"key2,value_c",
"key3,value_a"

)

val sparkConf = new SparkConf().setMaster("local").setAppName("example")
val sc = new SparkContext(sparkConf)

val lineRDD = sc.parallelize(data)

val pairedRDD = lineRDD.map { line =>
val fields = line.split(",")
(fields(0), fields(2))
}

val flatPairsRDD = pairedRDD.flatMap {
  (key, val) => ((key, val), 1)
}

val SumRDD = flatPairsRDD.reduceByKey((a, b) => a + b)

val resultsRDD = SumRDD.map{
  case ((key, val), count) => (key, (val,count))
 }.groupByKey.map{
  case (key, valList) => (name, valList.toList.sortBy(_._2).reverse.head)
}

resultsRDD.collect().foreach(println)

DataFrame , Using Windowing: I am trying with Window.partitionBy("key", "value") to aggregate the count over the window. and thn sorting and agg() respectively

Body:
According to what I understood from your question here's what you can do

First you have to read the data and convert it to dataframe

val df = sc.textFile("path to the data file")   //reading file line by line
  .map(line => line.split("="))                 // splitting each line by =
  .map(array => (array(0).trim, array(1).trim)) //tuple2(key, value) created
  .toDF("key", "value")                        //rdd converted to dataframe which required import sqlContext.implicits._

which would be

+----+-------+
|key |value  |
+----+-------+
|key1|value_a|
|key1|value_b|
|key1|value_b|
|key2|value_a|
|key2|value_c|
|key2|value_c|
|key3|value_a|
+----+-------+

Next step would be to count the repetition of identical values for each key and select the value that repeated the most for each key which can be done by using Window function, and aggregations as below

import org.apache.spark.sql.expressions._                   //import Window library
def windowSpec = Window.partitionBy("key", "value")         //defining a window frame for the aggregation
import org.apache.spark.sql.functions._                     //importing inbuilt functions
df.withColumn("count", count("value").over(windowSpec))     // counting repeatition of value for each group of key, value and assigning that value to new column called as count
  .orderBy($"count".desc)                                   // order dataframe with count in descending order
  .groupBy("key")                                           // group by key
  .agg(first("value").as("value"))                          //taking the first row of each key with count column as the highest

thus the final output should be equal to

+----+-------+
|key |value  |
+----+-------+
|key3|value_a|
|key1|value_b|
|key2|value_c|
+----+-------+


问:
Terracotta EhCache - concurrent modification creates huge byte array during serialization
If my heapdump Dominator Tree view looks like below, can I assume the major contributor (~1GB) to my heap is the Thread instance created by Weblogic? And in that Thread a reference to ByteArrayOutputStream is the reason for 1GB?

Follow up question: Can I also assume it is due to object serialization? Maybe triggered by Terracotta ehcahce (from the third line. Not because it is next to the ByeArrayOS, because in our code that is the only place serialization can happen)?

答:
The Dominator tree is saying that you have a Weblogic thread holding a ByteArrayOutputStream (and a SerializerObjectOutputStream). The Weblogic thread is a classical worker thread currently processing a request. And it is currently stuck on something.

So, this is the equivalent of

```<code>ByteArrayOutputStream in = new ByteArrayOutputStream();
Thread.wait();
</code>```

The thread is holding a ByteArrayOutputStream and it can't be garbage collected since the thread isn't done with it.

Seeing the serializer makes me think that you are currently deserializing from Ehcache disk or offheap.

Is it possible that you are putting pretty huge objects in your cache? As @louis-jacomet mentioned noticed.

Body:
The Dominator tree is saying that you have a Weblogic thread holding a ByteArrayOutputStream (and a SerializerObjectOutputStream). The Weblogic thread is a classical worker thread currently processing a request. And it is currently stuck on something.

So, this is the equivalent of

ByteArrayOutputStream in = new ByteArrayOutputStream();
Thread.wait();

The thread is holding a ByteArrayOutputStream and it can't be garbage collected since the thread isn't done with it.

Seeing the serializer makes me think that you are currently deserializing from Ehcache disk or offheap.

Is it possible that you are putting pretty huge objects in your cache? As @louis-jacomet mentioned noticed.


问:
System.Net.Mail.MailAddress send to multiple emails with one parameter
I've just switched from the deprecated System.Web.Mail.MailAddress to System.Net.Mail.MailAddress, but it doesn't seem to be particularly flexible when passing in a parameter holding multiple addresses when using the new System.Net.Mail.MailAddress.To.Add.

```<code>string emailAdd= "email1@emailus.com; email2@emailus.com";

System.Net.Mail.MailAddress.To.Add(emailAdd);
</code>```

In the above example, email2@emailus.com is emailed successfully, but email1@emailus.com is not.  I really need a way to do this since my addresses are defined in another class and passed to an email() method via a parameter.  I'm simply not passing five parameters for 5 separate emails.  Or indeed one and splicing on my end, .Web version is proving to be way more versatile.

This question is not a duplicate of the suggested one.  The answer to the "duplicate" is add them individually, I want to add multiple addresses simultaneously.  Since there is a way to do this, this question is more relevant than the one I'm accused of duplicating.

答:
In this purpose you can follow the function Parameter that it denotes actually which is show that you can use comma delimiter and function parameter is denoted as addresses which identify that you can send multiple email together using it</p>

```<code>mail.To.Add("to1mailaddress@domain,to2mailaddress@domain");
</code>```

Body:
I've just switched from the deprecated System.Web.Mail.MailAddress to System.Net.Mail.MailAddress, but it doesn't seem to be particularly flexible when passing in a parameter holding multiple addresses when using the new System.Net.Mail.MailAddress.To.Add.

string emailAdd= "email1@emailus.com; email2@emailus.com";

System.Net.Mail.MailAddress.To.Add(emailAdd);

In the above example, email2@emailus.com is emailed successfully, but email1@emailus.com is not.  I really need a way to do this since my addresses are defined in another class and passed to an email() method via a parameter.  I'm simply not passing five parameters for 5 separate emails.  Or indeed one and splicing on my end, .Web version is proving to be way more versatile.

This question is not a duplicate of the suggested one.  The answer to the "duplicate" is add them individually, I want to add multiple addresses simultaneously.  Since there is a way to do this, this question is more relevant than the one I'm accused of duplicating.

Body:
In this purpose you can follow the function Parameter that it denotes actually which is show that you can use comma delimiter and function parameter is denoted as addresses which identify that you can send multiple email together using it

mail.To.Add("to1mailaddress@domain,to2mailaddress@domain");


问:
Ambiguity in pow(x,y,z) and x**y%z speed in python 3. Which one is efficient?
results are not as expected. pow(x,y,z) must be efficient, but the results altered. why?

```<code>import timeit
print(timeit.timeit("pow(2505626,1520321,2700643)"))
output:3.700144177302718
print(timeit.timeit("pow(2505626,1520321,2700643)",number=1000000))
output:4.591832527890801
print(timeit.timeit("2505626**1520321%2700643",number=1000000))
output:0.014752348884940147
</code>```

答:
Indeed pow() doesn't have good performance on integers (in the three argument form). See the function's docstring:

code:

```<code>def pow(*args, **kwargs): # real signature unknown
    """
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.
    """
    pass
</code>```

Body:
results are not as expected. pow(x,y,z) must be efficient, but the results altered. why?

import timeit
print(timeit.timeit("pow(2505626,1520321,2700643)"))
output:3.700144177302718
print(timeit.timeit("pow(2505626,1520321,2700643)",number=1000000))
output:4.591832527890801
print(timeit.timeit("2505626**1520321%2700643",number=1000000))
output:0.014752348884940147

Body:
Indeed pow() doesn't have good performance on integers (in the three argument form). See the function's docstring:

code:

def pow(*args, **kwargs): # real signature unknown
    """
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.
    """
    pass


问:
Clone and insert node within createElement()
I'm working on a bit of code that changes image tags to support lazy loading, and I want to insert a  tag containing the original image node before each image.

I'm getting stuck on the part where I insert a duplicate of the image node inside of the  tag. I'm new to DomDocument, so I'm sure I must be doing something wrong. How can I clone the image tag and insert it in to the new  element I'm creating?

```<code>function lazy_load_images($content) {
    if ($content) {
        $DOM = new DOMDocument();
        $DOM->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

        $images = $DOM->getElementsByTagName("img");

        foreach ($images as $image) {
            $existing_src    = $image->getAttribute("src");
            $existing_srcset = $image->getAttribute("srcset");

            // add noscript before images (here's where the hang-up is)
            $DOM->documentElement->insertBefore($DOM->createElement("noscript", $image->cloneNode(false)), $image->nextSibling);

            // change src to data-normal
            if ($existing_src) {
                $image->removeAttribute("src");
                $image->setAttribute("data-normal", $existing_src);
            }

            // change srcset to data-srcset
            if ($existing_srcset) {
                $image->removeAttribute("srcset");
                $image->setAttribute("data-srcset", $existing_srcset);
            }

            // add _js class
            $image->setAttribute("class", "_js {$image->getAttribute("class")}");
        }

        return $DOM->saveHTML();
    }
}
</code>```

答:
As per comment.  createElement has parameters of a string for the names and values, so create the  node and the append the cloned node to that and then insert it.

```<code>$noscript = $DOM->createElement("noscript");
$noscript->appendChild($image->cloneNode());
$image->parentNode->insertBefore($noscript, $image->nextSibling);
</code>```

I've noticed that if you use $images = $DOM->getElementsByTagName("img"); that the loop seems to never end.  If you use $images = $xp->query('//img'); instead, it seems to work.

```<code>$xp = new DOMXPath($DOM);

$images = $xp->query('//img');
</code>```

Body:
I'm working on a bit of code that changes image tags to support lazy loading, and I want to insert a  tag containing the original image node before each image.

I'm getting stuck on the part where I insert a duplicate of the image node inside of the  tag. I'm new to DomDocument, so I'm sure I must be doing something wrong. How can I clone the image tag and insert it in to the new  element I'm creating?

function lazy_load_images($content) {
    if ($content) {
        $DOM = new DOMDocument();
        $DOM->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

        $images = $DOM->getElementsByTagName("img");

        foreach ($images as $image) {
            $existing_src    = $image->getAttribute("src");
            $existing_srcset = $image->getAttribute("srcset");

            // add noscript before images (here's where the hang-up is)
            $DOM->documentElement->insertBefore($DOM->createElement("noscript", $image->cloneNode(false)), $image->nextSibling);

            // change src to data-normal
            if ($existing_src) {
                $image->removeAttribute("src");
                $image->setAttribute("data-normal", $existing_src);
            }

            // change srcset to data-srcset
            if ($existing_srcset) {
                $image->removeAttribute("srcset");
                $image->setAttribute("data-srcset", $existing_srcset);
            }

            // add _js class
            $image->setAttribute("class", "_js {$image->getAttribute("class")}");
        }

        return $DOM->saveHTML();
    }
}

Body:
As per comment.  createElement has parameters of a string for the names and values, so create the <noscript> node and the append the cloned node to that and then insert it.

$noscript = $DOM->createElement("noscript");
$noscript->appendChild($image->cloneNode());
$image->parentNode->insertBefore($noscript, $image->nextSibling);

I've noticed that if you use $images = $DOM->getElementsByTagName("img"); that the loop seems to never end.  If you use $images = $xp->query('//img'); instead, it seems to work.

$xp = new DOMXPath($DOM);

$images = $xp->query('//img');


答:
I think the question is how can users of your site see the new font?  Try this out:  http://www.howtoplaza.com/how-to-use-custom-fonts-on-your-website-with-css

Such as this:

```<code>@font-face {
    font-family: cool_font;
    src: url('cool_font.ttf');
}
</code>```

Title: Adding Font To A CSS Page

Body:
I have a font I downloaded and I'm trying to apply that font to my site.

so I simply used font-family but my font isn't there(obviously) any idea on how to add it?

Body:
I think the question is how can users of your site see the new font?  Try this out:  http://www.howtoplaza.com/how-to-use-custom-fonts-on-your-website-with-css

Such as this:

@font-face {
    font-family: cool_font;
    src: url('cool_font.ttf');
}


问:
Regex to test for restricted word in email address not working correctly
I have a regular expression that is giving me some trouble.    I want to restrict domains that have a certain word in them, such as 'foobar'.    I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

internal.foobar.com

foobarcorp.com

randomdomainwithfoobarinit.co.uk

foobar.net

Etc

So far my regex, covers almost everything correctly, except if there are characters before foobar   so myfoobar.com would not be caught, but foobarcorp.com would.    I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo.   Any ideas?   I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

```<code>var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value));
</code>```

答:
You can try this:

var regex = /\w+@(\w+\.?)?foobar(\w+)?(\.\w+)+/i;

console.log(regex.test('a@internal.foobar.com'));
console.log(regex.test('a@foobarcorp.com'));
console.log(regex.test('a@foobarcorp.com'));
console.log(regex.test('a@randomdomainwithfoobarinit.co.uk'));
console.log(regex.test('a@foobar.net'));```

Body:
I have a regular expression that is giving me some trouble.    I want to restrict domains that have a certain word in them, such as 'foobar'.    I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

internal.foobar.com

foobarcorp.com

randomdomainwithfoobarinit.co.uk

foobar.net

Etc

So far my regex, covers almost everything correctly, except if there are characters before foobar   so myfoobar.com would not be caught, but foobarcorp.com would.    I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo.   Any ideas?   I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value));


问:
How to refactor my angularjs function with if validations and 2 foreach loops
I've written this function in order to loop through some files and their children items depending on certain criteria. Depending on what the criteria is for the file, it will return true or false.

I've made a variable validFile to keep track of the return value.

I feel like there is a cleaner way to make the function more fluid....if someone can give me some pointers on how i can make this function more simple that'd be great.

```<code>function checkFile() {
    // track file validity value
    var validFile;

    // check to see if files exists
    if($scope.files.length) {
      angular.forEach($scope.files, function(file) {
         // check to see that file has a child item
         if(file.item && file.item.child.length > 1) {
          angular.forEach(file.item.child, function(item) {
            if(item.child.code === 8) {
              validFile = true;
            }
          });
        } else {
          validFile = false;
        }

      });
    } else {
      validFile = false;
    }

    return validFile;
  }
</code>```

PS. the function works fine....just want to clean it up and refactor it to be neater

EDIT:

example of files goes something like this...

```<code> $scope.files = [{
      length: 1,
      type: pdf,
      item: {
        child:[{
           type: pdf,
           code: 8
        }]
      }
    }]
</code>```

The validFile will be true if

$scope.files and file.item.child exists

item.child.code has a value of 8

thanks

答:
I would do the following refactoring:

```<code>  function checkFile() {
    var result = false;
    if(angular.isArray($scope.files)) {
      angular.forEach($scope.files, function(file) {
         if(file.item && angular.isArray(file.item.child)) {
          angular.forEach(file.item.child, function(child) {
            if(child.code === 8) {
              result = true;
            }
          });
        }
      });
    }
    return result;
  }
</code>```

Main things that I did:

checking for an array of top-level object is switched to angular.isArray;

file.item.child.length could be 1;

inner loop is protected by angular.isArray condition;

inner loop iteration variable is child, not item;

also I generalized the result flag with false as initial value.

Furhter refactoring could contain following ideas:

replace forEach logic with breakabe logic (plain old for-loop or Array.prototype.some or something else) to reduce iterations amount...

Body:
I've written this function in order to loop through some files and their children items depending on certain criteria. Depending on what the criteria is for the file, it will return true or false.

I've made a variable validFile to keep track of the return value.

I feel like there is a cleaner way to make the function more fluid....if someone can give me some pointers on how i can make this function more simple that'd be great.

function checkFile() {
    // track file validity value
    var validFile;

    // check to see if files exists
    if($scope.files.length) {
      angular.forEach($scope.files, function(file) {
         // check to see that file has a child item
         if(file.item && file.item.child.length > 1) {
          angular.forEach(file.item.child, function(item) {
            if(item.child.code === 8) {
              validFile = true;
            }
          });
        } else {
          validFile = false;
        }

      });
    } else {
      validFile = false;
    }

    return validFile;
  }

PS. the function works fine....just want to clean it up and refactor it to be neater

EDIT:

example of files goes something like this...

 $scope.files = [{
      length: 1,
      type: pdf,
      item: {
        child:[{
           type: pdf,
           code: 8
        }]
      }
    }]

The validFile will be true if

$scope.files and file.item.child exists

item.child.code has a value of 8

thanks

Body:
I would do the following refactoring:

  function checkFile() {
    var result = false;
    if(angular.isArray($scope.files)) {
      angular.forEach($scope.files, function(file) {
         if(file.item && angular.isArray(file.item.child)) {
          angular.forEach(file.item.child, function(child) {
            if(child.code === 8) {
              result = true;
            }
          });
        }
      });
    }
    return result;
  }

Main things that I did:

checking for an array of top-level object is switched to angular.isArray;

file.item.child.length could be 1;

inner loop is protected by angular.isArray condition;

inner loop iteration variable is child, not item;

also I generalized the result flag with false as initial value.

Furhter refactoring could contain following ideas:

replace forEach logic with breakabe logic (plain old for-loop or Array.prototype.some or something else) to reduce iterations amount...