text:
Q: show that $\det(D) = 0$ where $D_{ij} = |P_i - P_j|^2$
Let $P_1,\cdots, P_6$ be points in $\mathbb{R}^3.$ Let $D$ be the $6\times 6$ matrix whose $(i,j)$th-entry is the square of the distance between $P_i$ and $P_j$. Show that $\det(D) = 0$.

Note that it suffices to write $D$ as a sum of $5$ matrices of rank at most 1, since for any matrices A and B, $\mathrm{rank}(A+B)\leq \mathrm{rank}(A) + \mathrm{rank}(B) $ and so by induction $\mathrm{rank}(\sum_{i=1}^n A_i) \leq \sum_{i=1}^n\mathrm{rank}(A_i)$. Also $D$ is symmetric since $|P_i - P_j| = |P_j-P_i|$ for all $i,j$.
$D$ can trivially be written as the sum of $6$ matrices with rank at most 1; let a distinct row of D be the first row of each matrix while all other rows are zero. Suppose we have the specific example where $P_1,P_2,\cdots, P_6 = (1,1,1),(1,1,2),(1,2,1),(2,1,1),(2,1,2),(2,2,1).$ Then $D = \begin{pmatrix}0 & 1 & 1  &2 & 2 & 2\\
1 & 0 & 2 & 2 & 1 & 3\\
1 & 2 & 0 & 2 & 3 & 1\\
1 & 2 & 2 & 0 & 1 & 1 \\
2 & 1 & 3 & 1 & 0 & 2\\
2 & 3 & 1 & 1 & 2 & 0\end{pmatrix}.$
One might be able to compute $\det(D)$ in this special case by using row or column operations. Also note that the determinant is $n$-linear and alternating.
If $P_i=P_j$ for some $i\neq j$ then $D$ will have two identical rows and hence determinant of zero, so we may suppose that all the $P_i$'s are distinct.

A: Let $P$ denote the matrix whose columns are $P_1,\dots,P_6$. Let $e,v \in \Bbb R^6$ denote vectors in $\Bbb R^6$ such that $e = (1,\dots,1)$ and $v = (|P_1|^2,\dots,|P_6|^2)$. Show that
$$
D = ev^T + ve^T - 2P^TP,
$$
which is the sum of 2 rank-1 matrices and one rank-3 matrix.


text:
Q: How to display multiple values of the same attribute when hovering on tooltip with highcharts/highmaps I'm using a highmaps worldmap, and when I hover on a country I want the tooltip to list out all of the food chains that are from that specific country. However I'm only managing to get the tooltip to list out the first result. The number of results for each country vary.
For example, I want the tooltip to list out the following food chains when hovering on the US:
1: {companyName: "Burger King", hc-key: "us"}

2: {companyName: "McDonalds", hc-key: "us"}

3: {companyName: "Kentucky Fried Chicken", hc-key: "us"}

4: {companyName: "Quiznos", hc-key: "us"}

5: {companyName: "Subway", hc-key: "us"}

6: {companyName: "In and Out", hc-key: "us"}

7: {companyName: "Taco Bell", hc-key: "us"}

8: {companyName: "Popeyes", hc-key: "us"}

9: {companyName: "Jack in the Box", hc-key: "us"}
10: {companyName: "Italia Pizza", hc-key: "it"}
10: {companyName: "Italia Pasta", hc-key: "it"}
My current code outputs the first result, I just don't know enough to edit the tooltip formatter to account for the rest of the results. Thank you.
mapdata(Highcharts){
this.companyData
        .getcompanyCountries(this.selectedIndustry)
        .subscribe(
            (data: any[]) => {
                this.companies = data.map(function(el){
                    return {companyName: el.name, 'hc-key':el.country_code}
                })
                console.log(this.companies)
                // Create the chart
                Highcharts.mapChart('container-map', {
                    chart: {
                        map: worldMap,
                    },
                    title: {
                        text: ''
                    },
                    legend: {
                        enabled: false
                    },
                    mapNavigation: {
                        enabled: false,
                        buttonOptions: {
                        alignTo: 'spacingBox'
                        }
                    },
                    series: [{
                        color: '#ffff00',
                        nullborderColor: '#d3d3d3',
                        type: 'map',
                        name: 'Food Chains',
                        tooltip: {
                           pointFormat: '{point.name}:
{point.companyName}',
                        },
                        states: {
                        hover: {
                            color: '#ffff00'
                        }
                        },
                        dataLabels: {
                        enabled: false,
                        format: ''
                        },
                        nullColor: 'white',
                        allAreas: true,
                        joinBy: 'hc-key',
                        data: this.companies,
                    }]

            })
            }

        )}

EDITED:
mapdata(Highcharts){
this.companyData
        .getcompanyCountries(this.selectedIndustry)
        .subscribe(
            (data: any[]) => {
                this.companies = data.map(function(code){
                    return {companyName: code.name, code: code.country_code}
                })
                console.log(this.companies)
                // Create the chart
                Highcharts.mapChart('container-map', {
                    chart: {
                        map: worldMap,
                    },
                    title: {
                        text: ''
                    },
                    legend: {
                        enabled: false
                    },
                    credits: {
                        enabled: false
                      },
                    mapNavigation: {
                        enabled: false,
                        buttonOptions: {
                        alignTo: 'spacingBox'
                        }
                    },
                    plotOptions: {
                        map: {
                          allAreas: true,
                          joinBy: ['hc-key','code'],
                          dataLabels: {
                            enabled: true,
                            color: '#FFFFFF',
                            style: {
                              fontWeight: 'bold'
                            },
                            // Only show dataLabels for areas with high label rank
                            format: null,
                            formatter: function() {
                              if (this.point.properties && this.point.properties.labelrank.toString() < 5) {
                                return this.point.properties['hc-key'];
                              }
                            }
                          },
                          tooltip: {
                            headerFormat: '',
                            pointFormatter: function() {
                              var string = '' + this.name + ':
';
                              data.forEach(function(companyName) {
                                string += companyName.name + '
'
                              });
                              return string;
                            }
                          }
                        }
                      },

                    series: [{

                        color: '#ffff00',
                        nullborderColor: '#d3d3d3',
                        type: 'map',
                        name: 'Food Chains',
                        states: {
                        hover: {
                            color: '#ffff00'
                        }
                        },
                        dataLabels: {
                        enabled: false,
                        format: ''
                        },
                        nullColor: 'white',
                        data: this.companies,
                    }]

            })
            }

        )}

A: It is possible to use tooltip pointFormatter or pointFormat options for adding custom information in Highcharts tooltip. You can find more information about this two parameters in Highcharts API:
https://api.highcharts.com/highcharts/tooltip.pointFormat
https://api.highcharts.com/highcharts/tooltip.pointFormatter
tooltip: {
    pointFormatter: function() {
      var string = '' + this.name + ':
';
      this.companyNames.forEach(function(name) {
        string += name + '
'
      });
      return string;
    }
  }

Live example:
https://jsfiddle.net/BlackLabel/gekrzdto/1/

redpajama_set_name: RedPajamaStackExchange


text:
Q: GWT Requestfactory performance suggestions I am observing really bad performance when using GWT requestfactory. For example, a request that takes my service layer 2 seconds to fullfil is taking GWT 20 seconds to serialize. My service is returning ~100 what will be EntityProxies. Each of these objects has what will become 4 ValueProxies and 2 more EntityProxies (100 root level EntityProxies, 400 ValueProxies and 200 additional EntityProxies). However, I see the same 10x performance degradation on much smaller datasets.
Example of log snippet:
D 2012-10-18 22:42:39.546 ServiceLayerDecorator invoke: Inoking service layer took 2265 ms
D 2012-10-18 22:42:58.957 RequestFactoryServlet doPost: Entire request took 22870 ms

I have added some profiling code to the ServiceLayerDecorator#invoke method and wrapped the entire servlet in a timer. I have profiled the service by itself, and it is indeed returning results in ~2s.
I am using GWT 2.4, but have tested this on GWT 2.5rc1 and GWT 2.5rc2. My backend is on GAE, but I dont think that is playing a role here.
I found this bug filed against 2.4, which seems to be very related. I have manually applied the patch from this google group without any luck.
My domain models look like:
class Trip {
  protected Address origin; // becomes ValueProxy
  protected Address destination; becomes ValueProxy
  protected Set<TripPassenger> tripPassengers; // Set of ValueProxies
}

class TripPassenger {
  protected Passenger passenger;
}

class Passenger {
  protected Account account;
}

My question is:

*

*Have I profiled the code correctly and isolated the problem to the GWT serialization?

*Could I be doing something wrong that would cause this behavior?

*How can I better profile the GWT serialization code to try and figure out the cause?

A:

*

*Have I profiled the code correctly and isolated the problem to the GWT serialization?

RequestFactory uses reflection a whole lot (much more than GWT-RPC for instance), so I'm not really surprised that it causes some perf issues in some cases. And GAE could play a role here.
I believe RequestFactory (the AutoBean part actually) could greatly benefit from code generation at build-time.

*

*Could I be doing something wrong that would cause this behavior?

Check your locators' find and/or isLive methods.

*

*How can I better profile the GWT serialization code to try and figure out the cause?

It would also be interesting to know the time spent on deserialization of the request, applying changes, and then serialization of the response. And don't forget to substract from those the time spent in find and isLive.


text:
Q: Gradle skip idea module generation I have a project setup that is as follows
Project A
|
|-Sub-Project B
|-Sub-Project C
| |
| \-src
|   |
|   |-Sub-Project D
|   \-Sub-Project E
\-Sub-Project F

In order to get the project to build and Idea modules created I need to put a build.gradle file at each level, however I dont really want idea modules created for Project C and the child src directory. Is there a way to suppress these modules?
Also is there a way to specify a group for idea modules?

