text:
Q: Possible decay process for a cubic scalar self-interaction and Yukawa interaction Consider the Lagrangian
$$\mathcal{L}=\frac{1}{2}\partial_{\mu}h\partial^{\mu}h-\frac{1}{2}m^{2}h^{2}-\frac{\lambda}{3!}h^{3}$$
for a real scalar field $h$.
This is the Klein-Gordon Lagrangian with a cubic self-interaction term.
Does this model allow the decay process
$$h \rightarrow h + h?$$
Clearly, in the rest frame, the incoming scalar is at rest, so its total energy is its rest energy, and therefore, it cannot decay to two copies of itself (with twice the rest energy), as that would violate energy conservation?
Edit to question based on answer:
Okay, so if instead, we had the Lagrangian
$$\mathcal{L} = \bar{\psi}_{e}(i\gamma^{\mu}{\partial_{\mu}}-y_{e}\nu)\psi_{e}-y_{e}\bar{\psi}_{e}h\psi_{e}+\bar{\psi}_{\mu}(i\gamma^{\nu}{\partial_{\nu}}-y_{\mu}\nu)\psi_{\mu}-y_{\mu}\bar{\psi}_{\mu}h\psi_{\mu}+\frac{1}{2}(\partial_{\mu}h)(\partial^{\mu}h)-\frac{1}{2}\left(2|\kappa^{2}|\right)h^{2}-\frac{\lambda}{6}\nu h^{3}-\frac{\lambda}{24}h^{4}$$
we can only write down processes like
$$h \rightarrow e^{-} + e^{+}, \qquad\qquad h \rightarrow e^{-} + e^{+} + e^{-} + e^{+}, \dots$$
$$h \rightarrow \mu^{-} + \mu^{+}, \qquad\qquad h \rightarrow \mu^{-} + \mu^{+} + \mu^{-} + \mu^{+}, \dots$$
$$h \rightarrow e^{-} + e^{+} + \mu^{-} + \mu^{+}, \dots $$
I was wondering if a particle (e.g. muon) must always be produced with its corresponding antiparticle (e.g. antimuon).
Also, I was wondering if there are only a finite number of processes for this reaction.

A: Well yes, the decay can't happen. What's the question?
Edit
Yes, particles and antiparticles are produced in pairs
No, there's an infinite number of possible processes. What you write down are the most probable to happen.


text:
Q: How to make launching screen to second tab I have created an tab bar application having 3 tab.
When I am launching the app the the first tab is shown to me first.
But I want to make second tab as launching screen.
The tab order will remain same. when I will open the app, it should show me the middle tab.

A: This will enable you in choosing the default tab at start up
[self.tabBarController setSelectedIndex:1];

A: Tabbar controller has a property which selects particular tab: selectedIndex.
Usage:  [self.tabBarController setSelectedIndex:1];
Note: Index for various tabs starts from 0, i.e. First tab has index 0, second tab has 2 and so on
Please mark correct answer if helps :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't add reference to System.ServiceProcess.dll I am using System.ServiceProcess.dll in my ASP.NET application. I added a reference and intellisense recognizes it. But when I build an application, there is no System.ServiceProcess.dll in bin folder and application says it can't find a namespace. What may be wrong? Can I use this dll in IIS?
This is what I get:
 Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0234: The type or namespace name 'ServiceProcess' does not exist in the namespace 'System' (are you missing an assembly reference?)

Source Error:

Line 5:  using System.Diagnostics;
Line 6:  using System.Linq;
Line 7:  using System.ServiceProcess;
Line 8:  using System.Web;
Line 9:  using System.Web.UI;

A: Add a reference in the process to System.ServiceProcess.dll.
To do this, in the solution window, right click on "References" and choose "Add Reference.."  Go to the .NET tab, and double click on System.ServiceProcess.dll.

A: Most likely you added reference to the DLL of wrong .NET version. (so it exists, but when trying to actually compile, it's breaking)
When adding the reference, make sure the version match the version of your project:


text:
Q: Using reduce fnt instead of map Any advise on how can I refactor my function using reduce, as I should not use map here?

A: Try this:
function serializeParams (object) {
    return Object.keys(object)
        .reduce((query, key) =>
            Array.isArray(object[key])
                ? query.concat(object[key].map(value => `${key}=${encodeURIComponent(value)}`))
                : query.concat(`${key}=${encodeURIComponent(object[key])}`)
        , [])
        .join('&');
}

Or without template strings:
function serializeParams (object) {
    return Object.keys(object)
        .reduce((query, key) =>
            Array.isArray(object[key])
                ? query.concat(object[key].map(value => key + '=' + encodeURIComponent(value)))
                : query.concat(key + '=' + encodeURIComponent(object[key]))
        , [])
        .join('&');
}

A: Using map instead of reduce is appropriate here, you only should map to an array of arrays that you can concat before joining.
function serializeParams(obj) {
  return Array.protoype.concat.apply([], keys(obj).map(key => {
    let value = obj[key];
    return Array.isArray(value)
      ? value.map(v => key +"=" + encodeURIComponent(v))
      : [key + "=" + encodeURIComponent(value)];
  })).join("&");
}

Since you tagged this with Ramda, you can either compose map with concat or use chain right away.


text:
Q: How to apply two animations to the same element simultaneously? I'm trying to apply two animations with different easings simultaneously to the same element but I can't get it to work. This is what I tried:
    $(window).load(function() {

        var speed = 1500;
        var delay = 0;

        for(var i = 0 + 1; i <= $('.skills li').length; i++) {

            var li = $('.skills li:nth-child(' + (i + 1) + ')');

            li.delay(delay).animate({
                left: "0"
            },{
                duration: speed,
                queue: false,
                easing: 'easeOutBounce'
            });
            li.delay(delay).animate({
                opacity: 1
            },{
                duration: speed,
                queue: false,
                easing: 'easeOut'
            });

            delay += 150;
        };
    });

Thanks in advance!

A: You can add more than one property change parameter into animation object.
for (var i = 0; i <= $('.skills li').length; i++) {

    var li = $('.skills li:nth-child(' + (i + 1) + ')');
    li.stop(true, true).delay(i * 150).animate({
        left: "0",
        opacity: 1
    }, {
        duration: speed,
        queue: true, //do you want one-by-one or all together , please specify?
        specialEasing: {
          width: "linear",
          height: "easeOutBounce"
        }
    });

};


text:
Q: How to determine all permutations of a set, with repeated symbols, but *without* "functionally identical" sets Assume the following set of symbols: [A, B, C]
Assume the following result set size of 4.
I would like to produce a list of all permutations, with repeated symbols, but without "functionally identical" items.
Ie: [A, A, A, A] is "functionally identical" to [B, B, B, B] and thus [B, B, B, B] should not be in the final result, etc.
I tried generating the full 3^4 possibilities, then "rotating the symbols", checking one by one if there is a dupe and removing them but I realized this doesn't catch cases where "two symbols swap", and of course, when increasing the number of symbols and set size, there are plenty of other "symbol swap" cases I'm not accounting for. Plus, it seems like "generate the worst case and then prune" is a terrible algorithm, I'm sure there is a much better way.
Here is a manually generated result of the expected output:
['A', 'A', 'A', 'A']
['A', 'A', 'A', 'B']
['A', 'A', 'B', 'A']
['A', 'A', 'B', 'B']
['A', 'A', 'B', 'C']
['A', 'B', 'A', 'A']
['A', 'B', 'A', 'B']
['A', 'B', 'A', 'C']
['A', 'B', 'B', 'A']
['A', 'B', 'B', 'B']
['A', 'B', 'B', 'C']
['A', 'B', 'C', 'A']
['A', 'B', 'C', 'B']
['A', 'B', 'C', 'C']

(And of course, at some point I want to extend the symbol set size and the result set size to see what results I get.)
(Preferred language is python but I'm not picky, I'm just trying to understand the algorithm)
Edit: Let me clarify my definition of "functionally identical". Essentially all that matters is the "topology" of the result. For example, let's say that random colors are assigned to the symbols once we have the sets generated.
[A A A A] simply means "All the items are the same color", thus, [B B B B] would be functionally identical. There is no difference between the two because we don't know what random color is going to be assigned to A or B, all we know is that they are all the same color.
Another example:
[A A A B] is functionally identical to [B B B C], because again, we don't know what colors will be assigned to what symbols, all we know is "The last color is different from the first three."
The order matters though!
[A A A B] != [B A A A]. In the first example, all items are the same color except the LAST item. In the second example, all items are the same color except the FIRST item.
This is absolutely a mathematical construct, more advanced than simple permutation, I just don't know the name for it.

A: Here's a recursive algorithm that does it. The key idea is that to break symmetry between the different letters, we are only allowed to add a letter that has already been used, or the first unused letter.
Given a partial solution t:

*

*If t has the required length, yield it.

*Otherwise:

*

*For each distinct letter already in t, recurse by extending t with that latter.

*If t doesn't use each possible letter, recurse by extending t with the first unused letter.

Here's a Python implementation, as a recursive generator function:
def gen_seqs(letters, n):
    def helper(used, t):
        if len(t) == n:
            yield t
        else:
            for i in range(used):
                yield from helper(used, t + letters[i])
            if used < len(letters):
                yield from helper(used + 1, t + letters[used])
    return helper(0, '')

Example:
>>> for t in gen_seqs('ABC', 4):
...     print(t)
...
AAAA
AAAB
AABA
AABB
AABC
ABAA
ABAB
ABAC
ABBA
ABBB
ABBC
ABCA
ABCB
ABCC


text:
Q: How to create this UI using GridLayoutManager inside RecyclerView and fix span to left or right
How to create this UI using recycler view and GridLayoutManager. The problem I am getting is placing the items to only at left position or only at right side in some cases.

A: That's a metro-like UI.  Having never implemented it, I will point you to google.  https://www.google.com/search?q=android+metro+ui+library


text:
Q: Is there a connection/memory limits for Apache Service while running cgi programs? I'm trying to run hundreds of cgi programs (perl or other languages) concurrently on Apache 2.0/2.2/2.4. My test environment is Windows Server 2003 R2 with 1GB of RAM.
In the program, I use either an infinite loop or "$_ = < STDIN >" to keep each process alive. In the Apache configuration, I set all relative configurations large enough such as ThreadPerChild to 1000. Then I use JMeter to test 200 requests. When I run Apache in console application, it works fine and all 200 cgi processes are running. However, when I run Apache as a windows service, only 60-100 processes will run in concurrent. Others won't start unless I kill any running process. I don't what's causing this. Is there a connection/memory limits for Apache Service while running cgi programs? Thanks!

A: MaxClients parameter in httpd.conf file sets the max limit of connections for apache server.
The default connection limit is 256.
You can check it for your server by opening httpd.conf file and searching for MaxClients.
The default location of httpd.conf in linux is /etc/httpd/conf/httpd.conf .
On windows, the default location of conf file is C:/Program Files/Apache Group/Apache/conf/httpd.conf
It looks something like this.
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# ServerLimit: maximum value for MaxClients for the lifetime of the server
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   20
ServerLimit      256
MaxClients       256
MaxRequestsPerChild  4000
</IfModule>

You can set MaxClients value to whatever is needed and then restart the server to apply chages.


text:
Q: How to delete a specific string from an array of strings in C? I need a function that receives an array of pointers to strings and it's size.
Then it should seek for those strings which occur in the array more than once - then I have to delete them and realloc the array.
Function should return new size of the array.
I'm trying to solve this, and not sure what`s wrong.
I want to move each string, that I want to delete, to the end of the array and then delete it, but not sure when the "realloc" should happen.
#include<stdio.h>
#include<stdlib.h>

int DeleteString(char** tab, int n){
    char* check=malloc(sizeof(char)*100);
    int deleted;
    int i,j,g,h;

    for(i=0;i<n;i++){
        strcpy(check, tab[i]);
        for(j=0;j<n;j++){
            if(strcmp(check, tab[j]) == 0){
                deleted++;
                char* temp = malloc(sizeof(char)*100);
                for(h=j;h<n-1;h++){
                    strcpy(temp, tab[h+1]);
                    strcpy(tab[h+1], check);
                    strcpy(tab[h], temp);
                }
            }

            if(deleted>0){
                realloc(tab, sizeof(char*)*(n-deleted));
            }
        }
    }
    return n-deleted;
}

For now there is "Segmentation fault" error

A: The reason for the SEGMENTATION FAULT is  tab[0] store the address of the variable which stores the actual string.
Here  tab[i] is in for loop,hence when it tries to fetch tab[1] itself memory error.
for(i=0;i<n;i++){
    strcpy(check, tab[i]);...}

FOR EXAMPLE:
 char *foo = "something";
 char **ptr2;
 ptr2 = &foo;
 printf("check = %s", *ptr2);
 for(int i=0;i<9;i++){
   printf(" check = %c",  ptr2[i]);
 }

Output
check = something check = 4check = �check = pcheck =

Actally it is an error.

A: Oops, your code contains numerous problems, because you failed to observe some major rules of C language:

*

*every non static variable shall be initialized (what about deleted?)

*any object that was malloced shall be freed (what about check and temp.)

*never change something that was passed as an input parameter to a function, or do not expect the change to be visible on return (tab has to be considered here because of next line).

*allways assign the result of realloc because it can be different from the input pointer (realloc(tab, sizeof(char*)*(n-deleted));).

The first one is probably the cause of the segmentation fault because as deleted is unitialized its value is just undeterminated. But all problems should be fixed.

A: First of all, don't forget to initialise variables like deleted, as it has been said in other answers.
Next, you are supposed to free memory (as you are deleting items) and you only call malloc(3)).  That seems a little counter-common sense, doesn't it?
Third, you make a lot of string copying in the loops, while it should be more efficient just to move pointers up, so you don't need to realloc the string elements and copy the cell contents (by the way, are you sure those strings will be feed to the function as malloc()d strings?  I will assume that as you do)
Fourth, consider sorting the array first, so all the similar strings will be adjacent in the array.  This has a cost O(n*log(n)) that, appended to the delete next string if equal (with cost O(n)) makes total cost O(n*(log(n)+1)) or O(n*log(n)) and not O(n^2) which is your actual cost)
Once sorted, only the strings deleted should be free(3)d, the pointers moved back to the start of the array as holes get appearing, and finally(when all is finished) you can just realloc(3) the array of pointers (only once, not at every pass through the loop)
Remaking the example is out of the scope of this answer, as it looks actually some school exercise.  Sorry for that.  I'm sure that the other hints will help you to retry the exercise with more success.
And think: thinking before writing is how one succeeds in this job.


