Convert script Jquery to Javascript

Question: I need to convert following jquery script into javascript

This is what i did
  document.querySelector('select.ddlVarianti').addEventListener('change', function() {
    var optionSelected = document.querySelector(this).querySelector("option:selected");
    var tagliaSelected   = optionSelected.text();
    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      'event':'GAevent',
      'eventID':'13',
      'eventCategory':'product',
      'eventAction':'taglia',
      'eventLabel': tagliaSelected,
    });

  });

but i have following error..
Failed to execute 'querySelector' on 'Document': '[object HTMLSelectElement]' is not a valid selector.
Thanks for any suggestion
Comment: `document.querySelector(this)` is the code causing the problem. You can't pass an element object into `querySelector`.
Comment: Please show the HTML related to this. In particular, is there **one** `select.ddlVarianti` element, or more than one?
Comment: For starters change this `'change', function()` to this `'change', function({ target })`. Then change this `document.querySelector(this).querySelector("option:selected");` to this `target.querySelector("option:checked");`
Answer: There are three issues I can see (maybe only two):

document.querySelector(this) is passing an element object into querySelector. You can't do that, it accepts strings defining CSS selectors. To look within the element this refers to, use this.querySelector("selector string"). But if you want to get the seelcted option from an HTMLSelectElement, you can use its selectedOptions array instead.

option:selected is jQuery-specific. To find the first selected option within the select, you can use "option:checked" instead. But see #1, you don't need to do it that way.

The jQuery code is waiting for the window load event and then, redundantly, waiting until the DOM is ready (which it will be; load doesn't fire until long after it is). Your code isn't doing anything to wait for things to be ready. These days, if you're using type="module", there's no need to, so that may be fine. If not, you might consider it (modules are useful), or use defer on the script element.

You haven't said whether there is just one element or multiple but if we assume multiple, loop through the result of querySelectorAll to set up the handlers:
for (const element of document.querySelectorAll("select.ddlVarianti")) {
    element.addEventListener("change", function () {
        const optionSelected = this.selectedOptions[0];
        if (optionSelected) {
            const tagliaSelected = optionSelected.text;
            window.dataLayer = window.dataLayer || [];
            dataLayer.push({
                event: "GAevent",
                eventID: "13",
                eventCategory: "product",
                eventAction: "taglia",
                eventLabel: tagliaSelected,
            });
        }
    });
}

Live Example:

for (const element of document.querySelectorAll("select.ddlVarianti")) {
    element.addEventListener("change", function () {
        const optionSelected = this.selectedOptions[0];
        if (optionSelected) {
            const tagliaSelected = optionSelected.text;
            console.log(`tagliaSelected = ${tagliaSelected}`);
            /*
            window.dataLayer = window.dataLayer || [];
            dataLayer.push({
                event: "GAevent",
                eventID: "13",
                eventCategory: "product",
                eventAction: "taglia",
                eventLabel: tagliaSelected,
            });
            */
        }
    });
}

    <select class="ddlVarianti">
        <option value="A">Option A</option>
        <option value="B">Option B</option>
        <option value="C">Option C</option>
        <option value="D">Option D</option>
    </select>

    <select class="ddlVarianti">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
    </select>

Convert script Jquery to Javascript


What specific modules are included in Drupal Commerce Kickstart?

Question: Drupal Commerce Kickstart is a project built on Drupal Commerce that bundles Drupal 7, Commerce and a host of additional modules with some preset settings to speed up Commerce-based development.
I'm trying to find out what specific modules are actually included in this bundle, but all I can find is uninformative advert pages like this.
There's nothing about what exactly is included in the Kickstart documention. The closest I can find elsewhere online is this list of modules not included.
Is there any simple list of the modules that are bundled in the Commerce Kickstart package?
Answer: Here's the actual makefile that builds the latest version of Commerce Kickstart.
http://cgit.drupalcode.org/commerce_kickstart/tree/drupal-org.make
Within it, you can find every module that is built in. It includes the machine name of the project and the version number used.
For example, the entry "projects[ctools][version] = 1.9" shows you the machine name ctools, which is the Chaos Tools module, and the version is 1.9. You can look up the modules on drupal.org by substituting the machine name into the following URL: http://drupal.org/project/MACHINENAME.
Answer: This is a list based on this page announcing the first release candidate for Commerce Kickstart 2 in 2012 of modules that were developed as part of Commerce Kickstart and subsequently released as independent modules.
It gives an overview of some of the non-standard modules most specific to Kickstart. Note it's not complete and may not be up to date, but might be a useful starting point for understanding what sort of things Kickstart adds to a typical Drupal site.
Modules

Commerce Backoffice
Commerce Search API
Commerce add to cart confirmation
Inline Entity Form
Views Megarow
Field Extractor
Commerce Fancy Attributes
Image Delta Formatter
Commerce Addressbook

Themes

Omega Kickstart - a branch of the Omega theme
Shiny - an admin theme


How to console.table(array) ONLY display array elements, not methods (Ember Array)

Question: Preface: Dealing with an Ember.js Array
Been testing out console.table. Seems handy. However, it's annoying to see the array's methods in the output as well:

I'm repeatedly printing this out to visually sanity check a comparator function.
How can I console.table ONLY the array elements?
Comment: It looks like you're using some framework that adds more functions to your arrays. Since your arrays seems to have a `_super` property maybe they're not actually `Array`s but a subclass? Does that framework use the `prototype` property?
Comment: ! sounds suspect! I am using Ember, tho I'm not explicitly using an Ember ArrayProxy (that I know of)... hmmmm good line of inquiry. lemme see if i can find out if it's a frd Array or a Ember fancy pants Array
Comment: Verified, Ember magic is happening here. Changing question title / tags.
Comment: `console.table` was probably not written with this in mind. You can always write a function that turns a magic array back into a normal array, to print it. `var normal = Array.prototype.slice.call(magic_array, 0)` works I think.
Comment: dang, var normal = Array.prototype.slice.call(magic_array, 0) doesn't work either. ember is catching it somewhere. i'm thinking bout closing question as "nope, not possible"
Answer: Not possible unless you turn off Ember Array Extensions
(afaict)
Answer: You can use tty-table to accomplish this in the console - and filter out unwanted array elements using the formatter option.


Electric field due to an uniformly charged ring: problem to plot a specific graphic

Question: We know that the intensity of an electric field $E_x$ due to an uniformly charged ring ($R$ is the radius, $r=d(\text{charge $dq$},P)$)

is
$$E_x=\frac{k_e\ q\ |x|}{(x^2+R^2)^{3/2}}\tag 1$$
where $k_e\approx 9\cdot 10^9$ N$\cdot$ m$^2$/C$^2$, and $q$ is the charge of the ring.
Since $k_e$ is very big, how appropriately should I choose $q$ (the charge) and $R$ (radius of the ring) to obtain the image below?

Addendum:
Here there is an image of the function $(1)$ with $q=R=1$:

Without $|x|$:
Comment: I would choose $q=\frac 1{9\cdot 10^9}$. That's the equivalent of plotting $\frac E{kq}$
Comment: Ok, will do that now
Comment: What is your question exactly?
Comment: Could you be more clear? The curve must always look more or less like that because it's always zero at $x=0$ and has a maximum at $x=R/\sqrt{2}$.
Comment: @bluestool and Cye Waldman I have forgotten the question of my problem. I have used DESMOS and Geogebra with arbitrary values but the graph are wrongs. Excuse me for my unclear question.
Comment: What are you asking about exactly? As Cye Waldman pointed out, the curve will always look more or less like this, depending on the parameters $q$ and $R$.
Comment: I have programmed this in Matlab and find that $q=1$ and $R=1$ is very much like what you show. However, I don't really know the range of $(x,q,R)$ that you are interested in.
Comment: @bluestool In fact. I have chosen $R=q=1$ and I have not obtain a similar graph.
Comment: Are you sure you plotted $|x|$, because taking $x$ instead yields a different curve
Comment: Can you indicate what you did in particular. Are you sure you represented the equation correctly? In fact, can you show us your result also?
Comment: Well that looks perfectly fine to me. It is certainly odd because the scaling factor is very large, but if you zoom out, you should see the curve you want
Comment: @bluestool I agree with the above.
Comment: @Andrei Excuse me again. Please, can you add an answer or your comment?
Comment: @bluestool Good evening. The same comment of Andrei. Could you add an answer instead of a comment, please?
Comment: I see that bluestool already added his answer
Comment: @Andrei All users are welcome for my opinion. I'm very happy if you want added another answer.
Answer: The main factor here is the large factor you are multiplying the function by. When plotting, it can be useful to play with parameters to get a good idea of what the curve looks like. If parameters are too large, the general shape of the curve can be hidden by the sheer size of the values. I believe that is what is happening with your graph here. The graph is odd because the scaling factor is very large, but if you zoom out, you should see the curve you want.
From Andrei's comment,

I would choose $q=\frac1{9\cdot10^9}$. That's the equivalent of plotting $\frac{E}{kq}$.

Plot for $f(x)=\frac{|x|}{(x^2+1)^{3/2}}$:

Plot for $f(x)=100\frac{|x|}{(x^2+1)^{3/2}}$:
Comment: Sure, I will do that.
Comment: Thank you very very much. But could you add also a graph, please? I hope that not disturb you.


Deserializing JSON using System.Runtime.Serialization.Json

Question: I'm having issues with deserializing some json with C#.
Suppose this is a snippet of the json I'm being sent (repeated many times, but nothing else other than id/name):
[
    {
    "id":0,
    "name":"N/A"
    },
    {
        "id":1,
        "name":"Annie"
    },
    {
        "id":2,
        "name":"Olaf"
    }
]

If the top level was named, I'd do something like
[DataContract]
public class ChampList
{
    [DataMember(Name = "SOMENAME")]
    public ElophantChamp[] ElophantChamps { get; set; }
}

[DataContract]
public class ElophantChamp
{
    [DataMember(Name = "id")]
    public int ID { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

}

and then deserialize it by calling this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ChampList));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ChampList jsonResults = objResponse as ChampList;

But in the case where there is no top level container object and I can't have blank datamember name, what do I do?  I just get a null value if I leave the DataMember unnamed (i.e. leave it as just [DataMember]), which I would take to indicate that couldn't parse it correctly.
No errors are thrown and the sesponse stream is populated with exactly what I expect.
From what I can tell searching around and basic reasoning, I shouldn't be very far off from where I need to be.  There's just something I'm doing wrong with handling that highest level.
Answer: Does it work without the parent class ChampList?
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ElophantChamp[]));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ElophantChamp[] jsonResults = objResponse as ElophantChamp[];