A: I have found the answer to the question of not adding the projects to the ipr file. Adding the following to my top level build.gradle file only adds projects where ideaModule.enabled == true.
gradle.projectsEvaluated {
    gradle.rootProject {
        ideaModule.enabled = false
        idea {
            project {
                modulesToInclude = subprojects.findAll {it.ideaModule.enabled == true}
                modules = modulesToInclude.idea.module
            }
        }
    }
}

A: Just create Sub-Project D directly in the Sub-Project C directory (without a src directory). You can also omit build.gradle in Sub-Project C. Idea 13 imports that structure without any problems. Just remember to add only the real subprojects to the settings.gradle:
include 'Sub-Project B', 'Sub-Project D', 'Sub-Project E', ...


text:
Q: How can I make external code 'safe' to run? Just ban eval()? I'd like to be able to allow community members to supply their own javascript code for others to use, because the users' imaginations are collectively far greater than anything I could think of.
But this raises the inherent question of security, particularly when the purpose is to allow external code to run.
So, can I just ban eval() from submissions and be done with it? Or are there other ways to  evaluate code or cause mass panic in javascript?
There are other things to disallow, but my main concern is that unless I can prevent strings being executed, whatever other filters I put in for specific methods can be circumvented. Doable, or do I have to resort to demanding the author supplies a web service interface?

A:
Or are there other ways to evaluate code

You can't filter out calls to eval() at a script-parsing level because JavaScript is a Turing-complete language in which it is possible to obfuscate calls. eg. see svinto's workaround. You could hide window.eval by overwriting it with a null value, but there are indeed other ways to evaluate code, including (just off the top of my head):

*

*new Function('code')()

*document.write('%3Cscript>code%3C/script>')

*document.createElement('script').appendChild(document.createTextNode('code'))

*window.setTimeout('code', 0);

*window.open(...).eval('code')

*location.href='javascript:code'

*in IE, style/node.setExpression('someproperty', 'code')

*in some browsers, node.onsomeevent= 'code';

*in older browsers, Object.prototype.eval('code')

or cause mass panic in javascript?

Well createElement('iframe').src='http://evil.iframeexploitz.ru/aff=2345' is one of the worse attacks you can expect... but really, when a script has control, it can do anything a user can on your site. It can make them post "I'm a big old paedophile!" a thousand times on your forums and then delete their own account. For example.

do I have to resort to demanding the author supplies a web service interface?

Yes, or:

*

*do nothing and let users who want this functionality download GreaseMonkey

*vet every script submission yourself

*use your own (potentially JavaScript-like) mini-language over which you actually have control

an example of the latter that may interest you is Google Caja. I'm not entirely sure I'd trust it; it's a hard job and they've certainly had some security holes so far, but it's about the best there is if you really must take this approach.

A: There really isn't any way that allowing arbitrary Javascript execution can be safe. Realistically, any sort of filtration you provide to prevent malicious code would strip out legitimate code that accesses similar functions or data. I don't think that what you're looking to do is feasible in this way.

A: You need to execute the untrusted code in a sandboxed environment. This means creating an iframe with the sandbox attribute (see this article), and additionally create a web-worker inside that frame (so that the code runs in a separate thread and does not hang up the UI in case if user has submitted something strange).
If you need to interact somehow with the code sandboxed in the described way, the messaging mechanism can be used. This is a bit tricky, but there are some libraries simplifying the task, including one created by myself: https://github.com/asvd/jailed

A: Since HTML5 has now become available you can use a sandbox for untrusted JavaScript code.
The OWASP HTML5 Security Cheat Sheet comments on Sandboxed frames:

*

*Use the sandbox attribute of an iframe for untrusted content.

*The sandbox attribute of an iframe enables restrictions on content within a iframe. The following restrictions are active when the sandbox attribute is set:

*

*All markup is treated as being from a unique origin.

*All forms and scripts are disabled.

*All links are prevented from targeting other browsing contexts.

*All features that triggers automatically are blocked.

*All plugins are disabled.
It is possible to have a fine-grained control over iframe capabilities using the value of the sandbox attribute.

*In old versions of user agents where this feature is not supported, this attribute will be ignored. Use this feature as an additional layer of protection or check if the browser supports sandboxed frames and only show the untrusted content if supported.

*Apart from this attribute, to prevent Clickjacking attacks and unsolicited framing it is encouraged to use the header X-Frame-Options which supports the deny and same-origin values. Other solutions like framebusting if(window!== window.top) { window.top.location = location; } are not recommended.

You can allow scripts to run while keeping the other restrictions in place. However, you should make sure that scripts run from a different domain than your main content in order to prevent XSS attacks by an attacker redirecting a user to load the page directly (i.e. not via your IFrame).
This will restrict scripts from using eval to attack your main domain, but it may be that this would also prevent the scripts from actually being powerful enough for your needs. Any interaction with your main domain would have to be via Window.postMessage. If this is too restrictive then @bobince's answer still has the best suggestions for workarounds.
Please see my other answer for details of how a sandbox can be safely implemented.

A: No, you practically can't prevent user provided Javascript code to run whatever it wants - even disallowing eval() can't prevent it to run arbitrary programs (it could be a Javascript interpreter itself, in which case it just implements the eval() function, and many other ways - eg. it can add HTML with some event handlers in string form, then execute them, it can document.write() a new script etc.).
If your site doesn't need this user supplied JS to run on other users' computers, I'd just put a big fat warning, add some human control (that could flag rogue code as such), maybe some antivirus software on the server (don't know much about that).

A: Filtering out eval probably doesn't work. I imagine that you could hack round it like this: window['ev' + 'al']('alert("hello world");');. You could of course replace the eval function...


text:
Q: How can I drive column titles from cell values outside of the query? I have created a recurring (monthly) query tool.  Each month, the name of a column will change.  I would like the user to be able to type the value in a cell on the first sheet, and drive that value to become the title of a column in the table.
Thought 1:
Modify the following code:
#"Renamed Columns1" = Table.RenameColumns(#"Multiplied Column7",{{"Month1;BDG", "AAA"}})
to replace "AAA" with a call to a specific cell on another sheet directly in the "Renamed" step.  Is this possible?
Thought 2:
Manage the change as column data by doing the following:
 1. Demote the current column titles using "Use headers as first row"
 2. Write an IF statement if the value = "Column7" then "value of the cell on the other sheet" else [Column7].
 3. Then promote the top row to be column headers after the change.
Or is there a way easier way?  My searches have come up dry!

A: Create a table in Excel that has the column name you want to use. For example, if you want "AAA", then put this in a couple cells in your sheet:
ColumnName
AAA

Select those two cells and go to Insert > Table and make it a table. (Check the box for "My table has headers".)
Under Design, you can name this table whatever you'd like, say, "ColNameTable".
Then in your code, you can use
Excel.CurrentWorkbook(){[Name="ColNameTable"]}[Content]{0}[ColumnName]

instead of "AAA". I.E.
#"Renamed Columns1" = Table.RenameColumns(#"Multiplied Column7",{{"Month1;BDG", Excel.CurrentWorkbook(){[Name="ColNameTable"]}[Content]{0}[ColumnName]}})

This pulls in the value of the first row (index starts at zero) of the column named ColumnName in the table ColNameTable from your current workbook.

Note: You can also use named ranges instead of creating a new table. See here: How can I reference a cell's value in a Power Query


text:
Q: Adding the constraint "at least one entry of $x$ is $100$" to a convex program I have the following optimization problem in $x \in \mathbb R^p$
$$\begin{array}{ll} \text{minimize} & a^\top x\\ \text{subject to} & x \geq 0\end{array}$$
where $x \geq 0$ means that $x_1, x_2, \dots, x_p \geq 0$. To add the condition "at least one entry of $x$ is $100$", one option is to use the following
$$(x_1−100) (x_2−100) \cdots (x_p−100)=0$$
But how do I represent this in matrix form?

I used the example from the posted link. But looks like $$(x_1−100)(x_2−100) \cdots (x_p−100)=0$$ is difficult to express in matrix multiplication as it is not linear. The alternate solution, does not guarantee that value of 100 will be achieved.

A: If $p$ is not too large, you could solve the $p$ separate reduced problems where each $x_i$ is forced to $100$.  (Actually reduce them.  Set $x_i = 100$ and eliminate it from the rest of your system.)

A: Not sure if this is what you are looking for, but an alternative approach is to use binary variables:
$$\begin{align}
   & 100 \delta_i \le x_i \le 100 \delta_i + U_i (1-\delta_i) \\
   & \sum_i \delta_i = 1\\
   & \delta_i \in \{0,1\} \\
   & 0 \le x_i \le U_i
\end{align}$$
Here $U_i$ is an upper bound on $x_i$. This formulation would make your model a MIP (Mixed Integer Programming) model. Some MIP solvers allow socalled indicator constraints. For those solvers you can write:
$$\begin{align}
   & \delta_i = 1 \Rightarrow x_i = 100 \\
   & \sum_i \delta_i = 1\\
   & \delta_i \in \{0,1\} \\
   &  x_i \ge 0
\end{align}$$
Binary variables are often used to "bypass" non-convexities.
Of course this is mainly interesting if you have other linear constraints in your model. I believe as stated we can solve it just by sorting.


text:
Q: JPA optimistic lock version handling - version value should be carried onto client side or? I'm wondering how to handle optimistic lock version property in entity class using JPA (toplink essentials) from server to client and vice versa.
Here is the scenario.

*

*From browser user send request to the server asking for individual user info to edit.

*Server processes the request and return the result to the browser. The server code looks something like:
EntityManager em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
User u = (User)em.find(User.class, myUserId);
return u; //response back to the browser
Here, my confusion is User table has "version" column for optimistic locking.
That means value of version field is also sent back to the client even though the client (me or anyone) would never use it. The version field is to be used in server side code.
So is it correct to send version number to client? Because otherwise I can't figure out how to check version number in case user clicks on "UPDATE" button on web page with modified data.
Please let me know if you need more clarification.

