问:
Most elegant way to extract block by skipping every 2 element
Let's say I have

```<code>block: [a 1 b 2 c 3]
</code>```

I want

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

Something like this is clunky and it doesn't work because I use word type (I'd like to have it word with word not string):

```<code>  block: [a 1 b 2 c 3]
  block2: []

  counter: -1
  foreach 'element block [
    counter: negate counter
    if counter append block2 element
  ]
</code>```

答:
The EXTRACT function should fit the bill here:

```<code>>> extract/index [a 1 b 2 c 3] 2 2
== [1 2 3]
</code>```

It's fairly versatile for this type of thing.

```<code>>> help extract
USAGE:
     EXTRACT series width

DESCRIPTION:
     Extracts a value from a series at regular intervals.
     EXTRACT is a function! value.

ARGUMENTS:
     series       [series!]
     width        [integer!] "Size of each entry (the skip)".

REFINEMENTS:
     /index       => Extract from an offset position.
        pos          [integer!] "The position".
     /into        => Provide an output series instead of creating a new one.
        output       [series!] "Output series".
</code>```

Body:
Let's say I have

block: [a 1 b 2 c 3]

I want

[1 2 3]

Something like this is clunky and it doesn't work because I use word type (I'd like to have it word with word not string):

  block: [a 1 b 2 c 3]
  block2: []

  counter: -1
  foreach 'element block [
    counter: negate counter
    if counter append block2 element
  ]

Body:
The EXTRACT function should fit the bill here:

>> extract/index [a 1 b 2 c 3] 2 2
== [1 2 3]

It's fairly versatile for this type of thing.

>> help extract
USAGE:
     EXTRACT series width

DESCRIPTION:
     Extracts a value from a series at regular intervals.
     EXTRACT is a function! value.

ARGUMENTS:
     series       [series!]
     width        [integer!] "Size of each entry (the skip)".

REFINEMENTS:
     /index       => Extract from an offset position.
        pos          [integer!] "The position".
     /into        => Provide an output series instead of creating a new one.
        output       [series!] "Output series".


来源: stackexchange

问:
Execution failed for task ':app:mergeDebugResources'. Android studio
..

I am facing an error as Error:Execution failed for task ':app:mergeDebugResources'.

C:\Users\ankur\AndroidStudioProjects\source1\app\src\main\res\values\public.xml: Error: Found item ###/icon more than one time

I tried to remove the icon mentioned from public.xml but it does not work

答:
Remove the copy of the items which is present more than one time.
you can do it as follows:-</p>

```<code>-in android studio go to res>>values>>Strings.xml
-then remove the item which is underlined red(delete a line and then wait for it to refresh )
-then rebuild your project.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Remove the copy of the items which is present more than one time.
you can do it as follows:-

-in android studio go to res>>values>>Strings.xml
-then remove the item which is underlined red(delete a line and then wait for it to refresh )
-then rebuild your project.


问:
How can I remove the 'Update Strategy: No Reboots' message on CoreOS/Container Linux?
I am running a Kubernetes cluster on CoreOS and using coreos/container-linux-update-operator to update each node in a controlled way. When I ssh into one of the nodes however I am getting the message Update Strategy: No Reboots, presumably because I have disabled and masked locksmithd.service (as it is no longer needed).

How can I stop that message from appearing? It isn't actually true since update-operator is handling updates instead.

答: There is an outstanding issue for this problem on github https://github.com/coreos/bugs/issues/1968</p>


问:
Push notification system in Nodejs with Android and iOS
I want to create a push notification system in nodejs, which will be suitable for both iOS and Android. I've been searching, and at the moment I am thinking about this one:

http://devcenter.kinvey.com/nodejs/guides/push

Can anyone, who has been working on something like this, tell me what is the best way to implement that?

答:
I think the best way is to use Firebase Cloud Message (FCM), you can send notifications to your Android and iOS devices over an fcm_token provided by Firebase SDK. It's Google solution and simple to use.

https://firebase.google.com/docs/cloud-messaging/?refresh=1

If you dont like Google, this is an other 100% free option that allow you to do the same job, One Signal.

https://onesignal.com/


问:
Give the code below, I was told that if a hash is called and pass through as argument, I can't return Nil. Can anyone explain to me how come?
```<code>def key_for_min_value(name_hash)

name_hash.max_by {|k, v| 0-v}[0]

end
</code>```

This was my code to fulfill the test suite for finding the lowest value of a hash (this was for one of my lessons online).

I know there are much easier ways to do this but I had some restrictions, as you can see below:

**A Few Restrictions:
We want you to build this on your own. Some of the following methods are helpful but off limits for this exercise. (We'll cover a few below in more depth in subsequent lessons).

I could not use keys, values, min, sort, min_by to make it pass.

This code returned the key with the lowest value (a hash of key ==> integers) but here was the requirement I could not figure out.

If the method is called and passed an argument of an empty hash, it should return nil.

Only first month programming, so this may be obvious but is there a way to return nil for an empty hash, and keep my existing code intact?

Thanks for your help

答:
There a lot of different possibilities to do what you want. The most obvious one is to literally translate the sentence: "return nil if the hash is empty" into Ruby:

```<code>def key_for_min_value(name_hash)
  return nil if name_hash.empty?
  name_hash.max_by {|k, v| 0-v}[0]
end
</code>```

Another possibility would be to use the safe navigation operator:

```<code>def key_for_min_value(name_hash)
  name_hash.max_by {|k, v| 0-v}&.[](0)
end
</code>```

Yet another way would be to ensure that the value you are trying to index into is never nil:

```<code>def key_for_min_value(name_hash)
  (name_hash.max_by {|k, v| 0-v} || [])[0]
end

# or

def key_for_min_value(name_hash)
  Array(name_hash.max_by {|k, v| 0-v})[0]
end
</code>```

Body:
def key_for_min_value(name_hash)

name_hash.max_by {|k, v| 0-v}[0]

end

This was my code to fulfill the test suite for finding the lowest value of a hash (this was for one of my lessons online).

I know there are much easier ways to do this but I had some restrictions, as you can see below:

**A Few Restrictions:
We want you to build this on your own. Some of the following methods are helpful but off limits for this exercise. (We'll cover a few below in more depth in subsequent lessons).

I could not use keys, values, min, sort, min_by to make it pass.

This code returned the key with the lowest value (a hash of key ==> integers) but here was the requirement I could not figure out.

If the method is called and passed an argument of an empty hash, it should return nil.

Only first month programming, so this may be obvious but is there a way to return nil for an empty hash, and keep my existing code intact?

Thanks for your help

Body:
There a lot of different possibilities to do what you want. The most obvious one is to literally translate the sentence: "return nil if the hash is empty" into Ruby:

def key_for_min_value(name_hash)
  return nil if name_hash.empty?
  name_hash.max_by {|k, v| 0-v}[0]
end

Another possibility would be to use the safe navigation operator:

def key_for_min_value(name_hash)
  name_hash.max_by {|k, v| 0-v}&.[](0)
end

Yet another way would be to ensure that the value you are trying to index into is never nil:

def key_for_min_value(name_hash)
  (name_hash.max_by {|k, v| 0-v} || [])[0]
end

# or

def key_for_min_value(name_hash)
  Array(name_hash.max_by {|k, v| 0-v})[0]
end


问:
How to have only the key with no value or how to put distinct values or into IndexedDb?
I need to put strings into IndexedDb that are distinct. I can have them as the key with no value (pretty new to indexedDb so don't even know if that's possible). The problem right now is that every time these strings are read they are put into IndexDb repeatedly. Don't want to write another method that would check if these values already exist, to maintain method reusability. I believe there should be a way to rewrite upgradeDb.createObjectStore('categories', { autoIncrement: true }); to do this, just can't find how. My code:

Creating the database with the table:

```<code>function idbOpen() {
    return idb.open('greedy', 1, upgradeDb => {
        upgradeDb.createObjectStore('categories', { autoIncrement: true });
    });
}
</code>```

Writing to database:

```<code>putArrayToDb = (tableName, arrayToPut) => {
    if (this.dbPromise) {
        this.dbPromise.then(db => {
            if (!db) return;

            var tx = db.transaction(tableName, 'readwrite');
            var store = tx.objectStore(tableName);
            arrayToPut.map(arrayItem => {
                store.put(arrayItem);
            });
        })
    }
}

putArrayToDb('categories', ["value1", "value2", "value3"]);
</code>```

Thanks in advance.

答:
Since you want to use the strings as the keys, autoIncrement is not what you want - it generates keys for you.

Remove the autoIncrement option when defining the object store, and simply put with explicit keys and a dummy value (e.g. true):

```<code>var DUMMY_VALUE = true;

arrayToPut.map(arrayItem => {
    store.put(/*value=*/DUMMY_VALUE, /*key=*/arrayItem);
});
</code>```

Body:
I need to put strings into IndexedDb that are distinct. I can have them as the key with no value (pretty new to indexedDb so don't even know if that's possible). The problem right now is that every time these strings are read they are put into IndexDb repeatedly. Don't want to write another method that would check if these values already exist, to maintain method reusability. I believe there should be a way to rewrite upgradeDb.createObjectStore('categories', { autoIncrement: true }); to do this, just can't find how. My code:

Creating the database with the table:

function idbOpen() {
    return idb.open('greedy', 1, upgradeDb => {
        upgradeDb.createObjectStore('categories', { autoIncrement: true });
    });
}

Writing to database:

putArrayToDb = (tableName, arrayToPut) => {
    if (this.dbPromise) {
        this.dbPromise.then(db => {
            if (!db) return;

            var tx = db.transaction(tableName, 'readwrite');
            var store = tx.objectStore(tableName);
            arrayToPut.map(arrayItem => {
                store.put(arrayItem);
            });
        })
    }
}

putArrayToDb('categories', ["value1", "value2", "value3"]);

Thanks in advance.

Body:
Since you want to use the strings as the keys, autoIncrement is not what you want - it generates keys for you.

Remove the autoIncrement option when defining the object store, and simply put with explicit keys and a dummy value (e.g. true):

var DUMMY_VALUE = true;

arrayToPut.map(arrayItem => {
    store.put(/*value=*/DUMMY_VALUE, /*key=*/arrayItem);
});


问:
Why wont Backgrounder plugin work in Firefox or Explorer
I am using a full screen image with Backgrounder Plugin, It works great in Chrome, but wont show the image in Firefox or Explorer, I am using Jquery 4.4</p>

```<code> $(document).ready(function(){
$(function() {
  $("#my_background").backgrounder();
});
});