Comment: Yes, perfectly.  I'd tried that, but didn't realize I could do it as (typeof(ElophantChamp[]) and had only tried typeof(ElophantChamp) (which failed).


setting background image on canvas from web camera

Question: My goal is set Background image from web-camera. Every time i click on button, background image should change. I am drawing an image from web-camera in update function. But there is the problem. Background image is always changing. I have to draw this image in update function.

window.onload = function() {

  backgroundImage = null;

  // Grab elements, create settings, etc.
  var video = document.getElementById('video');

  // Get access to the camera!
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    // Not adding `{ audio: true }` since we only want video now
    navigator.mediaDevices.getUserMedia({
      video: true
    }).then(function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
    });
  }

  //get canvas and context element
  var c = document.getElementById("canvas");
  var ctx = c.getContext("2d");

  // Trigger photo take
  document.getElementById("snap").addEventListener("click", function() {
    backgroundImage = video;
  });

  //call update function every 80 nanoseconds
  setInterval(function() {
    update(c, ctx);
  }, 80);
}

function update(c, ctx) {
  if (backgroundImage) {
    ctx.drawImage(backgroundImage, 0, 0, 640, 480);
  }
  ctx.rect(20, 20, 150, 100);
  ctx.stroke();
}
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
Answer: You'll have to use an offscreen canvas to take the snapshot, then draw this offscreen canvas on your visible one.

//get canvas and context element
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
// create an offscreen canvas to take your snapshots
var snapper = c.cloneNode().getContext('2d');

window.onload = function() {

  // Grab elements, create settings, etc.
  var video = document.createElement('video');

  // Get access to the camera!
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    // Not adding `{ audio: true }` since we only want video now
    navigator.mediaDevices.getUserMedia({
      video: true
    }).then(function(stream) {
      // don't use createObjectURL(stream), it's deprecated because it locks hardware
      video.srcObject = stream;
      video.play();
    })
    .catch(e =>{
      console.log('Please visit the https fiddle at https://jsfiddle.net/Kaiido/7uugy7td/');
      });
  }
  // Trigger photo take
  document.getElementById("snap").addEventListener("click", function() {
    // draw the video's current frame on the off-screen canvas
    snapper.drawImage(video, 0, 0);
  });
}

function update() {
  // draw our offscreen canvas on the visible one.
  ctx.drawImage(snapper.canvas, 0, 0, 640, 480);
  ctx.rect(20, 20, 150, 100);
  ctx.stroke();
  // don't use setInterval for animations
  requestAnimationFrame(update);
}
update();
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>

And a live fiddle for chrome.


Using .split(), I want save a string into 2 or 3 separate variables

Question: Lets assume I have this in the line
line=vaddpd %ymm8,%ymm7,%ymm6
what I want is to get a=%ymm8, b=%ymm7, c=%ymm6
or lets say we have in the line
line=cmp %rsi,%rbx
i want to get a=%rsi, b=%rbx
x=line.split(",")

Answer: Start with using split on the space:
line="vaddpd %ymm8,%ymm7,%ymm6"
split_list = line.split(" ")[1].split(",")

Then you have a list of your desired variables. You can assign them however you like, for instance a dictionary:
import string
keys = list(string.ascii_lowercase)
my_dict = dict(zip(keys, split_list))

Answer: import re

line = "vaddpd %ymm8,%ymm7,%ymm6"
splt_line = re.split(r"[ ,]", line)

After this, you can assign elements of splt_line to any variable you want.
Answer: Using the Python 3.10+ pattern matching seems both simpler and more robust than simple splits (which would throw IndexError on malformed data).
Kids, don't try this at home on a Python version lower than 3.10 => syntax errors
    def do_2or3(input_):
        print(f"\n\n{input_}:")

        match input_.split():
            case _, data:
                match data.split(","):
                    case a,b,c:
                        print(f"  {a=} {b=} {c=}")
                    case a,b:
                        print(f"  {a=} {b=}")
                    case _:
                        print(f"  !not a,b,c with {input_=}")
            case _:
                print(f"  !not a,b,c with {input_=}")

    do_2or3("line=vaddpd %ymm8,%ymm7,%ymm6")
    do_2or3("line=cmp %rsi,%rbx")
    do_2or3("line=cmp.%rsi,%rbx")
    do_2or3("line=cmp %rsi,%rbx,d,e")

output:

line=vaddpd %ymm8,%ymm7,%ymm6:
  a='%ymm8' b='%ymm7' c='%ymm6'

line=cmp %rsi,%rbx:
  a='%rsi' b='%rbx'

line=cmp.%rsi,%rbx:
  !not a,b,c with input_='line=cmp.%rsi,%rbx'

line=cmp %rsi,%rbx,d,e:
  !not a,b,c with input_='line=cmp %rsi,%rbx,d,e'


I'm trying to make string parser but something is going wrong

Question: I was trying to make a text parser which separates words in a string based on the space character. However, something is going wrong.
#include <stdio.h>
#include <string.h>

int main() {
    //the string should end with a space to count the all words
    char name[30] = "hello world from jordan ";
    int start = 0;
    int end = strlen(name);
    int end_word = start;
    char full[20][20];

    memset(full, 0, 400);

    int number_of_words = 0;

    for (int w = 0; w < end; w++) {
        if (name[w] == ' ') {
            number_of_words++;
        }
    }

    int counter = 0;

    while (counter < number_of_words) {
        for (int i = start; i < end; i++) {
            if (name[i] == ' ') {
                start = i;
                break;
            }
        }

        for (int j = end_word; j < start; j++) {
            full[counter][j] = name[j];
        }

        end_word = start;
        start++;
        counter++;
    }

    for (int x = 0; x < 20; x++) {
        for (int y = 0; y < 20; y++) {
            printf("%c", full[x][y]);
        }

        printf("%d", x);
    }

    return 0;
}

here is the strange thing happening when I run the code:
 hello0 world1 from2 jor3dan45678910111213141516171819

the first three words are being initialized in the right way but the fourth is not and I don't know why this is happening.
I want an explanation for the problem and if possible I want a more efficient way of writing this code without pointers pointers.
Note: I'm a beginner that's why I'm asking for a solution without pointers.
Comment: Strings are arrays, which you access via pointers. A pointer can be thought of as the address of a block of memory. They seem intimidating at first, but you may as well not shy away from them since you can't really get away from them in the end anyway.
Comment: For example, `strlen(name);` is actually passing in the pointer to the first element of `name` to `strlen`.
Comment: Yes I know but I really don't understand them now but I'm trying to. I just need to make this work without pointers just for now. @MadPhysicist
Comment: Why have you `number_of_words++;` after you counted how many words? That makes 5 but there are only 4 words.... Uh, you compensated for that later by using `while(counter < number_of_words - 1)`
Comment: I started the w form 0 so when the 3 spaces are added to 0 the number_of_words will be equal to 3 but there are four words so I add 1 to get the right number of words. @WeatherVane
Comment: There are 4 spaces. If you `printf("%d", number_of_words);` you'll find that says 5, but you actually only count to (5-1) later.
Comment: true sorry for that @WeatherVane
Answer: To start, trying to avoid pointers in C will be (very) hard. Just by their nature, arrays become pointers the instant you want to do anything useful with them. Array subscription is syntactic sugar over pointer arithmetic (foo[2] is the same as *(foo + 2)). Passing an array to a function will cause it to decay to a pointer to the first element.
You use pointers several times in your code, whether you realise it or not.

As for the code...
Quick note: size_t, not int, is the appropriate type to use when working with memory sizes / indexing. I'll be using it in the "corrected" versions of the code, and you should try to use it in general, moving forward.
The output is a bit confusing because everything is printed on a single line. Let's clean that up, and add some debugging information, like the length of each string you've stored.
for (size_t x = 0; x < 20; x++) {
    printf("%zu [length: %zu]: ", x, strlen(full[x]));

    for (size_t y = 0; y < 20; y++)
        printf("%c", full[x][y]);

    putchar('\n');
}

Now we get the output, across several lines (some duplicates collapsed for brevity), of:
0 [length: 5]: hello
1 [length: 0]:  world
2 [length: 0]:  from
3 [length: 0]:  jor
4 [length: 3]: dan
5 [length: 0]:
...
19 [length: 0]:

From this we can see a few notable things.

We have an additional, fifth "string", when we were only expecting four.
Our first and fifth "strings" have the apparent correct length, whilst
Our second through fourth "strings" have an apparent length of 0, and would seem to include spaces.

The zero lengths mean some of our arrays are starting with the null-terminating byte ('\0'), and we are only seeing output because we manually walk the entirety of each array.
Note that most terminals will do "nothing" when a null character is to be printed, meaning we appear to skip directly to our "strings". We can better visualize what is happening by always printing something:
printf("%c", full[x][y] ? full[x][y] : '*');

In this case we print an asterisk when we encounter a null character, giving us the output:
0 [length: 5]: hello***************
1 [length: 0]: ***** world*********
2 [length: 0]: *********** from****
3 [length: 0]: **************** jor
4 [length: 3]: dan*****************
5 [length: 0]: ********************
...
19 [length: 0]: ********************

This very clearly shows where in memory our characters have been placed.
The primary issue is that in this loop
for (int j = end_word; j < start; j++) {
    full[counter][j] = name[j];
}

j is initialized to a position relative to the beginning of name, but is used to index a memory offset of full. Excluding our first substring, when end_word is 0, this puts us farther and farther away from the zeroth index of each subarray, eventually crossing the borders between arrays.
This happens to work because 2D arrays in C are laid out contiguously in memory.
To fix this, we must copy our characters using a separate index that starts at zero for each subarray.
for (size_t j = end_word, k = 0; j < start; j++, k++) {
    full[counter][k] = name[j];
}

Now when we print our arrays out we can limit ourselves to our known number_of_words (for (size_t x = 0; x < number_of_words; x++)), giving us the output:
0 [length: 5]: hello***************
1 [length: 6]:  world**************
2 [length: 5]:  from***************
3 [length: 7]:  jordan*************

This looks roughly correct, but includes the preceding space in the "word". We can skip past these spaces by setting end_word to the next character instead:
start++;
end_word = start;
counter++;

Now our output looks properly split:
0 [length: 5]: hello***************
1 [length: 5]: world***************
2 [length: 4]: from****************
3 [length: 6]: jordan**************

Note that these are (now properly formatted) null-terminated strings, and could be printed using the %s specifier, as in:
for (size_t x = 0; x < number_of_words; x++)
    printf("%zu [length: %zu]: %s\n", x, strlen(full[x]), full[x]);

Overall this is a bit fragile, as it requires the trailing delimiting space in order to work, and will create an empty string each time a delimiting space is repeated (or if the source string starts with a space).