A: Yes, you would send the version number to the client, so that he can later send it back to the server (together with the changes he wants to do to the entity), who can use it to check for conflicting updates.
How else would the server know against which version to check? (One could also put the number in a server-side session, but that is basically a variation on the same theme). The point is that when you "check out" the version to edit, you carry the version number from that point in time along.

That means value of version field is also sent back to the client even though the client (me or anyone) would never use it.

Well, you could use it on the client. For example if the editing operation takes a long time, the client could poll once in a while if the entity has concurrently been updated, and then alert the user about it. (Similar to the "A new answer has been posted" message here on Stackoverflow).


text:
Q: Firebase function to return document result inside swift func I wrote a function to get a specific document from the Firebase Firestore. This is my code:
func getDocumentFromFirebase(collection: String, documentId: String) -> [String: String] {

    var firebaseResult = [String: String]()
    let docRef = db.collection(collection).document(documentId)

    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            var property = document.get("name") as! String
            //print("Document data string: \(property)")
            firebaseResult["name"] = property

            return firebaseResult
        } else {
            print("Document does not exist")
        }
    }
}

As you can see I would like to return the result in a Dictionary, but I get an error on my return line:

"Unexpected non-void return value in void function."

But when I move it a few lines down, returns before the Firebase call is completed and the Dictionary is empty.
I understand that I am trying to return the result in a Dictionary, inside a Void function to get the document from Firebase.
My question is, how do I return the result of the Firebase call in the Dictionary after the document is retrieved?
Thanks!

A: You need a completion as you can't return a value inside fireStore closure
func getDocumentFromFirebase(collection: String, documentId: String,completion:@escaping(([String: String]?) -> ()))   {
    var firebaseResult = [String: String]()
    let docRef = db.collection(collection).document(documentId)
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            var property = document.get("name") as! String
            //print("Document data string: \(property)")
            firebaseResult["name"] = property
            completion(firebaseResult)
        } else {
            print("Document does not exist")
            completion(nil)
        }
    }
}

call
getDocumentFromFirebase(_,_) { res in

}

A: the function calling the getDocumentFromFirebase would have access to the what's passed in the completion(....)
the "res" as the above answer details is what was passed into the completion as a parameter which would be the result from firebase this is an example I have implemented
func getUser(userId: String, completion: @escaping((_ user: User?) -> ())) {
    let docRef = db.collection(Collection.users.rawValue).document(userId)

    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let returnedUser = try? document.data(as: User.self)
            completion(returnedUser)
        } else {
            print("user doesn't exist")
            completion(nil)
        }
    }
}


text:
Q: KeyError: "['Close'] not found in axis" I am making an algorithm with ML in Python but I came across this error.
KeyError: "['Close'] not found in axis"
Here is my code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.metrics import precision_score, recall_score, f1_score
from sklearn.metrics import plot_roc_curve

plt.style.use("seaborn")
%matplotlib inline

data = pd.read_csv("data.csv")
data.head()

X = data.drop(columns="Close", axis=1)
y = data["Close"].values


text:
Q: How to get data from an array of specific paths in Firebase? I'm working with dates now, and I structured the database like this:
database[userId][work][year][month][date]

So if I want to get the working hours of an user, on a specific date, I call:
const getWorkData = (userId, year, month, date, callback) => {
    usersRef.child(`${userId}/work/${year}/${month}/${date}`).on("value", snap =>
        callback(snap.val())
    )
}

If I need just one date's data, this function works perfectly. But I want to show the user a whole week of data. Here comes the problem.
I have two possible solutions, but neither of them are practical.

//loop through an array of the week's dates

const weeksDates = [
  {year: 2018, month: 11, date: 12},
  {year: 2018, month: 11, date: 13},
  {year: 2018, month: 11, date: 14},
  {year: 2018, month: 11, date: 15},
  {year: 2018, month: 11, date: 16},
  {year: 2018, month: 11, date: 17},
  {year: 2018, month: 11, date: 18},
];

const userId = "userId";
const getWorkData = (userId, year, month, date, callback) => {
    usersRef.child(`${userId}/work/${year}/${month}/${date}`).on("value", snap =>
        callback(snap.val())
    )
}

//loop through the dates, and fetch data at each date

const getWorkDataOfWeek = (userId, weeksDates) => {
  const data = [];
  const pushToData = value => data.push(value)
  weeksDates.forEach(dateObj => {
    const { year, month, date } = dateObj;
    getWorkData(userId, year, month, date, pushToData)
  })
}

//fetch the whole database, and filter it

const getWorkDataOfWeek = (userId, weeksDates, callback) => {
  usersRef.child(userId).on("value", snap => {
    const workData = snap.val();
    const data = weeksDates.map(dateObj => {
      const { year, month, date } = dateObj;
      return workData[year][month][date];
    })
    callback(data)
  })
}

The problem with the first method is that it creates too much requests. The problem with the second is that it requests too large amount of data. Is there a solution for firebase which is similar to the first except that it just requests once?

A: Principle of an object database like Firebase is to be able to arrange the data the way you want and will need it for futur use.  This prevent heavy CPU loads when retrieving data and so on, you achieve this by doing denormalization.  This meanss you anticipate how you would need the data back and write it has so.  So you need data by week and by date, write the data has week and date in the first place.
Something like this:
/UID/year/month/date
/UID/year/week/date . ( you should already know that week is 12, 13 ...)
With Firebase it's really easy to save data on multiple path at once, you use multi paths updates.
Articles about denormalization: https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html
Articles about multi path updates: https://medium.com/@danbroadbent/firebase-multi-path-updates-updating-denormalized-data-in-multiple-locations-b433565fd8a5
P.S. I would also add that it seems to me that you want to read that data only when you need it so use once instead of on.


text:
Q: how to make an axios get server side call then send to client I am getting cors issues when I make this request on the client side:
  componentDidMount = () => {
    console.log('app loading...');
    axios.get('some/random/api').then((res) => {
      console.log(res, 'res');
    })
  }

this is part of my server side code:
app.use('/', express.static('public'));

axios.get(url, {
        "headers": {"Authorization": "Bearer "}
      })
      .then(response => {
        console.log(response)
       //I WANT TO SEND THE RESPONSE HERE TO THE REACT CLIENT
      })
      .catch(err => {
        console.log(err)
      })

how can I then pick this data up on the client side?
thanks

A: *

*Install cors library:
npm install --save cors

*Import it to your express project: const cors = require('cors');

*Attach cors to your express app, before routes definitions: app.use(cors())
const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())

app.get('/', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
});

A: As a quick fix, you can also install this chrome extension

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

However, the long-lasting solution is using the yarn add cors and adding it to your root file in express js.  as highlighted above by @Artem Mirchenko

A: you need to wrap your server code in a route, as per artem's answer likey so:
app.get('/some/random/api', function (req, res, next) {
  // axios request to other server goes here
  axios.get(...)
    .then( other_server_response => {
      // process other server response if necessary here
      res.json({ returned_data: other_server_response });
    });
});

edit: now I look at it, I'm not sure this is what you want. Might just need to call the other service from your client and include cors info.


text:
Q: How do I stack a fixed positioned element in front of a statically positioned element? z-index won't work because they're (as I understand it) in different stacking contexts.  I don't mind using javascript or jquery to do it, I just can't figure out how to get a statically positioned element in front of a fixed positioned element.

A: You just need to make your statically positioned element position: relative; (which wont move it anywhere) and then you can use z-index to put it where you want.

A: You need to define a stacking context in (probably) the parent elements. Simply setting position:relative will enable stacking (z-index requires positioning) - whereas an element with the default position:static can not be stacked.
Trace your elements up the tree and find where two siblings can be layered, give them a relative position and a z-index;
Javascript wont be useful here.


text:
Q: How to iterate through keys of object with Yup Could someone suggest best way to iterate through generically created form using Yup?
So in my application user can add infinite amount of small forms asking only for client name(required), surname and age. I used Formik to generically create them and validation runs only in the end during submission of all forms at once. The final format of values coming from Formik is:
 `` {
     0:{name:"Valentin", surname:"Ivanov", age:26}
     1:{name:"Sam"}
     ...}``

Therefore I need to iterate through every object and validate whether "name" field is not undefined(required) and has length more than 5 characters with Yup. But I struggle to find a way how to do so even after trying couple things with lazy(). I use Formik v1.5.8, Yup v0.28.1 and Typescript v3.6.2
Cheers

A: I don't know Yup, but I'll suggest this code as a generic solution to iterate over objects:
const yourObject: any = {
  0: { name: 'Valentin', surname: 'Ivanov', age: 26 },
  1: { name: 'Sam' }
}

for (const propertyName in yourObject) {
  if (yourObject[propertyName]) {
    // Do anything with your object
    // For example:
    console.log(yourObject[propertyName].name);
  }
}


text:
Q: Cómo sacar una alerta cuando varios elementos se alinean en el código de esta pregunta? He estado intentando crear una alerta cuando los siguientes #div se muestran a la vez:

*

*layer0_1

*layer1_1

*layer2_1

*layer3_1

*layer4_1

*layer5_1
Sé que os resultará sencillo pero no sé por qué me esta presentando tantísimos problemas, seguro que es un error muy básico.

$(this).ready(function()
{
   if ($('#layer0_1').is(':visible'))
   {
alert(new Date());
   }

});

function mostrarEsconder(selector, tiempo, inicial) {
  var $els = $('div[id^=' + selector + ']'),
      i = inicial,
      len = $els.length;

  $els.not( ':eq('+i+')' ).hide(); /*Ocultamos los que no sean el inicial */
  setInterval(function () {
    $els.eq(i).fadeOut(0, function () {
      i = (i + 1) % len;
   $("#layer6_").text($els.eq(i).attr('id'));
      $els.eq(i).fadeIn(0);
    })
  }, tiempo)
}