<div id="my_background"><img src="../images/bk/luft.jpg" alt="Lufthavn"/></div>
</code>```

答:
I face the same problem with backgrounder. I think the best plugin for your needs is fullscreenr.
The use is something like this:

js

```<code>// You need to specify the size of your background image here (could be done automatically by some PHP code)
            var FullscreenrOptions = {  width: 1024, height: 683, bgID: '#bgimg' };
            // This will activate the full screen background!
            jQuery.fn.fullscreenr(FullscreenrOptions);
</code>```

html

```<code><img id="bgimg" src="img/bg.jpg" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using a full screen image with Backgrounder Plugin, It works great in Chrome, but wont show the image in Firefox or Explorer, I am using Jquery 4.4

 $(document).ready(function(){
$(function() {
  $("#my_background").backgrounder();
});
});

Body:
I face the same problem with backgrounder. I think the best plugin for your needs is fullscreenr.
The use is something like this:

js

// You need to specify the size of your background image here (could be done automatically by some PHP code)
            var FullscreenrOptions = {  width: 1024, height: 683, bgID: '#bgimg' };
            // This will activate the full screen background!
            jQuery.fn.fullscreenr(FullscreenrOptions);

html

<img id="bgimg" src="img/bg.jpg" />


问:
The vocabulary of first class functions
When people say that Python, for instance, has first class functions, it makes it sound like Python also has second class functions. However, I've never yet (knowingly) encountered a second class function in Python. When we say this, does it really mean "All Python functions are first class?" Or is there an example of a second class function in Python? </p>

答:
First, to clarify the nomenclature.

The term "first class functions" means that it is "first class" in the type system: that is, that functions themselves are values. In languages where functions are not first class, functions are defined as a relationship between values, which makes them "second class".

Put another way, "first class" functions implies that you can use a function as a value, which means (among other things) that you can pass functions into functions. You couldn't do this in Java before Java 7 (reflection doesn't count), so that's an example of a programming language only having "second class" functions. In order to "pass a function", you had to define a type where that function could live (as a method), and then pass an instance of that type.

So, in Python, all functions are first class, because all functions can be used as a value.

Now, there is another concept which you might be getting confused with. There is also a concept of a "higher order function". A higher order function is a function that takes a function as an argument. Not all functions in Pythons are higher-order, because not all functions take another function as an argument. But even the functions that are not higher-order are first class. (It's a square/rectangle thing.)

Title: The vocabulary of first class functions


问:
Line breaking a logical symbol
I'm relatively new to python and don't quite understand what's going on here. I have the following code:

```<code>if cell.location != (always_empty_location
                     and random.random() < self.settings['OBSTACLE_RATIO']):
</code>```

And it's broken, but if I remove the parenthesis and do a simple

```<code>and \
</code>```

on the first line, it works. I can't seem to find a solid explanation of how python treats scenario's like this. Everything online suggests this should work.

答:
In Python, you can only do multi-line conditionals if you wrap it in paren or if you use \.

So this works:

```<code>if foo == 1 and \
     bar == 2:
   do_something()
</code>```

And this will work:

```<code>if (foo == 1 and
      bar == 2):
    do_something()
</code>```

What you did, however, was putting a parenthesis around half of a condition!

```<code>if foo == (1
       and bar == 2):
    do_something()
</code>```

So what is happening here is that it's evaluating (1 and bar == 2), and then testing foo for that value. If foo == True then that would work. But if foo == False and bar != 2, then it'll pass.

Title: Line breaking a logical symbol

Body:
I'm relatively new to python and don't quite understand what's going on here. I have the following code:

if cell.location != (always_empty_location
                     and random.random() < self.settings['OBSTACLE_RATIO']):

And it's broken, but if I remove the parenthesis and do a simple

and \

on the first line, it works. I can't seem to find a solid explanation of how python treats scenario's like this. Everything online suggests this should work.

Body:
In Python, you can only do multi-line conditionals if you wrap it in paren or if you use \.

So this works:

if foo == 1 and \
     bar == 2:
   do_something()

And this will work:

if (foo == 1 and
      bar == 2):
    do_something()

What you did, however, was putting a parenthesis around half of a condition!

if foo == (1
       and bar == 2):
    do_something()

So what is happening here is that it's evaluating (1 and bar == 2), and then testing foo for that value. If foo == True then that would work. But if foo == False and bar != 2, then it'll pass.


问:
Error running Node.js' fs.rename() inside of a loop
I'm developing an application that has to organize some uploaded files, I'm separating them in folders with the ID of their request (I'm using express-request-id to get this ID).

The problem is that everytime I have more than a single file the "moving" process fails and I can't seem to fix it.

```<code>let request_folder = path.resolve(tmp_folder + "/" + req.id);

/* Checking if the folder exists */
fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) { // it doesn't
        /* Trying to create it */
        fs.mkdir(request_folder, function(error) {
            if(error) {
                console.log("Error: Couldn't create the directory.");
                console.log(error);
            }
        });
    }
});

/* Moving uploaded files to their respective request folder */
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    fs.rename(file.path, new_file_path, function(error) {
        if(error) {
            console.log("Error: Couldn't move " + file.filename + ".");
            console.log(error);
        }
    });
});
</code>```

I'm one hundred percent sure both the folders and the files exist, but I when trying to move two files at once I get:

```<code>Error: Couldn't move Desert.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Desert.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f5725a73
\Desert.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Desert.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Desert.jpg' }
Error: Couldn't move Chrysanthemum.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Chrysanthemum.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f
5725a73\Chrysanthemum.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Chrysanthemum.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Chrysanthemum.jpg' }
</code>```

Does anyone know what am I doing wrong? Thanks!

答:
It is possible you are trying to move the file even before the destination folder exists.

try the new await keyword to structure the code.

```<code>const {promisify} = require('util');

const fs = require('fs');
const accessFileAsync = promisify(fs.access);
const mkdirFileAsync = promisify(fs.mkdir);
const renameFileAsync = promisify(fs.rename);
try{
  await accessFileAsync(request_folder, fs.constants.F_OK);
}
catch(ex)
{
  await mkdirFileAsync(request_folder);
}
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    try{
      await renameFileAsync(file.path, new_file_path);
    }
    catch(ex)
    {
      console.log(ex);
    }
});
</code>```

Body:
I'm developing an application that has to organize some uploaded files, I'm separating them in folders with the ID of their request (I'm using express-request-id to get this ID).

The problem is that everytime I have more than a single file the "moving" process fails and I can't seem to fix it.

let request_folder = path.resolve(tmp_folder + "/" + req.id);

/* Checking if the folder exists */
fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) { // it doesn't
        /* Trying to create it */
        fs.mkdir(request_folder, function(error) {
            if(error) {
                console.log("Error: Couldn't create the directory.");
                console.log(error);
            }
        });
    }
});

/* Moving uploaded files to their respective request folder */
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    fs.rename(file.path, new_file_path, function(error) {
        if(error) {
            console.log("Error: Couldn't move " + file.filename + ".");
            console.log(error);
        }
    });
});

I'm one hundred percent sure both the folders and the files exist, but I when trying to move two files at once I get:

Error: Couldn't move Desert.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Desert.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f5725a73
\Desert.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Desert.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Desert.jpg' }
Error: Couldn't move Chrysanthemum.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Chrysanthemum.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f
5725a73\Chrysanthemum.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Chrysanthemum.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Chrysanthemum.jpg' }

Does anyone know what am I doing wrong? Thanks!

Body:
It is possible you are trying to move the file even before the destination folder exists.

try the new await keyword to structure the code.

const {promisify} = require('util');

const fs = require('fs');
const accessFileAsync = promisify(fs.access);
const mkdirFileAsync = promisify(fs.mkdir);
const renameFileAsync = promisify(fs.rename);
try{
  await accessFileAsync(request_folder, fs.constants.F_OK);
}
catch(ex)
{
  await mkdirFileAsync(request_folder);
}
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    try{
      await renameFileAsync(file.path, new_file_path);
    }
    catch(ex)
    {
      console.log(ex);
    }
});


问:
assign values/string to cells using array vba
I am trying to assign values to column z using an array but I am not getting desire results. I am testing to assign cell Z1 = A, cell Z2 = B, cell Z3 = C
Right now my codes assign all 3 cells to C.  I have posted my desire results below.

```<code>Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(i)
            Next j
        Next i
End With

End Sub
</code>```