As an aside, this similar example should showcase a straight-forward method for tokenizing a string, while skipping over all delimiters, and includes some important annotations.
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[30] = "hello world from jordan";
    char copies[20][30] = { 0 };
    size_t length_of_copies = 0;

    size_t hold_position = 0;
    size_t substring_span = 0;
    size_t i = 0;

    do {
        /* our substring delimiters */
        if (name[i] == ' ' || name[i] == '\0') {
            /* only copy non-zero spans of non-delimiters */
            if (substring_span) {
                /* `strncpy` will not insert a null terminating character
                 * into the destination if it is not found within the span
                 * of characters of the source string...
                 */
                strncpy(
                    copies[length_of_copies],
                    name + hold_position,
                    substring_span
                );

                /* ...so we must manually insert a null terminating character
                 * (or otherwise rely on our memory being initialized to all-zeroes)
                 * */
                copies[length_of_copies++][substring_span] = '\0';
                substring_span = 0;
            }

            /* let's assume our next position will be the start of a substring */
            hold_position = i + 1;
        } else
            substring_span++;

        /* checking our character at the end of the loop,
         * and incrementing after the fact,
         * let's us include the null terminating character as a delimiter,
         * as we will only fail to enter the loop after processing it
         */
    } while (name[i++] != '\0');

    for (size_t i = 0; i < length_of_copies; i++)
        printf("%zu: [%s]\n", i + 1, copies[i]);
}


1 file server 2 nic's 2 PHYSICAL SEPARATED networks 2 routers same ip

Question: I'm an IT administrator in school. I use a windows 2003(also have a windows 2008 server ready for testing) file server with 2 NICs. At the moment only one NIC from file server is connected to the Science Labs Network. For simple security purposes the school has 2 separate physical networks: Science Labs and School Administration. For convenience each network has 1 router with same IP address 192.168.1.244 and each router get's internet from different ISP. Rarely when internet goes down on one network I simply switch the cable from the router with no internet to the other, as a result for this down time 2 physical networks become one with the internet from one ISP only and when internet is back on the other ISP I revert the changes. My question is how can I have one file server with 2 NICs connected to these both networks and still keep them separated? I don't need the server to have internet access I just use it for file sharing. To understand my question better here is a diagram of what I wan't to do:

I still want to keep routers on the same IP because it's convenient for me to switch the cable without changing any other settings on computers. And having two physical networks separate is secure without much of the hassle.
The purpose of this is to schedule on the school administration computers an automatic image backup to a network path on the file server.
Comment: I stopped reading after "2003"...
Comment: Ok, how about on windows server 2008, would that make a difference ? I have a windows server 2008 ready for testing.
Comment: You would need another device that is aware of this new network and the other network, and you would then (for example) 1:1 NAT 192.168.1.0/24 to 192.168.2.0/24, then your server could be 192.168.1.3 and 192.168.2.3, pfsense for example http://sysadmin.circularvale.com/firewall/configuring-a-network-to-network-nat-in-pfsense/
Comment: I have a third router wich i can set it on openwrt with dhcp disabled. I will search on internet how to do 1:1 NAT on openwrt and will play with it next week.
Comment: "Ok, how about on windows server 2008, would that make a difference ? I have a windows server 2008 ready for testing." You have an eight-year old server operating system "ready for testing"? I'm sorry but the whole arrangement seems crazy to me. And I'm talking as someone who works in educational IT and is aware that budgets and resources can be an issue. Deploying Windows Server 2008 (or even 2008r2 if that's what you meant to say) on a new server now is a poor decision.
Answer:
"For convenience each network has 1 router with same ip address 192.168.1.244"

this issue is the first of many many inconveniences using the same ip range for both networks will cause you.
The solution is to use non-overlapping  IP ranges  I.e use 192.168.1.244 for one  router and 192.168.2.224 for the other.  Give the routers unique ip addresses and use dhcp to automatically make the config changes needed when you move a device from one network to the other.  If there are a few machines moving regularly between the  2  networks use static dhcp reservations so you know what IP it's going to get to on each network. There are lots of ways to make it easy to move devices between the networks convenient without giving them the same IP ranges.
Comment: +1. Total incompetence = funny results. That is a big bad no, never do that.
Comment: TomTom you mean the quote or the answer ??
Comment: Nath, i hope you do get the networks are physically separated. Your ideea applies when both networks are conected and as I see it for me would be too much of a hastle : 1 Firstly i need to use on like 150 computers static ip addreses (either set on device or on a router through static dhcp) and would best work of course setting static dhcp on both routers but the hastle would come when i need to do the switch from one network to the other when one of the isp is down.
Comment: 2. As a security stand point i don't like where is going: for ex. a student can with his laptop set manually his ip to either of the networks witch is a no go for me.
Comment: I need to use 150 computers static ip addresses (static dhcp or device) because i have scripts set in openwrt to shutdown the internet (and not the network) on one of the labs. Each lab is set on a range of ip's.
Comment: Let me rephrase that sentence regarding convienience : In my particular case(physical separated networks) I have the convienience to manually fall back(cable switch) to one of the ISP each network has when the other is down(rarely happens). That's why  the routers have the same ip address so when one ISP is down I can manually fall back to the other via cable switch. Everything becomes one network on one router only and one ISP: security is an issue here (administration computers are exposed to students) but personally i take that risk for half a day that usually takes to solve the problem.
Answer: You have overlapping namespaces. I suppose you could install a NAT device and expose the file server as a different address. To the FS it will belive the source is a different network.
Comment: You mean a third router, how would i configure that third router say using openwrt conecting the other 2 routers with the same ip. Using vlans?
Comment: Or maybe you mean a third router (openwrt) between the nic2 and the adsl router and somehow configure it's nat to not have overlapping namespaces. Could you elaborate a bit on how would i do that ??? :D
Comment: Setting a 1:1 Nat like Jacob Evans proposed in the question comment section??
Comment: There aren't overlapping namespaces, overlapping networks is the issue.
Comment: The IP addressing is the naming of ethernet addresses, therefore the namespace.


VBA, Add mapping table to change header name

Question: I have a code that takes headers from sheet 1 with its data, finds those headers in sheet 2 and pastes the data where headers match between sheets.
But what if my headers from sheet 1 does not exist in sheet 2, I want to include a mapping table in another sheet which translates unlike headers into like headers. But I want to explicilty list these  headers in a mapping table.
I am having trouble finding the mapping then pasting into the new headers, as I dont want to replace or change the headers in my sheet 1.
Option Explicit
Sub stack(from_ws, to_ws, mapping)
    Dim rng As Range, trgtCell As Range
    Dim src As Worksheet
    Dim trgt As Worksheet
    Dim helper As Worksheet
    Set src = Worksheets(from_ws)
    Set trgt = Worksheets(to_ws)
    Set helper = Worksheets(mapping)
    Application.ScreenUpdating = False

    With src
        For Each rng In Intersect(.Rows(1), .UsedRange).SpecialCells(xlCellTypeConstants)

            'mapping code to go here

            Set trgtCell = trgt.Rows(1).Find(rng.value, LookIn:=xlValues, lookat:=xlWhole)

            If Not trgtCell Is Nothing Then
                .Range(rng.Offset(1), .Cells(.Rows.count, rng.Column).End(xlUp)).copy
                With trgt
                    .Range(Split(trgtCell.Address, "$")(1) & .Cells(.Rows.count, trgtCell.Column).End(xlUp).row + 1).PasteSpecial
                End With
            End If
        Next rng
    End With
    Application.ScreenUpdating = False
End Sub

i have a sheet named "mappings" like so, in BU:BW.
So if in sheet 1 my header is id , I want to find segment1 in sheet2 and paste the data there from sheet1 , header id.
+----------+-----------------+------------+
| Tab Name | Original Header | New Header |
+----------+-----------------+------------+
| sheet1   | id              | segment1   |
| sheet1   | id2             | segment2   |
+----------+-----------------+------------+

Answer: You could use VLOOKUP to retrieve the actual header to look for.
By declaring lkup as variant, the value to be returned by the VLookup, and using Application.VLookup, you can test whether a value was found using IsError. You could also use a scripting.dictionary and .Exists method to retrieve mapped value by key; which would be the src header.
You would want your lookup range to be comprehensive. In the example I give, note how it is not just new names covered but also if the name remains the same.
Obviously, you could refactor this a bit and, for example, pull the lookup range out so it is passed in as a variable to the sub stack. I might also change the name stack to something more descriptive of what the sub does. I have added in dynamically finding the last row of the lookup table so as to avoid hardcoding the end of the range. In case you add more lookup key value pairs.
Code:
Option Explicit
Public Sub test()
    Application.ScreenUpdating = False
    stack "Sheet1", "Sheet2", "Sheet3"
    Application.ScreenUpdating = True
End Sub

Public Sub stack(ByVal from_ws As String, ByVal to_ws As String, ByVal mapping As String)
    Dim rng As Range, trgtCell As Range, src As Worksheet, trgt As Worksheet, helper As Worksheet
    Set src = Worksheets(from_ws)
    Set trgt = Worksheets(to_ws)
    Set helper = Worksheets(mapping)

    With src
        For Each rng In Intersect(.Rows(1), .UsedRange).SpecialCells(xlCellTypeConstants)
            Dim lkup As Variant
            With helper
                lkup = Application.VLookup(rng.Value, .Range("A2:B" & .Cells(.Rows.Count, "A").End(xlUp).Row), 2, False)
            End With
            If Not IsError(lkup) Then
                Set trgtCell = trgt.Rows(1).Find(lkup, LookIn:=xlValues, lookat:=xlWhole)

                If Not trgtCell Is Nothing Then
                    .Range(rng.Offset(1), .Cells(.Rows.Count, rng.Column).End(xlUp)).Copy
                    With trgt
                        .Range(Split(trgtCell.Address, "$")(1) & .Cells(.Rows.Count, trgtCell.Column).End(xlUp).Row + 1).PasteSpecial
                    End With
                End If
            End If
        Next rng
    End With
End Sub

Data in Sheet3 (lookup sheet):

Version 2:
Here is a version using a dictionary to handle the replacement:
Option Explicit
Public Sub test()
    Application.ScreenUpdating = False
    Dim headerDict As Object
    Set headerDict = CreateObject("Scripting.Dictionary")
    headerDict.Add "id1", "segment1"
    headerDict.Add "id2", "segment2"
    headerDict.Add "id3", "segment3"

    stack "Sheet1", "Sheet2", headerDict
    Application.ScreenUpdating = True
End Sub

Public Sub stack(ByVal from_ws As String, ByVal to_ws As String, dictHeader As Object)
    Dim rng As Range, trgtCell As Range, src As Worksheet, trgt As Worksheet
    Set src = Worksheets(from_ws)
    Set trgt = Worksheets(to_ws)
    With src
        For Each rng In Intersect(.Rows(1), .UsedRange).SpecialCells(xlCellTypeConstants)
            If dictHeader.exists(rng.Value) Then
                Set trgtCell = trgt.Rows(1).Find(dictHeader(rng.Value), LookIn:=xlValues, lookat:=xlWhole)
            Else
                Set trgtCell = trgt.Rows(1).Find(rng.Value, LookIn:=xlValues, lookat:=xlWhole)
            End If
            If Not trgtCell Is Nothing Then
                .Range(rng.Offset(1), .Cells(.Rows.Count, rng.Column).End(xlUp)).Copy
                With trgt
                    .Range(Split(trgtCell.Address, "$")(1) & .Cells(.Rows.Count, trgtCell.Column).End(xlUp).Row + 1).PasteSpecial
                End With
            End If
    Next rng
End With
End Sub


Google cardboard, barrel, lens distorsion for a static image

Question: Input: the couple of the left and right stereoscopic image;
Desired output: the image formatted as Google cardboard expects, e.g.:
https://lh3.googleusercontent.com/vNacK7nx0HXU1g28FyqfnjYbaF0SKe86nDXhgetSfG8HTcsbhc7QcJtalcRHUEgU2A4k=h900-rw
I was wondering if I could get the barrel/lens distortion using Core Image Filter API for iOS.
If not, a "pixel" level algorithm would be also useful.
I don't want to use google cardboard sdk because I'm not using 3d scenes and openGL in my project.
Answer: You will somehow need to get the lens distortion parameters, since different viewers will have different lens parameters.  The easiest way to do this is to use the Cardboard SDK.
However, if you know the lens distortion parameters ahead of time, you can use the Brown-Conrady model to perform the correction yourself.


carousel bootstrap 4 somente no modo mobile

Question: Dada a imagem a baixo que representa o modo desktop, gostaria de saber como faz para virar um carousel somente no modo mobile.

!--- Team ----->

Meet our team

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

Comment: E a sua pergunta é?
Comment: como que eu faço?
Comment: Como faz o que?
Comment: dada a imagem, gostaria de no modo mobile(somente) elas sejam exibidas no formato de carousel
Comment: Posta o resto relevante do se código, o postado não reflete a imagem de exemplo. E nem o cenário atual onde o problema ocorre.
Comment: O carousel tá funcionando?
Comment: tá sim, eu só queria fazer uma verificação if modo mobile ai sim habilita o carousel
Comment: Só adicione o atributo data-ride="carousel" na @mediaquery para mobile. Mas para um exemplo mais detalhado, coloque aqui o seu código html e js para verificar o comportamento e corrigir
Comment: Coloquei o código que é do html, ai tipo, tem esse modelo with controls:https://v4-alpha.getbootstrap.com/components/carousel/ gostaria de tipo fazer ele aparecer só no mobile, tipo eu posso adicionar esse atributo data-ride="carousel" na  ?
Answer: Fiz esse modelo com apenas algumas linhas de CSS. A ideia é deixar o "componente" do time estático apenas em telas grandes, e em telas pequena eu dou um display:none nele enquanto dou um display:block no Slider. Logo com essa opção vc tem dois "componentes" ok.
Veja o Exemplo funcionando: (quando a tela for menor que 790px ele vai mostrar o Slider, mas se for maior ele mostra a lista estática.) Clique em "Página toda" para o slider sumir e ele ficar estático.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name=
 content=
>
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

Meet our team

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe 2

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe 3

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

          Previous

          Next

OBS1: para controlar a largura de tela onde o Slider aparece configure aqui
@media (max-width: 790px) { /* largura que vc quer que apareça */
    .carousel {
        display: block;
        text-align: center;
    }
    etc.....
}

OBS2: Aqui vc controla a velocidade do Slider
$('.carousel').carousel({
    interval: 500 /* quanto maior o número mais devagar a transição */
})

Comment: Muito obrigada! <3


How do I gracefully quit out the Sass interactive shell (on Windows)

Question: I launched the SASS interactive shell, as described at http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#interactive_shell
I can't (gracefully) quit.
I've tried:

quit
exit
^C
^.
^D
^Q

Anyone know how to do this?
Answer: ^D should do it. What OS are you using?
Answer: Given that you are on Windows, you might get Ctrl-Z (^Z) to be recognized as the end-of-file marker.
Answer: Try ctrl-c or ctrl-d (works on Windows).
Answer: I had the same error the first time and on my second time installing the Gem i added sudo which worked perfectly
Sass is watching for changes. Press Ctrl-C to stop.

Just a heads up if that helps.
Comment: My question was about using the interactive shell, not the watcher, but thanks anyhow - its not me down-voting you.


Treetop: parsing single node returns nil

Question: I'm trying to get the basic of Treetop parsing. Here's a very simple bit of grammar so that I can say ArithmeticParser.parse('2+2').value == 4.
grammar Arithmetic
  rule additive
    first:number '+' second:number {
      def value
        first.value + second.value
      end
    }
  end

  rule number
    [1-9] [0-9]* {
      def value
        text_value.to_i
      end
    }
  end
end

Parsing 2+2 works correctly, returning a node. However, parsing 2 or 22 returns nil.
What did I miss?
Answer: Got it! Though I'd normally delete the question, I wouldn't be surprised if someone else also fundamentally misunderstands Treetop, so I'll leave this here for reference.
Treetop doesn't just go through the rules, looking for which one applies. Instead, it starts at the first rule, and, if the first rule does not match, it must be forced to consider alternatives. Therefore, / number must appear at the end of the additive rule.
grammar Arithmetic
  rule additive
    first:number '+' second:number {
      def value
        first.value + second.value
      end
    }
    / number
  end

  rule number
    [1-9] [0-9]* {
      def value
        text_value.to_i
      end
    }
  end
end

Comment: +1 for a good question/answer, but I don't know if "number" should be considered "additive" perhaps you could define an "equation" rule that can return either the result of "additive" or a "number".


Probability of observing no heads in infinite coin tosses

Question: In class, the professor went through a sample solution of showing why the probability of observing 0 heads in infinite coin tosses is zero, using the limit of decreasing sequences.
She defined $A_i$ to be the cone set of obtaining no heads in the first i tosses, and showed that $A_i$ is a decreasing sequence.
She then said that
$\lim_{i\to \infty} A_i := \cap_{i\in \Bbb{N}} A_i =$ {no heads ever}
I can see why the above is intuitively true, but is there a rigorous proof for this? To my understanding, $\lim_{i\to \infty} A_i$ is just a notation which is defined as $\lim_{i\to \infty} A_i := \cap_{i\in \Bbb{N}} A_i$, so then what I need to figure out is why
$\cap_{i\in \Bbb{N}} A_i =$ {no heads ever}
The way I tried to prove this is by showing that an element in one set is in another, but I could only do this for one direction. The direction is proved is that if $x$ is an element of the LHS, then it is an element of the RHS via contrapositive.
To do this, I said that if $x$ is not in the LHS, then it has a "head" at some point $n$. So then $x \in A_i^c$ and hence $x \notin \cap_{i\in \Bbb{N}} A_i$.
However, I'm not sure if this approach is correct, and I have no idea how to prove the other direction. Any help would be great!
Thank you!
Answer: For the definition of set-theoretic limit I would just refer you to this wiki page.
We want to prove $\bigcap_{i\in\Bbb N}A_i=\{\text{no heads ever}\}$. Let us denote $\omega=\{\omega_i\}_{i=1}^{\infty}$, denote the outcome of a particular trial consisting of an infinite coin tosses, where $\omega_i$ is the outcome of the $i^{th}$ toss. Then $$\{\text{no heads ever}\}=\{\omega\mid\omega_i\ne\mathsf{H}\ \forall i\}$$ Let us call this set $S$.
Also $$A_n=\{\omega\mid\omega_i\ne\mathsf{H}\ \forall i\in\{1,2,\cdots,n\}\}$$ Then we really need to prove $\bigcap_{i\in\Bbb N}A_i=S$.
$\bigcap_{i\in\Bbb N}A_i\subseteq S$: Let us take $\omega\not\in S$. Then there exists $n\in\Bbb N$, such that $\omega_n=\mathsf{H}$. But then $\omega\not\in A_n$. Hence $\omega\not\in\bigcap_{i\in\Bbb N}A_i$. Thus any $\omega$ that doesn't belong to $S$, does not belong to $\bigcap_{i\in\Bbb N}A_i$ either. Hence $\bigcap_{i\in\Bbb N}A_i\subseteq S$.
$\bigcap_{i\in\Bbb N}A_i\supseteq S$: Let us take $\omega\in S$. Fix any $n\in\Bbb N$. We know that $\omega_i\ne\mathsf{H}$ for all $i\in\Bbb N$, and hence obviously $\omega_i\ne\mathsf{H}$ for all $i\in\{1,2,\cdots,n\}$. Hence $\omega\in A_n$. Since $n$ was arbitrary we can say that $\omega\in A_n$ for all $n\in\Bbb N$. Hence $\omega\in\bigcap_{i\in\Bbb N}A_i$.


Unit Tests with SpringJUnit4ClassRunner fails loading context with PersistenceUnitInfo.getValidationMode()

Question: I am trying to write some unit (integration) tests with Spring. I am using the SpringJUnit4ClassRunner. I have written tests using this runner before in my domain layer without an issue. Now that I'm trying to write tests in my web application and get the 'Failed to load ApplicationContext' exception.
The application is based on Hibernate / JPA 2.0. Here is the main exception:
Caused by: java.lang.NoSuchMethodError: javax.persistence.spi.PersistenceUnitInfo.getValidationMode()Ljavax/persistence/ValidationMode;
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:641)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:91)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1485)
Comment: Can you post your classpath? Judging by the stacktrace you have mixed JPA versions in your classpath.
Comment: My main app runs without issue and its using the same pom file. Which jars should I be looking for? I'm using Maven so I can't post the classpath.
Answer: Thans for the tip M. Deinum. I looked through my pom file and noticed that Spring Skyway Software Utils where bringing in JPA1. Once I removed the Skyway utils, my unit tests started to work.


Rails app returns HTTP 422 for new ServerAlias - Internet Explorer only

Question: I have a long-standing Rails app running on Mac OS X (apache2). The set-up uses Apache virtual hosts and Passenger.  The Rails app also uses HTTP Basic Authentication.
I need to migrate the app from one url domain to another - with some overlap of both domain names being accessible simultaneously for a period.
To do this, I've added the new domain name as a ServerAlias of the existing domain name in the Passenger Virtual Host config.
I can now Browse the Rails app using both the legacy url, and the new url from any of Safari, Chrome, Firefox, or Internet Explorer.
I can also 'HTTP post' updates to the Rails app using Safari, Chrome, or Firefox. All good.
Except, attempts to post updates from Internet Explorer result in the Rails app rejecting the update,
The Rails app log contains the message,
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