jQuery(function() {
  /* Este sería el número que debería proporcionar el código del lado del servidor,
   por ejemplo en PHP: round(microtime(true) * 1000)*/
   var startdate = " May 20 2016 21:49:57 GMT+0200  ",
   timestamp =  new Date() - new Date(startdate) ;

  mostrarEsconder('layer0_', 300,  Math.floor(timestamp / 300) % 11),
  mostrarEsconder('layer1_', 300, Math.floor(timestamp / 300) % 12),
  mostrarEsconder('layer2_', 300, Math.floor(timestamp / 300) % 13),
  mostrarEsconder('layer3_', 300, Math.floor(timestamp / 300) % 14),
  mostrarEsconder('layer4_', 300, Math.floor(timestamp / 300) % 15),
  mostrarEsconder('layer5_', 300, Math.floor(timestamp / 300) % 30);
});
.numero {
  position: absolute;
  color: black;
  left: 20px;
  top: 20px;
  z-index: 500; }

.numero1 {
  position: absolute;
  color: blue;
  left: 20px;
  top: 40px;
  z-index: 500; }

.numero2 {
  position: absolute;
  color: red;
  left: 20px;
  top: 60px;
  z-index: 500; }

.numero3 {
  position: absolute;
  color: green;
  left: 20px;
  top: 80px;
  z-index: 500; }

.numero4 {
  position: absolute;
  color: orange;
  left: 20px;
  top: 100px;
  z-index: 500; }

.numero5 {
  position: absolute;
  color: cyan;
  left: 20px;
  top: 120px;
  z-index: 500; }

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

A: No hay ningún evento que se genere tras mostrarse u ocultarse un elemento por lo que deberías ejecutar esta comprobación cada vez que muestres un elemento:

function checkVisible()
{
  if ($('#layer0_1').is(':visible') &&
      $('#layer1_1').is(':visible'))
  {
    alert(new Date());
  }

};

function mostrarEsconder(selector, tiempo, inicial) {
  var $els = $('div[id^=' + selector + ']'),
      i = inicial,
      len = $els.length;

  $els.not( ':eq('+i+')' ).hide(); /*Ocultamos los que no sean el inicial */
  setInterval(function () {
    $els.eq(i).fadeOut(0, function () {
      i = (i + 1) % len;
      $("#layer6_").text($els.eq(i).attr('id'));
      $els.eq(i).fadeIn(0, checkVisible);
    })
  }, tiempo)
}

jQuery(function() {
  /* Este sería el número que debería proporcionar el código del lado del servidor,
       por ejemplo en PHP: round(microtime(true) * 1000)*/
  var startdate = " May 20 2016 21:49:57 GMT+0200  ",
      timestamp =  new Date() - new Date(startdate) ;

  mostrarEsconder('layer0_', 300,  Math.floor(timestamp / 300) % 11),
    mostrarEsconder('layer1_', 300, Math.floor(timestamp / 300) % 12),
    mostrarEsconder('layer2_', 300, Math.floor(timestamp / 300) % 13),
    mostrarEsconder('layer3_', 300, Math.floor(timestamp / 300) % 14),
    mostrarEsconder('layer4_', 300, Math.floor(timestamp / 300) % 15),
    mostrarEsconder('layer5_', 300, Math.floor(timestamp / 300) % 30);
});
.numero {
  position: absolute;
  color: black;
  left: 20px;
  top: 20px;
  z-index: 500; }

.numero1 {
  position: absolute;
  color: blue;
  left: 20px;
  top: 40px;
  z-index: 500; }

.numero2 {
  position: absolute;
  color: red;
  left: 20px;
  top: 60px;
  z-index: 500; }

.numero3 {
  position: absolute;
  color: green;
  left: 20px;
  top: 80px;
  z-index: 500; }

.numero4 {
  position: absolute;
  color: orange;
  left: 20px;
  top: 100px;
  z-index: 500; }

.numero5 {
  position: absolute;
  color: cyan;
  left: 20px;
  top: 120px;
  z-index: 500; }

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

En este ejemplo compruebo que estén visibles los dos primeros divs con "1".

A:

$(document).ready(function()
{
   if ($('#layer0_1').is(':visible'))
   {
alert(new Date());
   }

});

function mostrarEsconder(selector, tiempo, inicial) {
  var $els = $('div[id^=' + selector + ']'),
      i = inicial,
      len = $els.length;

  $els.not( ':eq('+i+')' ).hide(); /*Ocultamos los que no sean el inicial */
  setInterval(function () {
    $els.eq(i).fadeOut(0, function () {
      i = (i + 1) % len;
   $("#layer6_").text($els.eq(i).attr('id'));
      $els.eq(i).fadeIn(0);
    })
    if ($els.eq(i) === 1){
    alert('1');
     }
  }, tiempo)
}

jQuery(function() {
  /* Este sería el número que debería proporcionar el código del lado del servidor,
   por ejemplo en PHP: round(microtime(true) * 1000)*/
   var startdate = " May 20 2016 21:49:57 GMT+0200  ",
   timestamp =  new Date() - new Date(startdate) ;

  mostrarEsconder('layer0_', 300,  Math.floor(timestamp / 300) % 11),
  mostrarEsconder('layer1_', 300, Math.floor(timestamp / 300) % 12),
  mostrarEsconder('layer2_', 300, Math.floor(timestamp / 300) % 13),
  mostrarEsconder('layer3_', 300, Math.floor(timestamp / 300) % 14),
  mostrarEsconder('layer4_', 300, Math.floor(timestamp / 300) % 15),
  mostrarEsconder('layer5_', 300, Math.floor(timestamp / 300) % 30);
});
.numero {
  position: absolute;
  color: black;
  left: 20px;
  top: 20px;
  z-index: 500; }

.numero1 {
  position: absolute;
  color: blue;
  left: 20px;
  top: 40px;
  z-index: 500; }

.numero2 {
  position: absolute;
  color: red;
  left: 20px;
  top: 60px;
  z-index: 500; }

.numero3 {
  position: absolute;
  color: green;
  left: 20px;
  top: 80px;
  z-index: 500; }

.numero4 {
  position: absolute;
  color: orange;
  left: 20px;
  top: 100px;
  z-index: 500; }

.numero5 {
  position: absolute;
  color: cyan;
  left: 20px;
  top: 120px;
  z-index: 500; }

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

A: Solo compruebas si el div es visible al cargar la página, tienes que comprobarlo siempre que cambien los valores:

function mostrarEsconder(selector, tiempo, inicial) {
  var $els = $('div[id^=' + selector + ']'),
    i = inicial,
    len = $els.length;

  $els.not(':eq(' + i + ')').hide(); /*Ocultamos los que no sean el inicial */
  setInterval(function() {
    if ($('#layer0_1').is(':visible')) {
      alert(new Date());
    }
    $els.eq(i).fadeOut(0, function() {
      i = (i + 1) % len;
      $("#layer6_").text($els.eq(i).attr('id'));
      $els.eq(i).fadeIn(0);
    })
    if ($els.eq(i) === 1) {
      alert('1');
    }
  }, tiempo)
}

jQuery(function() {
  /* Este sería el número que debería proporcionar el código del lado del servidor,
   por ejemplo en PHP: round(microtime(true) * 1000)*/
  var startdate = " May 20 2016 21:49:57 GMT+0200  ",
    timestamp = new Date() - new Date(startdate);

  mostrarEsconder('layer0_', 300, Math.floor(timestamp / 300) % 11),
    mostrarEsconder('layer1_', 300, Math.floor(timestamp / 300) % 12),
    mostrarEsconder('layer2_', 300, Math.floor(timestamp / 300) % 13),
    mostrarEsconder('layer3_', 300, Math.floor(timestamp / 300) % 14),
    mostrarEsconder('layer4_', 300, Math.floor(timestamp / 300) % 15),
    mostrarEsconder('layer5_', 300, Math.floor(timestamp / 300) % 30);
});
.numero {
  position: absolute;
  color: black;
  left: 20px;
  top: 20px;
  z-index: 500;
}

.numero1 {
  position: absolute;
  color: blue;
  left: 20px;
  top: 40px;
  z-index: 500;
}

.numero2 {
  position: absolute;
  color: red;
  left: 20px;
  top: 60px;
  z-index: 500;
}

.numero3 {
  position: absolute;
  color: green;
  left: 20px;
  top: 80px;
  z-index: 500;
}

.numero4 {
  position: absolute;
  color: orange;
  left: 20px;
  top: 100px;
  z-index: 500;
}

.numero5 {
  position: absolute;
  color: cyan;
  left: 20px;
  top: 120px;
  z-index: 500;
}

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15


text:
Q: TripleDES encryption working fine in java but not in c# i am facing weak key error while doing tripleDES encryption.Code working fine in java but giving error in C# .net.
i have java code in which TripleDES ecryption is working fine i need to convert my java code in c#.i am facing Weak key error during conversion.Below both java and c# code given.
1) Java Code
public class TripleDES {
    private DESedeKeySpec desKeySpec;