答:
You can set option base 1 so use valid row references when writing values out (if array lbound was 0 you wouldn't be able to use .Cells(0, 26) = v(0) as no row 0 in the sheet.

Option Base: Used at module level to declare the default lower bound for array subscripts. Default is base 0.

Using Base 1 means can access all array elements and use same incremental variable for sheet and array i.e. can use just one long variable i.

```<code>Option Base 1
Sub test()

Dim ws1 As Worksheet
Dim i Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")

v = Array("A", "B", "C")

With ws1

        For i = LBound(v) To UBound(v)
                   .Cells(i, 26) = v(i)
        Next i

End With

End Sub
</code>```

Body:
I am trying to assign values to column z using an array but I am not getting desire results. I am testing to assign cell Z1 = A, cell Z2 = B, cell Z3 = C
Right now my codes assign all 3 cells to C.  I have posted my desire results below.

Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(i)
            Next j
        Next i
End With

End Sub

Body:
You can set option base 1 so use valid row references when writing values out (if array lbound was 0 you wouldn't be able to use .Cells(0, 26) = v(0) as no row 0 in the sheet.

Option Base: Used at module level to declare the default lower bound for array subscripts. Default is base 0.

Using Base 1 means can access all array elements and use same incremental variable for sheet and array i.e. can use just one long variable i.

Option Base 1
Sub test()

Dim ws1 As Worksheet
Dim i Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")

v = Array("A", "B", "C")

With ws1

        For i = LBound(v) To UBound(v)
                   .Cells(i, 26) = v(i)
        Next i

End With

End Sub


问:
JS Compute width of children element in parent
For some reason this trivial task has been giving me a proper headache.

So far I have

```<code><div class="nowrap">
  <span>Content</span>
  <span>Content</span>
  <span>Content</span>
</div>

<div class="nowrap">
  <span>Content</span>
  <span>Content</span>
</div>
</code>```

—

```<code>var width = 0;
$('.nowrap').each(function() {
    width += $(this).outerWidth( true );
});
console.log(width) //1946
</code>```

Which gives me the total sum of all the children under the .nowrap parent. But what I want is to have 2 separate values of each .nowrap
childrens. So if I had 3 .nowrap divs I'd get something like

```<code>[443 totalWidth of .nowrap, 755 totalWidth of .nowrap, 457 totalWidth of .nowrap]
</code>```

What do?

https://codepen.io/umbriel/pen/JOOxeL

答:
I realize this is labeled with jQuery, but just for propriety's sake I'll provide a solution that uses only standard functions:

let totalWidths = Array.from(
  document.querySelectorAll('.nowrap'),
  nowrap => Array.from(
    nowrap.children,
    child => child.offsetWidth
  ).reduce((total, width) => total + width)
)

console.log(totalWidths)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nowrap">
  <span>div→ [2035] — </span>
  <span> Funky figures </span>
  <span>6'2" • 180° m² </span>
</div>

<div class="nowrap">
  <span> Sick ligatures </span>
  <span class="dlig">rf rt</span>
</div></code>```

Body:
For some reason this trivial task has been giving me a proper headache.

So far I have

  Content
  Content
  Content

  Content
  Content

—

var width = 0;
$('.nowrap').each(function() {
    width += $(this).outerWidth( true );
});
console.log(width) //1946

Which gives me the total sum of all the children under the .nowrap parent. But what I want is to have 2 separate values of each .nowrap
childrens. So if I had 3 .nowrap divs I'd get something like

[443 totalWidth of .nowrap, 755 totalWidth of .nowrap, 457 totalWidth of .nowrap]

What do?

https://codepen.io/umbriel/pen/JOOxeL

Body:
I realize this is labeled with jQuery, but just for propriety's sake I'll provide a solution that uses only standard functions:

let totalWidths = Array.from(
  document.querySelectorAll('.nowrap'),
  nowrap => Array.from(
    nowrap.children,
    child => child.offsetWidth
  ).reduce((total, width) => total + width)
)

console.log(totalWidths)

<div class="nowrap">
  <span>div→ [2035] — </span>
  <span> Funky figures </span>
  <span>6'2" • 180° m² </span>
</div>

<div class="nowrap">
  <span> Sick ligatures </span>
  <span class="dlig">rf rt</span>
</div>


问:
Using attr_accessor and attr_accessible on the same field
What happens in the background with the following code?

```<code>class User < ActiveRecord::Base

 attr_accessor :name
 attr_accessible :name

end
</code>```

Hint: When instantiating the class, will it be persisted to the database? Why or why not?

答:
Thanks everyone for quick answers!
Your answers combined gave me the pieces I needed to understand this puzzle, I think.

(In a related problem, I was getting a lot of nil errors like "Object doesn’t support #inspect", and "undefined method ‘keys’ for nil:NilClass". I managed to solve it now, by removing the att_accessor field altogether.)

By experimenting with this particular case, this is what I've found out:

Actually, the :name field won't be persisted to the database.

```<code>user = User.new(:name=>"somename")
</code>```

Will only set the attribute on the object, but not persist the :name column to the database. Like the following 'rails console' output shows:

```<code>> user
=> <User id: nil, created_at: nil, updated_at: nil>
> user.save
=> true
> user
=> <User id:1, created_at: 2011-01-19 12:37:21, updated_at: 2011-01-19 12:37:21>
</code>```

I assume this is because *the setter made by attr_accessor will override ActiveRecord's setter* (which takes care of the database persistence). You can still retrieve the value from the :name field from the object though, like this:

```<code>> user.name
=> "somename"
</code>```

So, in conclusion, I've learnt that using attr_accessor on fields might lead to them not being persisted to the database. And while I thought attr_accessible describes fields in the database that should be accessible from the outside, it doesn't seem to make a difference in this case.

Body:
What happens in the background with the following code?

class User < ActiveRecord::Base

 attr_accessor :name
 attr_accessible :name

end

Hint: When instantiating the class, will it be persisted to the database? Why or why not?

Body:
Thanks everyone for quick answers!
Your answers combined gave me the pieces I needed to understand this puzzle, I think.

(In a related problem, I was getting a lot of nil errors like "Object doesn’t support #inspect", and "undefined method ‘keys’ for nil:NilClass". I managed to solve it now, by removing the att_accessor field altogether.)

By experimenting with this particular case, this is what I've found out:

Actually, the :name field won't be persisted to the database.

user = User.new(:name=>"somename")

Will only set the attribute on the object, but not persist the :name column to the database. Like the following 'rails console' output shows:

> user
=> <User id: nil, created_at: nil, updated_at: nil>
> user.save
=> true
> user
=> <User id:1, created_at: 2011-01-19 12:37:21, updated_at: 2011-01-19 12:37:21>

I assume this is because *the setter made by attr_accessor will override ActiveRecord's setter* (which takes care of the database persistence). You can still retrieve the value from the :name field from the object though, like this:

> user.name
=> "somename"

So, in conclusion, I've learnt that using attr_accessor on fields might lead to them not being persisted to the database. And while I thought attr_accessible describes fields in the database that should be accessible from the outside, it doesn't seem to make a difference in this case.


问:
How can I preserve null alt attributes in Sightly?
I'm working on an ADA level AAA compliant site. For accessibility purposes, you are supposed to use an empty string for the alt attribute alt='' if the image has no semantic value (a background pattern, etc) so that screen readers don't read the long filename of the image to the user.

We've built-in the option of authorable alt text along with every image, but Sightly/HTL's default behavior is to remove any attributes which result in an empty string.

I tried using a conditional to fall back to an empty string explicitly, but that didn't help.

```<code><img src="${properties.imgMobile}" alt="${properties.altText || ''}" />
</code>```

Any suggestions?

答:
The above answer is a sightly specification bug.
Reference:
https://github.com/Adobe-Marketing-Cloud/htl-spec/issues/39

One solution for me is put true if is empty the sightly value like the follow example.

```<code><img src="${properties.imgMobile}" alt="${properties.altText || true}"/>
output:
<img src="http://google.com" alt />
</code>```

Body:
I'm working on an ADA level AAA compliant site. For accessibility purposes, you are supposed to use an empty string for the alt attribute alt='' if the image has no semantic value (a background pattern, etc) so that screen readers don't read the long filename of the image to the user.

We've built-in the option of authorable alt text along with every image, but Sightly/HTL's default behavior is to remove any attributes which result in an empty string.

I tried using a conditional to fall back to an empty string explicitly, but that didn't help.

Any suggestions?

Body:
The above answer is a sightly specification bug.
Reference:
https://github.com/Adobe-Marketing-Cloud/htl-spec/issues/39

One solution for me is put true if is empty the sightly value like the follow example.

<img src="${properties.imgMobile}" alt="${properties.altText || true}"/>
output:
<img src="http://google.com" alt />


问:
How to connect a Windows Mobile PDA to Windows 10
Does anyone know how I can get a Windows Mobile 6.5 PDA to connect up to a Windows 10 PC?

Before upgrading the PC from Window 8.1 I was able to use Windows Mobile Device Center to link up to the PDA over USB. This allowed me to access files on the PDA via Windows Explorer, access the internet from the PDA over our network and deploy to the PDA via Visual Studio 2008.

I had to uninstall Windows Mobile Device Center as part of the Windows 10 installation, as it was flagged as incompatible with Windows 10. I can't seem to find an alternative for Windows 10?

答:
Had the same problem.  Came across an article from Zebra with the fix that worked for me:

Open services.msc

Go to Windows Mobile-2003-based device connectivity

Right click Windows Mobile-2003-based device connectivity and click Properties

Go to Log On Tab

Choose Local System Account

Click Apply

Go to General Tab

Press Stop and wait

Once stopped, press Start

Press OK

Restart your PC

Retry the Windows Mobile Device Center

Original article can be found here

ContentLicense: CC BY-SA 4.0


问:
Magento 2 - Wrong logo url in Newsletter Template

Magento ver. 2.1.4

PHP 7.0.25

Nginx 1.10.2

Mode: Production

I create Newsletter Template with Template Content:

```<code>{{template config_path="design/email/header_template"}}
TEST TEXT
{{template config_path="design/email/footer_template"}}
</code>```

Then i make Newsletter Queue and on my email box comes email without logo image;
On debug i saw, that logo lies in the folder: http://SITE.DOMAIN/static/version1510233956/frontend/vendor-magento/vendor-magento/en_US/Magento_Email/logo_email.png
And i can see image when open that url. But email template try to take logo from folder:
http://SITE.DOMAIN/pub/static/version1510585793/frontend/vendor-magento/vendor-magento/en_US/Magento_Email/logo_email.png
And there no image.

When i try to debug this bug on another machine with apache: logo lies in the folder http://SITE.DOMAIN/static/version1510569003/frontend/vendor-magento/vendor-magento/en_US/Magento_Email/logo_email.png and email template take image from this folder. As result i saw logo image in email message.

So, what could be the reason that on the "nginx - production server" does not display the logo image?

答:
Try this : turn off version numbers for the static files.

Store -> Configuration -> Developer -> Static Files Settings -> Sign Static Files

Body:
Magento ver. 2.1.4

PHP 7.0.25

Nginx 1.10.2

Mode: Production

I create Newsletter Template with Template Content:

{{template config_path="design/email/header_template"}}
TEST TEXT
{{template config_path="design/email/footer_template"}}

Then i make Newsletter Queue and on my email box comes email without logo image;
On debug i saw, that logo lies in the folder: http://SITE.DOMAIN/static/version1510233956/frontend/vendor-magento/vendor-magento/en_US/Magento_Email/logo_email.png
And i can see image when open that url. But email template try to take logo from folder:
http://SITE.DOMAIN/pub/static/version1510585793/frontend/vendor-magento/vendor-magento/en_US/Magento_Email/logo_email.png
And there no image.

When i try to debug this bug on another machine with apache: logo lies in the folder http://SITE.DOMAIN/static/version1510569003/frontend/vendor-magento/vendor-magento/en_US/Magento_Email/logo_email.png and email template take image from this folder. As result i saw logo image in email message.

So, what could be the reason that on the "nginx - production server" does not display the logo image?


答:
Try this</p>

```<code>Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(j - 1)
            Next j
        Next i
End With

End Sub
</code>```

Title: assign values/string to cells using array vba

Body:
Try this

Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(j - 1)
            Next j
        Next i
End With

End Sub


问:
How can one avoid DatabaseObjectNotClosedException
How one we avoid this exception??</p>

```
01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): Releasing statement in a finalizer.    Please ensure that you explicitly call close() on your cursor: SELECT * FROM test

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:62)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:46)
```

答: Well, as it says, call close() on your cursor!</p>

Body:
How one we avoid this exception??

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): Releasing statement in a finalizer.    Please ensure that you explicitly call close() on your cursor: SELECT * FROM test

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:62)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:46)


问:
Removing One Negative Margin and replacing it with a different value
How would I remove this negative margin and replace it?

What are the ways in which this can be done?

Click on the image to see the links.

You have to Click on the image to see the links.

https://jsfiddle.net/j8fL15s5/15/

Screenshot

```<code>.link a {
        display: block;
        width: 50px;
        height: 50px;
        margin: -50px 0 0;
        background: black;
        box-Shadow: inset 0 0 0 3px #0059dd;
      }