I have other domains & aliases working just fine on this same machine.
Any suggestions as to what is causing the Rails app to reject posts from IE would be appreciated.
UPDATE:  I've tried changing the new domain to be ServerName, and the old domain to be the ServerAlias, but still get the 422 with the new domain name.  I'm baffled.
Answer: Watch the logs closely, you must have an unencoded symbol there.
422 means that you got a correct request, but it can't be processed due to (generally) encoding problems.
From the rfc
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained
instructions.  For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.

Comment: Thanks for the reply.  The app works perfectly well with IE when using the original domain so, unless I'm missing something, I don't think it's an encoding problem.  It seems to be the authentication code being used that's causing the issue (it suspects a CSRF).
Answer: I don't know why this works, but in the hope that it helps someone else...
I found that Rails POSTs from MSIE are accepted if I've configured the new URL to use the same subdomain.
So,
If it's set up as,
originalsubdomain.originaldomainname.com

If a set up the new URL as,
newsubdomain.newdomainname.com

...then Safari, FireFox and Chrome are all happy, but MSIE causes Rails to baulk on a POST (tested across several machines).
However, if I set up the new URL to be,
originalsubdomain.newdomain.com

It works fully with all the listed browsers (tested across several machines).
Any suggestions as to why this might be, appreciated.
Comment: having underscores in the sub-domain? take a look http://bit.ly/1cgQzqE


Haproxy as a mail protocols reverse proxy with SSL termination

Question: Looking for guidance of how to configure haproxy 2.4 in a container, to proxy for a mail server (all protocols, imap/s, smtp/s, pop3/s, http/s) and having haproxy doing ssl termination, but also sending properly to the encrypted ports (pop3s, imap/s, especially) on the backend mail server.
Here is my configuration:
<code> frontend smtp-in
  bind *:25
  mode tcp
  tcp-request inspect-delay 5s
  tcp-request content accept if { req_ssl_hello_type 1 }
  use_backend smtp if { req_ssl_sni -i mailer.example.com }

frontend imap-in
  bind *:143
  mode tcp
  tcp-request inspect-delay 5s
  tcp-request content accept if { req_ssl_hello_type 1 }
  use_backend imap if { req_ssl_sni -i mailer.example.com }

frontend smtps-in
  bind *:587 ssl crt /usr/local/etc/haproxy/ssl
  mode tcp
  tcp-request inspect-delay 5s
  use_backend smtps

frontend imaps-in
  bind *:993  ssl crt /usr/local/etc/haproxy/ssl
  mode tcp
  tcp-request inspect-delay 5s
  use_backend imaps

frontend pops-in
  bind *:995  ssl crt /usr/local/etc/haproxy/ssl
  mode tcp
  tcp-request inspect-delay 5s
  use_backend pops
  log /dev/log local0 info

frontend pop-in
  bind *:110
  mode tcp
  tcp-request inspect-delay 5s
  use_backend pop

backend smtp
  mode tcp
  server mailserver 192.168.2.254:25

backend imap
  mode tcp
  server mailserver 192.168.2.254:143

backend smtps
  mode tcp
  server mailserver 192.168.2.254:587

backend imaps
  mode tcp
  server mailserver 192.168.2.254:993

backend https
   mode tcp
   server mailserver 192.168.2.254:443

backend pop
   mode tcp
   server mailserver 192.168.2.254:110

backend pops
   mode tcp
   server mailserver 192.168.2.254:995
</code>
I am testing with pop3/s and so far requests are being rejected for SSL(pop3), and odd timeouts (pop3s).
Am I doing this correctly? Can someone please enlighten me?
Comment: Maybe this discussion can help somehow: https://discourse.haproxy.org/t/smtp-imap-proxy-based-on-domain-pass-through/5480
Comment: Thanks, my takeaway from the discussion is 'But haproxy is definitely the wrong tool for this job.'
I need to find something else.
Answer: From here 'https://discourse.haproxy.org/t/smtp-imap-proxy-based-on-domain-pass-through/5480'
it appears that 'haproxy is the wrong tool for the job'.
Comment: My opinion is that your approach (tcp proxy) is not the right one, because haproxy is one of the best tools for that. I believe that email tools (postfix etc.), if configured properly, can do what you are trying to achieve. But I am not able to show you how.
Comment: Uhh .... thanks, I think?


How does a keyboard extension know that the document proxy has changed?

Question: Keyboard extensions on iOS are subclasses of the UIInputViewController class and have the textDocumentProxy property to interact with the underlying document. The textDocumentProxy object exposes some important traits of the document, like the autocapitalization type. The question is, how does the keyboard extension know when the underlying document changes?
For example, when I tap to compose a new message in the Messages app, the "To" field uses different input traits than the message body input box. But since the keyboard doesn't dissapear when switching focus from one field to the other, the text document proxy object changes on the fly. Can the keyboard extension notice such a change?
I've tried watching both the textDocumentProxy and [[self textDocumentProxy] autocapitalizationType] properties through KVO, but that doesn't work. Checking the autocapitalizationType property using a timer reveals the change, but obviously I'd like to avoid a polling solution.
Answer: My UIInputViewController supports the UITextInput protocol, which has a textDidChange method. From textDidChange, I compare self.textDocumentProxy with my own self.currentTextProxy property. When the two differ, I update self.currentTextProxy, then refresh my GUI based upon the self.textDocumentProxy's UITextInputTraits.
Comment: Thanks! I have completely missed the `UITextInputDelegate`.
Comment: This doesn't seem to work in iOS 10. it looks like the textDocumentProxy memory address never changes and they are just swapping out the input field behind the scenes.  Have you found a solution that still works?


how to make a list using while with input function

Question: How to collect a list of user inputs using the While loop?
I tried using an if statement to stop inputs when the input is 'quit' but it doesn't print after the input, it either prints 1 input and with some tweaking it goes on appending the same input over and over.
#input methods with lists
x=input('Type to fill your list here:')
list=[]
while x.lower()!='quit':
  print()
  if x.lower()!='quit':
    list.append(x)
    print(list)