text:
Q: How can I get the link from href in "a" with class name by using python 3 I've tried to get the link from google map which the element is:

  Google Map

which I only would like to get https://www.google.com/maps/dir//11111/@22222
My code is
 gpslocation = []
 for gps in (secondpage_parser.find("a", {"data-track-id":"Google Map"})):
     gpslocation.append(gps.attrs["href"])

I'm using 2 url pages (main and secondpage) for scraping a blog website which this is in the secondpage. The other info like Story-Title or Author Name work as it appears as text so I can use get_text().
But this case, I could not get the link after href. Please help.
Ps. In the case I only want Latitude and Longtitude in the link which are (11111 and 22222) is there is a way to use str.rplit?
Thank you so much

A: You can use the following :
secondpage_parser.find("a", {"data-track-id":"Google Map"})['href']

A: *

*Use soup.find(...)['href'] for finding all links with an href or soup.find_all('a' ... , href=True)for all links

*Yes you can use split to only get lat and long

*

*First split on // and get the latest [-1]

*Then split on /@ to get both lat and long

from bs4 import BeautifulSoup

data = """

  Google Map

"""

soup = BeautifulSoup(data, "html.parser")
for gps in soup.find_all('a', href=True):
    href = gps['href']
    print(href)
    lati, longi = href.split("//")[-1].split('/@')
    print(lati)
    print(longi)


text:
Q: Postgres force fire trigger on foreign key table Table fk_parent

id integer,
amount numeric,
account_id int,

Table fk_child
id integer,
fk_parent_id integer,
amount numeric

I have an after update trigger on fk_parent which deletes rows in another table (a different module) and inserts data afresh which includes data from fk_child too.
Any update of fk_child does not fire the trigger on fk_parent when fk_parent is not saved simultaneously.
Is there any way by which I can force the trigger on update of fk_child if fk_parent is not being updated in the same transaction.
As there are deletes I want to fire the trigger as little time as possible.
I am using Postgres 12.0
Thanks


text:
Q: Negation of -2147483648 not possible in C/C++? #include <iostream>
#include <stdlib.h>

int main(int argc, char *argv[])
{

  int num=-2147483648;
  int positivenum=-num;
  int absval=abs(num);

  std::cout<<positivenum<<"\n";
  std::cout<<absval<<"\n";

  return 0;
}

Hi I am quite curious why the output of the above code is
-2147483648
-2147483648

Now I know that -2147483648 is the smallest represntable number among signed ints, (assuming an int is 32 bits). I would have assumed that one would get garbage answers only after we went below this number. But in this case, +2147483648 IS covered by the 32 bit system of integers. So why the negative answer in both cases?

A: The value -(-2147483648) is not possible in 32-bit signed int. The range of signed 32-bit int is –2147483648 to 2147483647

A: Ahhh, but its not... remember 0, largest signed is actually 2147483647

A:
But in this case, +2147483648 IS covered by the 32 bit system of integers.

Not quite correct. It only goes up to +2147483647. So your assumption isn't right.
Negating -2147483648 will indeed produce 2147483648, but it will overflow back to -2147483648.
Furthermore, signed integer overflow is technically undefined behavior.