    public TripleDES(String key) {
        try {
            byte[] keyBytes = { (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02,
                    (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02,
                    (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02,
                    (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02,
                    (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02,
                    (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02};

            this.desKeySpec = new DESedeKeySpec(keyBytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public byte[] encrypt(byte[] origData) {
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
            SecretKey key = factory.generateSecret(this.desKeySpec);
            Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(origData);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public byte[] decrypt(byte[] crypted) {
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
            SecretKey key = factory.generateSecret(this.desKeySpec);
            Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");  //DESede/CBC/PKCS5Padding
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(crypted);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        TripleDES des = new TripleDES("");

      byte[] data = { (byte)0x04, (byte)0x12, (byte)0x05, (byte)0xFF, (byte)0xFB, (byte)0xA6, (byte)0x66, (byte)0xCF};
      //byte[] data = { (byte)0x04, (byte)0x12, (byte)0x15, (byte)0xAF, (byte)0xFD, (byte)0xD8, (byte)0x88, (byte)0xBB};

//-----------------Edited-----------------
String text = new BigInteger(1, data).toString(16);
System.out.println("Before encryption = " +text);
    byte[] crypted = des.encrypt(data);
String text1 = new BigInteger(1, crypted).toString(16);
    System.out.println("Encrypted = " +text1);
byte[] decrypted = des.decrypt(crypted);
String text2 = new BigInteger(1, decrypted).toString(16);
    System.out.println("Decrypted = " +text2);
    }

}

2) C# Code
    static void Main(string[] args)
    {
        String Data = EncryptDES("041205FFFBA666CF");
    }

    public static string EncryptDES(string InputText)
    {
        byte[] key = new byte[] { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
        byte[] clearData = System.Text.Encoding.UTF8.GetBytes(InputText);
        MemoryStream ms = new MemoryStream();
        TripleDES alg = TripleDES.Create();
        alg.Key = key;
        alg.Mode = CipherMode.ECB;
        CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(clearData, 0, clearData.Length);
        cs.FlushFinalBlock();
        byte[] CipherBytes = ms.ToArray();
        ms.Close();
        cs.Close();
        string EncryptedData = Convert.ToBase64String(CipherBytes);
        return EncryptedData;

    }

Key: 02020202020202020202020202020202
Data : 041205FFFBA666CF
Result : A334C92CEC163D9F
Can anyone please write code in c# which produce result same as java.

A: Before I start, I want to say that I do not recommend or endorse you to follow this way for forcing TripleDES to use a key it thinks is weak, however, given that you are using it for Decryption only, here is a way to do it using Reflection.
Firstly, you must 'force' the TripeDES class to take the weak key you want to use.  To do this, we use Reflection to bypass the check for a weak key that is performed when you attempt to set the key (alg.Key = key) and set the member variable directly:
//alg.Key = key; - THIS IS REPLACED BY THE BELOW
FieldInfo keyField = alg.GetType().GetField("KeyValue", BindingFlags.NonPublic | BindingFlags.Instance);
keyField.SetValue(alg, key);

The key value of TripleDES will now be set to your weak key (alg.Key);
Next you have a minor mistake, in that you have forgotten to turn off padding:
alg.Mode = CipherMode.ECB;
alg.Padding = PaddingMode.None; // Add this, as the default padding is PKCS7

Finally, there will be a further check for a weak key when creating the Decryptor, so we must use Reflection again to bypass the check and create the ICryptoTransform:
// Comment out the below line and use the code below
// CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
ICryptoTransform Decryptor;
MethodInfo createMethod = alg.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic | BindingFlags.Instance);
Decryptor = createMethod.Invoke(alg, new object[] { alg.Key, alg.Mode, alg.IV, alg.FeedbackSize, 1 }) as ICryptoTransform;
CryptoStream cs = new CryptoStream(ms, Decryptor, CryptoStreamMode.Write);

The code will now run and accept weak keys, and perform the decryption you are looking for.
However, it does not look to me that the output is what you are expecting:
?Data
"4aU3DcHkiCTEywpiewWIow=="

At least now though you are able to use whichever key you want with TripleDES.

A: A 3DES key is a 24-byte value which is broken down two three 8-byte values: key0, key1, key2.
Because 3DES is DES_Encrypt(key2, DES_Decrypt(key1, DES_Encrypt(key0, data))) any time key1 is equal to key2 or key0 the algorithm is reduced to DES.  This is what .NET's TripleDES is warning you about.
The proper test here should account for clearing (or setting, or fixing) the parity bits in each byte, but a hand-waved version is:
SymmetricAlgorithm alg;
IEnumerable<byte> key0 = key.Take(8);
IEnumerable<byte> key1 = key.Skip(8).Take(8);
IEnumerable<byte> key2 = key.Skip(16);

if (key0.SequenceEquals(key1))
{
    alg = DES.Create();
    alg.Key = key2.ToArray();
}
else if (key1.SequenceEquals(key2))
{
    alg = DES.Create();
    alg.Key = key0.ToArray();
}
else
{
    alg = TripleDES.Create();
    alg.Key = key;
}

To replace your two liner:
TripleDES alg = TripleDES.Create();
alg.Key = key;


text:
Q: ffmpeg RTSP stream decoding memory leak I need to decode rtsp stream from Ip camera using ffmpeg, below is the code for decoder
ffmpeg_decoder.h
class ffmpeg_decoder
{
public:
    ffmpeg_decoder();
    int initial(QString & url);
    int h264Decodec();
    void close_stream();
    virtual ~ffmpeg_decoder();
    AVPicture  picture;
    int width;
    int height;
    QMutex mutex;
    QImage imageDecoded;

private:
    AVFormatContext *pFormatCtx;
    AVCodecContext *pCodecCtx;
    AVFrame *pFrame;
    AVPacket packet;

    SwsContext * pSwsCtx;
    int videoStream;

    QString rtspURL;

};

ffmpeg_decoder.cpp
ffmpeg_decoder::ffmpeg_decoder()
{
    pCodecCtx = NULL;
    videoStream=-1;

}

ffmpeg_decoder::~ffmpeg_decoder()
{
    sws_freeContext(pSwsCtx);
}

int ffmpeg_decoder::initial(QString & url)
{
    int err;
    rtspURL=url;
    AVCodec *pCodec;
    av_register_all();
    avformat_network_init();
    pFormatCtx = avformat_alloc_context();
    pFrame = av_frame_alloc();
    err = avformat_open_input(&pFormatCtx, rtspURL.toStdString().c_str(), NULL,
                              NULL);
    if (err < 0)
    {
        printf("Can not open this file");
        return -1;
    }
    if (avformat_find_stream_info(pFormatCtx,NULL) < 0)
    {
        printf("Unable to get stream info");
        return -1;
    }
    int i = 0;
    videoStream = -1;
    for (i = 0; i < pFormatCtx->nb_streams; i++)
    {
        if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoStream = i;
            break;
        }
    }
    if (videoStream == -1)
    {
        printf("Unable to find video stream");
        return -1;
    }
    pCodecCtx = pFormatCtx->streams[videoStream]->codec;

    width=pCodecCtx->width;
    height=pCodecCtx->height;
    avpicture_alloc(&picture,PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height);
    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    pSwsCtx = sws_getContext(width, height, PIX_FMT_YUV420P, width,
            height, PIX_FMT_RGB24,
            SWS_BICUBIC, 0, 0, 0);

    if (pCodec == NULL)
    {
        printf("Unsupported codec");
        return -1;
    }
    printf("video size : width=%d height=%d \n", pCodecCtx->width,
           pCodecCtx->height);
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
    {
        printf("Unable to open codec");
        return -1;
    }
    printf("initial successfully");
    return 0;
}

int ffmpeg_decoder::h264Decodec()
{
    int frameFinished=0;
   // while (av_read_frame(pFormatCtx, &packet) >= 0)

    if(av_read_frame(pFormatCtx, &packet) >= 0)
    {
        if(packet.stream_index==videoStream)
        {
            avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
            if (frameFinished)
            {
                printf("***************ffmpeg decodec*******************\n");
                mutex.lock();
                int rs = sws_scale(pSwsCtx, (const uint8_t* const *) pFrame->data,
                                   pFrame->linesize, 0,
                                   height, picture.data, picture.linesize);

               imageDecoded = QImage();
               imageDecoded= QImage(this->picture.data[0],this->width,this->height,QImage::Format_RGB888);
               //imageDecoded = imageDecoded.copy();
                mutex.unlock();

                if (rs == -1)
                {
                    printf("__________Can open to change to des imag_____________e\n");
                    return -1;
                }
            }
        }
    }
    av_free_packet(&packet);
    av_frame_unref(pFrame);
    av_packet_unref(&packet);
    avpicture_free(&picture);

    return 1;

}

void ffmpeg_decoder::close_stream(){

    /*if (pFrame)
        av_free(&pFrame);*/

    if (pCodecCtx)
        avcodec_close(pCodecCtx);

    if (pSwsCtx)
        sws_freeContext(pSwsCtx);

    avpicture_free(&picture);

    if (pFormatCtx)
        avformat_close_input(&pFormatCtx);

}

Below is the main thread which do the decoding.
I am using Qt for creating thread and do decoding
ffmpeg_decoder * ffmpeg =  new ffmpeg_decoder();;

if(ffmpeg->initial(rtspURL)==0){
    while (1) {

        ffmpeg->h264Decodec();
        //get frame and do processing right now it disabled, and still see the memory leak.
           .......

        if(stopFlg.load()==1)
            break;

    }
    //close stream if break
    ffmpeg->close_stream();

   }
   else {

       ffmpeg->close_stream();
   }

When I run 36 thread with different URL  I can see the memory usage of the program increase over time.
I have used valgrind to detect the leak, and here is the relevant part of the log
This is the first memory leak location
=14402==    by 0x692017F: av_malloc (in /usr/lib/x86_64-linux-gnu/libavutil-ffmpeg.so.54.31.100)
==14402==    by 0x692048D: av_mallocz (in /usr/lib/x86_64-linux-gnu/libavutil-ffmpeg.so.54.31.100)
==14402==    by 0x691915E: av_frame_alloc (in /usr/lib/x86_64-linux-gnu/libavutil-ffmpeg.so.54.31.100)
==14402==    by 0x419663: ffmpeg_decoder::initial(QString&) (ffmpeg_decoder.cpp:24)
==14402==    by 0x41ABEC: RTSP_Player_Object::run() (rtsp_player_object.cpp:15)

Another
==14402== 2,176 bytes in 16 blocks are indirectly lost in loss record 23,113 of 23,379
==14402==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14402==    by 0x7780A4E: QImageData::create(unsigned char*, int, int, int, QImage::Format, bool, void (*)(void*), void*) (in /home/vapplica/Qt5.11.1/5.11.1/gcc_64/lib/libQt5Gui.so.5.11.1)
==14402==    by 0x7780C30: QImage::QImage(unsigned char*, int, int, QImage::Format, void (*)(void*), void*) (in /home/vapplica/Qt5.11.1/5.11.1/gcc_64/lib/libQt5Gui.so.5.11.1)
==14402==    by 0x419B21: ffmpeg_decoder::h264Decodec() (ffmpeg_decoder.cpp:96)

I have check the documentation and sample on ffmpeg site, and I think I am releasing the allocated memory, but still I can see the memory leak when I run the program.


text:
Q: Get all Images except "base image" and "small image" I would like to output all Images except 'base image' and 'small image' for an image Slider. Right now this code below outputs all Images:
    <?php
    $_product = $this->getProduct();
    $_helper = $this->helper('catalog/output');
?>
<?php if ($_product->getImage() != 'no_selection' && $_product->getImage()): ?>

            <?php foreach ($this->getGalleryImages() as $_image): ?>

                  <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile()); ?>" class="sliderImage" alt="<?php echo $this->escapeHtml($_image->getLabel()) ?>" />

            <?php endforeach; ?>

<?php endif; ?>

What is the best way to display all Images not tagged with anything?

A: based on the comments....
You can go to the backend and check the "Exclude" checkbox for the images you don't want shown in the media gallery.
All the images that have this "exclude" checkbox checked are ignored by the getGalleryImages method.


text:
Q: RuntimeError: can't add a new key into hash during iteration in Rack I built a pretty small Rails 5.1.4 (Ruby 2.3.1) application. Once I've deployed it to production, I'm getting this particular error from time to time:
RuntimeError: can't add a new key into hash during iteration
Pointing here:
# rack/request.rb, line 67
def set_header(name, v)
  @env[name] = v
end

I understand, this error happens when you're attempting to add new key to the hash while iterating over that hash. Since @env is a hash, it makes sense. But:

*

*in a stacktrace I found nothing related to iterations over @env, it's a dead simple chain of app.call(env) calls.

*this error occurs not always, but just once per hour or two, so this is also super weird to me

*I can't reproduce it locally: I've tried to load server with multiple request hits, assuming this might be thread-safety issue, but locally it works like a charm...

Full stacktrace only consists of rack middlewares can be found here:
https://gist.github.com/Nattfodd/e513122400b4115a653ea38d69917a9a
Gemfile.lock:
https://gist.github.com/Nattfodd/a9015e9204544302bf3959cec466b715
Server is running with puma, config is very simple: just amount of threads and workers:
threads 0, 5
workers 5

My current ideas are:

*

*one of monitoring gems has a bug (sentry-raven, new_relic)

*concurrent-ruby has a bug (I read about one, but it was fixed in 1.0.2, and actual version I'm using for Puma is 1.0.5)

*something super stupid, I missed, but I have no idea where to look, since the controller's action contains 3 lines of code and application config is mostly default...

*this is something config-related, since backtrace does not contain the controller at all...

A: can you can paste the full stack-trace?
My assumption is set_header is getting called from method which iterating env.


text:
Q: horizontal slider container positions up when page is called from url hash If you view the page here @ http://8020indie.com/wp-content/uploads/TEC/ ,
you will see everything works fine, but when you access the page with a hash, such as http://8020indie.com/wp-content/uploads/TEC/index.htm#content2 , the horizontal positioning of the content div is off. Any ideas would be greatly appreciated. Thanks
$(document).ready(function(){
    var width = '1000';
    var slides = 3;
    $('.main_inner').css({
        width: slides * width,
    });
    $('a.tab_link').click(function(){
        var contentNum = $(this).attr('rel');
        var marginToScroll = width * contentNum - width;
        $('.main_inner').animate({
        marginLeft: '-' + marginToScroll,
        }, 1000);
        return false;
    });
    jQuery('#parallax1').jparallax({mouseport:jQuery('#content1')},{xtravel: '15px',                     ytravel: '0px'},{xtravel: '15px', ytravel: '0px'}, {xtravel: '15px', ytravel: '0px'});
    jQuery('#parallax2').jparallax({mouseport:jQuery('#content1')},{xtravel: '15px', ytravel: '0px'},{xtravel: '15px', ytravel: '0px'}, {xtravel: '15px', ytravel: '0px'});
    jQuery('#parallax3').jparallax({mouseport:jQuery('#content1')},{xtravel: '15px', ytravel: '0px'},{xtravel: '15px', ytravel: '0px'}, {xtravel: '15px', ytravel: '0px'});
});

function changeMySrc(i) {
    if (i == 1) {
        document.getElementById("ui_tab").src="images/buttonUiOn.png";
        document.getElementById("design_tab").src="images/buttonDesignOff.png";
        document.getElementById("integration_tab").src="images/buttonIntegrationOff.png";
    }
    if (i == 2) {
        document.getElementById("ui_tab").src="images/buttonUiOff.png";
        document.getElementById("design_tab").src="images/buttonDesignOn.png";
        document.getElementById("integration_tab").src="images/buttonIntegrationOff.png";
    }
    else if (i == 3) {
        document.getElementById("ui_tab").src="images/buttonUiOff.png";
        document.getElementById("design_tab").src="images/buttonDesignOff.png";
        document.getElementById("integration_tab").src="images/buttonIntegrationOn.png";
    }
}

A: As you probably know, if the hash matches the name of an "a" tag, such as <a name="content2"/> , the browser would scroll down to it automatically.
In HTML5, if the hash matches the ID of any DOM object, the browser will scroll down to it.
That's not exactly what's happening here, but my guess is that the final position of your content2 div is getting messed up due to that auto-scrolling. Do you really have to use a hash that matches the ID of the div? To avoid that, for example, you can use window.location.hash and map that to the actual div ID.


text:
Q: Call different methods by type in Java private void foo(int a, int b) {
  // do something
  System.out.println(add(a, b));
  // do something else
}

private void bar(String a, String b) {
  // do something
  System.out.println(add(a, b));
  // do something else
}

private int add(int a, int b) {
  return a + b;
}

private String add(String a, String b) {
  return a.concat(b);
}

Is it possible to merge duplicated logic in foo and bar into one function?
e.g.
private <T> void baz(T a, T b) {
  // do something
  System.out.println(add(a, b));
  // do something else
}

-- EDIT --
Just tried to put a simple example to describe my question.
Actually in my real code I don't need the return type, the functions are like following:
void func(Integer a);
void func(String a);
void func(MyEnum a);
void func(MyClass a);
void func(List<MyClass> a);

And I'd like to have a function like:
private <T> void baz(T a) {
  // do something
  func(a);
  // do something else
}

So I don't have to write the same logic multiple times.

A: Your baz code is valid, but won't work for your case because generic parameters get reduced to Object at runtime, so it needs to be resolved at compile time. To be able to do that, you'd need a common interface like Addable, then you could declare it
private <T extends Addable> void baz(T a, T b) {
  // do something
  System.out.println(add(a, b));
  // do something else
}

but you wouldn't be able to call it with int or String because those don't implement Addable; you could wrap them, but not much gained in what you're trying to do.
So in short: no, not possible; you need to design around this.
interface Addable<T extends Addable<T>> { T add(T to Add); }

class IntAddable implements Addable<IntAddable> {
  Integer value;
  Integer add(IntAddable toAdd {
    return new IntAddable(value + to Add.value);
 }
}
IntAddable a = new IntAddable(1);
IntAddable b = new IntAddable(2);
IntAddable sum = baz(a, b);
// assuming an analogue class for String
StringAddable concatted = baz(s1, s2);

A: No, you can't do this as you've written it.
The biggest blocker (as I see it) is that add(String,String) returns an object, but add(int,int) returns a primative(int), so there's a problem with return type.
But I think you are over complicating things here. Why can't the two add functions could stand on their own? Do you really need a generic baz function?


text:
Q: Could not create epoll instance. errno=24 what does this runtime-error mean?
I already googled it, some say, it belongs to timers, other say its a socket error and more say, it belongs to pictures. I have sockets and timers (lot of timers) and i have no idea, which of these causes it. SOmetimes it works for over an hour, and other times just for 5 minutes. Any Ideas?
A basic impression of what this error is about is enough. If i would post all the code, where it could happen, this page  would be multiple kilometres long ( a little extreme of course, but it is lot of code.)
Found right now, it could belong to too many open files but im not using any extern files in my app.
Seems to be a memory leak, belonging to this part:
public static Runnable connection() throws IOException {
    Log.e("Communication", "connection");

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();
            try {
                serv = new ServerSocket(port);                                                                      sock = serv.accept();
                reader();                                                                               } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
    return null;

A: After deleting a part of the code above everything works fine again. Deleted the looper.prepare() and my app does not die anymore.

A: public static void sendJsonList(final List<String> jsonStrlist,
        final String resturl) {
    Thread t = new Thread() {
        public void run() {
            Looper.prepare();
            /* Your HTTP clients code */
            try {
                for (String jsonStr : jsonStrlist) {
                    /* Loop logic */
                    response = client.execute(post);
                    if (response != null) {
                        /*reponse handler logic */
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            Looper.loop();
        }
    };

    t.start();
}


text:
Q: Is there a way to take a snap shot of a uploaded file ex PDF, DOCX and save it to server as an image in PHP? I have a form and that allows you to upload your resume with a pdf, docx ext.  I would like to save their ip as an image and turn their uploaded file also into an image and send the images to hr in email.
Any suggestions on how to best get this done?  All with PHP

A: The PDF part is easy using PHP and ImageMagick.
I am not aware of anything that creates images from DOCXs.
Out of interest, why would you want to send HR the images rather than the original documents?


text:
Q: JSON parsing dynamic button I have a json in this format:
        [{
    "name": "Selection",
    "link": ["https://d1u5p3l4wpay3k.cloudfront.net/testSelect.ogg"]
},
{
    "name": "Introduction",
    "link": ["https://d1u5p3l4wpay3k.cloudfront.net/introSelect.ogg",
        "https://d1u5p3l4wpay3k.cloudfront.net/introSelect2.ogg".ogg"
    ]
},
{
    "name": "Abilities",
    "link": ["https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg",
        "https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg",
        "https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg",
        "https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg"
    ]
}]

i would like to create activity where the button are created depending on link given in that json for example first key is 1 button second key is 2 while for 3rd one 4 button
this is my get_data()
 private void getData() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading...");
    progressDialog.show();

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);

                    Image image = new Image(); // this class has getter and setter
                    image.setVoicline(jsonObject.getString("name"));
                    image.setLarge(jsonObject.getString("link"));
                    imageList.add(image);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

my output for now:

im trying to create soundboard for some game characters each link is sound it make clicking on a button would play that sound
this is full code for my soundboard_activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_soundboard);

    mList = findViewById(R.id.main_list);

    imageList = new ArrayList<>();
    adapter = new SoundAdapter(getApplicationContext(),imageList);

    linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());

    mList.setHasFixedSize(true);
    mList.setLayoutManager(linearLayoutManager);
    mList.addItemDecoration(dividerItemDecoration);
    mList.setAdapter(adapter);

    getData();

}

private void getData() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading...");
    progressDialog.show();

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);
                    JSONArray jsonArrayLink = jsonObject.getJSONArray("link");

                    Image image = new Image();
                    image.setVoicline(jsonObject.getString("name"));
                    for (int j = 0; j < jsonArrayLink.length(); j++) {
                        String link = jsonArrayLink.getJSONObject(j).toString();
                        image.setLarge(link);
                        imageList.add(image);
                    }

                    imageList.add(image);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}}

this is exception error
screenshot
and this is my Recycleview adapter
public class SoundAdapter extends RecyclerView.Adapter {
    private Context context;
    private List list;
public SoundAdapter(Context context, List<Image> list) {
    this.context = context;
    this.list = list;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Image image = list.get(position);
    holder.vname.setText(image.getVoicline());
    //holder.link.setText(image.getLarge());
}

@Override
public int getItemCount() {
    return list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView vname,link;

    public ViewHolder(View itemView) {
        super(itemView);

        vname = itemView.findViewById(R.id.vname);
        link = itemView.findViewById(R.id.play);

    }
}}

my image model getter setter
    public Image(String name, String small, String medium, String large, String timestamp, String voicline) {
    this.name = name;
    this.small = small;
    this.medium = medium;
    this.large = large;
    this.timestamp = timestamp;
    this.voicline = voicline;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSmall() {
    return small;
}

public void setSmall(String small) {
    this.small = small;
}

public String getMedium() {
    return medium;
}

public void setMedium(String medium) {
    this.medium = medium;
}

public String getLarge() {
    return large;
}

public void setLarge(String large) {
    this.large = large;
}

public String getTimestamp() {
    return timestamp;
}

public void setTimestamp(String timestamp) {
    this.timestamp = timestamp;
}

public String getVoicline() {
    return voicline;
}

public void setVoicline(String voicline) {
    this.voicline = voicline;
}}

A: After you have the initial JSON array you need to query the JSON object:
JSONObject jsonObject = response.getJSONObject(i);

this should be getting the following similar block each time you go though the loop:
{"name": "Introduction",
"link": ["https://d1u5p3l4wpay3k.cloudfront.net/introSelect.ogg",
    "https://d1u5p3l4wpay3k.cloudfront.net/introSelect2.ogg".ogg"
]}

You need to something like this to grab the "link" part of the object and assign it to JSONArray since we know this is an array we want:
JSONArray jsonArrayLink = jsonObject.getJSONArray("link");

And again you can set a for loop to get each item of this array and save it to a string:
for (int i = 0; i < jsonArrayLink.length(); i++) {
    String link = jsonArrayLink.getJSONObject(i).toString();
    // do what you want with the string
}

Extra tip for JSON:
It is good practice to do the following:
String testJSON = attributes.has("test") ? attributes.getString("test") : "";

Rather then:
String testJSON = jsonObject.getString("test");

This will make a check to see if it has that item, if it doesn't then it will set the variable to empty string "" rather than creating an error if nothing is found.


text:
Q: Order of polygon vertices in general GIS: clockwise or counterclockwise Two days ago I asked a question about the internal storing order for the vertices of a polygon in ESRI shapefiles. That question was answered (Are polygons stored clockwise or counterclockwise in a shapefile?) and it was also answered in an old post (Polygon creation (Clockwise rotation or not))
But now my question is more general, and I don't know if it has an unique answer.
Is the clockwise order only for ESRI shapefiles or for general GIS formats?
And what about the internal representation for a GIS software?
For example, if I use QGIS and I read a *.shp containing polygons I suppose the internal representation of the outer bound is clockwise as in the original shapefile, but what about for all the file formats supported by QGIS?
And for ArcGIS?
And in the case there exists a file format with polygons stored in counterclockwise, if these files are loaded in QGIS, ArcGIS, etc., is the orientation changed internally, so if I read the data using PyQGIS, for example, the polygons are clockwise ordered?
My purpose is to write a plugin for QGIS, but the source of data can be ESRI shapefiles or other formats. As I need to check the angles between consecutive sides of polygons using their azimuths I need to known if the order is clockwise. One solution is computing the area of each polygon and, if I remember correctly, if it is positive the order is clockwise and if negative the order is counterclockwise.
Area computation is not an intensive task, so it will not slow my plugin so much.
But in the special case of QGIS, anybody knows if it stores the polygons clockwise or counterclockwise, regardless the order in the original source?
By now I'm working with ESRI shapefiles and the coordinates in layer.getFeatures().geometry().asPolygon() are stored in clockwise for the outer border and counterclockwise for the holes, i. e. as in the original *.shp.

A: I don't know that anybody will be able to provide a definitive answer for your question since each vector file format is different and each GIS, in terms of how they internally handle these data, will also be different. But I can tell you for certain that the clockwise ordering is not only for ESRI Shapefiles. There are other formats that use a similar designation of clockwise ordering for external rings and counter-clockwise for interior hole polygons. For example, the JTS vector polygon structure uses a similar format. In fact, it is stated here, that historically this was to be similar to the ESRI approach. I can also definitively say that no, not all formats have this requirement. For example, the GeoJSON format specifications make no such requirement about the ordering of vertices in their polygon format. The KML specification actually state:

The  for polygons must be specified in counterclockwise
  order. Polygons follow the "right-hand rule," which states that if you
  place the fingers of your right hand in the direction in which the
  coordinates are specified, your thumb points in the general direction
  of the geometric normal for the polygon.

So the full range of options exist and are implemented out there. It's a wild world!

A: Ring (boundary) directions are needed to prevent ambiguities for geographic coordinate systems that cover a finite surface, since the boundary would define two areas, one left and one right of the boundary along it's direction. Determining which of those two areas is the bigger one is possible, but still leaves the ambiguity.
Here is an overview on outer ring directions of polygons in various formats by their specifications:

*

*Simple Feature Access (ISO 19125-1)
also used in WKT/GML/KML and various SQL implementations:

*

*exterior rings: counter-clockwise

*interior rings (holes): clockwise direction.

A Polygon is a planar Surface defined by 1 exterior boundary and 0 or more interior boundaries. Each interior boundary defines a hole in the Polygon. [...]

The exterior boundary LinearRing defines the "top" of the surface which is the side of the surface from which the exterior boundary appears to traverse the boundary in a counter clockwise direction. The interior LinearRings will have the opposite orientation, and appear as clockwise when viewed from the "top"... Simple Feature Access specs

In most implementations the order of rings in a POLYGON is important (as opposed to shapefiles)

For a polygon with holes, its first subelement is its exterior ring, its second subelement is its first interior ring, its third subelement is its second interior ring, and so on. Oracle Spatial

Deeper nestings, aka island-in-a-lake-on-an-island-... have to be represented as MultiPolygons (see figure 2.10 (4)), since there can be only one exterior border and deeper nestings than interior rings are not defined.

*

*ESRI Shapefiles/ SHP:

*

*exterior rings: clockwise

*interior rings: counter-clockwise

A polygon consists of one or more rings. A ring is a connected sequence of four or more points that form a closed, non-self-intersecting loop. A polygon may contain multiple outer rings. The order of vertices or orientation for a ring indicates which side of the ring is the interior of the polygon. The neighborhood to the right of an observer walking along the ring in vertex order is the neighborhood inside the polygon. Vertices of rings defining holes in polygons are in a counterclockwise direction. Vertices for a single, ringed polygon are, therefore, always in clockwise order. [...]

The order of rings in the points array is not significant. ESRI Whitepaper

Since multiple outer boundaries are allowed island-in-a-lake-on-an-island configurations are possible with this polygon definition. Topologically the island in a lake would be just another clockwise outer ring. Effectively this makes an ESRI Shapefile Polygon a Simple Feature MultiPolygon

If you don't order the points correctly you'll just have overlapping polygons. pyshp

*

*GeoJSON (RFC7946):

NOTE: Original GeoJSON 2008 spec had no winding order enforced

*

*winding order: exterior ring is counter-clockwise (right hand rule)

*

*interior rings are clockwise

*order of rings is important:

For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes. GeoJSON spec

*

*TopoJSON: forces exterior rings clockwise by default

Excursion:
The mathematical reasoning on why winding orders of nested rings alternate is, that calculating the area with the shoelace formula (visual explanation) computes signed areas depending on the ring direction.
In general nested rings (interior boundaries) are considered holes and have the alternate direction of the outer ring. Their contributing signed area value is negative. Where as outer rings are positive. The total area of all ring features is the sum of all signed areas.
As implemented by ESRI see this Knowledge Base entry: What algorithm is used by ArcGIS to determine a polygon's area?
Proposed Mnemonic
Open ends of letterforms interpreted as arrows:

*

*Shapefile: S → ᔑ → ↻

*Simple Features: e → ᘓ (winding outwards cc-wise) → ↺

*GeoJSON: G (stem of G is arrow) → ↺

A: In the OGC specification, which can be downloaded here they state:

Polygon rotation is not defined by this standard; actual polygon rotation may be in a clockwise or counter-clockwise direction.

In the Oracle docs, it is clearly stated that exterior ring boundaries are oriented counterclockwise, and interior ring boundaries, clockwise. Likewise, in SQL Server Spatial, the geography datatype follows a counter-clockwise rule for the exterior ring, and clockwise for the interior rings -- see this Microsoft blog for more details. Postgis seems to allow it either way, for geometries, and has functions that will force a polygon's geometry to follow either a right or left hand rule, see ST_ForceRHR and ForceLHR. JTS/Geos seem to have followed the right-hand rule, i.e. a clockwise orientation of the outer ring, so it is all a bit unclear, really.
In general it makes sense for a geography datatype to force orientation, as otherwise it would be impossible to tell if a small polygon was just that or the inner ring of a whole world polygon. With a geometry datatype on a planar surface, this confusion cannot arise, as the outer ring and inner ring follow in order, and if there is only a single ring, it will be enclosing (no matter what the orientation), unlike on a globe, which wraps round.

From a comment by @mxfh: OGC's OpenGIS Simple Features Access (ISO 19125-1) specifies a counter-clockwise direction for outer rings as of version 1.2.1 document [OGC 06-103r4] 6.1.11.1/page 26 from opengeospatial.org/standards/sfa. The change got introduced between version 1.1.0 and 1.2.0 in 2006 latest. The footnote you're citing from hasn't been updated since 2005


text:
Q: Teradata SQL Find numbers in a Character field I have a table with a character column called "Name".  In some cases the "Name" columns contains string with just characters.  In other cases it contains any of the 10 numeric digits (i.e. 0 - 9).  I want to query this table and only produce the records where the Name column contains any numbers (0 -9) regardless of what order the numbers are in or in what position they are in.  Below is a hypothetical example:
The table contains the following 5 records of data in the Name column:
"ABC Company" ,
"Terry Smith" ,
"Trucking 365 LLC" ,
"Lumber3foryou" ,
"24/7 Carwash"
I want to create a query that will produce the Name column with only those records that have any number (0 - 9), regardless of what order the numbers are in or in what positions they are in.
So the output should include only the last three records:
"Trucking 365 LLC" ,
"Lumber3foryou" ,
"24/7 Carwash"

A: You can use REGEXP_INSTR :
select
name
from

where
REGEXP_INSTR (name,'[0-9]') > 0

A: An option would be:
name like any ('%0%','%1%','%2%','%3%','%4%',
               '%5%','%6%','%7%','%8%','%9%')

A: SELECT name
FROM

WHERE name LIKE ANY ('%0%','%1%','%2%','%3%','%4%','%5%','%6%','%7%','%8%','%9%');


text:
Q: Calculating day-of-week in years greater than 9999 I was wondering if there are any algorithms that calculate the day of week in years that are greater than the year 9999.
Algorithms such Zeller's algorithm or this one here gives false results, since they handle only 4 digit year.
Thank you.

A: You don't actually need a new algorithm. As long as you have one algorithm with a range of 400 years (or more), you can bring any date inside the range of that algorithm. This works because the Gregorian calendar repeats every 400 years (XX/YY/ZZZZ is the same weekday as XX/YY/(ZZZZ+400)).
So, if we assume that you have some algorithm that works for the dates 1/1/1600 to 31/12/1999 (both inclusive), you can calculate the weekday for any date by using (year mod 400)+1600 as the year.
If you don't have a 400-year range starting on 1/1/XXXX (where XXXX mod 400 = 0), you need to manipulate the date slightly different to get the right result (instead of adding 1600 to the year, add X*400, where X is an integer such that some of the dates will be in the range, then add or subtract 400 to the year for those dates that are outside of the range).

A: http://lxr.linux.no/linux/net/netfilter/xt_time.c for example simply counts it out. To reduce the number of iterations in loops, static tables may be used, as has been done there.


text:
Q: conditional CSS in dart polymer I'm trying to figure out how to get the visibility of two elements to toggle based on the same variable. Wrapping the elements with  isn't an option, since I need to interact with the elements while they're invisible. I tried this, which I found an example of somewhere, but it didn't work, both elements are always visible:
  #fieldsList {
    display:{{ {none: editing == true, block: editing == false} | tokenList }};
  }
  #fieldsEdit {
    display:{{ {none: editing == false, block: editing == true } | tokenList}};
  }

And I tried it by wrapping the CSS in template conditionals, but this also results in both elements being always visible:
  <template if="{{ editing == true}}">
    #fieldsList {
      display: none;
    }
  </template>
  <template if="{{ editing == false}}">
    #fieldsEdit {
      display: none;
    }
  </template>

Am I going about this wrong? I'm using Dart 1.7.2 with Polymer 0.15.1+5.

A: Personally, I would use the hidden attribute, like so:

and

Polymer includes CSS that looks for the presence of the hidden attribute and applies the appropriate CSS. The ?= syntax removes and applies the attribute based on the boolean expression.

A: You can use conditional CSS like this:
#fieldsList {
  display:{{editing ? 'none' : 'block'}};
}
#fieldsEdit {
  display:{{editing ? 'block' : 'none'}};
}