I need to print the list after every input appended with the previous results too but the actual output is either it stops after 1 input or it appends the same input over and over again.
PS: I'm trying it with strings and not int
Comment: Possible duplicate of [How to fix a while loop that goes on forever in Python?](https://stackoverflow.com/questions/58343621/how-to-fix-a-while-loop-that-goes-on-forever-in-python)
Comment: You only ever ask the user for input once.
Answer: Your input method needs to be in the loop too, otherwise what basically is happening is that it asks for the user input just once and then moves on to the while loop.
Here you go:
list = []
while True:
    x=input('Type to fill your list here: ')
    if x.lower()!='quit':
        list.append(x)
        print(list)
    else:
        print(list)
        break

Answer: Kalyan the input function should be included in the while loop.
Your code when corrected would look like this.
list=[]
while True:
    x=input('Type to fill your list here:')
    if x.lower() == "quit":
        print(list)
        break
    list.append(x)

Answer: Sorry guys, that worked using a break after the if and moving the if logic to else
Here's the sample code
list=[]
while True:
 x=input('Type to fill your list here:')
 if x.lower()=='quit':
  break
 else:
  list.append(x)
  print(list)

Comment: You should just upvote all the correct answers and accept one of them
Comment: @Trollsors - Not quite correct, you should upvote answers you found useful, if additional answers didn't add anything new then there's no need to upvote them
Answer: You can use try for End of file exception.
list_ = []
while 1:
    try:
        string = input()
        list_.append(string)
        print(list_)
    except EOFError:
        break

input string is appended to list list_. But I think it will work if input is taken through a file


Question 10.7 of schaum's outlines linear algebra regarding Invariant Direct-Sum Decompositions

Question: The following theorem is proposed: let W, W', W",... be subspaces of V with B, B', B'',... bases. V is the direct sum of all W's if and only if the union of all the B's bases is a basis of V. I wonder what is wrong with the following counter example: let W be the subspace of R3 formed by the basis B={(1,0,0),(0,1,0)} and let W' be the subspace of R3 formed by the basis B'={(0,1,0),(0,0,1)}. The union of B and B' forms the canonical base for R3, yet R3 is not the direct sum of W and W', for the intersection between W and W' is not empty.enter image description here
Comment: It should say "the disjoint union", or perhaps "all the $\;B\,'$s bases are disjoint and...". Otherwise, yours indeed is a good counter example.
Comment: The theorem, as stated, is indeed wrong.  Good eye.
Comment: I'm happy my question wasn't pointless nor vain, as is often their fall.
Comment: yet, I wonder how is the solution proposed by the autor wrong. I must confess it is too convoluted for me to understand it (the solution is in the image annexed to the question where it says enter image description here).
Answer: I think their proof falls apart when they say "because $B$ is a basis of $V$, $a_{ij} = b_{ij}$ for each $i$ and each $j$". This is not correct because if, say $w_{11} = w_{12}$, then we can only conclude that $a_{11} + a_{12} = b_{11} + b_{12}$, so uniqueness can fail.


É possível utilizar C# e Python no mesmo executável?

Question: Quero criar um software executável para desktop e estou utilizando Python, porém a interface gráfica gostaria de fazer no C#, visto que é muito mais pratico e bonito. Como eu posso correlacionar a interface gráfica no C# com o código criado em Python? Caso não for possível, onde posso fazer essa interface gráfica?
Comment: IronPython seria uma opção, mas acho que é um projeto que está meio devagar, semi-abandonado.
Answer: Não ficou muito claro em qual parte você utiliza o python mas estou assumindo que seria o backend.
Nesse caso você poderia criar um servidor HTTP para troca de informações via API:
Criação de uma API Rest com Python
Outra forma seria criar os scripts que tu precisa em python e fazer com que o C# os rode passando por parametro os valores:
Como executo um script Python a partir de c #?
Rodar Python e C# juntos


How to get a list of RUs, SPs and other updates installed for Exchange from a command line or PowerShell?

Question: Is there a way to get a list of updates, rollups, service packs installed for the MS Exchange Server from a command line, PowerShell or Exchange Management Shell?
I already tried Get-Hotfix, Get-WmiObject and Systeminfo but all of the above seem to return lists of updates installed only for the system (Windows) and not for the Exchange.
Edit: Get-ExchangeServer does not satisfy my needs as for Exchange 2010 SP3 it seems to always report Build version 123.4 despite all newer Rollups installed and real build number being 224.2.
Answer: The Microsoft-recommended way of getting your Exchange service pack and rollup version is to get the file version info on Exsetup.exe.
In the Exchange Management Shell, use:

Get-Command  Exsetup.exe | ForEach-Object {$_.FileversionInfo}

And then look up the version returned against Microsoft's Exchange Server Updates: build numbers and release dates page.
And yeah, that's really as granular as you can get, unless you want to parse a list of all installed updates for Exchange-specific updates.
Comment: Awesome, this seems to work.


Closest hermitian matrix in operator norm induced metric

Question: Let $M (n)$ be the set of $n \times n$ complex matrices and $\| \cdot \|$ an
operator norm on $M (n)$ arising from some inner-product on $\mathbb{C}^n$.
Note the Cartesian Decomposition of $A \in M (n)$ is
$$ A = \left( \frac{A + A^{\ast}}{2} \right) + i \left( \frac{A -
   A^{\ast}}{2 i} \right) . $$
I'd like to show $\frac{A + A^{\ast}}{2}$ is the closest hermitian to $A$ in
the $\| \cdot \|$ induced metric. That is, how to prove
$$ \left\| A - \frac{A + A^{\ast}}{2} \right\| \leqslant \| A - H \| $$
for all hermitian matrices $H$ in $M(n)$?
For the Frobenius norm, I proved the result using $\| H+iK \|_F^2 = \| H\|_F^2+\|K\|_F^2$ (for hermitian $H$ and $K$). Unfortunately, this strategy doesn't work here, and I'm unsure what else to try.
Answer: Yes, this is true. Note that:
$$\left\|A - \frac{A + A^*}{2}\right\| = \left\|\frac{A - A^*}{2}\right\| = \left\|\frac{(A - H) - (A - H)^*}{2}\right\|,$$
for all Hermitian $H$. Given $A - H$ ranges over all $M(n)$ for $A \in M(n)$ and Hermitian $H$, the conjecture is equivalent to
$$\left\|\frac{A - A^*}{2}\right\| \le \|A\|$$
for all $A \in M(n)$.
Recall that $\|A\|$ is the greatest singular value of $A$, and since $A^*A$ and $AA^*$ share the same (non-zero) eigenvalues, we therefore have $\|A^*\| = \|A\|$. Therefore,
$$\left\|\frac{A - A^*}{2}\right\| \le \frac{\|A\| + \|A^*\|}{2} = \|A\|,$$
as required.


Linux mysql server 5.6 will not start, or restart

Question: I have a problem with mysql server; it doesn't want to start
do you have an idea
thank you.
    janv. 29 10:51:15 clicshopping mysqld_safe[20076]: 160129 10:51:15 mysqld_safe Can't log to error log and syslog at the same time.  Remove all --log-error configuration options for --syslog to take effect.
janv. 29 10:51:15 clicshopping mysqld_safe[20076]: 160129 10:51:15 mysqld_safe Logging to '/var/log/mysql/error.log'.
janv. 29 10:51:15 clicshopping mysqld_safe[20076]: 160129 10:51:15 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
janv. 29 10:51:15 clicshopping mysqld_safe[20076]: 160129 10:51:15 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
janv. 29 10:51:55 clicshopping sudo[19837]: pam_unix(sudo:session): session closed for user root

My process
sudo service mysql stop
sudo service apparmor stop
sudo mv /var/lib/mysql /home/mysql
sudo ln -s /home/mysql /var/lib/mysql
sudo chown -R mysql:mysql /home/mysql
vi /etc/apparmor.d/usr.sbin.mysqld (change var/lib/mysql ot /home/mysql)
sudo service apparmor start
sudo service mysql start

after deleted /var/log/mysql/error.log : results
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2016-01-29 11:21:17 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2016-01-29 11:21:17 0 [Note] /usr/sbin/mysqld (mysqld 5.6.28-0ubuntu0.15.10.1) starting as process 27093 ...
2016-01-29 11:21:17 27093 [Warning] Buffered warning: Changed limits: max_open_files: 1024 (requested 5000)

2016-01-29 11:21:17 27093 [Warning] Buffered warning: Changed limits: table_open_cache: 431 (requested 2000)

2016-01-29 11:21:17 27093 [Warning] Using unique option prefix myisam-recover instead of myisam-recover-options is deprecated and will be removed in a future release. Please use the full name instead.
2016-01-29 11:21:17 27093 [Note] Plugin 'FEDERATED' is disabled.
/usr/sbin/mysqld: Table 'mysql.plugin' doesn't exist
2016-01-29 11:21:17 27093 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2016-01-29 11:21:17 27093 [Note] InnoDB: Using atomics to ref count buffer pool pages
2016-01-29 11:21:17 27093 [Note] InnoDB: The InnoDB memory heap is disabled
2016-01-29 11:21:17 27093 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2016-01-29 11:21:17 27093 [Note] InnoDB: Memory barrier is not used
2016-01-29 11:21:17 27093 [Note] InnoDB: Compressed tables use zlib 1.2.8
2016-01-29 11:21:17 27093 [Note] InnoDB: Using Linux native AIO
2016-01-29 11:21:17 27093 [Note] InnoDB: Not using CPU crc32 instructions
2016-01-29 11:21:17 27093 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2016-01-29 11:21:17 27093 [Note] InnoDB: Completed initialization of buffer pool

Comment: The solution is in the error above - `Remove all --log-error configuration options for --syslog to take effect.`
Comment: It's not asking you to delete the log file. It's asking you to change the configuration to never try to write to that file in the first place.
Comment: in var/log/mysql/error.log, i deleted all data, does'nt work :see above
Comment: How about posting your my.cnf, since that's what MySQL uses for configuration?
Answer: Starting mysqld daemon with databases from /var/lib/mysql
You didn't change the datadir in /etc/my.cnf or wherever your distro places it. Changing it to datadir=/home/mysql should fix your problem.
Comment: I have this element.
Comment: Sorry, I missed that. I did notice another error - `2016-01-29 11:21:17 27093 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.`. Are you sure you're not missing any tables?
Answer: Seems like your 'mysql.plugin' table is not exsist or mysql data dir is not owned by mysql user.
Answer: The very first line tells you about the problem:

janv. 29 10:51:15 clicshopping mysqld_safe[20076]: 160129 10:51:15 mysqld_safe Can't log to error log and syslog at the same time.  Remove all --log-error configuration options for --syslog to take effect.

You responded to that by saying this:

in var/log/mysql/error.log, i deleted all data, does'nt work :see above

But you missed the point!  MySql doesn't care what data is or is not in that file. It cares that you're still trying to write new data to the file. You need to change your configuration file so you never try to write to that log in the first place. Alternatively, you could remove the --syslog option. You get to write to one or the other log location; not both.
Also, what in the world did you do to your plugin table!?

2016-01-29 11:21:17 27093 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.

As it suggests, try running mysql_upgrade.
Comment: I reinstall all and it work ! tk


How to add a cron task

Question: I am new to drupal, now I have function get_node_from_rss() which the file is inside mysite\sites\all\modules\node\node_rss\node_from_rss.module the function will update node from the rss link every 1 hour. Now, I dun know how to make this function add to the cron task. Can I run it without using cron.php? I search in google, they something like simple change the function name like get_node_from_rss_cron(), I also putting some code like:
$interval = variable_get('get_node_from_rss_interval', 60 * 60);
if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }

inside my code, but those still not working for me,
Any solution?
Comment: `get_node_from_rss_cron()` this is incorrect. Cron Functions should be of format `MODULE_NAME_cron()`. Any hook should follow this format.
Comment: So you've written this in a custom module?  Or you written it in the core node module?
Comment: Change `get_node_from_rss_cron()` to `node_rss_cron()` and `node_from_rss.module` filename to `node_rss.module`. And don't put your custom module inside core modules.
Answer: A hook implementation is simply a my_module_name_function implentation.
Your module's internal name is what you have used in the .module file's name.
So for in this case, it's node_from_rss (I'd recommend you to rename the folder name to node_from_rss as well so it reduces any confusion).
If you rename your cron function to comply with the above my_module_name_function pattern, function name has to be node_from_rss_cron
function node_from_rss_cron() {
 $interval = variable_get('get_node_from_rss_interval', 60 * 60);
 if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }
}

Other than these changes, here are some of the Drupal best practices.
Drupal 7 has a REQUEST_TIME constant defined at the beginning of page processing. If this code is for D7, use it instead of time().
drupal_set_message() function sets a message to the screen. but cron functions will run without use interaction. You will not see this message unless you are running cron manually at admin/reports/status page.
Avoid placing folders such as 'node' inside sites/all/modules folder. Technically it's completely ok to do so. But I think it will confuse you and others in the long run. Usually we place modules like:
sites/all/modules/MY_MODULE/MY_MODULE.module

Comment: Just an FYI `drupal_set_message` is of no use inside a cron function unless you are debugging and calling cron function explicitly. Better to use `watchdog` all time
Comment: that mean i should put as mysite\sites\all\modules\node\node_from_rss.module? i thought all custom module should put like mysite\sites\all\modules\node\node_rss\node_from_rss.module, cause i got another 2 custom module also put at the folder. Another question, if this module disable at admin module setting the cron still working?
Comment: If you disable it, no hook will be fired. You can't use functions in disabled modules either.

How to add a cron task


Non-uniqueness in the $L^1$ martingale representation