A: Because the 2's complement representation of signed integers isn't symmetric and the minimum 32-bit signed integer is -2147483648 while the maximum is +2147483647. That -2147483648 is its own counterpart just as 0 is (in the 2's complement representation there's only one 0, there're no distinct +0 and -0).
Here's some explanation.
A negative number -X when represented as N-bit 2's complement, is effectively represented as unsigned number that's equal to 2N-X. So, for 32-bit integers:
if X = 1, then -X = 232 - 1 = 4294967295
if X = 2147483647, then -X = 232 - 2147483647 = 2147483649
if X = 2147483648, then -X = 232 - 2147483648 = 2147483648
if X = -2147483648, then -X = 232 + 2147483648 = 2147483648 (because we only keep low 32 bits)
So, -2147483648 = +2147483648. Welcome to the world of 2's complement values.

A: The previous answers have all pointed out that the result is UB (Undefined Behaviour) because 2147483648 is not a valid int32_t value. And we all know, UB means anything can happen, including having daemons flying out of your nose. The question is, why does the cout behavior print out a negative value, which seems to be the worst value it could have chosen randomly ?
I'll try to justify it on a two's complement system.  Negation on a CPU is actually somewhat of a tricky operation. You can't do it in one step. One way of implementing negation, i.e. int32_t positivenum = -num is to do a bit inversion followed by adding 1, i.e. int32_t positivenum = ~num + 1, where ~ is the bitwise negation operator and the +1 is to fix the off-by-one error. For example, negation of 0x00000000 is 0xFFFFFFFF + 1 which is 0x00000000 (after roll over which is what most CPUs do). You can verify that this works for most integers... except for 2147483648. 2147483648 is stored as 0x80000000 in two's complement.  When you invert and add one, you get
- (min)        = -(0x80000000)
               = ~(0x80000000) + 1
               =   0x7FFFFFFF  + 1
               =   0x80000000
               =   min

So magically, the unary operator - operating on min gives you back min!
One thing that is not obvious is that two-complement CPUs' arithmetic have no concept of positive or negative numbers! It treats all numbers as unsigned under the hood.  There is just one adder circuit, and one multiplier circuit. The adder circuit works for positive and negative numbers, and the multiplier circuit works for positive and negative number.
Example: -1 * -1
 = -1         * -1
 = (cast both to uint32_t)
 = 0xFFFFFFFF * 0xFFFFFFFF
 = FFFFFFFE00000001         // if you do the result to 64 bit precision
 =       0x00000001         // after you truncate to 32 bit precision
 =                1

The only time you care about signed vs unsigned is for comparisons, like < or >.


text:
Q: Stored procedure to add a row to top of list Oracle 12c
I currently have the following three tables: Physician, Patient, and Wait_List. The Wait_List table is a bridge table to  hold patients who are waiting on individual doctors.
I would like to track priority for each of these patients in a way other than the date they entered the wait list. For instance, if a given doctor is waiting on 3 patients each of these patients are assigned a value of 1-3 in their Priority field.
The issue I am having is figuring out how I would begin to write the procedure to enter a fourth patient who is to have a priority higher than 4, for instance a priority of 1. I understand that the procedure would require each of the 3 current patients' priorities to be pushed down in value.
Any guidance to this question would be greatly appreciated.
Thank you,

A: This procedure will insert values into the wait_list table and it will set the priority number to one if there are already three patients waiting for that particular physician. Just edit the column and table names
  create procedure insertinto_Wait_List(i_patient_name IN Patient.patient_namecolumn%TYPE, i_physician Physician.Physician_column%TYPE)
  IS
  v_max_priority NUMBER;
  BEGIN
  select max(prioritynumber_column) into v_max_priority from Wait_List where Physician_column = i_physician;
  if v_max_priority > 2 THEN
  update Wait_List set prioritynumber_column = prioritynumber_column + 1 where Physician_column = i_physician;
  insert into Wait_List (prioritynumber_column, patient_namecolumn, Physician_column) values (1,i_patient_name, i_physician);
  else
  insert into Wait_List (prioritynumber_column, patient_namecolumn, Physician_column) values (v_max_priority + 1,i_patient_name, i_physician);
  end if;
  end;

A: There could be better answers using advanced PL/SQL. But using unique constraint is what comes to my mind. When you create the table wait_list, add the following unique constraint to create statement:
CONSTRAINT priority_unique UNIQUE (prioritynumber_column, Physician_column)

Then the procedure, can use the exception as follows
CREATE PROCEDURE proc_insert_wait_list(i_priority IN wait_list.prioritynumber_column%TYPE, i_patient_name IN Patient.patient_namecolumn%TYPE, i_physician Physician.Physician_column%TYPE)
IS
BEGIN
INSERT INTO Wait_List (prioritynumber_column, patient_namecolumn, Physician_column) values (i_priority,i_patient_name, i_physician);
COMMIT;
EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
      FOR i IN (SELECT prioritynumber_column, patient_namecolumn, Physician_column
          FROM Wait_List
          WHERE Physician_column = i_physician
          AND prioritynumber_column >= i_priority)
      LOOP
      UPDATE Wait_List
      SET prioritynumber_column = prioritynumber_column + 1;
      END LOOP;
      INSERT INTO Wait_List (prioritynumber_column, patient_namecolumn, Physician_column) values (P_priority,i_patient_name, i_physician);
END proc_insert_wait_list;

The idea, you can set the priority you want. But if it collides with existing one, RDBMS will throw the exception DUP_VAL_ON_INDEX. Which you handle by pushing down all the existing records and then insert the priority.


text:
Q: Mongoose nested schema CastError I have the following data which contains a nested schema:
User Schema
(function userModel() {

var mongoose = require('mongoose');
var Entry    = require('./entry');
var Schema   = mongoose.Schema;

var usersSchema = new Schema({
    entries: [Entry]
});

module.exports = mongoose.model('Users', usersSchema);

})();

Entry Schema
(function entryModel() {
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var entrySchema = new Schema({
    timeStamp: {
        type: Date,
        default: Date.now
    },
    data : [Schema.Types.Mixed]
});

module.exports = mongoose.model('Entry', entrySchema);

})();

I'm returning the the following error:
errors:
   { entries:
      { [CastError: Cast to Array failed for value "[object Object]" at path "entries"]`

As far as I can tell this is the correct way to include subdocuments. Am I doing something wrong here?

A: This line module.exports = mongoose.model('Entry', entrySchema); exports the model not the schema. You need to export entrySchema and use that to construct the userSchema
EDIT:
If you want to export both model and schema, you'd need to do something like
module.exports = {
  schema: entrySchema,
  model: mongoose.model('Entry', entrySchema)
}

In general however, you rarely ever need to export the actual model. This is because whenever you want to have access to that particular model in a different file, you would simply call mongoose.model('Entry') and get that model instance back. It is not necessary to call require('.path/to/model') just to get access to the model.


text:
Q: Tensorflow Extended: Is it possible to use pytorch training loop in Tensorflow extended flow I have trained an image classification model using pytorch.
Now, I want to move it from research to production pipeline.
I am thinking of using TensorFlow extended. I have a very noob doubt that will I'll be able to use my PyTorch trained model in the TensorFlow extended pipeline(I can convert the trained model to ONNX and then to Tensorflow compatible format).
I don't want to rewrite and retrain the training part to TensorFlow as it'll be a great overhead.
Is it possible or Is there any better way to productionize the PyTorch trained models?

A: You should be able to convert your PyTorch image classification model to Tensorflow format using ONNX, as long as you are using standard layers. I would recommend doing the conversion and then look at both model summaries to make sure they are relatively similar. Also, do some tests to make sure your converted model handles any particular edge cases you have. Once you have confirmed that the converted model works, save your model as a TF SavedModel format and then you should be able to use it in Tensorflow Extended (TFX).
For more info on the conversion process, see this tutorial: https://learnopencv.com/pytorch-to-tensorflow-model-conversion/

A: You could considering using the torchX library. I haven't use it yet, but it seems to make it easier to deploy models by creating and running model pipelines. I don't think it has the same data validation functionality that Tensorflow Extended has, but maybe that will be added in the future.


text:
Q: Is there a way to group a dataframe by certain elements of its content without a given delimiter? I'm facing the following situation. I have a dataframe which looks like this (due to sensitivity of the data I have to paraphrase it)
Column A     Column B
A1B12C123    Japan
A2B34C456    Switzerland
A3B45C789    Japan
A1B15C729    Japan

My goal is to group Column A by the recurring pattern, which describes a certain property.
Meaning: Group by A1, Group by B12, Group by C123.
In order to do that, I split the Column and created new ones for each level of hierarchy, e.g.:
  Column A     Column B  Column C
    A1           B12      C123
    A2           B34      C456
    A3           B45      C789
    A1           B15      C729

Those columns I have to add to my existing dataframe, and then I'll be able to group the way I wanted to.
I think this can work, but it seems a bit tedious and unelegant.
Is there a possibility or a way in Pandas to do this more elegantly?
I'd be happy about any input on that matter.
Best regards

A: Taking Seyi Daniel's idea from the comments, you can use exctractall() string method on the Column A to explode it based on regex groups and join Column B on to it.
import pandas as pd
from io import StringIO

data = StringIO("""
Column_A     Column_B
A1B12C123    Japan
A2B34C456    Switzerland
A3B45C789    Japan
A1B15C729    Japan
""")

df = pd.read_csv(data, delim_whitespace=True)

regex_df = df["Column_A"].str.extractall(r"(A\d*)|(B\d*)|(C\d*)")

# drop extra levels
regex_s = regex_df.stack().reset_index((1,2), drop=True)
# give the new column a name
regex_s.name = "group"
# add column B
result = pd.merge(regex_s, df["Column_B"], left_index=True, right_index=True)

print(result)

  group     Column_B
0    A1        Japan
0   B12        Japan
0  C123        Japan
1    A2  Switzerland
1   B34  Switzerland
1  C456  Switzerland
2    A3        Japan
2   B45        Japan
2  C789        Japan
3    A1        Japan
3   B15        Japan
3  C729        Japan


text:
Q: "Http failure response for (unknown url): 0 Unknown Error" mobile device I have an issue with CORS on my Angular 6/Symfony 4 project.
This project have login/register module. I'm using FOSUserBundle and set enabled to false by default. Then, I send an email with a confirmation link (https://subdomain.example.com/confirm-email/CONFIRMATION_TOKEN) to verify that it's not a bot.
The link redirects to a special page in Angular who PUT the user account to enable it.
The thing is, everything works fine on laptop with any browser but when I want to do it with my phone, nothing append. I've tried to alert the error message and I got this :
{"headers":{"normalizedNames":{}, "lazyUpdate":null,"headers": {}},"status":0,"statusText":"UnknownError","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

So, I've got some researches and I found out that it is a CORS problem, some topics said it's Angular, some others said that the server has a wrong configuration. I've read lots of articles on CORS and I actually didn't any progress to resolve this issue.
Here are some samples :
Symfony, .env
CORS_ALLOW_ORIGIN=^https://subdomain.example.com$

Symfony, nelmio_cors.yaml
nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        max_age: 3600
    paths:
        '^/': ~

Angular, login.service.ts
async confirmUser(confirmToken: string): Promise<any> {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json; charset=UTF-8'
        })
    };

    return await this.http.post(`${this.url}/user/${confirmToken}`, httpOptions).toPromise();
}

Angular, confirm-user.component.ts
async confirmUser() {
    try {
      await this.loginService.confirmUser(this.confirmToken);
      setTimeout(() => {
        window.location.href = 'https://example.com/';
      }, 1000);
    } catch (error) {
      swal({
        type: 'error',
        title: 'Oops...',
        text: error.statusText,
        showConfirmButton: false,
        showCancelButton: false,
        timer: 2000
      });
    }
}

I really don't know what is the problem and why it's not working on mobile device while it's works perfectly with a laptop. I'm using Browserstack to test on multiple devices (iOS, Android). Same with my mobile (iOS12) with Safari and Chrome.
FYI, those two project are on the same server but with two different url.
Ex : subdomain.example.com and subdomain-api.example.com
If someone has ever encountered this and has a solution, please be my guest.
EDIT 1
Thanks to sideshowbarker for removing my cors tag, while checking your profile I saw one of your answers and tried "How to use a CORS proxy to get around "No Access-Control-Allow-Origin header" problems" method. And it works for the OPTIONS request but not for the POST (image: https://imgur.com/0WkeYlQ). And for this I have maybe a solution : My CTO blocked by IP the access to the API. We only allow example.com, subdomain.example.com and IP's from our company. So, I guess we should allow https://cors-anywhere.herokuapp.com/ IP but is there another alternative ?

A: I don't think this is a CORS issue - that would normally show up as a CORS-specific error message - something like "No Access-Control-Allow-Origin response header found".
Can you supply a full set of request and response headers for a failing request?


text:
Q: Can one obtain Neumann boundary conditions via Friedrichs extension? According to the book "Applied Functional Analysis" vol. I by Zeidler, the Friedrichs extension of an operator $B\colon D(B)\subset X\to X$, where $X$ is a real Hilbert space, is obtained as follows. One needs:

*

*that $B$ be symmetric, that is $(Bu, v)=(u, Bv)$ for all $u, v\in D(B)$;

*that $B$ be strongly monotone (aka strictly positive), that is, $(Bu, u)\ge c\|u\|^2$ for all $u\in D(B)$ for a constant $c>0$.

If those assumptions are satisfies, one defines the energetic space
$$X_E=\text{completion of }D(B)\text{ with norm }\|u\|_E^2=(Bu, u).$$
This gives rise to a triple (Hilbert triple as it is sometimes called)
$$X_E\subset X\subset X_E^\star, $$
and one defines the energetic extension
$$
B_E\colon X_E\to X_E^\star,\qquad {}_{X_E^\star}\langle B_E u, v\rangle_{X_E}=(u, v)_{X_E},$$
that is, $B_E$ equals the Riesz isomorphism of the real Hilbert space $X_E$ with its dual. (It is here that one uses the fact that $X$ is real. In the complex case, this mapping is not linear but conjugate-linear. This is not a big deal nonetheless).
This said, the Friedrichs's extension is the maximal restriction of $B_E$ that does not leave $X$:
$$
Au=B_E u\qquad D(A)=\left\{ u\in X_E\ :\ B_E u\in X\right\}.$$
The standard example is obtained on $X=L^2(\Omega)$, where $\Omega$ is a bounded open set in $\mathbb{R}^n$, with $B=-\Delta$ and $D(B)=C^\infty_0(\Omega)$  In this case one has that $X_E=H^1_0(\Omega)$ and the relation
$$
Au=f$$
is the abstract reformulation of the boundary value problem
$$
\begin{cases} -\Delta u=0 & \Omega \\ u=0 & \text{on }\partial \Omega.\end{cases}$$
In particular, one has obtained Dirichlet boundary conditions.

Question. Can one abstractly obtain Neumann's boundary conditions by means of the same construction? Of course one can assume that $\Omega$ boundary is as smooth as one wishes. If it simplifies things one can even assume that $\Omega$ is the unit ball.

A: For smooth functions $u$ with vanishing normal derivative on $\partial\Omega$,
\begin{align}
(Bu,u) & = \int_{\Omega}(-\Delta u)udx \\
       & =\int_{\Omega}\nabla\cdot((-\nabla u)u)+|\nabla u|^2dx \\
       & = -\int_{\Omega}u\frac{\partial u}{\partial n}dS+\int_{\Omega}|\nabla u|^2dx \\
       & = \int_{\Omega}|\nabla u|^2dx.
\end{align}
You cannot have $(Bu,u) \ge c\|u\|^2$ for some $c > 0$ because the constant functions $u$ are in the subspace you're considering and $Bu=0$ for a constant function. However, you do have $(Bu,u) \ge 0$. So $(B+\epsilon I)$ is positive definite.

A: The answer is affirmative and is based on the idea of the user Justpassingby (see comments to main question). Details are on Davies's book "Spectral theory and differential operators", section 7.2 pag.146. (link)


text:
Q: Modified OAuth tokens can still authenticate / authorize successfully Using Owin and OAuth, I've noticed that if you modify the last character of a token you can still get authenticated / authorized successfully.
I'm using a C# WebAPI application, but I don't know if this applies to OAuth in general. This might be by design but it seems like strange behaviour to me so I'm curious to know why this happens.
To replicate this behaviour:

*

*In Visual Studio, create a new project and select 'ASP.NET Web Application' as the template.

*Choose the 'Web API' template, and choose 'Individual User Accounts' as the authentication type.

*Build the project.

*Using a REST client, POST to http://localhost:23220/api/account/register * with a Content-Type: application/json header and the following body:
{
  "UserName": "test",
  "Password": "password",
  "ConfirmPassword": "password"
}

*Using a REST client, POST to http://localhost:23220/token * with no headers and the following body:
grant_type=password&username=test&password=password

*Using a REST client, GET http://localhost:23220/api/values * with a Authorization: Bearer xxx header, where xxx is the access token you generated in the previous request. This request should be authorized and you should get a 200 response.

*Make the same GET request again, but this time modify the last character of the Authorization header value by incrementing it by 1. So for example, if the last character is a, change it to b; if it's 1, change it to 2 etc. The request will still be successful.

* Change the port accordingly.

A:
AccessTokenFormat - The data format used to protect the information contained in the
  access token. If not provided by the application the default data
  protection provider depends on the host server. The SystemWeb host on
  IIS will use ASP.NET machine key data protection, and HttpListener and
  other self-hosted servers will use DPAPI data protection.

Since setting up the project this way will run under IIS Express, the token is protected with the MachineKey API. I was not able to find a description of the exact data format of the encrypted value, but from previous work in cryptography, I expect perhaps there is padding at the end. This padding would not be protected by the token's signature, but this doesn't matter as it is just stripped off and discarded. Note that the range of changes is limited, so I expect only the last few bits of the last byte can be modified.


text:
Q: How can I test that a Promise is never fulfilled? I'm testing a library I wrote to throttle execution of a function.
The API is throttler.do(fn) and it returns a promise of fn's return value (resolved at whichever point the throttler decides it's ok to run it).
I'm using lolex to fake Date() and setTimeout so if I set the throttler to allow two actions per minute and do
throttler.do(() => {});
throttler.do(() => {});
throttler.do(() => {}).should.eventually.equal(5);

this fails as expected (it times out because it's waiting on the last promise forever since I never call lolex.tick).
Is there a way I can turn this into a passing test, something like
throttler.do(() => {}).should.never.be.fulfilled;

I can't do
setTimeout(() => done(), 1500)

because the setTimeout method is faked by lolex.

A: You can mock the Promise to be synchronous and then check the Promise state. Here is a library you can use promise-sync


text:
Q: Friction component?
Why is the component of contact force is not like contact force cos theta and contact force sin theta but here they have no trigonometric values like we normally make components for a force.Like F
contact
cosθ
F
c
o
n
t
a
c
t
cos

θ
and
F
contact
sinθ
F
c
o
n
t
a
c
t
sin

θ
.Since here we have normal force and friction.Why is that?

A:
Why is the component of contact force is not like $F_{contact} \cos \theta$ and $F_{contact} \sin \theta$ but here they have no trigonometric values like we normally make components for a force. Like $F \cos \theta$ and $F \sin \theta$.

They are still the components of the contact force and that's why you get a relation between the normal force and the friction force i.e. $F_{friction} = \mu F_{Normal}$ .
But since we don't know the magnitude of this contact force and also the angle at which it acts (since there are lots of factors affecting this contact force like the amount and orientation of the charges in the molecules of the surfaces in contact , the exact amount of foreign atoms like atoms of air between the surfaces in contact and many other things) , we generally call them as Normal force and frictional force. And regard them differently but they are still the components of that contact force.
Hope it helps ☺.


text:
Q: Proof system soundness and completeness Is a proof system with the single rule of inference {}⊢ φ for all φ sound, complete, both, or neither?
I think it is sound but I feel like there is a caveat, am I wrong?

A: It's complete if anyone interested...


text:
Q: Maximum likelihood estimation and sampling bias, application of class weights If I train a model (e.g. a neural net) via maximizing the likelihood function on a given training set, then do I need to adjust for sampling bias?
Let me give you an example for a classification task (where the cross entropy loss would be used to maximize the likelihood). I want to classify people into group $y \in\{ A,B\}$ depending on their answers $x$ in a survey. However,
the training data $\{x,y\}$ were generated in a biased manner, e.g. via a survey and survey sampling
https://en.wikipedia.org/wiki/Survey_sampling such that 1000 people of group A and 1000 people of group B were asked - although the probability of finding a person of group A in the population is 99% and the probability of finding a person of group B in the population is only 1%.
Should I adjust in the training of my neural net for this biased sampling via e.g. setting sample weights such that the samples of class A have 99% weight and the samples of class B have 1 weight?
Can one make an argument that setting these class weights makes the trained model a maximum aposteriori estimator? https://en.m.wikipedia.org/wiki/Maximum_a_posteriori_estimation
Is there literature or is this just too obvious?
Thanks in advance!


text:
Q: Bootstrap modal showing multiple times I have a .NET application using C#, Bootstrap 2.3.2 and the latest version of jQuery.
In my Javascript file, I show a Modal everytime the user clicks a button, by making an Ajax request to the server which then returns the HTML for the modal with all the information:
Sounds complex, but in reality is quite simple.
This is the CSHTML file:
//div for the EditPackage modal

This is the JavaScript that shows the modal:
//Show Edit Package modal
    $("a.btn.btn-default.editPackage").click(function () {
        $.ajax({
            url: $(this).data('url'),
            type: 'get',
            cache: false,
            success: function (result) {
                $('#editModal').html(result).find('.modal').modal({
                    show: true
                });

            //the popup needs these files to work
            //so we send them over the internet to the client !
            dyamicallyLoadJS("Scripts/myCustom.js");
            }
        });
        return false; //prevent browser defualt behavior
    });

So, when I click the said button, the server receives the request, and sends me the HTML with the modal code, which then is placed inside the editModal div, which then is shown to the user.
The dynamic loading of the Javascript needed by the Modal is done by a function in the same file:
//http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
function dyamicallyLoadJS(filePath) {
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", filePath);
    document.getElementsByTagName("head")[0].appendChild(fileref)
}

The Modal itself is just plain HTML. It is quite boring:
@model AmarisGate.Model.ModalPackageInfo

@{
    ViewBag.Title = "_ModalPackageInfo";
}

@Model.modalTitle

                <form class="form-horizontal">

                        Package Name:

                            <input type="text" class="form-control" id="package-name" placeholder="@Model.pkgNamePlaceHolder">

                        Select the Function:

                            <input class="select2s" data-edit-values="@Model.functionsString" data-o2f-placeholder="Select Employee Function..." data-o2f-url="@Url.Action("FunctionsMultiple", "Home")" data-val="false" id="SubCategoryId" name="SubCategoryId" multiple="multiple" type="text"/>

                        Select the materials:

                            <input class="select2s" data-edit-values="@Model.materialsString" data-o2f-placeholder="Select Materials..." data-o2f-url="@Url.Action("MaterialsMultiple", "Home")" data-val="false" id="MaterialId" name="MaterialId" multiple="multiple" type="text" />

                        Company:

                            <input class="select2s" data-edit-values="@Model.companiesString" data-o2f-placeholder="All Companies (default)" data-o2f-url="@Url.Action("CompaniesMultiple", "Home")" data-val="false" id="CompaniesId" name="CompaniesId" multiple="multiple" type="text" />

                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="@Model.saveButtonId" data-url="@Model.saveButtonUrl">@Model.saveButtonText</button>

However, I have a problem. If I click the button once, the popup shows once, which is quite fine. If I click it twice, it shows twice, which is annoying. If I click it X times, it appears X times, which is simply terrible.
From my understanding, this bug occurs because each time I click the Edit button, I send and load a Javascript file. Then the next time I click the button, I will run the previous file that I got, plus the new one, and so on.
How do I fix this?
How do I keep the JavaScript files from being run multiple times?

A: The solution to the bug:

*

*Make sure the content in MyCustom.js is not being loaded by the main page either. In short, its contents should be unique and for the Modal only!


text:
Q: Using a global boolean variable for logger "on/off"? I develop a mobile and desktop app which has a checkbox "enable/disable debug logger". A logger will write data into a file.
Since none of the Rust loggers I know of are capable of switching its on/off state dynamically, I've decided to use a global boolean variable for it and wrap every log::info/debug/error into a condition of whether or not the variable is true.
A user will check/uncheck a checkbox, and the IS_LOGGER_ENABLED will change its value accordingly.
Then, in each place I want to debug, I'll use this statement:
//..........
if IS_LOGGER_ENABLED { //check the state each time
  log::debug!("test123")
}

Are there caveats?
Is there a better way, or more canonical one?

A: For the general case your solution should be fine, but there is one small caviat. Your project may not be the only one using the log crate. Some of your dependencies may also use it. Most of the time you need to explicitly enable a features to enable logging, but there might be some edge cases.
Here is an example of how you can implement a custom logger using the Log trait and link it so it gets used whenever one of the log macros is called. This way you won't need to wrap every log macro and it should also cover the edge case of a dependency logging messages when it should be disabled.
pub struct ToggledLogger<L> {
    toggle: Arc<AtomicBool>,
    inner_logger: L,
}

impl<L: Log> Log for ToggledLogger<L> {
    // Usually this gets used to check if a logger accepts a certain message level, but
    // we can add the enable check here. It calls this before sending each log message
    // to avoid the overhead of formatting a log messages that might get discarded.
    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
        self.inner_logger.enabled(metadata) && self.toggle.load(Ordering::SeqCst)
    }

    fn log(&self, record: &Record<'_>) {
        self.inner_logger.log(record);
    }

    fn flush(&self) {
        self.inner_logger.flush();
    }
}

// This Arc<AtomicBool> is used in place of a global variable to toggle logging.
let toggle = Arc::new(AtomicBool::new(true));

let custom_logger = ToggledLogger {
    toggle: toggle.clone(),
    // Just use a log handler from any of a number of supported crates or write your own
    inner_logger: Foo,
};

// Tell the log crate to direct all log messages through the custom logger
log::set_boxed_logger(Box::new(custom_logger));

// Enable/disable later using the Arc<AtomicBool> we passed to the logger.
toggle.store(should_logging_be_enabled, Ordering::SeqCst);


text:
Q: How to know when the app launch screen is gone in SwiftUI? I mimic the launch screen in a SwiftUI view. In the launch screen I have a logo. Once the launch screen is gone it needs to move to a different position. However now when I launch the app the animation begins earlier than the launch screen that is fading out. Giving a ghosting effect. I like this to be one smooth transition. In order to do this, I like to know when the launch screen is completely vanished so I can start the animation, but how?

A: Since I haven't received an answer I presume it does not exist. So my 'close enough' solution is based on the following:

*

*Wait for the scene to become active. It will be when the app finished the animation from app icon to full screen on iOS.

*Wait for the launch screen fading out animation to complete.

struct MainView: View {
    var body: some View {
        Text("Hello World")
            .onFinishLaunching {
                // Do stuff
            }
    }
}

struct FinishLaunchingViewModifier: ViewModifier {
    @Environment(\.scenePhase) var scenePhase

    @State private var didFinishLaunching: Bool = false

    let perform: () -> Void

    func body(content: Content) -> some View {
        content
            .onChange(of: scenePhase) { newPhase in
                guard newPhase == .active, didFinishLaunching == false else { return }
                didFinishLaunching = true
            }
            .onChange(of: didFinishLaunching) { _ in
                guard didFinishLaunching else { return }
                perform()
            }
    }
}

extension View {
    func onFinishLaunching(perform: @escaping () -> Void) -> some View {
        modifier(FinishLaunchingViewModifier(perform: perform))
    }
}


text:
Q: Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.) As detailed elsewhere, and otherwise apparently well-known, Internet Explorer (definitely version 7, and in some instances, version 8) do not implement key functions, in particular on Array (such as forEach, indexOf, etc).
There are a number of workarounds here and there, but I'd like to fold a proper, canonical set of implementations into our site rather than copy and paste or hack away at our own implementations. I've found js-methods, which looks promising, but thought I'd post here to see whether another library comes more highly-recommended. A couple of miscellaneous criteria:

*

*The library should just be a no-operation for those functions that a browser already has implementations for (js-methods appears to do quite well here).

*Non-GPL, please, though LGPL is acceptable.

A: Kris Kowal has compiled a small library that acts as a shim for ECMAScript 5 functions that may be missing from the browser's implementation.  Some of the functions have been revised numerous times by other people to be optimized for speed and to work around browser bugs.  The functions are written to follow the specification as closely as possible.
es5-shim.js was released under the MIT license, the Array.prototype extensions are near the top and you can chop and remove any functions you don't need quite easily.  I also suggest you minify the script as the comments make it much larger than it needs to be.

A: Take a look at Underscore.js.

A: Many use the MDC fallback implementations (eg. for indexOf). They're generally rigorously standards-compliant, even to the extent of explicitly checking the types of all the arguments.
Unfortunately whilst it is clear that the authors regard this code as trivial and freely-usable, there doesn't seem to be an explicit licence-grant to put this in writing. The wiki as a whole is CC Attribution-ShareAlike, if that's an acceptable licence (though CC isn't designed for code as such).
js-methods looks OK in general, but is not as standards-compliant around the edges of how the functions are supposed to be (eg. undefined list items, functions that mutate the list). It's also full of other random non-standard methods, including some questionable ones like the dodgy stripTags and the incomplete UTF-8 codec (which is also a bit unnecessary given the unescape(encodeURIComponent) trick).
For what it's worth, here's what I use (which I hereby release into the public domain, if it can be said to be copyrightable at all). It's a bit shorter than the MDC versions as it doesn't attempt to type-sniff that you haven't done something silly like pass non-function callbacks or non-integer indexes, but apart from that it attempts to be standards-compliant. (Let me know if I've missed anything. ;-))
'use strict';

// Add ECMA262-5 method binding if not supported natively
//
if (!('bind' in Function.prototype)) {
    Function.prototype.bind= function(owner) {
        var that= this;
        if (arguments.length<=1) {
            return function() {
                return that.apply(owner, arguments);
            };
        } else {
            var args= Array.prototype.slice.call(arguments, 1);
            return function() {
                return that.apply(owner, arguments.length===0? args : args.concat(Array.prototype.slice.call(arguments)));
            };
        }
    };
}

// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}

// Add ECMA262-5 Array methods if not supported natively
//
if (!('indexOf' in Array.prototype)) {
    Array.prototype.indexOf= function(find, i /*opt*/) {
        if (i===undefined) i= 0;
        if (i<0) i+= this.length;
        if (i<0) i= 0;
        for (var n= this.length; i<n; i++)
            if (i in this && this[i]===find)
                return i;
        return -1;
    };
}
if (!('lastIndexOf' in Array.prototype)) {
    Array.prototype.lastIndexOf= function(find, i /*opt*/) {
        if (i===undefined) i= this.length-1;
        if (i<0) i+= this.length;
        if (i>this.length-1) i= this.length-1;
        for (i++; i-->0;) /* i++ because from-argument is sadly inclusive */
            if (i in this && this[i]===find)
                return i;
        return -1;
    };
}
if (!('forEach' in Array.prototype)) {
    Array.prototype.forEach= function(action, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this)
                action.call(that, this[i], i, this);
    };
}
if (!('map' in Array.prototype)) {
    Array.prototype.map= function(mapper, that /*opt*/) {
        var other= new Array(this.length);
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this)
                other[i]= mapper.call(that, this[i], i, this);
        return other;
    };
}
if (!('filter' in Array.prototype)) {
    Array.prototype.filter= function(filter, that /*opt*/) {
        var other= [], v;
        for (var i=0, n= this.length; i<n; i++)
            if (i in this && filter.call(that, v= this[i], i, this))
                other.push(v);
        return other;
    };
}
if (!('every' in Array.prototype)) {
    Array.prototype.every= function(tester, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this && !tester.call(that, this[i], i, this))
                return false;
        return true;
    };
}
if (!('some' in Array.prototype)) {
    Array.prototype.some= function(tester, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this && tester.call(that, this[i], i, this))
                return true;
        return false;
    };
}

Other ECMA262-5 methods not implemented here include Array reduce/reduceRight, the JSON ones and the few new Object methods that can be reliably implemented as JS functions.

A: By 'not implement key functions' you actually means 'conforms to the ECMA 262 3'rd ed' right? :)
The methods you are referring to are part of the new 5'th edition - for browsers not supporting this you can use the following 'shim' that extends 3'rd into 5'th
http://github.com/kriskowal/narwhal-lib/blob/narwhal-lib/lib/global-es5.js.

A: Those scripts don't work well in my tests. I create a file with the same functions based on MDN documents.
Too many problems areas are solved in Internet Explorer 8. See the code in  egermano / ie-fix.js.

A: With the Underscore.js
var arr=['a','a1','b']
_.filter(arr, function(a){ return a.indexOf('a') > -1; })


text:
Q: Change font color by WPF Converter Into my xaml I have label:
<Label Content="{Binding Path=HSValidation, Converter={StaticResource HSFontConverter}}" />

Into converter I want to change label font to "RED":
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  if (value != null)
   {

       return value; //should be value with changed color
   }
  return value;
}

Can I use just c# code?
OR do I need name property of my label?

A: Converters only convert the source value to something else, so you would only be able to convert the "Content" property to something else with your binding.
So you should have your content be bound to something as you have and then have the "Foreground" property be bound to the color.
<Label
    Content="{Binding Path=HSValidation}"
    Foreground="{Binding Path=HSValidation, Converter={StaticResource HSFontConverter}}" />

You should return Brushes.Red for instance in your converter code, and a Brush on all branches in the converter, not the bound value:
public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value != null)
    {
        return Brushes.Red;
    }

    return Brushes.Black;
}


text:
Q: Python: Easy PC to PC communcation I am interested in making an application that will transmit strings from one computer to another. I am interested in TCP or UDP communication. I have implemented UDP but it seems to be able to send up to 512 bytes of data / packet. Implementing packet splitting and joining at both ends should be a pain in the ass, so I was wondering if there's a library or anything like this to allow me to transmit a long string (No more than 10-20 KB hopefully, usually around 1-2KB) directly to the other computer. I don't care about encrypted communication since no sensitive data is sent/retrieved. Any suggestions I could use?
Here's what I am thinking of right now:
import easylib
def receivedData(text):
     print(text)
sendData("Hello world! Oh my gosh, this is a pretty long string. Good to know I can send it without any problems.")

Thank you in advance.

A: Nice small example of Python socket server.
Also you can user some more higher level protocols, like XMLRPC


text:
Q: Two related but opposite variables, how to calculate a score for them? I want to create two related values from similar data that actually mean opposites.
I'm wanting to create two values that describes how efficient someone is at a game, the values should describe how deadly they are and also how good they are at surviving damage.
At first I just used damage dealt/kills to create the first value and then damage taken/deaths for the second, which is fine since it's easy to compare the the two values, however the problem I have is that low damage dealt ratio is a good thing but a low damage taken ratio is also a good thing.
What I would like is for a high value in both to be a good thing but also keep them comparable, how would I go about this?
A high score for the deaths variable would involve a lower number of deaths and a high number of damage taken while a high score for the kills variable would involve a high number of kills for a low number of damage dealt.

A: Use the inverse of your measures:
deaths/damage taken
kills/damage dealt
Edit based on OP comment:
You can modify the above expressions so that they satisfy your requirements as such:
damage taken/deaths
kills/damage dealt
If you want to prevent dividing by zero on the first one you can go
damage taken/(deaths+1) or assign an otherwise max_value to this scenario.


text:
Q: How to configure eclipse che to use https? I have been using eclipse che for a few days and would like to enable https on it. I did not find any reliable information on how one would start eclipse che in https mode. I looked into che.env and could not find anything.
Any suggestions would be helpful.

A: Che does not officially support https.

A: You can deploy to OpenShift/K8s and have TLS support. But not on Docker


text:
Q: p:commandLink in p:subTable header fires only for first p:subTable I need to display a commandlink in the subTable header.The page renders correctly however only the first commandlink fires and action method gets invoked.All the subsequent commandlinks don't call the action method. I looked at the html source for the first two anchor elements. There is a slight difference in the generated ids. The first link's id has no digit after j_dt68 whereas the second link's id has j_dt68:0. Not sure if it is important or not. Please help!
First commandlink's html code:
                    DGI5120_GI:SB-5120 | 06634CVJTKH5

Second commandlink's html code:
DAR502G_ARRIS:TM502G | 6A7BMU47P225361

<f:facet name="header">

    <h:outputText
        value="#{equipment_msgs['assign.equipment.button.label']}"
        styleClass="table-header" />
</f:facet>

    <f:facet name="header">

            <f:setPropertyActionListener value="#{equipment}"
                target="#{equipmentBean.selectedEquipment}" />

    </f:facet>

            <f:setPropertyActionListener value="#{equipment}"
                target="#{equipmentBean.selectedEquipment}" />

            <f:setPropertyActionListener value="#{equipment}"
                target="#{equipmentBean.selectedEquipment}" />

#{port.portType}

#{port.portDetails.portCategory}

#{port.portDetails.serviceCategory}

#{port.portDetails.occurrence}

#{port.portDetails.modemText}

A: I made a workaround:
put a onclick attribute on your link/button (inside your subTable) to remove the additional digit from id and call PrimeFaces.ad(..) function
like this:

and on your button:

A: try this.
id replace js:


text:
Q: Creating a QgsFillSymbol from serialized QgsSymbolLayers I have a QgsFillSymbol:
>>> symbol = QgsFillSymbol.createSimple({'color': '#ffa500'})

I can dump the symbol's QgsSymbolLayers' properties in a dictionary structure:
>>> [symbol_layer.properties() for symbol_layer in symbol.symbolLayers()]
[
    {
        "border_width_map_unit_scale": "3x:0,0,0,0,0,0",
        "color": "255,165,0,255",
        "joinstyle": "bevel",
        "offset": "0,0",
        "offset_map_unit_scale": "3x:0,0,0,0,0,0",
        "offset_unit": "MM",
        "outline_color": "35,35,35,255",
        "outline_style": "solid",
        "outline_width": "0.26",
        "outline_width_unit": "MM",
        "style": "solid",
    }
]

How can I create a new QgsSymbol/QgsFillSymbol from this dictionary?
I can create a QgsFillSymbol from a list of symbol layers but I seem unable to create a QgsSymbolLayer from those properties.

A: You can create a specific type of QgsSymbolLayer, i. e. for this case a QgsSimpleFillSymbolLayer:
properties = {
    "border_width_map_unit_scale": "3x:0,0,0,0,0,0",
    "color": "255,165,0,255",
    "joinstyle": "bevel",
    "offset": "0,0",
    "offset_map_unit_scale": "3x:0,0,0,0,0,0",
    "offset_unit": "MM",
    "outline_color": "35,35,35,255",
    "outline_style": "solid",
    "outline_width": "0.26",
    "outline_width_unit": "MM",
    "style": "solid",
}

symbol_layer = QgsSimpleFillSymbolLayer.create(properties)

And then create the symbol like this:
symbol = QgsFillSymbol()
symbol.deleteSymbolLayer(0)
symbol.appendSymbolLayer(symbol_layer.clone())

You might be tempted to use the QgsFillSymbol(layers: Iterable[QgsSymbolLayer]) constructor but if you do, you are going to have lots of fun with crashes due to issues with object ownerships.


text: Q: Interpreting high deviance in logistic regression ANOVA output I'm performing logistic regression. I notice when I introduce one of my variables 'admissions_R,' which is a continuous count of the number of admissions, that the deviance is quite high. However, I'm uncertain as to how to interpret that, and what it means. I'm concerned because my DV is readmissions, so I'm wondering if its flagging a violation?


text:
Q: openquery conversion failed because the data value overflowed the data type used by the provider I'm using SQL Server 2008 to fetched data from another server using linked server.
SELECT * FROM OPENQUERY (METER,
       'SELECT
             ME.Col1
            ,ME."ext"               AS ext
            ,ME."t-date"                AS Date
            ,ME."per-id"                    AS Person
            ,PE."con-id"                AS Contact
            ,PE."add-id"                AS Address
            ,SC."contact-title"         AS Member
            ,SC."given"             AS Giver
            ,SC."surname"               AS lastname

        FROM PU."member" ME
            LEFT JOIN PU."personal" PE
              ON ME."per-id" = PE."per-id"
            LEFT JOIN PU."cont" SC
              ON PE."contactid" = SC."contactid"

        WHERE ME."t-date" IS NULL
           OR ME."t-date" >= NOW()')

I'm getting error:
 OLE DB provider "MSDASQL" for linked server "METER" returned message    "Multiple-step OLE DB operation generated errors. Check each OLE DB status   value, if available. No work was done.".
  Msg 7341, Level 16, State 2, Line 1
  Cannot get the current row value of column "[MSDASQL].T_DATE" from OLE DB   provider "MSDASQL" for linked server "METER". Conversion failed because the data   value overflowed the data type used by the provider.

If I remove where condition and executing this, I'm getting same error as well. So I think "Date" is not causing any issue here. Please Correct me if I'm wrong.
However, if I remove ,SC."contact-title" AS Member from the above query, it gives me result and works fine.
I got information that:
Length of the data in each field must be less than the length described in the schema. For contact-title defined as certain character and data need to be less than that. - I understand this.
My question is in select query I'm trying to fetch the data and I'm not inserting any where. But, still why this character length mismatch ? As per my understanding if I'm inserting it somewhere then there could be a issue. But just select should not give issue.
I'm just fetching data from 3rd party server and displaying. Is there any issue could be at my end/my database? If yes, how?
Could anyone has faced similar issue and how to solve this?

A: Just changed  SC."contact-title"  to substring(SC."contact-title",1,14) and it worked. Note- both SUBSTR and SUBSTRING is working fine.


text:
Q: relationship of an instantiated class - Laravel/Eloquent I'm working on an api for a website, where I have the tables of blogs and categories
every blog belongs to category
and each category has many blogs
OK?
So, I created a BlogController and configured the routes to access the corresponding function.
/api/blog/ url via GET is redirected to the index function of my controller, and the function looks like this:
public function index()
{
    $blog = Blog::with('category')->get();
    return response()->json($blog, 200);
}

which returns this (correct)
[
    {
        "id": 1,
        "title": "title from blog",
        "body": "texto do meu blog",
        "category_id": 1,
        "created_at": "2018-09-05 21:08:21",
        "updated_at": "2018-09-05 21:08:21",
        "category": {
            "id": 1,
            "name": "Web development",
            "created_at": "2018-09-05 20:54:54",
            "updated_at": "2018-09-05 20:54:54"
        }
    }
]

/api/blog/ url via POST is redirected to the store function of my controller, to store the data in the database and the function looks like this:
public function store(Request $request)
{
    $blog = new Blog($request->all());
    $saved = $blog->save();

    if ($saved) {
        return response()->json($blog, 200);
    }

    return response()->json([
        'message' => '400 Bad Request'
    ], 400);
}

then returns (missing category information)
{
    "title": "title from blog",
    "body": "texto do meu blog",
    "category_id": "2",
    "updated_at": "2018-09-06 00:56:13",
    "created_at": "2018-09-06 00:56:13",
    "id": 12
}

then, missing category information
after storing data in the database, I need it to come in response to category information for that specific blog
someone to help?

A: I can with
$blog->load('category');


text:
Q: Why doesnt my webpage refresh when calling RedirectToAction? So I'm currently developing a webpage which has a table with some table data, each row of table data has a button which is responsible of starting a process, and when I click one of the buttons, it fires an ajax call. Once the ajax call finishes, it then updates something on the webpage, this "something" is a span element, it updates the class and the text.
However if I refresh the page manually in between the process of me clicking the button when it fires the ajax call and it finishing, it wont update.
Let' me explain this with some code.
I have this button, which invokes the ajax call when clicked
<button type="button" class="btn btn-icon waves-effect waves-light btn-success" onclick="@("StartProcess('"+model.ProcessName+"')")"> <i class="fa fa-power-off"></i> </button>

The Ajax call looks like this
 function StartProcess(ProcessName) {

        var dataPost = { processName: ProcessName};
        $.ajax({
            data: dataPost,
            url: '@Url.Action("Start", "Dashboard")',
            type: "POST",
            dataType: "text",
            beforeSend: function () {
                // Handle the beforeSend event
                $("#" + ProcessName).removeClass("badge-danger").addClass("badge-info").html("Starting");
            },
            success: function (redirect) {
                // Handle the complete event
                window.location = redirect;
                $("#" + ProcessName).removeClass("badge-info").addClass("badge-success").html("Online");

            },
            error: function() {
                //AJAX request not completed
                $("#" + ProcessName).removeClass("badge-info").addClass("badge-danger").html("Error");
    }
            // ......
        });
    };

And what this does, is that it makes a request to a IActionResult on the back-end which does run perfectly.
Here is what it looks like, keep in mind that it reaches the RedirectToAction every single time even if I refresh or not.
 [HttpPost]
        public IActionResult Start(string ProcessName)
        {
            ProcessFactory.StartProcess(ProcessName, _user);
            while (ProcessFactory.ServerFlag == null)
            {
                //Stalling until "ProcessFactory.StartProcess" has finished

            }

            //It reaches this no matter what
            if (ProcessFactory.ServerFlag == "Online")
            {
                Debug.Print("===========ONLINE============");
                Response.StatusCode = 200;

                //It reaches this no matter what
                return RedirectToAction("Dashboard", "Dashboard");
            }
            else if (ProcessFactory.ServerFlag == "Already running")
            {
                Response.StatusCode = 200;
                return RedirectToAction("Dashboard", "Dashboard");
            }
            else if (ProcessFactory.ServerFlag == "Error")
            {
                Response.StatusCode = 401;
                return RedirectToAction("Dashboard", "Dashboard");
            }

            return RedirectToAction("Dashboard", "Dashboard");
        }

Here is the issue that I am facing, when I click start and I just let it run without refreshing the page, it works just fine, it updates the element without any issues.
If however I refresh the browser after I click the start button, while it inside the while loop, it finishes the exact same way by hitting the RedirectToAction but this time it doesnt refresh the browser, it doesnt even invoke the "Dashboard" IActionResult. I tried putting a breakpoint inside it before refreshing the page, and it hit it, but when I tried it again, but this time refreshing the page, it didn't hit the breakpoint. And keep in mind that it reaches the RedirectToAction every single time inside one of the if statements, no matter what, even if I refresh or not.
public async Task<IActionResult> Dashboard()
        {
            ProcessFactory.LoadProcesses(_user);

            //Load all processes
            var model = ProcessFactory.LoadProcesses(_user);

            return View(model);
        }

Is this a case of losing context or what's going on here?

A: You're returning a RedirectToAction() (equivalent of a 302) to JavaScript and it doesn't know how to handle that.  I see you're trying to manually set the response code but the easiest solution would be to simply change your what you're returning to a URL.
[HttpPost]
public IActionResult Start(string ProcessName)
{
    ProcessFactory.StartProcess(ProcessName, _user);
    //[....lots of stuff]
    return Json(Url.Action("Dashboard", "Dashboard"));
}

On your JavaScript, change return type to JSON.  Arguably you could return a string from your controller without wrapping in JSON but this allows you to return more data in the future if you so choose (by simply adding more to the JSON response)
function StartProcess(ProcessName) {

    var dataPost = { processName: ProcessName};
    $.ajax({
        data: dataPost,
        url: '@Url.Action("Start", "Dashboard")',
        type: "POST",
        dataType: "json",
        beforeSend: function () {
            // Handle the beforeSend event
            $("#" + ProcessName).removeClass("badge-danger").addClass("badge-info").html("Starting");
        },
        success: function (redirect) {
            // Handle the complete event
            window.location = redirect;
            //changing any part of the UI is redundant here as you are redirecting
            //the browser window
        },
        error: function() {
            //AJAX request not completed
            $("#" + ProcessName).removeClass("badge-info").addClass("badge-danger").html("Error");
}
        // ......
 });
};


text:
Q: Odd Websocket Error at Build Time - "Unable to Resolve websocket/lib/BufferUtil"? Even though I have Websocket installed, at build time, using the Meteor build tool, I'm getting this console error:
Unable to resolve some modules:

  "../build/Release/bufferutil" in /Volumes/RAM Disk/myWebApp/node_modules/websocket/lib/BufferUtil.js (os.osx.x86_64)
  "../build/default/bufferutil" in /Volumes/RAM Disk/myWebApp/node_modules/websocket/lib/BufferUtil.js (os.osx.x86_64)
  "../build/Release/validation" in /Volumes/RAM Disk/myWebApp/node_modules/websocket/lib/Validation.js (os.osx.x86_64)
  "../build/default/validation" in /Volumes/RAM Disk/myWebApp/node_modules/websocket/lib/Validation.js (os.osx.x86_64)

What might be causing this?

A: It looks like this is just a warning, not a fatal error.
https://github.com/meteor/meteor/issues/6601


text:
Q: Column truncated with a relation to another entity When I try to update the schemes, I get the following error :
  An exception occurred while executing 'ALTER TABLE TechSummaryRdvDocuments CHANGE carRegistration_i
  d carRegistration_id VARCHAR(255) NOT NULL, CHANGE idCardRecto_id idCardRecto_id VARCHAR(255) NOT N
  ULL, CHANGE idCardVerso_id idCardVerso_id VARCHAR(255) NOT NULL, CHANGE vehicleInspection_id vehicl
  eInspection_id VARCHAR(255) NOT NULL, CHANGE idCardRectoPartOwner_id idCardRectoPartOwner_id VARCHA
  R(255) NOT NULL, CHANGE idCardVersoPartOwner_id idCardVersoPartOwner_id VARCHAR(255) NOT NULL':

  SQLSTATE[01000]: Warning: 1265 Data truncated for column 'idCardRecto_id' at row 848

It is defined this way in my entity :
/**
 * @var FileValid
 * @ORM\Column(name="idCardRecto_id")
 * @ORM\OneToOne(targetEntity="Carizy\CoreBundle\Entity\FileValid", cascade={"persist"})
 * @Assert\Valid()
 */
private $idCardRecto;

Where FileValid is an entity with differents fields.
Do you know how I can fix it ?

A: Sounds like you have some data already in your existing database table where the idCardRecto_id column value exceeds the new column length of 255 characters (which is the default length of the string column as you don't have any explicit column definitions written)? I.e. you can define the max length of that column to be something bigger to match your existing data, like:
@ORM\Column(name="idCardRecto_id", length=1000)


text:
Q: Finiteness property of virtually torsion-free groups
Do virtually torsion-free groups always have finitely many conjugacy classes of finite subgroups?

A paper I'm reading about $\operatorname{Out}(F_n)$ mentions this finiteness property is a corollary of it being virtually torsion-free, but I'm having difficulty seeing how to establish this fact. Is it possible that a proof uses more structure of $\operatorname{Out}(F_n)$ than it being virtually torsion-free?
Really any hints would be helpful.

A: It is easy to find examples of groups that are not finitely generated  in which this is not true, but it appears that it not true in general, even for finitely generated groups. There is an example here:
let $G = (F_2 \times F_2) \rtimes C_2 =$
$\ \ \ \ \ \ \ \ \ \langle a,b,c,d,t \mid t^2=1, a^t=b,  c^t=d,
[a,c]=[b,c]=[a,d]=[b,d]=1 \rangle,$
let $\phi:G \to {\mathbb Z}$ with $a,b,c,d \mapsto 1$, $t \mapsto 0$, and let $H= \ker \phi$. Then $H$ is virtually torsion-free and has infinitely many classes of finite order elements. The group $H$ is not finitely presented, so it would be interesting to know if there is a finitely presented example.


text:
Q: PowerShell: Multiple Body responses from API I am using a GET method to pull data from StatusHub API.
This is an example response from the API
{
        "id": 3570,
        "title": "[SevA] Test title",
        "incident_updates": [
            {
                "id": 9329,
                "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. Lorem ipsum dolor sit amet, consectetur.INC1085710
",
                "id": 9328,
                "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. INC1085710
",

As you can see there are two different "body" responses under "incident_updates" which ultimately fall under the same issue title of  "title": "[SevA] Test title".
How am I able to pull out just the latest "body" response and not all of them?
I have tried doing something like
$response.incident_updates.body[0]

however the problem with that is that it picks up the first latest body response which is perfect, however I need the first response for every single incident and not just one.
Any ideas?
Thanks

A: First of all the Json shouldn't have duplicate values. When I look at the documentation of StatusHub for incidents and incidentUpdates it shows a clear separation of each incident id in a different array index.
second the json you post will truncate the properties id and body when using ConvertFrom-JSON because a PSCustomObject or Hashtable do not allow duplicate keys.
if you keep getting duplicate properties within a single object, I would advise on reporting this to StatusHub and describing Cleary on the exact steps taken that cause this issue to arise. Due to this issue not being in line with the documentation of the StatusHub API I would not advise on doing a workaround, as you are bypassing a bug in the application.


text:
Q: Bash equivalent for SQL "1.%" I'm aware than whenever I want to filter columns or... basically anything in a SQL query, i can use something like
Select * from table1 where name1 like "Mr.%"

This part
like "Mr.%"

Should grab any row in which the var name1 starts with "Mr." no matter what else is after it.
My question: Is there an equivalent for it in bash?  anything to go with grep, maybe?

A: You can do it with grep easily:
For a file:
grep '^Mr\.' myfile.txt

For command output:
my-command-with-output | grep '^Mr\.'

EDIT: Adding an example with your example text file string:
grep '^1' myfile.txt

The example above will find any lines with starting with the number 1.


text:
Q: Timemanager not working with Integer Timestamp format I'm trying to create an animation using Timemanager on QGIS 2.18 but I'm struggling.
I have a dataset composed by a list of businesses and their opening/closing time. This is what the dataset looks like:

'Start' and 'End' columns contain the day and the opening hours of the business converted in Unix Timestamp.
I upload my CSV in QGIS and add the layer on TimeManager. The plugin seems to accept the data. This is the slider after I uploaded my data:

Even if everything looks ok my animation doesn't work, nothing happens to the points on my map. I simply need the points to appear when the business is open and disappear when the business is closed.
Do I do something wrong? I never used this plugin before, so I don't know how to tackle the problem.

A: The problem is with the Time frame start date.

Yours says 2000 instead of 2018.
I just tried the plugin, whit similar format and data for start and end fields, and it works fine.

A: Be sure that the data type of the fields is Integer.
I'm seeing that the plugin doesn't work if I pass the selected fields because they are of type String.

If that is the case, create new fields of type Integer and convert your original data.

A: Well, it's not easy to explain, but I think the TimeManager plugin does not work with CSV layers. At least not directly. Probably because the CSV layers are not editable.
First of all you will need to copy the attributes of latitude and longitude to all the rows before importing the layer in QGIS, so that for each row a point is generated. I think it's the simplest way to import the .csv file and have a spatial entity related to each of its rows. In addition, "start" and "end" fields must be well recognized with the Integer type.

The TimeManager plugin exposes, when it works, the animation_datetime() function that returns the timestamp of the current animation. The epoch function can converte the timestamp to Unix epoch, but in milliseconds and believing that the timestamp is in the time zone of the machine (GMT-03:00 in my case). I don't know why, but I had to recalculate it.
So, one option is to add a rule in the symbology of the CSV layer, which in my case was like this:
("start" <= epoch(animation_datetime())/1000 - 3*60*60)
AND
("end" >= epoch(animation_datetime())/1000 - 3*60*60)

But still, the plugin needs a valid layer to work. I had created a dot shape layer previously, so the plugin worked with it. And CSV layer symbology works itself with that rule. You should create one with at least one dot that contains the start and end field for the first start and last end of the sequence. Add it to the plugin to work and disable it so it does not show up.

The other option, which seems to be much simpler, is to export the CSV layer to a dot shape layer and load it in the plugin.


text:
Q: what is the complexity/BIG O of this function "loops" void mystery2 (int n)
{
  int i;
 for (i = 1; i <= n; i++) {
   double x = i;
   double delta = 1 / (double)i;
   while ( x > 0 )
     x -= delta;
  }
return 0;
}

Why is the BIG O, The time complexity of this function is O(n^3) and not O(n^2)?
What I done is when i=1 ==> 1 iterations, i=2 ==> 2iterations(in while) i=3 ==> 3 iteration ........ i=n ==> n iteration, if we sum all the iterations we get 1+2+3+4....+n = n*(n+1)/2. so what I missing here?

A: This is because inner loop runs like this.
For i=1, inner loop runs 1 time,
For i=2, inner loop runs 4 time,
 //because x=2 and delta=0.5 so for x to become 0 it has to iterate 4 time
For i=3, inner loop runs 9 time
 //because x=3 and delta=0.33 so for x to become 0 it has to iterate 9(atleast) time
and so on..

So inner loop run i^2 time and the equation becomes 1^2+2^2+3^2+...+n^2=n(n+1)(2n+1)/6 which is equal to O(n^3) complexity.

A: I think you are looking at it as a standard integer decrement loop, which I also did at first, but the number are doubles, and delta is not 1 but actually 1 / (double)i, so the number of inner loop iterations it takes to fully decrement x does not increase linearly as n increases, but much more sharply, because delta gets smaller as n gets larger.


text:
Q: Traffic Camera XML feed I was checking MassDOT Traffic Cameras site (http://www.massdot.state.ma.us/portals/0/docs/developers/trafficcams_xml.pdf), and try to copy the example XML/Summary feed (inside the link) to my own server, but it doesn't work.
I got error message "error on line 14 at column 7: Extra content at the end of the document." I wonder if this code is still valid..Please help!

A: Quick answer:
It was a bit difficult to understand what you meant, but yes, the example XML in the PDF is wrong. Last line should not be <Cam> but the closing tag </TrafficCams>.
Longer answer:
I can just show you what I did, so that next time you can be more independent:

*

*checked in your PDF the XML that was having problems (I had issues to copy it from Safari, better to copy/paste here in stackoverflow, maybe)

*pasted to a XML validator (I used the first appearing in Google: www.xmlvalidation.com, not good but usable), and saw that it was copied wrongly (90% of the XML was at line 8, actually)

*pasted in a text editor, to clean it (I use www.sublimetext.com but want to try www.atom.io soon...); cleaned it, and observed the strange last line...

*pasted the new cleaned XML (now looks exactly as in the PDF) to the same XML validator, and of course the error was what I expected:

Errors in the XML document:   15: 6   XML document structures must start
  and end within the same entity.

*

*changing the last line to the proper one (</TrafficCams>) is now okay

No errors were found

*

*last suggestion, if you use a nice editor (such as SublimeText) he will suggest you the change you've to make, when you try to edit it... simple!


text:
Q: See github commits in files of cloned project I know that you can see the commits and the people that executed these on the github page.
But can you see all the commits and the people responsible for these commits in the files of a cloned project?
For example: Person A clones a project and gives a copy to Person B.
Can Person B simple use git log on the project to see the commits?
Or can Person A only do this?


text:
Q: Symbolic visibility markers in MetaUML My question is very similar to this:Omitting visibility marker in MetaUML
Is there any way to leave +, - and # symbols as they are, without drawing locks?

A: The latest MetaUML version from Github uses the standard accesibility symbols instead of the locks.


text:
Q: jQuery Datepicker - Programatically Limit Second Datepicker I've recently been using the following piece of code to limit my 2nd Date picker (end date) so that it does not precede the date of the 1st Date picker.
$("#datepicker").datepicker({
 minDate: +5,
 maxDate: '+1M +10D',
 onSelect: function(dateText, inst){
           var the_date = dateText;
           $("#datepicker2").datepicker('option', 'minDate', the_date);

 }
 });
 $("#datepicker2").datepicker({

    maxDate: '+1M +10D',
    onSelect: function(dateText, inst){

    }
});

However, lately, I wanted to format my datepickers using:
dateFormat: 'yy-mm-dd'

But now, the 2nd datepicker actually allows the user to pick a date 1 day before.
For example, if the user picks the 1st date: 2010-04-03, when the 2nd Datepicker pops up, they are able to pick 2010-04-02 (1 day before their first selected date).
I do not want the user to be able to pick a date that was before their first selected day.
Any ideas why this isn't working after I added in the "dateFormat"?

A: option minDate expect a date object not a string object.. you can however specify the format and do the conversion as follow:
$(document).ready(function() {  //Runs when tab is loaded

var dateFormat = "yy-mm-dd";

$("#datepicker").datepicker({
 minDate: +5,
 dateFormat:dateFormat,
 maxDate: '+1M +10D',
 onSelect: function(dateText, inst){
           var the_date = $.datepicker.parseDate(dateFormat,dateText);
           $("#datepicker2").datepicker('option', 'minDate', the_date)
 }
 });
 $("#datepicker2").datepicker({

    maxDate: '+1M +10D',
    dateFormat:dateFormat,
    onSelect: function(dateText, inst){

    }
});

});

A: You could alternatively do this
       onSelect: function(){
           $("#datepicker2").datepicker('option', 'minDate', $(this).val());
       }