A: According to the discussion in https://github.com/Polymer/polymer/issues/270 the best supported way (cross-browser) is to use the <core-style> element https://www.polymer-project.org/docs/elements/core-elements.html#core-style


text:
Q: will fb:name stop working completely? I see that fbml will stop working on 6'th of June 2012. So I assume these are the tags like fb:name and so on.
Is fb:name also xfbml and will xbml also stop working?
How else can I display a non auth'ed user his own name?
I tried the following but for this I need an access token, so it is of no use:
http://graph.facebook.com/me?fields=name
Any ideas?

A: XFBML is not the same as FBML, and only the latter has been deprecated, so fb:name will continue working.


text:
Q: Preview of (Desktop Site) on Mobile browser is not responsive as compared to computer browser Here the pictures of the Mobile browser (Desktop Site) and Computer browser at the same width. It is not giving me the same result.
Here the pic that is set to 980px on mobile browser desktop site:
[image 1]
And here the whole pic of the page on mobile
[image 2]
And this is the last image on computer browser
[image 3]
And here it is hosted check it - click here

A: You can set the width or height in % not by px, another method using css here documentation: [@media method]
[1]: https://developer.mozilla.org/es/docs/Web/CSS/Media_Queries/Using_media_queries

A: I depends on what you want to accomplish. Responsive means that it will look good on all devices, not necessary the same. Even if the resolutions are the same, the mobile screen is smaller.
I can't see you site on that link, maybe you were logged in or something. But it has to do with how background-size was handled on <body> element, and I assume it is set to cover.
You can take a look here and play a bit:
https://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover


text:
Q: How can I capture **PRINT** and **PREVIEW** functionality in google drive API? How can I capture PRINT and PREVIEW functionality in google drive API?
If I have a document in google drive and if I perform the below functionalities: 1) Edit 2) Download 3) Print 4) Preview 5) Trash 6) UnTrash - only edit, download, trash and untrash events are being captured in reports. Print and preview functionality are not being captured. I did try as an administrator from the google report screen (admin.google.com --> Reports --> Drive --> Click on Search) and I also did try from API related to drive SDK.
Question: Is there any additional setting required for PRINT and PREVIEW functionality to work?
Steps to reproduce
1) Even the google inbuilt report does not capture print and preview logs
   Login as admin --> Manage Domain --> Audit --> Drive --> Search
2) From code
    new Reports.Builder( HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName("TestApp").build().activities().list("all", "drive").execute())
Thank you!


text:
Q: GCM Sender Id Mismatch I have setup the third party GCM server with the API key, setup the Android app with the APP_SERVER_URL= "http://(localIPAddress):4430/gcm.php?shareRegId=1" and placed my computers public IP address, not the localIPAdderss in the "Allowed IPs" in the Google App Console.
The Android app notes its' Registration_id is shared with the 3rd party server, yet when testing to send a message from my server to the app it notes:
{"multicast_id":7181230864355412704,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

How can I get this to work?
gcm.php in Apache htdocs on port 4430:
<?php
    //generic php function to send GCM push notification
   function sendPushNotificationToGCM($registatoin_ids, $message) {
        //Google cloud messaging GCM-API url
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
        // Google Cloud Messaging GCM API Key
        define("GOOGLE_API_KEY", "(my console API key)"); // My API Key form Google console
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
?>
<?php

    //this block is to post message to GCM on-click
    $pushStatus = "";
    if(!empty($_GET["push"])) {
        $gcmRegID  = file_get_contents("GCMRegId.txt");
        $pushMessage = $_POST["message"];
        if (isset($gcmRegID) && isset($pushMessage)) {
            $gcmRegIds = array($gcmRegID);
            $message = array("m" => $pushMessage);
            $pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
        }
    }

    //this block is to receive the GCM regId from external (mobile apps)
    if(!empty($_GET["shareRegId"])) {
        $gcmRegID  = $_POST["regId"];
        file_put_contents("GCMRegId.txt",$gcmRegID);
        echo "Ok!";
        exit;
    }
?>

        <title>Google Cloud Messaging (GCM) Server in PHP</title>

Google Cloud Messaging (GCM) Server in PHP

        <form method="post" action="gcm.php/?push=1">

                <textarea rows="2" name="message" cols="23" placeholder="Message to transmit via GCM"></textarea>

<input type="submit"  value="Send Push Notification via GCM" />

        </form>

<?php echo $pushStatus; ?>

Tutorial Source: http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/

A: Looks like the sender ID you called gcm.register(senderID) with is not the sender ID of your server. You'll have to double check this in your Android code. It is the project number of your project from the Google Developers Console.
Full description of the error is here.