</code>```

One way is by using:

display: flex;

https://jsfiddle.net/j8fL15s5/18/

Are there any other ways to do this?

Can this be accomplished 'without' the use of flex?

答:
Add display: flex to .link div:

```<code>.link div {
    margin: 0 0 12px 0;
    display: flex;
 }
</code>```

Remove margin: -50px 0 0 from .link a:

```<code>.link a {
    width: 50px;
    height: 50px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
}
</code>```

Replace the following block:

```<code>a.x1 {
    margin: 0;
}

a.x2 {
    margin-left: 54px;
}

a.x3 {
    margin-left: 108px;
}

a.x4 {
    margin-left: 162px;
}

a.x5 {
    margin-left: 216px;
}
</code>```

By

```<code>a.x2, a.x4 {
    margin: 0 4px;
}
</code>```

Updated Fiddle

Edit (without flexbox):

Give .link div a fixed height (this is necessary to avoid the extra space after the last div):

```<code>.link div {
    margin: 0 0 12px 0;
    height: 50px;
}
</code>```

Add display: inline-block to .link a:

```<code>.link a {
    width: 50px;
    height: 50px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
    display: inline-block;
}
</code>```

Remove all a.x* selectors.

Fiddle

Body:
How would I remove this negative margin and replace it?

What are the ways in which this can be done?

Click on the image to see the links.

You have to Click on the image to see the links.

https://jsfiddle.net/j8fL15s5/15/

Screenshot

.link a {
        display: block;
        width: 50px;
        height: 50px;
        margin: -50px 0 0;
        background: black;
        box-Shadow: inset 0 0 0 3px #0059dd;
      }

One way is by using:

display: flex;

https://jsfiddle.net/j8fL15s5/18/

Are there any other ways to do this?

Can this be accomplished 'without' the use of flex?

Body:
Add display: flex to .link div:

.link div {
    margin: 0 0 12px 0;
    display: flex;
 }

Remove margin: -50px 0 0 from .link a:

.link a {
    width: 50px;
    height: 50px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
}

Replace the following block:

a.x1 {
    margin: 0;
}

a.x2 {
    margin-left: 54px;
}

a.x3 {
    margin-left: 108px;
}

a.x4 {
    margin-left: 162px;
}

a.x5 {
    margin-left: 216px;
}

By

a.x2, a.x4 {
    margin: 0 4px;
}

Updated Fiddle

Edit (without flexbox):

Give .link div a fixed height (this is necessary to avoid the extra space after the last div):

.link div {
    margin: 0 0 12px 0;
    height: 50px;
}

Add display: inline-block to .link a:

.link a {
    width: 50px;
    height: 50px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
    display: inline-block;
}

Remove all a.x* selectors.

Fiddle


问:
didSelectRowAtIndexPath: not being called
I have a UITableView as a subview of my UIScrollVIew, which is the main view controlled by my MainViewController.

In MainViewController.h

```<code>@interface MainViewController : UIViewController <UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource>

// other stuff here...

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
</code>```

In MainViewController.m

```<code>@synthesize myTableView;

// other stuff here...

- (void)viewDidLoad {
    myTableView.delegate = self;
    myTableView.datasource = self;
}

// other stuff here...

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath {
   [self performSegueWithIdentifier:@"listAttributesSegue" sender:self];
}
</code>```

I know that didSelectRowAtIndexPath is not being called because I have set breakpoints on both the method itself and the line of code inside it, and neither is being called.  I also know that the datasource is working correctly because I have other functions which modify the cells at runtime and they are working perfectly fine.  I am using the latest Xcode with iOS 5.0 set as the development target.  I have searched and searched for an answer.  Anyone have any ideas?

Edit:
I have found the answer. I had a UITapGestureRecognizer set for myTableView's superView.  This overrode the selection call.  Credit to whoever suggested that that might be it.  Your answer was deleted before I could mark it correct.

Edit 2:
A lot of people have been commenting about this, so I though I would share it. If you are experiencing this problem, simply set myGestureRecognizer.cancelsTouchInView to false and everything should work fine.

答:
I had intermittent failure of didSelectRowAtIndexPath: being called on my custom cell press.

I discovered that if I stopped calling [tableView reloadData] very often (10 Hz), and changed it to update every 2 seconds, almost every press would successfully call didSelectRowAtIndexPath:

It seems like reloading the view blocks presses.

Body:
I have a UITableView as a subview of my UIScrollVIew, which is the main view controlled by my MainViewController.

In MainViewController.h

@interface MainViewController : UIViewController <UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource>

// other stuff here...

@property (weak, nonatomic) IBOutlet UITableView *myTableView;

In MainViewController.m

@synthesize myTableView;

// other stuff here...

- (void)viewDidLoad {
    myTableView.delegate = self;
    myTableView.datasource = self;
}

// other stuff here...

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath {
   [self performSegueWithIdentifier:@"listAttributesSegue" sender:self];
}

I know that didSelectRowAtIndexPath is not being called because I have set breakpoints on both the method itself and the line of code inside it, and neither is being called.  I also know that the datasource is working correctly because I have other functions which modify the cells at runtime and they are working perfectly fine.  I am using the latest Xcode with iOS 5.0 set as the development target.  I have searched and searched for an answer.  Anyone have any ideas?

Edit:
I have found the answer. I had a UITapGestureRecognizer set for myTableView's superView.  This overrode the selection call.  Credit to whoever suggested that that might be it.  Your answer was deleted before I could mark it correct.

Edit 2:
A lot of people have been commenting about this, so I though I would share it. If you are experiencing this problem, simply set myGestureRecognizer.cancelsTouchInView to false and everything should work fine.


问:
PHP - Multidimensional array based placeholders find and replace
I have a multidimensional array and I need to be able to replace JSON placeholders with the relevant value.
Also I need to be able to cascade the values too.

I'm probably just missing a simple thing but its been bugging me for days now.
I'd me very greatful if someone could point out a fix for me.

For example this is my data array:

```<code>$SCREEN = array(
    'z5OrfqifU8RiA' =>
    array(
        'current_status' => 'Completed',
        'email' => 'luke@test.com',
        'Messages' =>
        array(
            array(
                array(
                    'type' => 'message',
                    'messageIndex' => 0,
                    'ReceivedAt' => '17/11/2017 17:06:23',
                    'Name' => 'Luke ',
                    'Message' => 'Hello.'
                ),
                array(
                    'type' => 'message',
                    'messageIndex' => 1,
                    'ReceivedAt' => '17/11/2017 17:06:25',
                    'Name' => 'Luke2 ',
                    'Message' => 'Hello back.'
                )
            )
        ),
        'Message Count' => 2,
    )
);
</code>```

I need to take the placeholders that represent the array values as dot notation and replace them with the correct string OR child array using a wildcard.

Here are a few examples of before and afters...

From this:

```<code>{ "Messages": "{{SCREEN.Messages}}"}
</code>```

To:

```<code>{
    "Messages": [
        {
          "type": "message",
          "messageIndex": 0,
          "ReceivedAt": "17/11/2017 17:06:23",
          "Name": "Luke",
          "Message": "Hello."
        },{
          "type": "message",
          "messageIndex": 1,
          "ReceivedAt": "17/11/2017 17:07:06",
          "Name": "Luke2",
          "Message": "Hello back."
        }
      ]
}
</code>```

From this:

```<code>{ "email": "{{SCREEN.email}}"}
</code>```

To:

```<code>{ "email": "luke@test.com"}
</code>```

From this:

```<code>{ "everything": "{{SCREEN.*}}"}
</code>```

To:

```<code>{
  "everything": {
    "z5OrfqifU8RiA": {
      "current_status": "Completed",
      "email": "luke@test.com",
      "Messages": [
        [
          {
            "type": "message",
            "messageIndex": 0,
            "ReceivedAt": "17/11/2017 17:06:23",
            "Name": "Luke",
            "Message": "Hello."
          },
          {
            "type": "message",
            "messageIndex": 1,
            "ReceivedAt": "17/11/2017 17:07:06",
            "Name": "Luke2",
            "Message": "Hello back."
          }
        ]
      ],
      "Message Count": 2
    }
  }
}
</code>```

This is the current code that works if you explicitly target a value but not for an array using a wildcard to get anything that is a child to that key.

```<code>$SCREEN = array(
    'z5OrfqifU8RiA' =>
    array(
        'current_status' => 'Completed',
        'email' => 'luke@test.com',
        'Messages' =>
        array(
            array(
                array(
                    'type' => 'message',
                    'messageIndex' => 0,
                    'ReceivedAt' => '17/11/2017 17:06:23',
                    'Name' => 'Luke ',
                    'Message' => 'Hello.'
                ),
                array(
                    'type' => 'message',
                    'messageIndex' => 1,
                    'ReceivedAt' => '17/11/2017 17:06:25',
                    'Name' => 'Luke2 ',
                    'Message' => 'Hello back.'
                )
            )
        ),
        'Message Count' => 2,
    )
);