Question: Let $\xi \in L^1(P,\mathfrak F_T)$ on some probability space with measure $P$, supporting a Brownian motion, we consider the augmented filtration $\mathfrak F$ associated to $W$, and a time $T>0$. Then, there exists a predictable process $H$ such that $\int_0^T H^2_t ~ dt < \infty$ and
\begin{equation*}
\xi = E[\xi] + \int_0^T H_t ~ dW_t.
\end{equation*}
If $\xi \in L^2(P)$, then $H$ is unique (this follows from the Ito isometry). In general, the Ito isometry argument does not work. Do you know an interesting counterexample (i.e. two different martingale representations for $\xi \in L^1(P)$)?
Answer: Suppose $\xi$ is only integrable.  Let $X=(X_t)_{t\in[0,T]}$ denote a continuous version of the martingale $\Bbb E[\xi|\mathfrak F_t]$, $0\le t\le T$. By localizing the usual $L^2$ martingale representation, there is a predictable process $K$ with $\int_0^T K_s^2\,ds<\infty$ a.s., such that
$$
X_{t}=\Bbb E[\xi]+\int_0^t K_s\,dW_s,\qquad 0\le t\le T, \hbox{ a.s.}
$$
The process $K$ is uniquely determined by the martingale $X$.
On the other hand, using the representation you cite, we can define a local martingale $Y$ by
$$
Y_t=\Bbb E[\xi]+\int_0^t H_s\,dW_s,\qquad 0\le t\le T.
$$
The difference $X_t-Y_t$ is a local martingale on $[0,T]$ with terminal value $0$. If we knew that this implied  $X_t=Y_t$ for all $t$, then we would have $H=K$ and the uniqueness you seek. But examples show that a local martingale need not be determined by its terminal value.
For example (modifying an example found in R. Williams' text on Math. Finance), take $T=1$ and define $Z_t=\int_0^t (1-s)^{-1/2}\,dW_s$ for $0\le t<1$. Then $Z$ is a local martingale on $[0,1)$, and one checks $\langle Z\rangle_t\uparrow+\infty$ as $t\uparrow 1$. It follows that the stopping time $\tau:=\inf\{t>1/2: Z_t=0\}$ satisfies $0<\tau<1$ a.s. The stopped process $Z_{t\wedge\tau}$ is then a local martingale on $[0,1]$ with terminal value $Z_1=0$, but also $Z_1=\int_0^1 J_s\,dW_s$, where $J_s=1_{\{s\le\tau\}}(1-s)^{-1/2}$. Notice that $J$ is non-zero!
More intriguing, R.M. Dudley showed in 1977 that any $\mathfrak F_T$ measurable r.v. $\xi$ admits a representation $\xi=c+\int_0^T H_s\,dW_s$ with $H$ predictable such that $\int_0^T H_s^2\,ds<\infty$ a.s., and the constant $c$ chosen arbitrarily by you ahead of time.


How to avoid unwanted scratching/squeaking/hissing noise from the fretting hand when playing hi-gain electric guitar?

Question: I have been playing the electric guitar for over ten years now, and this is an issue that has been troubling me for ages.
Whenever I play hi-gain songs and have to switch fretting hand positions quickly (there is no time to lift fingers from the fretboard and replace them somewhere else without touching the strings), my fingers sliding over the strings make an awful lot of scratching/squeaking/hissing noises. It's something you usually hear on acoustic guitars as well but when playing hi-gain electric the noise can be so loud it gets really problematic, it sounds very sloppy indeed.
Obviously, playing accurately is essential, and when playing slowly it's usually possible to lift your fingers off of the fretboard quietly when switching positions but at shredding speeds when there is too little time I really don't see how to avoid this.
My picking hand causes some of these noises as well but I think the problem there is playing too cramped when playing fast and having a tendency to rest my hand on the strings too much.
My favourite guitar players seem not to have this problem, even when hearing them perform live, so I assume it is possible to avoid this using proper technique. I know using too much gain will make noise uncontrollable but I'm not one to turn the gain knob to 10 at all. Hearing guys like John Petrucci play at lightning speed with no unwanted noise at all - even when using an extremely aggressive hi-gain tone - baffles me quite a bit.
How do they avoid or minimise these unwanted noises?
Answer: How often do you play loud volume/high gain?  This is definitely a skill that is "picked up" over time, and playing in that kind of environment will help you out.
One definitely needs to "learn" to play loud.  If that makes sense.
It can be tackled a few thousand different ways, as I'm sure we'll see in the answers here but what has worked for me is muting, since inevitably, we'll have problems with strings being ever-so-slightly plucked as you try to quickly lift your fingers off of them.
So learning to mute can be taken from a few different angles.
This assumes you're playing right-handed guitar.  Easily think in reverse if this assumption is not true.

Left Hand

Assuming you've been playing for some time now (which you have) I can assume you're left hand is pretty good with muting.  It may even be subconscious, but you'll need to make sure that an unintended glissando is not apparent (moving up or down the neck on a single string) in your playing.  An easy way to work on this is playing at stage volume (whatever you consider that being) and really focusing on what's happening between the parts you're playing where a position switch is necessary.  It may even be beneficial to record a few sessions and listening to the extraneous noise you encounter so you can focus on when and where it happens.
The other muting most of us are used to is the left hand finger's muting the strings as you lay them down.  This is picked up pretty easily with enough volume and gain in practice, but it's always good to see how the interaction between horizontal (sliding) and vertical (laying down hand/muting) positioning works, and if there's any minimize-able gaps between these.

Right Hand

The right hand was really the Eureka moment for me as I started to play louder amplifiers, since we'll inevitably get finger/string noise.  I practice a combination of left and right hand muting to really get a noise-free (or, as much as possible) performance and find a sweet mix of technique to properly play high gain.
With the right hand, you can easily rotate your wrist out towards the audience and get a nice fatty, fleshy (hate those words - better adjectives for that?) part of your right hand on the strings.  Depending on where you pick most of your time, this will be more or less effective with either a full-stop mute, or a palm-muted sort of sound.  The goal is to come up more on the string to effectively mute the noise you'll get from the string being amplified 10,000 times.  I've found that with practice between this and the left hand traditional styles of muting, a lot of gain and volume can be played and still come out "cleanly".

Gear

A noise gate or compressor with a threshold can help slightly, assuming you have the cut-off point set well enough.  The noise gate will allow you to "tune-out" some of this noise with proper muting technique applied, but it can have an overall "choppy" sound to it.  The compressor will work in reverse of this, but bring up the overall volume of sound that's not the string noise making it a bit less apparent.  But you really shouldn't focus entirely on this solution as it's gear-dependent, especially since you've admitted you're not playing with extreme high gain.
This is out of left field, but how often are you changing strings?  Dirty strings can have more funk on them, making them a bit rougher and allowing perpendicular vibration to happen more easily (think of a violin bow across a violin's strings).  A newer set of strings are "slick" and inherently allow you to slide across them more easily; you'll find the noise as you move across them lower than an older set that has maybe started to corrode or "die".  If you find that your technique can not be improved, a look at the strings and their state of affairs may be in order.  We're talking about unwound strings, but this even slightly applies to wound (although some may make the argument that gunk in the wound strings makes them smoother).

It's important to understand that some of this sound is intended, and subconsciously requested by many.  It keeps you from sounding like a keyboard and that's a good thing.  Acoustic guitarists can't always get away from this sound, and it's better to embrace it at times.
However, I understand the likeness of this sound is bipolar.  Either people can't stand guitar because of it (and don't even realize that's the sound they hate) or can't get enough of it.  It's good to find a nice mix of silence and this human aspect of playing the instrument.  I mean, pick slides are the reason a lot of guitarists picked up the instrument in the first place!
P.S.

My picking hand causes some of these noises as well but I think the problem there is playing too cramped when playing fast and having a tendency to rest my hand on the strings too much.

...You definitely should learn to relax your hand if you intend on playing for a long time.  It allows you to mute strings a bit easier, possible, but more importantly it's something too many guitarist don't focus on until it's too late.
Comment: +1 If I had answered this, I would have written something similar and also added that you can roll the tone control off on the guitar a little bit and get high-end brightness from the distortion itself. I also would have mentioned string/finger lubricants as Rockin Cowboy did.
Comment: Some really good suggestions here, I'll have to experiment with these. Strings are changed reasonably often
Answer: I play acoustic guitar primarily but I do use a great deal of sliding on strings to emulate bends that I would do on an electric guitar - and I like to keep the string noise toned down a bit. Most of the string noise I get comes from the lateral movement of my fingers down the strings which can sound like sawing wood on the wound strings as my fingers run across the ridges.
You asked about ways to minimize the noise.  Shawn has addressed this question with technique - and with modifications to the electrical signal.  I will offer possible ways to reduce the noise based on what you can do with your strings.
Shawn makes an excellent and valid point about keeping fresh strings on your guitar.  Beyond that - what works for me is coated strings.  I use either Elixir or D'Adderio EXP.  They make these for electric guitar as well and they really help cut down on string noise on the wound strings.
If you don't like coated strings you have two other options.  I see many electric guitar players (myself included) use a product such as Finger Ease (see picture below) which does a great job of reducing string talk.  It's a spray on string lubricant.

Another thing I have done on stage if the Finger Ease was not accessible, is to actually get some oil off my forehead and rub it on the strings.  It works - but I do change the strings often.
Finally - if you don't like coated strings and don't want to spray stuff on your fretboard or strings, you can use flat wound strings for your wound strings.  You can't make them talk if you try.  But it does affect your tone if used with clean settings.  I have not really tried the flat wound with hi gain.
That's what I know.  Hope you can use one of my ideas to reduce the noise.  Perhaps others will share what has worked for them.  Good luck.
Comment: @JeroenMoons  read the label carefully before you spray it on.  And protect anything that might catch any overspray.  You might even try spraying it on a soft cloth and then rubbing it on the strings.
Comment: I will try a product like that, very curious how strong the effect will be!
Answer: Flatwound strings
It's an extreme option to be sure, but flatwound strings have drastically reduced scraping noises compared to roundwound. It's in their very design. Rather than a rippled profile like with roundwound, the edge of flatwound strings is nearly flat, with tiny gaps between the windings. When very new, they may have a slight very high pitched squeak, but this usually fades as they wear-in.
Tapewound strings
If flatwounds are not extreme enough, then tapewound is the answer. All the wound strings are encased in a sheath of nylon/plastic. There is literally nothing to snag on rims of your fingerprints. It's smoooooth.
Both of these options will also radically change your overall tone. Notes will have more fundamental and fewer higher harmonics. So you may need to boost the treble quite a bit to get closer to a roundwound sound.
Comment: Also, if you go this route with flat wounds you'll need to make sure you wipe the strings off well before installing.  Otherwise you'll be posting a question asking why your new strings are turning your fingers black.
Comment: I don't remember having that problem. But I've been using tapewound for a while now. Some flats have a coating or plating that may wear off.
Comment: I tried some Thomastiks for a while that had this. Then I switched to D'Addario and it seemed pretty bad. Nothing terrible, just something to remember. I'm sure the tape coating on tape wounds prevents this "grind off" from sticking to your fingers like bare flat wounds may.
Comment: I don't use coated or flatwound strings except for my hollow body guitar. The problem is less apparent there because of that obviously. I will try some, but I still have the feeling the problem is technique mainly. Thanks for all your suggestions in any case, much appreciated!


How do I parse application/vnd.surveymonkey.response.v1+json?

Question: I recently asked a question about setting up SurveyMonkey webhooks here: https://drupal.stackexchange.com/questions/252571/surveymonkey-v3-webhook-callback
After laborious troubleshooting, I've determined that the issue is that I need to be able to parse the request as application/vnd.surveymonkey.response.v1+json.
How do I do that?
There's no option to add this type of parser, or a custom parser, in the REST server config. Googling for a few hours has come up with nothing. In a Drupal REST endpoint, how can I use this parser type?
Comment: I'm not sure what the correct protocol is - if I should close my other question, please let me know and I would be glad to do so. I would also appreciate it if someone could add a SurveyMonkey tag.
Comment: I don't think we need a tag for that particular service, but we could instead make this question much more generic and provide extra value that way. It could essentially be "how do I assign a particular parser to a non-standard content type through the rest module?", with SurveyMonkey mentioned as an example
Answer: So the answer is to use hook_rest_server_request_parsers_alter(). This way, the application/vnd.surveymonkey.response.v1 Content-Type can be mapped to the standard JSON parser.
function MY_MODULE_rest_server_request_parsers_alter(&$parsers) {
  $parsers['application/vnd.surveymonkey.response.v1+json'] =  'ServicesParserJSON';
}


Question regarding a statement in A course in Arithmetic by Serre.

Question:
Can anyone explain why the author used the derivative of the function to bound $\phi_n(s)$? It is on page 70 in the book.
Comment: I guess that, for $f(t)=n^{-s}-t^{-s}$, he writes $f(t)=f(n)+\int_n^{n+1} f'(\tau)\, d\tau$.
Answer: He uses mean value theorem for vector (in your case $\mathbb{C}$) valued functions (version with inequality). If $f(t) = n^{-s} - t^{-s}$, then
$$|\phi_n(s)| \leq \sup_{n\leq t\leq n+1}|f(n) - f(t)|\leq \sup_{n\leq t\leq n+1}\sup_{\xi\in [0,t]}|f'(\xi)|\cdot |t-n|\leq $$
$$ \sup_{n\leq \xi\leq n+1}|f'(\xi)|\cdot |n+1 - n| = \sup_{n\leq \xi\leq n+1}|f'(\xi)| = \frac{|s|}{\inf_{n\leq \xi\leq n+1}|\xi^{s+1}|} = \frac{|s|}{\inf_{n\leq \xi\leq n+1}\xi^{x+1}} \leq \frac{|s|}{n^{x+1}} $$
Comment: I think your 0 is supposed to be n
Comment: @JhonDoe Yes, you are right. Let me fix this.


What the set $I$ of invertible elements in $\mathbb{Z}_{9}$?

Question: $5.2 = 1$
The set of invertible elements in $\mathbb{Z}_{9}$ is $I = \{1,2,5\}$.
Q1: Is it correct?
I was also asked to show that it is not isomorphic to $S_{3}$
How can I show that it is not isomorphic? Thank you.
Comment: Cf. my answer below.
Comment: When did $10$ become an element of $\Bbb Z_9$?
Comment: @DHMO I have just edited. Is it correct? Thank you.
Comment: @DHMO. What about now? Is it correct? Thank you.
Comment: @DHMO Thank you so much for your help sir.
Comment: Is the question $\Bbb{Z}_9$ not isomorphic to $\mathcal{S}_3$ or is it the multiplicative group of the invertible elements $\Bbb{Z}_9^{\times}$ that has six elements?
Comment: @DHMO sorry a copy paste issue.
Comment: @marwalix Sorry Marwalix for answering your question late. The multiplicative group of the invertible elements is not isomorphic to $S_3$
Answer: $$\begin{array}{c|c}
\times&0&1&2&3&4&5&6&7&8\\\hline
0&0&0&0&0&0&0&0&0&0\\\hline
1&0&\color{red}1&2&3&4&5&6&7&8\\\hline
2&0&2&4&6&8&\color{red}1&3&5&7\\\hline
3&0&3&6&0&3&6&0&3&6\\\hline
4&0&4&8&3&7&2&6&\color{red}1&5\\\hline
5&0&5&\color{red}1&6&2&7&3&8&4\\\hline
6&0&6&3&0&6&3&0&6&3\\\hline
7&0&7&5&3&\color{red}1&8&6&4&2\\\hline
8&0&8&7&6&5&4&3&2&\color{red}1
\end{array}$$
Therefore, the invertible elements of $\Bbb Z_9$ are $\{1,2,4,5,7,8\}$.
Indeed, $S_3$ has $6$ elements while $\Bbb Z_9$ has $9$ elements, so they are not isomorphic to each other.

In general, for $\Bbb Z_n$, $x$ is invertible iff $\gcd(x,n)=1$.
By Bézout's Lemma, $\gcd(x,n)=1 \iff \exists a,b:ax+bn=1 \iff \exists a:ax=1$.
Comment: I think you mean $4, 7$ from your table?
Comment: @q.Then Thanks, corrected
Comment: @marwalix Ask the OP, not me.
Comment: It's also probably worth noting somewhere that in general, the units in  $\mathbb Z_n$ will be those elements $x$ such that gcd$(x,n)$=1. That is, precisely those elements coprime with the order $n$.
Comment: @kholli Is it better now?
Answer: Yes, you are correct. Clearly two groups that are not the same order cannot be isomorphic to each other...
We wish to find all elements that have a multiplicative inverse in $\mathbb{Z}_9$ (as indicated by your question). 9 is not prime, so some inverses may not exist, luckily for you, $\mathbb{Z}_9$ is a relatively small group to check.
$$1, 2\cdot5, 4 \cdot 7, 8 \cdot 8$$
Those are the multiplicative inverse pairings


Handlebars validate button submit

Question: Olá,
preciso fazer uma verificação usando handlebars...
após clicar no botão cadastrar , caso seja bem sucedido o cadastro, exibe uma modal
caso contrario o usuário é forçado a preencher os campos,
porem eu só quero exibir o modal se o submit for feito...
estou usando uma lógica de onclick, entao toda vez que clica no botão ....
mesmo que dê erro no formulário o modal é exibido ...
alguém sabe se via handlebars consigo resolver esse problema com if else? ou vou ter que trabalhar a logica em JS
Segue o código a seguir:
JavaScript

Html

Desde já agradeço
Comment: Com handlebars dá também, desde que vc mande algo do back-end para validar, acho mais fácil fazer isso no front com javascript, agora tem que ver o que deseja fazer, pois quando vc submete o form você automaticamente é redirecionado, acho que não vai dar pra fazer como quer fazer!
Answer: Resolvi o problema usando addEventListenet('submit');
porém será que no handlebars seria possível ?
desde já agradeço

Handlebars validate button submit


Batch process stuck repeating first operation over and over

Question: It's my first time working with the Batch API. I have a batch operation that I have almost working, but it gets stuck on the first item and I'm out of ideas on how to fix it.
What the batch thing does is iterate over a bunch of nodes and transform the fake-locations scattered over a dozen text fields into real Location CCK fields. When the batch process runs, it continually fixes the first node over and over again. My logs fill up with the Location module deleting orphaned locations, and if I dpm($node), it shows the first node over and over again.
I've checked my $batch variable, and the operations array does have all different nids.
Here's the code:

function rlh_tweaks_menu() {
    $items['location-fix'] = array(
        'title' => 'Location fixer',
        'page callback' => 'rlh_tweaks_location_fix',
        'access callback' => '_rlh_tweaks_user_one_only',
    );

    return $items;
}

function rlh_tweaks_location_fix() {
    $batch = array(
        'finished' => '_rlh_tweaks_batch_finished',
    );

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'business');
    $result = $query->execute();

    foreach($result['node'] as $nid => $data) {
        $batch['operations'][] = array('_rlh_tweaks_batch_update_location', array($nid));
    }

    batch_set($batch);
    batch_process('node');
}

function _rlh_tweaks_batch_update_location($nid, &$context) {
    if (!isset($context['sandbox']['progress'])) {
            $context['sandbox']['progress'] = 0;
            $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node} WHERE type = \'business\'')->fetchField();
        }

            // Here we actually perform our processing on the current node.

            $node = node_load($nid);
        $location = _rlh_tweaks_update_node_location($node);

        $lid = location_save($location);

        if(!empty($lid)) {
            $node->field_location[LANGUAGE_NONE]['0'] = location_load_location($lid);
        }

        node_save($node);

            // Store some result for post-processing in the finished callback.
            $context['results'][] = check_plain($node->title);
            // Update our progress information.
            $context['sandbox']['progress']++;
            $context['sandbox']['current_node'] = $node->nid;
            $context['message'] = t('Now processing %node', array('%node' => $node->title));
        // Inform the batch engine that we are not finished,
        // and provide an estimation of the completion level we reached.
        if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
            $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
        }
}