$X = parseVariables('{ "everything": "{{SCREEN.*}}"}');

$Y = parseVariables('{ "email": "{{SCREEN.email}}"}');

function parseVariables($array) {
    GLOBAL $SCREEN;

    foreach(flatten($SCREEN) AS $K => $V)$array = MD_ArrayFandR("{{SCREEN.".$K."}}",$V,$array);

    return $array;
}

function flatten($array) {
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + flatten($value, $key . '.');
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

function MD_ArrayFandR($Find, $Replace,$Array){
    if (is_array($Array)){
        $ex=json_encode($Array);
        return json_decode(str_replace($Find, $Replace,$ex),true);
    } else {
        return str_replace($Find, $Replace,$Array);
    }
}

print_r($X);

print_r($Y);
</code>```

答:
Write a recursive function that can descend into the structure, like:</p>

```<code>function recurse($foo) {
    foreach( $foo as $key => $value ) {
        if( is_array($value) ) {
            $foo[$key] = recurse($value);
        } else if( /* $value is a placeholder */ ) {
            $foo[$key] = /* replacement */;
        }
    }
    return $foo
}
</code>```

Body:
I have a multidimensional array and I need to be able to replace JSON placeholders with the relevant value.
Also I need to be able to cascade the values too.

I'm probably just missing a simple thing but its been bugging me for days now.
I'd me very greatful if someone could point out a fix for me.

For example this is my data array:

$SCREEN = array(
    'z5OrfqifU8RiA' =>
    array(
        'current_status' => 'Completed',
        'email' => 'luke@test.com',
        'Messages' =>
        array(
            array(
                array(
                    'type' => 'message',
                    'messageIndex' => 0,
                    'ReceivedAt' => '17/11/2017 17:06:23',
                    'Name' => 'Luke ',
                    'Message' => 'Hello.'
                ),
                array(
                    'type' => 'message',
                    'messageIndex' => 1,
                    'ReceivedAt' => '17/11/2017 17:06:25',
                    'Name' => 'Luke2 ',
                    'Message' => 'Hello back.'
                )
            )
        ),
        'Message Count' => 2,
    )
);

I need to take the placeholders that represent the array values as dot notation and replace them with the correct string OR child array using a wildcard.

Here are a few examples of before and afters...

From this:

{ "Messages": "{{SCREEN.Messages}}"}

To:

{
    "Messages": [
        {
          "type": "message",
          "messageIndex": 0,
          "ReceivedAt": "17/11/2017 17:06:23",
          "Name": "Luke",
          "Message": "Hello."
        },{
          "type": "message",
          "messageIndex": 1,
          "ReceivedAt": "17/11/2017 17:07:06",
          "Name": "Luke2",
          "Message": "Hello back."
        }
      ]
}

From this:

{ "email": "{{SCREEN.email}}"}

To:

{ "email": "luke@test.com"}

From this:

{ "everything": "{{SCREEN.*}}"}

To:

{
  "everything": {
    "z5OrfqifU8RiA": {
      "current_status": "Completed",
      "email": "luke@test.com",
      "Messages": [
        [
          {
            "type": "message",
            "messageIndex": 0,
            "ReceivedAt": "17/11/2017 17:06:23",
            "Name": "Luke",
            "Message": "Hello."
          },
          {
            "type": "message",
            "messageIndex": 1,
            "ReceivedAt": "17/11/2017 17:07:06",
            "Name": "Luke2",
            "Message": "Hello back."
          }
        ]
      ],
      "Message Count": 2
    }
  }
}

This is the current code that works if you explicitly target a value but not for an array using a wildcard to get anything that is a child to that key.

$SCREEN = array(
    'z5OrfqifU8RiA' =>
    array(
        'current_status' => 'Completed',
        'email' => 'luke@test.com',
        'Messages' =>
        array(
            array(
                array(
                    'type' => 'message',
                    'messageIndex' => 0,
                    'ReceivedAt' => '17/11/2017 17:06:23',
                    'Name' => 'Luke ',
                    'Message' => 'Hello.'
                ),
                array(
                    'type' => 'message',
                    'messageIndex' => 1,
                    'ReceivedAt' => '17/11/2017 17:06:25',
                    'Name' => 'Luke2 ',
                    'Message' => 'Hello back.'
                )
            )
        ),
        'Message Count' => 2,
    )
);

$X = parseVariables('{ "everything": "{{SCREEN.*}}"}');

$Y = parseVariables('{ "email": "{{SCREEN.email}}"}');

function parseVariables($array) {
    GLOBAL $SCREEN;

    foreach(flatten($SCREEN) AS $K => $V)$array = MD_ArrayFandR("{{SCREEN.".$K."}}",$V,$array);

    return $array;
}

function flatten($array) {
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + flatten($value, $key . '.');
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

function MD_ArrayFandR($Find, $Replace,$Array){
    if (is_array($Array)){
        $ex=json_encode($Array);
        return json_decode(str_replace($Find, $Replace,$ex),true);
    } else {
        return str_replace($Find, $Replace,$Array);
    }
}

print_r($X);

print_r($Y);

Body:
Write a recursive function that can descend into the structure, like:

function recurse($foo) {
    foreach( $foo as $key => $value ) {
        if( is_array($value) ) {
            $foo[$key] = recurse($value);
        } else if( /* $value is a placeholder */ ) {
            $foo[$key] = /* replacement */;
        }
    }
    return $foo
}


问:
How to convert UIColor to HEX and display in NSLog
I have checked several links on how to convert UIColor codes to HEX however I am not sure on how to  call to the method to display them in NSLog. I haven't got the reputation to comment so posting as a question is my last resort. I want it to display when I run my app in the log.

Second, where do I input the RGB color number ( R = 30, G = 171, B = 13)? I see that all examples use Array [0], [1], [2] which normally refers to index position, so where do I add the color values?

I have this code:

```<code>- (NSString *) hexFromUIColor:(UIColor *)color {

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[30] green:components[141] blue:components[13] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];

}
</code>```

Links I have checked:

hex color from uicolor

How to convert HEX RGB color codes to UIColor?

I have tried to call the method in viewDidLoad however it wont work without UIColor. I am sure it's something simple.

Thanks to anyone who answers.

What is the code I use in my viewDidLoad to call to this method in order to display in NSLog?

答:
Other Swift answers crash for UIColors like white, where there are only 2 components returned by CGColor.

Here's a Swift 4 version that does not have that problem and also returns transparency information in the end of the string if that is required (web format).

The color is first converted to the sRGB colorspace before generating the HEX String to work properly even with Grayscale or other color spaces.

For example:

White will return #FFFFFF

White with 50% opacity will return #FFFFFF7F

```<code>extension UIColor {
    var hexString: String {
        let cgColorInRGB = cgColor.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil)!
        let colorRef = cgColorInRGB.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )

        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a * 255)))
        }

        return color
    }
}
</code>```

OLD VERSION

This version did not work properly with certain colors in non-RGB color spaces.

```<code>extension UIColor {
    var hexString: String {
        let colorRef = cgColor.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )

        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a)))
        }

        return color
    }
}
</code>```

Body:
I have checked several links on how to convert UIColor codes to HEX however I am not sure on how to  call to the method to display them in NSLog. I haven't got the reputation to comment so posting as a question is my last resort. I want it to display when I run my app in the log.

Second, where do I input the RGB color number ( R = 30, G = 171, B = 13)? I see that all examples use Array [0], [1], [2] which normally refers to index position, so where do I add the color values?

I have this code:

- (NSString *) hexFromUIColor:(UIColor *)color {

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[30] green:components[141] blue:components[13] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];

}

Links I have checked:

hex color from uicolor

How to convert HEX RGB color codes to UIColor?

I have tried to call the method in viewDidLoad however it wont work without UIColor. I am sure it's something simple.

Thanks to anyone who answers.

What is the code I use in my viewDidLoad to call to this method in order to display in NSLog?

Body:
Other Swift answers crash for UIColors like white, where there are only 2 components returned by CGColor.

Here's a Swift 4 version that does not have that problem and also returns transparency information in the end of the string if that is required (web format).

The color is first converted to the sRGB colorspace before generating the HEX String to work properly even with Grayscale or other color spaces.

For example:

White will return #FFFFFF

White with 50% opacity will return #FFFFFF7F

extension UIColor {
    var hexString: String {
        let cgColorInRGB = cgColor.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil)!
        let colorRef = cgColorInRGB.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )

        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a * 255)))
        }

        return color
    }
}

OLD VERSION

This version did not work properly with certain colors in non-RGB color spaces.

extension UIColor {
    var hexString: String {
        let colorRef = cgColor.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )

        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a)))
        }

        return color
    }
}


问:
Need help in constructing a case statement
I need help in writing a case statement. I've a column in one of my table which has some values and I would like to generate a string out of that values. Below is the column which I've in my table along with the output which I would like to see.

Risk Score

```<code>1.70
2.10
2.60
3.00
3.20
3.60
3.80
4.00
4.10
4.30
4.60
4.90
5.20
5.40
5.50
5.60
5.80
6.10
6.40
6.60
6.80
7.10
7.50
</code>```

So my requirement is I want a case statement where if the risk score is >0 and <=3 it has to got to Low bucket, if the risk score is >3 and <=6 it has to got to Medium bucket, if the risk score is >6 it has to got to High bucket

Regards,

Vikas

答:
You just need a simple CASE

```<code>SELECT val
    ,CASE
        WHEN val > 0
            AND val <= 3
            THEN 'LOW'
        WHEN val <= 6
            THEN 'medium'
        WHEN val > 6
            THEN 'High'
        END AS bucket
FROM table1;
</code>```

Result:

```<code>+-----+--------+
| VAL | BUCKET |
+-----+--------+
| 1.7 | LOW    |
| 2.1 | LOW    |
| 2.6 | LOW    |
| 3   | LOW    |
| 3.2 | medium |
| 3.6 | medium |
| 3.8 | medium |
| 4   | medium |
| 4.1 | medium |
| 4.3 | medium |
| 4.6 | medium |
| 4.9 | medium |
| 5.2 | medium |
| 5.4 | medium |
| 5.5 | medium |
| 5.6 | medium |
| 5.8 | medium |
| 6.1 | High   |
| 6.4 | High   |
| 6.6 | High   |
| 6.8 | High   |
| 7.1 | High   |
| 7.5 | High   |
+-----+--------+
</code>```

DEMO

Body:
I need help in writing a case statement. I've a column in one of my table which has some values and I would like to generate a string out of that values. Below is the column which I've in my table along with the output which I would like to see.

Risk Score

1.70
2.10
2.60
3.00
3.20
3.60
3.80
4.00
4.10
4.30
4.60
4.90
5.20
5.40
5.50
5.60
5.80
6.10
6.40
6.60
6.80
7.10
7.50

So my requirement is I want a case statement where if the risk score is >0 and <=3 it has to got to Low bucket, if the risk score is >3 and <=6 it has to got to Medium bucket, if the risk score is >6 it has to got to High bucket

Regards,

Vikas

Body:
You just need a simple CASE

SELECT val
    ,CASE
        WHEN val > 0
            AND val <= 3
            THEN 'LOW'
        WHEN val <= 6
            THEN 'medium'
        WHEN val > 6
            THEN 'High'
        END AS bucket
FROM table1;

Result:

+-----+--------+
| VAL | BUCKET |
+-----+--------+
| 1.7 | LOW    |
| 2.1 | LOW    |
| 2.6 | LOW    |
| 3   | LOW    |
| 3.2 | medium |
| 3.6 | medium |
| 3.8 | medium |
| 4   | medium |
| 4.1 | medium |
| 4.3 | medium |
| 4.6 | medium |
| 4.9 | medium |
| 5.2 | medium |
| 5.4 | medium |
| 5.5 | medium |
| 5.6 | medium |
| 5.8 | medium |
| 6.1 | High   |
| 6.4 | High   |
| 6.6 | High   |
| 6.8 | High   |
| 7.1 | High   |
| 7.5 | High   |
+-----+--------+

DEMO


问:
ajax request in javascript - asp.net mvc
how to make a proper ajax request in javascript function?
can somebody give some clear and simple examples based on asp.net mvc technology?</p>

答:
Could this be what you are looking for:

http://www.nikhilk.net/Ajax-MVC.aspx


问:
Simplify a code in R
I have written a code that runs through the columns of a dataframe and returns TRUE if it has a number 1 in any of them, and sends the value to a vector with the same size as a column of the dataframe. I would like to know if there is a way to simplify the code snippet below, since I will have to repeat it for several numbers.</p>

```<code>n1 <- (tab[, 2]==1|  tab[, 3]==1 | tab[, 4]==1 | tab[, 5]==1 |
     tab[, 6]==1 | tab[, 7]==1 | tab[, 8]==1 | tab[, 9]==1 |
     tab[, 10]==1 | tab[, 11]==1 | tab[, 12]==1 | tab[, 13]==1 |
     tab[, 14]==1 | tab[, 15]==1 | tab[, 16]==1)
</code>```

答:
The other comments and answers can work, but I suggest they are encouraging bad behavior when dealing with a data.frame. First and foremost is that apply and rowSums expect a matrix as the data, and will happily coerce to such if given a data.frame. If any of the data.frame columns are character, then all columns will be converted to character. Some operations may still work as expected (e.g., == 1 since it will effectively be == "1" ... though some rounding errors may cause undesired effects), but anything mathematic will not work.

As an example,

```<code>n <- 20
set.seed(2)
tab <- data.frame(
  a = as.character(sample(n, replace = FALSE)),
  b1 = sample(5, size = n, replace = TRUE),
  b2 = sample(5, size = n, replace = TRUE),
  stringsAsFactors = FALSE
)
str(tab)
# 'data.frame': 20 obs. of  3 variables:
#  $ a : chr  "4" "14" "11" "3" ...
#  $ b1: int  4 2 5 1 2 3 1 2 5 1 ...
#  $ b2: int  5 2 1 1 5 4 5 2 3 5 ...

apply(tab, 1, function(y) any(y == 1))
#  [1] FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE
apply(tab, 1, sum)
# Error in FUN(newX[, i], ...) : invalid 'type' (character) of argument

rowSums(tab == 1)
#  [1] 0 0 1 2 0 0 1 0 0 1 2 2 0 0 0 0 0 1 0 1
rowSums(tab)
# Error in rowSums(tab) : 'x' must be numeric
</code>```

There are some easy ways to deal with this. Given your example, it appears that columns 2:16 are numeric and the ones you are concerned about. If that's the case, then you can safely use either one of:

```<code>rowSums(tab[,2:16] == 1)                      # Frank's comment
apply(tab[,2:16], 1, function(y) any(y == 1)) # suggested by You-leee's answer
</code>```

(the former being fairly specific, the latter can be extended to other functionality). If there's only one non-numeric, once can always do

```<code>rowSums(tab[,-1,drop=FALSE] == 1)
apply(tab[,-1,drop=FALSE], 1, function(y) any(y == 1))
</code>```

A third technique is to determine at run time which columns to choose:

```<code>isnum <- sapply(tab, is.numeric)
Reduce(`|`, lapply(tab[isnum], function(y) any(y == 1)))
</code>```

This was a little more complex, because the return from lapply is a list, but it still works fine. Realize that the use of isnum could be based on column names as well, using something like grepl. This method is fairly robust, too, in that it does not error if none of the columns match.

Title: Simplify a code in R

Body:
I have written a code that runs through the columns of a dataframe and returns TRUE if it has a number 1 in any of them, and sends the value to a vector with the same size as a column of the dataframe. I would like to know if there is a way to simplify the code snippet below, since I will have to repeat it for several numbers.

n1 <- (tab[, 2]==1|  tab[, 3]==1 | tab[, 4]==1 | tab[, 5]==1 |
     tab[, 6]==1 | tab[, 7]==1 | tab[, 8]==1 | tab[, 9]==1 |
     tab[, 10]==1 | tab[, 11]==1 | tab[, 12]==1 | tab[, 13]==1 |
     tab[, 14]==1 | tab[, 15]==1 | tab[, 16]==1)

Body:
The other comments and answers can work, but I suggest they are encouraging bad behavior when dealing with a data.frame. First and foremost is that apply and rowSums expect a matrix as the data, and will happily coerce to such if given a data.frame. If any of the data.frame columns are character, then all columns will be converted to character. Some operations may still work as expected (e.g., == 1 since it will effectively be == "1" ... though some rounding errors may cause undesired effects), but anything mathematic will not work.

As an example,

n <- 20
set.seed(2)
tab <- data.frame(
  a = as.character(sample(n, replace = FALSE)),
  b1 = sample(5, size = n, replace = TRUE),
  b2 = sample(5, size = n, replace = TRUE),
  stringsAsFactors = FALSE
)
str(tab)
# 'data.frame': 20 obs. of  3 variables:
#  $ a : chr  "4" "14" "11" "3" ...
#  $ b1: int  4 2 5 1 2 3 1 2 5 1 ...
#  $ b2: int  5 2 1 1 5 4 5 2 3 5 ...

apply(tab, 1, function(y) any(y == 1))
#  [1] FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE
apply(tab, 1, sum)
# Error in FUN(newX[, i], ...) : invalid 'type' (character) of argument

rowSums(tab == 1)
#  [1] 0 0 1 2 0 0 1 0 0 1 2 2 0 0 0 0 0 1 0 1
rowSums(tab)
# Error in rowSums(tab) : 'x' must be numeric

There are some easy ways to deal with this. Given your example, it appears that columns 2:16 are numeric and the ones you are concerned about. If that's the case, then you can safely use either one of:

rowSums(tab[,2:16] == 1)                      # Frank's comment
apply(tab[,2:16], 1, function(y) any(y == 1)) # suggested by You-leee's answer

(the former being fairly specific, the latter can be extended to other functionality). If there's only one non-numeric, once can always do

rowSums(tab[,-1,drop=FALSE] == 1)
apply(tab[,-1,drop=FALSE], 1, function(y) any(y == 1))

A third technique is to determine at run time which columns to choose:

isnum <- sapply(tab, is.numeric)
Reduce(`|`, lapply(tab[isnum], function(y) any(y == 1)))

This was a little more complex, because the return from lapply is a list, but it still works fine. Realize that the use of isnum could be based on column names as well, using something like grepl. This method is fairly robust, too, in that it does not error if none of the columns match.


问:
DATEXII XML file to DataFrame in Python
The last couple of days I have been trying to open and read a certain XML file (in DATEXII format), but have not succeeded so far. It is about traffic data from the NDW Open Data website (Dutch Databank for Road and Traffic Data), hyperlink for the source of the XML files. The head of the tree is like in this picture and continues like this, see also snippet below. Though these together only form a very small part of the data.

<?xml version="1.0"?> -
<soapenv:Envelope xmlns:_0="http://datex2.eu/schema/2/2_0" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header/> -
  <soapenv:Body>
    -
    <d2LogicalModel modelBaseVersion="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      -
      <exchange xmlns="http://datex2.eu/schema/2/2_0">
        -
        <supplierIdentification>
          <country>nl</country>
          <nationalIdentifier>NLNDW</nationalIdentifier>
        </supplierIdentification>
      </exchange>
      -
      <payloadPublication lang="nl" xmlns="http://datex2.eu/schema/2/2_0" xsi:type="MeasuredDataPublication">
        <publicationTime>2017-10-30T05:00:40.007Z</publicationTime>
        -
        <publicationCreator>
          <country>nl</country>
          <nationalIdentifier>NLNDW</nationalIdentifier>
        </publicationCreator>
        <measurementSiteTableReference targetClass="MeasurementSiteTable" version="955" id="NDW01_MT" /> -
        <headerInformation>
          <confidentiality>noRestriction</confidentiality>
          <informationStatus>real</informationStatus>
        </headerInformation>
        -
        <siteMeasurements>
          <measurementSiteReference targetClass="MeasurementSiteRecord" version="1" id="PZH01_MST_0690_00" />
          <measurementTimeDefault>2017-10-30T04:59:00Z</measurementTimeDefault>
          -
          <measuredValue index="1">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>60</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="2">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>0</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="3">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>0</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="4">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>60</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="5">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficSpeed">
                -
                <averageVehicleSpeed numberOfInputValuesUsed="1">
                  <speed>38</speed>
                </averageVehicleSpeed>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="6">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficSpeed">
                -
                <averageVehicleSpeed numberOfInputValuesUsed="0">
                  <speed>-1</speed>
                </averageVehicleSpeed>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="7">```