function _rlh_tweaks_update_node_location($node) {
    $street_part_keys = array('street_no', 'pre_dir', 'street_name', 'post_dir', 'street_type');

    $all_parts = array('street_no', 'pre_dir', 'street_name', 'post_dir', 'street_type', 'suite_no', 'city', 'po_box', 'state', 'zip');

    $parts = array();

    foreach($all_parts as $key) {
        $parts[$key] = _rlh_tweaks_get_text_field_value($node, $key);
    }

    $street_parts = array();

    foreach($street_part_keys as $key) {
        if(!empty($parts[$key])) {
            $street_parts[] = $parts[$key];
        }
    }

    $street = implode(' ', $street_parts);

    if(empty($street)) {
        if(empty($parts['po_box'])) {
            continue;
        } else {
            $street = $parts['po_box'];
        }
    }

    $location = array(
        'street' => $street,
        'additional' => $parts['suite_no'],
        'city' => $parts['city'],
        'province' => $parts['state'],
        'postal_code' => $parts['zip'],
        'country' => 'us'
    );

    return $location;
/*
    if(!empty($lid)) {
        $node->field_location[LANGUAGE_NONE]['0'] = location_load_location($lid);
    }

    return $node); */
}

function _rlh_tweaks_batch_finished($success, $results, $operations) {
    if ($success) {
        // Here we do something meaningful with the results.
        $message = t("!count items were processed.", array(
            '!count' => count($results),
        ));
        $message .= theme('item_list', array('items' => $results));
        drupal_set_message($message);
    }
    else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
            '%error_operation' => $error_operation[0],
            '@arguments' => print_r($error_operation[1], TRUE),
        ));
        drupal_set_message($message, 'error');
    }
}

function _rlh_tweaks_get_text_field_value($node, $field_name) {
    $item = field_get_items('node', $node, 'field_' . $field_name);
    return $item[0]['safe_value'];
}

function _rlh_tweaks_user_one_only() {
    global $user;

    if($user->uid == '1') {
        return TRUE;
    }

    return FALSE;
}

Why is this not moving on to the rest of the batch operations?
Answer: Your approach is slightly incorrect.
You should add a single batch operation and within that operation callback query the relevant node ids (once and only if not already set in sandbox) then add them to $context['sandbox'] for processing. Set and check the current node id in the sandbox to process the next set on each batch run.
At the moment, it can never reach the "max" count and finish as only a single $nid is passed at a time.
Comment: I had something like that originally, but had trouble, then saw an example in another question on here that seemed to do it the way I pasted above. Working now; thanks!