</div>
</div>
</p>

<p>Ideally I would want to load the information with Python in a Jupyter Notebook as DataFrame, so I can perform some predictive analytics if the data allows. I have tried it with ElementTree, lxml like this, inspired from numerous other threads:</p>

```# Standard Packages
import pandas as pd
import numpy as np

# Necessary Packages for XML and setting Working Directory
import os
import xml.etree.ElementTree as ET
import lxml

os.chdir("C:/.../Intensiteiten en snelheden/30-10-2017")

xml_file = open('0600_Trafficspeed.xml').read() # Unzipped the file manually

def xml2df(xml_data):
    root = ET.XML(xml_data) # element tree
    all_records = [] #This is our record list which we will convert into a
    dataframe
    for i, child in enumerate(root): #Begin looping through our root tree
        record = {} #Place holder for our record
        for subchild in child: #iterate through the subchildren
            record[subchild.tag] = subchild.text #Extract the text create a new
    dictionary key, value pair
        all_records.append(record) #Append this record to all_records.
return pd.DataFrame(all_records) #return records as DataFrame

print(xml2df(xml_file))
```

Though this only returns one single entry with the first line, like   column name: d2LogicalModel, row: 0, entry: None.

I was able to see the tree like structure with difficulty in Microsoft Edge, requiring a lot of the CPU (Notepad++ and the plugin XMLtools also sufficed, but crashes with "bigger" size files, i.e. > 20mb). Though, in my opinion, this structure was still difficult to comprehend. There are so many layers that I do not know how to define the xml2df() with the correct sub-subchilds etc.

My questions thus boils down to, first of all, how would I be able to identify the variables/columns with data? Herewith getting an overview of the relevant data that I want to import. And secondly, how to import this into a DataFrame?

Note: Since the DATEXII format is the standard for traffic data in Europe, I was hoping their guides would help (see documents), but they haven't made sense to me yet. Maybe they will to any of you :)

Any help is greatly appreciated!

答:
Consider transforming your nested XML input source into a flatter structure using XSLT the special-purpose transformation language designed to transform XML files into other XML, HTML, even text (CSV/TAB). Therefore, consider the below XSLT that transforms original XML into comma-separated values in tabular format for import into pandas with read_csv():

XSLT (save as .xsl file, a special xml file)

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                              xmlns:pub="http://datex2.eu/schema/2/2_0"
                              xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/soapenv:Envelope">
    <xsl:text>publicationTime,country,nationalIdentifier,msmtSiteTableRef_targetClass,msmtSiteTableRef_version,msmtSiteTableRef_id,</xsl:text>
    <xsl:text>msmtSiteRef_targetClass,msmtSiteRef_version,msmtSiteRef_id,measurementTimeDefault,</xsl:text>
    <xsl:text>measuredValue_index,basicData_type,vehicleFlowRate,averageVehicleSpeed_numberOfInputValues,averageVehicleSpeed_value</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:apply-templates select="soapenv:Body"/>
  </xsl:template>

  <xsl:template match="soapenv:Body">
    <xsl:apply-templates select="d2LogicalModel"/>
  </xsl:template>

  <xsl:template match="d2LogicalModel">
    <xsl:apply-templates select="pub:payloadPublication"/>
  </xsl:template>

  <xsl:template match="pub:payloadPublication">
    <xsl:apply-templates select="pub:siteMeasurements"/>
  </xsl:template>

  <xsl:template match="pub:siteMeasurements">
    <xsl:apply-templates select="pub:measuredValue"/>
  </xsl:template>

  <xsl:template match="pub:measuredValue">
    <xsl:value-of select="concat(ancestor::pub:payloadPublication/pub:publicationTime,',',
                                 ancestor::pub:payloadPublication/pub:publicationCreator/pub:country,',',
                                 ancestor::pub:payloadPublication/pub:publicationCreator/pub:nationalIdentifier,',',
                                 ancestor::pub:payloadPublication/pub:measurementSiteTableReference/@targetClass,',',
                                 ancestor::pub:payloadPublication/pub:measurementSiteTableReference/@version,',',
                                 ancestor::pub:payloadPublication/pub:measurementSiteTableReference/@id,',',
                                 ancestor::pub:payloadPublication/pub:siteMeasurements/pub:measurementSiteReference/@targetClass,',',
                                 ancestor::pub:payloadPublication/pub:siteMeasurements/pub:measurementSiteReference/@version,',',
                                 ancestor::pub:payloadPublication/pub:siteMeasurements/pub:measurementSiteReference/@id,',',
                                 ancestor::pub:siteMeasurements/pub:measurementTimeDefault,',',
                                 @index,',',
                                 pub:measuredValue/pub:basicData/@xsi:type,',',
                                 descendant::pub:vehicleFlowRate,',',
                                 descendant::pub:averageVehicleSpeed/@numberOfInputValuesUsed,',',
                                 descendant::pub:speed)"/><xsl:text>
</xsl:text>
  </xsl:template>

</xsl:stylesheet>
</code>```

Python

```<code>from io import StringIO
import lxml.etree as et
import pandas as pd

# LOAD XML AND XSL FILES
doc = et.parse('/path/to/Input.xml')
xsl = et.parse('/path/to/XSLT.xsl')

# INITIALIZE AND RUN TRANSFORMATION
transform = et.XSLT(xsl)
# CONVERT RESULT TO STRING
result = str(transform(doc))

# IMPORT INTO DATAFRAME
df = pd.read_csv(StringIO(result))
</code>```

Output (parent node values become repeated indicators with different numeric data)

```<code>print(df)

#           publicationTime country nationalIdentifier msmtSiteTableRef_targetClass  msmtSiteTableRef_version msmtSiteTableRef_id msmtSiteRef_targetClass  msmtSiteRef_version     msmtSiteRef_id measurementTimeDefault  measuredValue_index basicData_type  vehicleFlowRate  averageVehicleSpeed_numberOfInputValues  averageVehicleSpeed_value
# 0  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    1    TrafficFlow             60.0                                      NaN                        NaN
# 1  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    2    TrafficFlow              0.0                                      NaN                        NaN
# 2  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    3    TrafficFlow              0.0                                      NaN                        NaN
# 3  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    4    TrafficFlow             60.0                                      NaN                        NaN
# 4  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    5   TrafficSpeed              NaN                                      1.0                       38.0
# 5  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    6   TrafficSpeed              NaN                                      0.0                        1.0
</code>```

Title: DATEXII XML file to DataFrame in Python

Body:
The last couple of days I have been trying to open and read a certain XML file (in DATEXII format), but have not succeeded so far. It is about traffic data from the NDW Open Data website (Dutch Databank for Road and Traffic Data), hyperlink for the source of the XML files. The head of the tree is like in this picture and continues like this, see also snippet below. Though these together only form a very small part of the data.

<?xml version="1.0"?> -
<soapenv:Envelope xmlns:_0="http://datex2.eu/schema/2/2_0" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header/> -
  <soapenv:Body>
    -
    <d2LogicalModel modelBaseVersion="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      -
      <exchange xmlns="http://datex2.eu/schema/2/2_0">
        -
        <supplierIdentification>
          <country>nl</country>
          <nationalIdentifier>NLNDW</nationalIdentifier>
        </supplierIdentification>
      </exchange>
      -
      <payloadPublication lang="nl" xmlns="http://datex2.eu/schema/2/2_0" xsi:type="MeasuredDataPublication">
        <publicationTime>2017-10-30T05:00:40.007Z</publicationTime>
        -
        <publicationCreator>
          <country>nl</country>
          <nationalIdentifier>NLNDW</nationalIdentifier>
        </publicationCreator>
        <measurementSiteTableReference targetClass="MeasurementSiteTable" version="955" id="NDW01_MT" /> -
        <headerInformation>
          <confidentiality>noRestriction</confidentiality>
          <informationStatus>real</informationStatus>
        </headerInformation>
        -
        <siteMeasurements>
          <measurementSiteReference targetClass="MeasurementSiteRecord" version="1" id="PZH01_MST_0690_00" />
          <measurementTimeDefault>2017-10-30T04:59:00Z</measurementTimeDefault>
          -
          <measuredValue index="1">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>60</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="2">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>0</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="3">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>0</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="4">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficFlow">
                -
                <vehicleFlow>
                  <vehicleFlowRate>60</vehicleFlowRate>
                </vehicleFlow>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="5">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficSpeed">
                -
                <averageVehicleSpeed numberOfInputValuesUsed="1">
                  <speed>38</speed>
                </averageVehicleSpeed>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="6">
            -
            <measuredValue>
              -
              <basicData xsi:type="TrafficSpeed">
                -
                <averageVehicleSpeed numberOfInputValuesUsed="0">
                  <speed>-1</speed>
                </averageVehicleSpeed>
              </basicData>
            </measuredValue>
          </measuredValue>
          -
          <measuredValue index="7">

Ideally I would want to load the information with Python in a Jupyter Notebook as DataFrame, so I can perform some predictive analytics if the data allows. I have tried it with ElementTree, lxml like this, inspired from numerous other threads:

# Standard Packages
import pandas as pd
import numpy as np

# Necessary Packages for XML and setting Working Directory
import os
import xml.etree.ElementTree as ET
import lxml

os.chdir("C:/.../Intensiteiten en snelheden/30-10-2017")

xml_file = open('0600_Trafficspeed.xml').read() # Unzipped the file manually

def xml2df(xml_data):
    root = ET.XML(xml_data) # element tree
    all_records = [] #This is our record list which we will convert into a
    dataframe
    for i, child in enumerate(root): #Begin looping through our root tree
        record = {} #Place holder for our record
        for subchild in child: #iterate through the subchildren
            record[subchild.tag] = subchild.text #Extract the text create a new
    dictionary key, value pair
        all_records.append(record) #Append this record to all_records.
return pd.DataFrame(all_records) #return records as DataFrame

print(xml2df(xml_file))

Though this only returns one single entry with the first line, like   column name: d2LogicalModel, row: 0, entry: None.

I was able to see the tree like structure with difficulty in Microsoft Edge, requiring a lot of the CPU (Notepad++ and the plugin XMLtools also sufficed, but crashes with "bigger" size files, i.e. > 20mb). Though, in my opinion, this structure was still difficult to comprehend. There are so many layers that I do not know how to define the xml2df() with the correct sub-subchilds etc.

My questions thus boils down to, first of all, how would I be able to identify the variables/columns with data? Herewith getting an overview of the relevant data that I want to import. And secondly, how to import this into a DataFrame?

Note: Since the DATEXII format is the standard for traffic data in Europe, I was hoping their guides would help (see documents), but they haven't made sense to me yet. Maybe they will to any of you :)

Any help is greatly appreciated!

Body:
Consider transforming your nested XML input source into a flatter structure using XSLT the special-purpose transformation language designed to transform XML files into other XML, HTML, even text (CSV/TAB). Therefore, consider the below XSLT that transforms original XML into comma-separated values in tabular format for import into pandas with read_csv():

XSLT (save as .xsl file, a special xml file)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                              xmlns:pub="http://datex2.eu/schema/2/2_0"
                              xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/soapenv:Envelope">
    <xsl:text>publicationTime,country,nationalIdentifier,msmtSiteTableRef_targetClass,msmtSiteTableRef_version,msmtSiteTableRef_id,</xsl:text>
    <xsl:text>msmtSiteRef_targetClass,msmtSiteRef_version,msmtSiteRef_id,measurementTimeDefault,</xsl:text>
    <xsl:text>measuredValue_index,basicData_type,vehicleFlowRate,averageVehicleSpeed_numberOfInputValues,averageVehicleSpeed_value</xsl:text>
    <xsl:text>&#xa;</xsl:text>
    <xsl:apply-templates select="soapenv:Body"/>
  </xsl:template>

  <xsl:template match="soapenv:Body">
    <xsl:apply-templates select="d2LogicalModel"/>
  </xsl:template>

  <xsl:template match="d2LogicalModel">
    <xsl:apply-templates select="pub:payloadPublication"/>
  </xsl:template>

  <xsl:template match="pub:payloadPublication">
    <xsl:apply-templates select="pub:siteMeasurements"/>
  </xsl:template>

  <xsl:template match="pub:siteMeasurements">
    <xsl:apply-templates select="pub:measuredValue"/>
  </xsl:template>

  <xsl:template match="pub:measuredValue">
    <xsl:value-of select="concat(ancestor::pub:payloadPublication/pub:publicationTime,',',
                                 ancestor::pub:payloadPublication/pub:publicationCreator/pub:country,',',
                                 ancestor::pub:payloadPublication/pub:publicationCreator/pub:nationalIdentifier,',',
                                 ancestor::pub:payloadPublication/pub:measurementSiteTableReference/@targetClass,',',
                                 ancestor::pub:payloadPublication/pub:measurementSiteTableReference/@version,',',
                                 ancestor::pub:payloadPublication/pub:measurementSiteTableReference/@id,',',
                                 ancestor::pub:payloadPublication/pub:siteMeasurements/pub:measurementSiteReference/@targetClass,',',
                                 ancestor::pub:payloadPublication/pub:siteMeasurements/pub:measurementSiteReference/@version,',',
                                 ancestor::pub:payloadPublication/pub:siteMeasurements/pub:measurementSiteReference/@id,',',
                                 ancestor::pub:siteMeasurements/pub:measurementTimeDefault,',',
                                 @index,',',
                                 pub:measuredValue/pub:basicData/@xsi:type,',',
                                 descendant::pub:vehicleFlowRate,',',
                                 descendant::pub:averageVehicleSpeed/@numberOfInputValuesUsed,',',
                                 descendant::pub:speed)"/><xsl:text>&#xa;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Python

from io import StringIO
import lxml.etree as et
import pandas as pd

# LOAD XML AND XSL FILES
doc = et.parse('/path/to/Input.xml')
xsl = et.parse('/path/to/XSLT.xsl')

# INITIALIZE AND RUN TRANSFORMATION
transform = et.XSLT(xsl)
# CONVERT RESULT TO STRING
result = str(transform(doc))

# IMPORT INTO DATAFRAME
df = pd.read_csv(StringIO(result))

Output (parent node values become repeated indicators with different numeric data)

print(df)

#           publicationTime country nationalIdentifier msmtSiteTableRef_targetClass  msmtSiteTableRef_version msmtSiteTableRef_id msmtSiteRef_targetClass  msmtSiteRef_version     msmtSiteRef_id measurementTimeDefault  measuredValue_index basicData_type  vehicleFlowRate  averageVehicleSpeed_numberOfInputValues  averageVehicleSpeed_value
# 0  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    1    TrafficFlow             60.0                                      NaN                        NaN
# 1  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    2    TrafficFlow              0.0                                      NaN                        NaN
# 2  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    3    TrafficFlow              0.0                                      NaN                        NaN
# 3  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    4    TrafficFlow             60.0                                      NaN                        NaN
# 4  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    5   TrafficSpeed              NaN                                      1.0                       38.0
# 5  20171030T05:00:40.007Z      nl              NLNDW         MeasurementSiteTable                       955            NDW01_MT   MeasurementSiteRecord                    1  PZH01_MST_0690_00     20171030T04:59:00Z                    6   TrafficSpeed              NaN                                      0.0                        1.0


问:
Assign a value to each element of a matrix inside a given region in Matlab
I have an y*x matrix in matlab, and I want to assign a value to any point of the region of the matrix between 4 points, like A,B,C,D the image of which I know the coordinates, if the point were aligned this wouldn't be a problem, but they aren't.

Is there a function to do this ?

Edit

I have an an input matrix of numbers between 0 and 1.
The size of the matrix is 720*1280
The region is defined like this

x = [3 10  27 20 3];
y = [10 40 31 1  10];

It doesn't matter too much if the pixels are excluded or included along the edge of the rectangle, but is better if they are included.

The output matrix should be equal to the input matrix but with the values of the points inside the region of interest replaced by some other value, for example 2.

The solution I was searching for is very similar to the one that m7913d gave me.

答:
You can use poly2mask to convert the polygon to a mask and then change the desired elements in the matrix using logical indexing as follows:

```<code>% Create a sample matrix
matrix = rand(50, 50);

% Define your region as a polygon
x = [3 10  27 20 3];
y = [10 40 31 1  10];

% Convert the polygon to a mask
mask = poly2mask(x,y,size(matrix, 1),size(matrix, 2));

% Change the elements in matrix which are inside the polygon
matrix(mask) = 123;

% Display the result
figure
imshow(matrix, 'InitialMagnification', 'fit')
hold on
plot(x, y, 'r')
</code>```

Body:
You can use poly2mask to convert the polygon to a mask and then change the desired elements in the matrix using logical indexing as follows:

% Create a sample matrix
matrix = rand(50, 50);

% Define your region as a polygon
x = [3 10  27 20 3];
y = [10 40 31 1  10];

% Convert the polygon to a mask
mask = poly2mask(x,y,size(matrix, 1),size(matrix, 2));

% Change the elements in matrix which are inside the polygon
matrix(mask) = 123;

% Display the result
figure
imshow(matrix, 'InitialMagnification', 'fit')
hold on
plot(x, y, 'r')