Q: How to Learn Noncommutative Geometry This is a more direct, and precise question of a previous one that I have deleted.
Obligatory Information/Background
I am currently a first-year undergraduate studying at a frequented Mathematical Institute in the United States. I am well versed in "basic" mathematics, I.e linear algebra, groups, etc…, and I have recently been reading ahead, in the form of Yau’s "Lectures on Differential Geometry" and certain Mathematical Physics papers, and I decided that I want to do research in Noncommutative Geometry due to the appeal of the work/questions Connes is engaging with this very field. I also wish to "truly" read and understand the work by Yau and other differential Geometers due to their importance in Mathematical Physics. This leads me to my next problem and first question for you all.
Where does one begin?
So far, I believe I should read through the "Rudin Trifecta" which is a coined name for Rudin’s Mathematical Analysis, Real (Measures) Analysis, and Functional Analysis book. This is in order to approach Noncommutative Geometry, which largely draws ideas from measure theory.
While doing so, I wish to learn more about Algebraic Topology due to its intrinsic link to Electromagnetism and other theories such as TQFT. Considering I already know a fair bit of Abstract Algebra, I’d hope after finishing some topology I am capable of approaching Peter May’s 2-Volume Concise Algebraic Topology course.
Now, I also wish to learn Differential Geometry due to its prolific nature in math phys (Calabi-Yau, Einstein, Kahler).
As you can see I want to learn a lot, but I have limited time, so is this really a good route for myself as someone interested in Math Phys on the Geometric side of things? You can likely guess my interests based on the things I have said thus far. If someone can point out some flaws in my plan, or point me in a direction far more efficient than my naive route, that would be largely appreciated.


Q: Angular 2 error: Playing around with Angular 2 and trying to get this simple code working.
yet I keep getting an error of:

EXCEPTION: Cannot resolve all parameters for Tab(undefined). Make sure
  they all have valid type or annotations.

As far ng2 is not injecting in constructor(tabs:Tabs) {… into the constructor
Here is the entire code:
///<reference path="../../typings/zone.js/zone.js.d.ts"/>

import {Component, Input} from 'angular2/core';

@Component({
    selector: 'tab',
    template: `

        {{tab.tabTitle}}

    <ng-content></ng-content>
  `,
})
export class Tab {
    @Input() tabTitle: string;
    public active:boolean;
    constructor(tabs:Tabs) {
        this.active = false;
        tabs.addTab(this);
    }
}

@Component({
    selector: 'tabs',
    directives: [Tab],
    template: `
    <tab tabTitle="Tab 1">
        Here's some content.
    </tab>
  `,
})

export class Tabs {
    tabs: Tab[] = [];
    selectTab(tab: Tab) {
        this.tabs.forEach((myTab) => {
            myTab.active = false;
        });
        tab.active = true;
    }

    addTab(tab: Tab) {
        if (this.tabs.length === 0) {
            tab.active = true;
        }
        this.tabs.push(tab);
    }
}

tx
Sean

A: That's because your Tabs class is defined after your Tab class and classes in javascript aren't hoisted.
So you have to use forwardRef to reference a not yet defined class.
export class Tab {
    @Input() tabTitle: string;
    public active:boolean;
    constructor(@Inject(forwardRef(() => Tabs)) tabs:Tabs) {
        this.active = false;
        tabs.addTab(this);
    }
}

A: You have two solutions:
Inject your Tabs class globally at bootstrap:
bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]);

On inject Tabs locally with a binding property,
@Component({
    selector: 'tab',
    bindings: [Tabs],   // injected here
    template: `

    [...]


Q: Hide formulas in excel without protecting the sheet I need to hid the formulas in my sheet without protecting the sheet,say i  have sheet 1 in that i need to hide the formulas from range(A1:G10) i can hide the formula but iam not able to provide input for  the whole sheet
My requirement is to hide the selected cells formulas and able to give inputs for other cells in the same sheet how can i achieve this.

A: Select the whole sheet, right click and then select Format Cells.... In the popup window, select Protection tab. Unselect both options and press OK button. This will unlock all cells on the sheet as by default all cells are locked. Next, select your range, repeat the above process again but this time ensure that both options (Locked and Hidden) are selected this time and press OK. Now protect your sheet (in Excel 2013, select the REVIEW tab and select Protect Sheet option and follow the steps).
This will hide your formulas and stop anyone changing the values in the protected cells


Q: Have border-bottom after grid-row css3 I have a grid container whose css is
.optionsInnerContainer {
        display: grid;
        // grid-template-columns: 1fr 1fr 1fr;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); /* see notes below */
        // grid-auto-rows: minmax(100px, auto);
        -webkit-column-gap: 10px;
        column-gap: 10px;
        row-gap: 2em;
        padding: 10px;
    }

I want to add a border-bottom below every row of grid. I dont know how to do that. Please help.


Q: Are my stock returns non-normally distributed? Hello stats community,
I have a Q-Q plot for my stock returns with a sample of n=262. I drew the plot with qqnorm and qqline(qtype=8). Most of the returns, except for 3 outliers, tend to follow the normal line.

However, when I perform the Shapiro Wilk test, I get a p-value of 0.003197, telling me that I can reject the null-hypothesis that my returns are drawn from a normal distribution.
Test Results:
STATISTIC:
W: 0.983
P VALUE:
0.003197

Am I missing something? Should I follow my observations or trust the SW test?

A: Your stock returns are normal enough for most purposes, but will not be strictly normally distributed.
No real world distribution is normally distributed (that distribution stretches from negative infinity up to infinity), and tests for normality will always indicate a statistically significant deviation from normality when the sample size is large enough.
Tests for normality have several good questions and answers on this site. Search if you need more.

A: There is no contradiction between the observation in the QQ plot and the result of the test.  Your stock returns have excess kurtosis compared with the normal distribution and this is why the test is rejecting the hypothesis that the data come from a normal distribution.  The presence of "outliers" in your data is really just a reflection of the fact that you are trying to fit it to a distribution with tails that are too thin.  Try fitting your data to a T-distribution and construct a corresponding QQ plot for this, and you will probably find that it fits quite well.
The presence of excess kurtosis in financial data is common, and it is usually important, since the occurrence of occasional extremes is of high consequence.  Extreme positive and negative returns tend to occur more often than in the tails of the normal distribution.  For this reason it is common to model financial data using fat-tailed distributions (e.g., the Lévy distribution) or at least fatter tails than the normal (e.g.,  the T-distribution).  The financial analyst Nassim Taleb was highly critical of modelling financial data with the normal distribution, due to the tendency to underestimate the risk of extreme losses (Taleb 2007).  He referring to it as "picking up pennies in front of a steam-roller".


Q: Selecting the longest connected lines from PostGIS ST_ApproximateMedialAxis I used PostGIS ST_ApproximateMedialAxis to transform polygons representing mountain ranges into a series of lines.  Now, I'd like to select only the "longest" line segment for each group, so that I can dissolve the lines and use it for "curved" labeling.  Can I extend the query in PostGIS to end up with the single series of arcs?
The end result should look something like the lines highlighted in yellow in the picture below.

A: I am publishing my answer for those who visit this page hoping to find an answer to the problem you have formulated!
So, I invite everyone to fly with me in a plane with the engine I have assembled with the name: "Free and Magic geoSQL", in order to admire the beautiful mountain scenery of the Cordillera mountain system and from a height of flight to see their centerlines :-)! We have a difficult and interesting task ahead of us, but we can do it even without SFCGAL library and ST_ApproximateMedialAxis and ST_StraightSkeleton functions, because we are pilots and navigators of high class :-), I strongly hope so! I command: "Fasten your seatbelts", "From the screw", "Fly"! and of course I start the engine, which works so far for only one polygon:
WITH
tbla AS (SELECT (ST_Dump(geom)).geom FROM <name_polygon_table>),
tblb AS (SELECT (ST_DumpPoints(geom)).geom FROM tbla),
tblc AS (SELECT ((ST_Dump(ST_VoronoiPolygons(ST_Collect(geom)))).geom) geom FROM tblb),
tbld AS (SELECT (ST_Dump(ST_Intersection(a.geom, b.geom))).geom FROM tblc a JOIN tbla b ON ST_Intersects(a.geom, b.geom)),
tble AS (SELECT line1, line2, CASE WHEN line1>line2 THEN line1 WHEN line1<=line2 THEN line2 END FROM (SELECT ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),1)),
(ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),2))) AS line1, ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),2)), (ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),3))) AS line2 FROM tbla) AS foo),
tblf AS (SELECT (ST_Buffer(line2, ST_Length(line2), 'endcap=flat join=round')) geom FROM tble),
tblg AS (SELECT DISTINCT (ST_Dump(ST_Difference(a.geom, b.geom))).geom FROM tblf a JOIN tbla b ON ST_Intersects(a.geom, b.geom)),
tblh AS (SELECT (ST_Dump(ST_Buffer(geom, -0.000001))).geom geom FROM tblg),
tbli AS (SELECT (ST_Buffer(geom, 0.000002)) geom FROM tblh a JOIN tble b ON ST_Intersects(a.geom, b.line2)),
tblj AS (SELECT ST_ExteriorRing(ST_Union(a.geom)) geom FROM tbld a JOIN tbli b ON ST_Intersects(a.geom, b.geom)),
tblk AS (SELECT ST_MakeLine(pt1, pt2) geom FROM (SELECT ST_PointN(geom, generate_series(1, ST_NPoints(geom)-1)) pt1, ST_PointN(geom, generate_series(2, ST_NPoints(geom))) pt2 FROM tblj) AS geom),
tbll AS (SELECT (ST_Dump(ST_Intersection(ST_Buffer(a.geom, -0.0001), b.geom))).geom FROM tbla a JOIN tblk b ON ST_Contains(a.geom, b.geom))
SELECT ST_Union(geom) geom FROM tbll

(If necessary, adjust it to the size of your polygons (function ST_Buffer), I played with data in EPSG:4326).
From now on, everyone will be able to see and create the centerline of the polygon.
Original solutions.
The script is called: ST_LongestAxisPolygonsFromVoronoiDiagrams.
(!Not to use for simple shapes like rectangle!)
"I want to thank all those who contribute to the creation and development of promising geoinstruments by sharing their ideas and codes..."
First editing:
CREATE OR REPLACE FUNCTION ST_LongestAxisPolygonsFromVoronoiDiagrams(
    geom GEOMETRY
)
RETURNS GEOMETRY AS
$BODY$
WITH
tbla AS (SELECT (ST_Dump(geom)).geom),
tblb AS (SELECT (ST_DumpPoints(geom)).geom FROM tbla),
tblc AS (SELECT ((ST_Dump(ST_VoronoiPolygons(ST_Collect(geom)))).geom) geom FROM tblb),
tbld AS (SELECT (ST_Dump(ST_Intersection(a.geom, b.geom))).geom FROM tblc a JOIN tbla b ON ST_Intersects(a.geom, b.geom)),
tble AS (SELECT line1, line2, CASE WHEN line1>line2 THEN line1 WHEN line1<=line2 THEN line2 END FROM (SELECT ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),1)),
(ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),2))) AS line1, ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),2)), (ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),3))) AS line2 FROM tbla) AS foo),
tblf AS (SELECT (ST_Buffer(line2, ST_Length(line2), 'endcap=flat join=round')) geom FROM tble),
tblg AS (SELECT DISTINCT (ST_Dump(ST_Difference(a.geom, b.geom))).geom FROM tblf a JOIN tbla b ON ST_Intersects(a.geom, b.geom)),
tblh AS (SELECT (ST_Dump(ST_Buffer(geom, -0.000001))).geom geom FROM tblg),
tbli AS (SELECT (ST_Buffer(geom, 0.000002)) geom FROM tblh a JOIN tble b ON ST_Intersects(a.geom, b.line2)),
tblj AS (SELECT ST_ExteriorRing(ST_Union(a.geom)) geom FROM tbld a JOIN tbli b ON ST_Intersects(a.geom, b.geom)),
tblk AS (SELECT ST_MakeLine(pt1, pt2) geom FROM (SELECT ST_PointN(geom, generate_series(1, ST_NPoints(geom)-1)) pt1, ST_PointN(geom, generate_series(2, ST_NPoints(geom))) pt2 FROM tblj) AS geom),
tbll AS (SELECT (ST_Dump(ST_Intersection(ST_Buffer(a.geom, -0.0001), b.geom))).geom FROM tbla a JOIN tblk b ON ST_Contains(a.geom, b.geom))
SELECT ST_Union(geom) geom FROM tbll
$BODY$
LANGUAGE SQL;

RUN
SELECT ST_LongestAxisPolygonsFromVoronoiDiagrams(geom) geom FROM <source_table>

If necessary, make the line smoother, add the function generate_series...
Second edition 13.03.2020
CREATE OR REPLACE FUNCTION ST_LongestAxisPolygonsFromVoronoiDiagrams_gs(
    geom GEOMETRY,
    n integer)
RETURNS GEOMETRY AS
$BODY$
WITH
    tbla AS (SELECT (ST_Dump(geom)).geom),
    tblb AS (WITH btbl AS (SELECT (ST_ExteriorRing(((ST_Dump(geom)).geom))) geom),
            intervals AS (SELECT generate_series (0, n) as steps)
            SELECT steps AS stp, ST_LineInterpolatePoint(geom, steps/(SELECT count(steps)::float-1 FROM intervals)) geom FROM btbl, intervals GROUP BY intervals.steps, geom),
    tblc AS (SELECT ((ST_Dump(ST_VoronoiPolygons(ST_Collect(geom)))).geom) geom FROM tblb),
    tbld AS (SELECT (ST_Dump(ST_Intersection(a.geom, b.geom))).geom FROM tblc a JOIN tbla b ON ST_Intersects(a.geom, b.geom)),
    tble AS (SELECT line1, line2 FROM (SELECT ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),1)),
        (ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),2))) AS line1, ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),2)), (ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),3))) AS line2 FROM tbla) AS foo),
    tblf AS (SELECT (ST_Buffer(line2, ST_Length(line2), 'endcap=flat join=round')) geom FROM tble),
    tblg AS (SELECT DISTINCT (ST_Dump(ST_Difference(a.geom, b.geom))).geom FROM tblf a JOIN tbla b ON ST_Intersects(a.geom, b.geom)),
    tblh AS (SELECT (ST_Dump(ST_Buffer(geom, -0.000001))).geom geom FROM tblg),
    tbli AS (SELECT (ST_Buffer(geom, 0.000002)) geom FROM tblh a JOIN tble b ON ST_Intersects(a.geom, b.line2)),
    tblj AS (SELECT ST_ExteriorRing(ST_Union(a.geom)) geom FROM tbld a JOIN tbli b ON ST_Intersects(a.geom, b.geom)),
    tblk AS (SELECT ST_MakeLine(pt1, pt2) geom FROM (SELECT ST_PointN(geom, generate_series(1, ST_NPoints(geom)-1)) pt1, ST_PointN(geom, generate_series(2, ST_NPoints(geom))) pt2 FROM tblj) AS geom),
    tbll AS (SELECT (ST_Dump(ST_Intersection(ST_Buffer(a.geom, -0.0001), b.geom))).geom FROM tbla a JOIN tblk b ON ST_Contains(a.geom, b.geom))
            SELECT ST_MakeLine(ST_Centroid(geom)) geom FROM tbll
$BODY$
LANGUAGE SQL;

RUN
SELECT ST_LongestAxisPolygonsFromVoronoiDiagrams_gs(geom, 300) geom FROM <source_table>

Third edition 30.03.2020
As an option, for 2 or more polygons run the following script:
SELECT DISTINCT b.geom
FROM <source_table> AS a
JOIN LATERAL (SELECT ST_LongestAxisPolygonsFromVoronoiDiagrams_gs(geom) AS geom
FROM <source_table>) AS b ON true;

Fourth edition 13.05.2021
CREATE OR REPLACE FUNCTION ST_CentraLAxisLongestLineFromPolygons_VD(
geom GEOMETRY,
n integer)
RETURNS GEOMETRY AS
$BODY$
WITH
    tbla AS (SELECT (ST_Dump(geom)).geom geom),
    tblb AS (SELECT ST_Buffer(ST_Boundary(ST_OrientedEnvelope(geom)),0.00001) geom FROM tbla),
    tblc AS (SELECT (ST_Dump(ST_Difference(ST_Boundary(a.geom), b.geom))).geom geom FROM tbla a JOIN tblb b ON true),
    tbld AS (SELECT (ST_Dump(ST_Difference(ST_Buffer(ST_OrientedEnvelope(a.geom), -0.00001), b.geom))).geom geom FROM tbla a JOIN tbla b ON true),
    tble AS (SELECT ST_Buffer(geom, 0.00001) geom  FROM (SELECT ST_MakeLine((ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),1)),
        (ST_PointN(ST_Boundary(ST_OrientedEnvelope(geom)),4))) AS geom FROM tbla) AS foo),
    tblf AS (SELECT generate_series (0, n) as steps),
    tblg AS (SELECT steps AS stp, ST_LineInterpolatePoint(geom, steps/(SELECT count(steps)::float-1 FROM tblf)) geom FROM tblc, tblf GROUP BY tblf.steps, geom),
    tblh AS (SELECT ((ST_Dump(ST_VoronoiPolygons(ST_Collect(geom)))).geom) geom FROM tblg),
    tbli AS (SELECT (a.geom) geom FROM tbld a JOIN tble b ON ST_Intersects(a.geom,  ST_Buffer(b.geom, 0.00001))),
    tblj AS (SELECT ST_ExteriorRing(ST_Union(a.geom)) geom FROM tblh a JOIN tbli b ON ST_Intersects(a.geom, b.geom))
            SELECT ST_Intersection(a.geom, b.geom) geom FROM tblj a JOIN tbla b ON ST_Intersects(a.geom, b.geom);
$BODY$
LANGUAGE SQL;

Run
SELECT ST_CentraLAxisLongestLineFromPolygons_VD(geom, 100) AS geom FROM <source_table>


Q: Are there some methods in golang manipulate function like std::bind in C++? Here is my design:
type Handler func(c *gin.Context)
func PreExecute(c *gin.Context, handle_func Handler) Handler {
    if c.User.IsAuthorized {
        return handle_func
    } else {
        return some_error_handle_func
    }
}

and I want to decorate every handler by PreExecute just like the decoration in Python. So I am looking for some std::bind functions in golang to get PreExecute a exactly same signature as Handler
What I expect:
handler = std::bind(PreExecute, _1, handler) // where _1 hold the position for parameter `c *gin.Context`

some function like std::bind
How can I do that in Golang? Are there some more elegant methods to get this work?

A: Closure, here is my solution:
handler_new = func(c *gin.Context){ return PreExecute(c, handler_old)(c) } // since there is no return value of handler, so just do not use `return` statements, I will not correct this error

and then handler_new can be used as:
handler_new(some_context)

It's the same as
handler_new = std::bind(PreExecute, _1, handler_old)

in C++


Q: Why to use new to initialize something in JAVA? Why do we use this syntax in JAVA
FreshJuice juice = new FreshJuice();

instead of just
FreshJuice juice;

A: For many reasons, including:

*

*There is no guarantee that FreshJuice will be a concrete class; it can be an interface or an abstract class instead.

*You might not have a default constructor available.

*You might not have any constructor available at all.

A: Because you need to create an object before initializing it.
When you call new FreshJuice(); it firsts allocates memory for the object on heap, and then initializes it.(with default values in this case as provided in corresponding default constructor)


Q: How to make `format` function in python 2 to work with `unicode` type objects with UTF-8 encoding? I have huge code base with lots of format functions. I want to pass unicode type objects as arguments like:
# -*- coding: UTF-8 -*-
x = u"ñö"
print isinstance(x,unicode)#prints "True"

y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)"
print y

A: This did the trick for me without changing every line where format is used:
from __future__ import unicode_literals

Basically I had problems whenever "string {}" in "string {}".format("hello") was str object. Writing a simple u"string {}" would have helped, but huge code base remember? "hello" doesn't really matter.

A: # -*- coding: UTF-8 -*-
x = r"ñö"
print isinstance(x,unicode)#prints "True"

y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)"
print y


Q: Avoiding array assignment in autograd I understand from the autograd tutorial that array assignment is not supported when the array is contained in the objective to be differentiated. However, I currently have the following objective function in my code which I would like to differentiate with respect to theta:
def obj(theta):
    """
    Computes the objective function to be differentiated.

    Args:
        theta: np.array of shape (n, d)

    Return:
        res: np.array of shape (n,)
    """
    theta = np.atleast_2d(theta)
    n = theta.shape[0]

    res = np.zeros(n)  # Scores
    for i in xrange(n):
        res[i] = ... # Do some computations with theta[i, :]

    return res

Typically I can avoid the for loop by vectorizing the computation over theta; however, in this case the computation already involves various linear algebra operations (inverses, etc.) given a specific row of theta (as hyperparameters), and I found it quite difficult to vectorize the operation over all rows of theta. In this case, I don't know of a better way than filling the res array row by row with a for-loop.
I have tried a naive way to avoid array assignments by creating a list and at each iteration append the results to that list, then finally convert the list to the array upon returning res, but I get all-zero gradients in the end...
I wonder what is the general recommend solution in this setup?

A: You can use numpy.apply_along_axis to apply a function for certain axis in your data.
def func(row):
    # return the computation result for "row"

def obj(theta):
    """
    Computes the objective function to be differentiated.

    Args:
        theta: np.array of shape (n, d)

    Return:
        res: np.array of shape (n,)
    """
    theta = np.atleast_2d(theta)
    n = theta.shape[0]

    res = np.apply_along_axis(func1d=func, axis=1, arr=a)

    return res


Q: comparison of randomized algorithms Sometimes randomized algorithms return quite good results and they are often much faster than a deterministic alternatives. But how can I compare two randomized algorithms (or at least their implementations) ? The results will differ after each call and the output will highly depend on a (pseudo)-coincidence.
I have to compare some clustering algorithms and the majority of solutions is randomized.

*

*is it smart to compare the distribution of the output? (This will highly depend on input and the coincidence.)

*it is also quit hard to estimate the duration because some algorithms work until a threshold is reached (= depends highly on input).


Q: Joining python threads, sum totals My issue is I'm trying to loop over an array with a number of threads, each thread then adds the value into the global array. But for some reason the array is coming out as planned, I have noticed you need to use the join() thread function but am a little confused on how to implement it here
totalPoints = []

def workThread(i):
    global totalPoints
    totalPoints += i

threads = []
for i in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=workThread, args=(i,))
    t.start()
    threads.append(t)

Any help would be appreciated. Thanks!

A: You just write a second loop to join the threads
totalPoints = []

def workThread(i):
    global totalPoints
    totalPoints += i

threads = []
for i in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=workThread, args=(i,))
    t.start()
    threads.append(t)
for t in threads:
    t.join()

Your code will fail at totalPoints += i because totalPoints is a list. You don't handle exceptions in your threads so you may fail silently and not know what happened. Also, you need to be careful how you access a shared resource such as totalPoints to be thread safe.

A: does this help: ?
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import time
import random

NUMBER_OF_THREADS=20

totalPoints = []

def workThread(i):
    global totalPoints
    time.sleep(random.randint(0, 5))
    totalPoints.append((i, random.randint(0, 255)))

threads = []
for i in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=workThread, args=(i,))
    t.start()
    threads.append(t)

for t in threads:
  t.join()
print totalPoints

It always prints something like this:
[(1, 126), (10, 169), (11, 154), (0, 214), (9, 243), (12, 13), (15, 152), (6, 24), (17, 238), (13, 28), (19, 78), (16, 130), (2, 110), (3, 186), (8, 55), (14, 70), (5, 35), (4, 39), (7, 11), (18, 14)]

or this
[(2, 132), (3, 53), (4, 15), (6, 84), (8, 223), (12, 39), (14, 220), (0, 128), (9, 244), (13, 80), (19, 99), (7, 184), (11, 232), (17, 191), (18, 207), (1, 177), (5, 186), (16, 63), (15, 179), (10, 143)]


Q: How to read pcapng (wireshark) files in Python? I have a capture of some TCP packets in pcapng format and I'd like to open it in python to inspect the TCP payloads with address 192.168.1.198. I've only found this library: https://python-pcapng.readthedocs.io/en/latest/api/blocks.html but it does not support inspecting TCP payloads.
Is there an easy way?

A: You can use python-pcapng package. First install python-pcapng package by following command.
pip install python-pcapng

Then use following sample code.
from pcapng import FileScanner

with open(r'C:\Users\zahangir\Downloads\MDS19 Wireshark Log 08072021.pcapng', 'rb') as fp:
    scanner = FileScanner(fp)
    for block in scanner:
        print(block)
        print(block._raw) #byte type raw data

Above code worked for me.
Reference: https://pypi.org/project/python-pcapng/


Q: Azure Logic Apps ACI Connector - BackOff state I am using the ACI connector in logic apps, and using a customized version of nginx docker image that keeps failing with "CrashLoopBackOff" error.

The customization I've made is just these two:
apt update
apt install ssh

and built a new image out of that. While using the base nginx image (from docker hub - library/nginx) works like a charm, the custom version with SSH installed, always gets into the loop with CrashLoopBackOff error.
I'm not a Linux/Ubuntu guy, any idea what could be the issue? I have in fact tried this many times and also used the Ubuntu base image to do the same customisation (install SSH), but the result is the same
Background: I am using ACI to run a simple shell script on creation. This probably doesn't have anything to do with the error since it works ok with the base nginx image.

A: To install the SSH in the image, you need to more than you have done. Here is the example:
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:THEPASSWORDYOUCREATED' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

When you have built the image, I suggest you push it into the ACR. Then you can use it in the Logic App and it will work fine. For more details, see Dockerize an SSH service.


Q: OleDbCommand, two sequential "using" With two sequential "using", will both connections be disposed when exiting from {}?
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand command = con.CreateCommand())
{
}

A: There's only one connection there - and a command using the same connection. Both will be disposed.
This is effectively:
using(OleDbConnection con = new OleDbConnection(conString))
{
    using(OleDbCommand command = con.CreateCommand())
    {
    } // command will be disposed here
} // con will be disposed here


Q: PHP remove duplicate values from a multidimensional array How to remove duplicate values from a multidimensional array.
For example, I have an array:
Array
(
    [0] => Array
        (
            [fruit_id] => cea2fc4b4058
            [title] => Apple title one
            [name] => Apple
            [weight] => 22
        )

    [1] => Array
        (
            [fruit_id] => sdfsdec4b4058
            [title] => Grapefruit title one
            [name] => Grapefruit
            [weight] => 19
        )

    [2] => Array
        (
            [fruit_id] => hjkvcbc4b4058
            [title] => Grapefruit title two
            [name] => Grapefruit
            [weight] => 17
        )

    [3] => Array
        (
            [fruit_id] => tyuutcgbfg058
            [title] => Lemon title one
            [name] => Lemon
            [weight] => 15
        )

    [4] => Array
        (
            [fruit_id] => lkjyurtws4058
            [title] => Mango title
            [name] => Mango
            [weight] => 13
        )

    [5] => Array
        (
            [fruit_id] => bner3223df058
            [title] => Lemon title two
            [name] => Lemon
            [weight] => 11
        )
)

In this array, I need to leave only one fruit with the maximum weight.
I want to save all the data, but at the same time remove duplicate fruits.
Thank.

A: You can sort by weight ascending and then create a result using the name as the key so the ones with larger weight will overwrite the smaller weight ones:
array_multisort(array_column($array, 'weight'), SORT_ASC, $array);
foreach($array as $v) { $result[$v['name']] = $v; }

Then if you want to re-index (not required):
$result = array_values($result);

A: Try to use array_unique($array); code


Q: Frame 1:26 - What does q unify with? We have:
(run* q
  (fresh (x)
    (==
      `(,x)
      q)))

In this case  `(,x) is a list where the refrence to the variable x isn't quoted.
Does q unifies with a single element list?
Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()?

A:
Does q unify with a single element list?

Yes. (== (list x) q) is the same as (== q (list x)). Both q and x are fresh before the execution of this unification goal (and q does not occur in (list x)). Afterwards, it is recorded in the substitution that the value of q is (list x). No  value for x is recorded.

Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()?

No, q does not unify with x, but rather with a list containing x.
When the final value of the whole run* expression is returned, the variables are "reified", replaced with their values. x has no value to be replaced with, so it is printed as _0, inside a list as it happens, which list is the value associated with q.
The value of (run* q ...) is a list of all valid assignments to q, as usual. There is only one such association, for the variable q and the value (list x).
So ( (_0) )  should be printed as the value of the (run* q ...) expression -- a list of one value for q, which is a list containing an uninstantiated x, represented as a value _0.


Q: jQuery slider not adding active slide class I'm having an issue with a slider I've put together (with navigation to each slide). The issue being that the .active-slide class is not being added correctly to the next slide. I've had this working in CodePen - http://codepen.io/davelivesey/pen/mEBkAa - but as soon as I transplant that into my project it breaks, the main issue being the .active-slide class is no longer added to the next slide.
I've added a $(document).ready( ... around it, but this doesn't fix it. There are no conflicts with any other code I've written and both the CodePen and the project use the same version of jQuery (2.2.4).
Here's the code that's not working in the project. I've removed some of the CSS for the sake of brevity!
HTML

I'm slide one.

I'm slide two.

I'm slide three.

CSS(SASS)
#slider {
  width: 100%;
  height: 600px;
  position: relative;
  background-color: rgb(240,240,240);

  .slide {
    width: 100%;
    height: 600px;
    position: absolute;
    top: 0;
    display: none;
  }
}

.slide.active-slide {
  display: block;
}

#slider-nav ul {
  list-style: none;
  text-align: center;

    li {
      display: inline-block;
      margin-right: 5px;

      a span {
        display: inline-block;
        width: 10px; height: 10px;
        border-radius: 10px;
        border: 1px solid rgb(130,130,130);
    }
  }

  li.active a span {
    background-color: rgb(180,180,180);
  }
}

jQuery:
$(document).ready( function() {

    var $slides  = $('#slider .slide'),
        $navWrap = $('#slider-nav ul');

    function nextSlide() {
        var $next = $('#slider-nav ul li.active').next();
        if ($next.length === 0){
            $next = $('#slider-nav ul li:first-of-type');
        }
        $next.click();
    }
    function slideTransition(index) {

        $('#slider .slide.active-slide').delay(6000).fadeOut(500, function() {
            $(this).removeClass('active-slide');
        });

        $('#slider .slide:eq(' + index + ')').fadeIn(500, function() {
            $(this).addClass('active-slide');
        });
    }

    $slides.each( function(index) {
        $navWrap.append('

');
    });

    var timer = setInterval(nextSlide, 6000);
    $('#slider .slide:first').addClass('active-slide').fadeIn(200);
    $('#slider-nav ul li').click(function() {
        clearInterval(timer);
        $(this).siblings('.active').removeClass('active');
        $(this).addClass('active');
        var index = $(this).index('li');
        slideTransition(index);
        timer = setInterval(nextSlide, 6000);
        return false;
    });

    $('#slider-nav ul li:first-of-type').click();

});


Q: Conditionally add class to image by jquery This JS replace image file name default.jpg to hqdefault.jpg from all images below. But now I'm trying to add class to Image, if Image src has img.youtube.com link on images by extending this JS.
JS:
$('#selector img').attr('src',function(i,e){
    return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});

HTML:

Means, If image src has Youtube image then add a class .video to parent image.

A: Try:
$('#selector img').each(function(i) {
    var self = $(this);
    var src = self.attr('src');
    if (src.match(/img.youtube.com/)) {
        self.attr('src', src.replace("/default.jpg","/hqdefault.jpg"));
        self.addClass('video');
    }
});

A: You can add a condition before replacing and add video class.
$('#selector img').attr('src',function(i,e){
    if($(this).attr('src').search('img.youtube.com') > 0){
         $(this).addClass('video');
    }
    return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});


Q: BIML: Issues about Datatype-Handling on ODBC-Source Columns with varchar > 255 I'm just getting into BIML and have written some Scripts to creat a few DTSX-Packages. In general the most things are working. But one thing makes me crazy.
I have an ODBC-Source (PostgreSQL). From there I'm getting data out of a table using an ODBC-Source. The table has a text-Column (Name of the column is "description"). I cast this column to varchar(4000) in the query in the ODBC-Source (I know that there will be truncation, but it's ok). If I do this manually in Visual Studio the Advanced Editor of the ODBC-Source is showing "Unicode string [DT_WSTR]" with a Length of 4000 both for the External and the Output-Column. So there everything is fine. But if I do the same things with BIML and generate the SSIS-Package the External-Column will still say "Unicode string [DT_WSTR]" with a Length of 4000, but the Output-Column is telling "Unicode text stream [DT_NTEXT]". So the mapping done by BIML differs from the Mapping done by SSIS (manually). This is causing two things (warnings):

*

*A Warning that metadata has changed and should be synced

*And a Warning that the Source uses LOB-Columns and is set to Row by Row-Fetch..

Both warnings are not cool. But the second one also causes a drasticaly degredation in Performance! If I set the cast to varchar(255) the Mapping is fine (External- and Output-Column is then "Unicode string [DT_WSTR]" with a Length of 255). But as soon as I go higher, like varchar(256) it's again treated as [DT_NTEXT] in the Output.
Is there anything I can do about this? I invested days in the Evaluation of BIML and find many things an increase in Quality of Life, but this issue is killing it. It defeats the purpose of BIML if I have to correct the Errors of BIML manually after every Build.
Does anyone know how I can solve this Issue? A correct automatic Mapping between External- and Output-Columns would be great, but at least the option to define the Mapping myself would be ok.
Any Help is appreciated!
Greetings
Marco
Edit As requested a Minimal Example for better understanding:

*

*The column in the ODBC Source (Postegres) has the type "text" (Columnname: description)

*I select it in a ODBC-Source with this Query (DirectInput):
SELECT description::varchar(4000) from mySourceTable

*The ODBC-Source in Biml looks like this:
<OdbcSource Name="mySource" Connection="mySourceConnection"> <DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput></OdbcSource>

*If I now generate the dtsx-Package the ODBC-Source throws the above mentioned warnings with the above mentioned Datatypes for External and Output-Column

A: As mentioned in the comment before I got an answer from another direction:
You have to use DataflowOverrides in the ODBC-Source in BIML. For my example you have to do something like this:
`<OdbcSource Name="mySource" Connection="mySourceConnection">
  <DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput>
  <DataflowOverrides>
    <OutputPath OutputPathName="Output">
      <Columns>
        <Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" />
      </Columns>
    </OutputPath>
    <OutputPath OutputPathName="Error">
      <Columns>
        <Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" />
      </Columns>
    </OutputPath>
  </DataflowOverrides>
</OdbcSource>`

You won't have to do the Overrides for all columns, only for the ones you have mapping-Issues with.
Hope this solution can help anyone who passes by.
Cheers


Q: Can we create a link with dynamic ID in SPA model I am developing a single page application using ReactJS. My whole application is running in Single Page. Now, I need one page that accept the used ID from the URL and show the result based on the user ID.
Is this possible in SPA model or I have to move the my website to MPA model?
I tried some answers and am not clear about it
for ex: https://stackoverflow.com/questions/id/101
I have to get the ID 101 and show the result based on the id in the page.

A: yes sure this is possible.
Let me give you some background over this. If you are building SPA with multiple pages, you would like to use a client-side routing in otder to display differen page based on the browser url. As I know defacto solution for routing in react is react-router but there are many other to chose from. See this link. Unfortunately, I won't be able to completely explain how to use react-router solution, but here is a brief example.
Inside your main component (like App.jsx) add routing:
// 1. do proper imports
import { BrowserRouter } from "react-router-dom";

// 2. wrap your application inside of BrowserRouter component

class App extends React.Component {
// your code

    render() {
        return (
            <BrowserRouter>
                {/* your app code */}

                {/* Add routing */}
                <Route path="/" exact component={Dashboard} />
                <Route path="/questions/id/:id" component={Question} />

                {/* your app code */}
            <BrowserRouter>
        )
    }
}

You should see now that when your browser url matches /questions/id/:id component Question should be mounted to the page. Inside this component, you can fetch id that was passed in. It will be inside this.props.match.param.id property
class Question extends React.Component {
// your code

    render() {
        const id = this.props.match.param.id;

        return (

                Page with { id } was opened

        )
    }
}

Sure you would like to familiarise yourself with react-router docs.

A: ReactJs don't include a router. But the most popular package to do this is React-router.
The official documentation references other good packages


Q: How to retrieve current server FQDN in a java class I need to compose a dynamic URL based on current host running the web application.
I have a backgrund process launched on startup via ServletContextListener.
This thread has to send emails to customers with a registration ticket. In the email text I need to print the complete URL to my webapp and the servlet. Lets say those emails like "click here to confirm your subscription or copy&paste blabla...."
How my I obtain the FQDN of my running webapp?
It's not a servlet so I cannot relay on a HttpServletRequest instance and the server has many virtual hosts.
Here is where I launch the thread:
public class Initializer implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        Log.addItem("SYSTEM START");

        PasswordRecoveryListener pwlisten = new PasswordRecoveryListener(1000 * 60 * 1);
        pwlisten.start();
    }
}

In arg0.getServletContext().getContextPath() I found nothing but the path.
I looked for the hostname in the Context (where I have other constants) but without success.


Q: prototype function error : is not a function I tried to encapsulate a javascript object and declared some prototype function. But there were some errors.
Here is my code:
const editor_theme = require('./editor-theme.js')

let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())

//main.js

module.exports = {
    Editor_Theme: function (data) {
        var _themeData = JSON.parse(data)

        var _titlebar_color = _themeData.titlebar_color
        var _background_color = _themeData.background_color

        const Func = function() { }

        Func.prototype = {
            getTitlebarColor : function () {
                return _titlebar_color
            },
            getBackgroundColor : function () {
                return _background_color
            },
            setTitlebarColor : function (titlebarColor) {
                _titlebar_color = titlebarColor || _titlebar_color
            }
        }

        Object.freeze(Func)
        Object.freeze(Func.prototype)

        return Func
    }

}

//editor-theme.js

The error log is it:

Uncaught TypeError: defaultTheme.setTitlebarColor is not a function

A: Your constructor now returns another constructor function, not an object. Return an instance of that constructor instead:

// module.exports = {
let moduleExports = {

  Editor_Theme: function(data) {

    var _themeData = JSON.parse(data)

    var _titlebar_color = _themeData.titlebar_color
    var _background_color = _themeData.background_color

    const Func = function() {}

    Func.prototype = {
      getTitlebarColor: function() {
        return _titlebar_color
      },
      getBackgroundColor: function() {
        return _background_color
      },
      setTitlebarColor: function(titlebarColor) {
        _titlebar_color = titlebarColor || _titlebar_color
      }
    }

    Object.freeze(Func)
    Object.freeze(Func.prototype)

    return new Func() //Instantiate constructor
  }

}

// const editor_theme = require('./editor-theme.js')
const editor_theme = moduleExports

let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())

Or even better, just Object.create an object with a custom prototype:

// module.exports = {
let moduleExports = {

  Editor_Theme: function(data) {

    var _themeData = JSON.parse(data)

    var _titlebar_color = _themeData.titlebar_color
    var _background_color = _themeData.background_color

    const prototype = {
      getTitlebarColor: function() {
        return _titlebar_color
      },
      getBackgroundColor: function() {
        return _background_color
      },
      setTitlebarColor: function(titlebarColor) {
        _titlebar_color = titlebarColor || _titlebar_color
      }
    }

    Object.freeze(prototype)

    return Object.create(prototype) //Object with custom prototype
  }

}

// const editor_theme = require('./editor-theme.js')
const editor_theme = moduleExports

let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())


Q: Emacs does not react when I press C-. (dot/period) I am learning Agda and when I type C-cC-. there is no reaction in my Emacs. I can type either C-c. or C-cM-. and then I will be told that these bindings are not defined. But when I try to type C-cC-. the mini-buffer only shows C-c and it seems that Emacs is waiting for the next key binding. So how should I fix this problem?
I am using a MacOS. Any help will be appreciated.


Q: The function $f:G \rightarrow G$ defined by $f(x)=x^2$ is a homomorphism iff G is abelian. Let G be a group. The function $f:G \rightarrow G$ defined by $f(x)=x^2$ is a homomorphism iff G is abelian.
I am having trouble with the 2nd part of the proof.
Proof:
Assume the function $f:G \rightarrow G$ is defined by $f(x)=x^2$ then:

*

*Assume $f$ is a homomorphism then $f$ satisfies the property:
$$ f(xy)=f(x)f(y) $$

where $x,y \in G$
Notice how:
$$f(xy)=(xy)^2=xyxy$$
$$f(x)f(y)=x^2y^2=xxyy $$
Since $f(xy)=f(x)f(y)$ then by substitution:
$$xyxy=xxyy$$
Multiplying the right by $y^{-1}$ and the left by $x^{-1}$ then:
$$yx=xy$$ which means G is abelian

*Assume G is abelian, we want to show $f$ is a homomorphism

For the 2nd part of the proof, would I just work backwards from the first part of the proof? Here is an outline:
then for $x,y \in G$
$$yx=xy$$ by definition of abelian groups.
Multiple the right by y and the left by x, we have:
$$xyxy=xxyy$$
which is equal to:
$$(xy)^2=(x)^2(y)^2$$
since we are given $f(x)=x^2$ then translating this to the above statement:
$$f(xy)=f(x)f(y)$$
which satisfies the property of homomorphism.
Does that look right?

A: Your solution is indeed correct and just to put it in a nice way what you can do for the 2nd part is the following
You need to show that $f(xy) = f(x)f(y)$. Proceed as follows
\begin{align*}
f(xy) &= (xy)^2\\
&=xyxy\\
&=xxyy & & (\text{because $xy=yx$})\\
&=x^2y^2\\
&=f(x)f(y).
\end{align*}


Q: Windows is unable to remember login credentials for DAV network share I have a WebDAV server running on a linux server through Apache, which I am then attempting to map on a windows machine.
The mapping works fine, I provide my credentials and it logs me in, but the windows machines are unable to remember my credentials and I am forced to hit the "Login" button every time I open a new document, as well as when the machine is turned on or woken up from sleep mode. On machines running anything lower then Windows 7, I am also forced to manually type my username and password into the login box for every resource used in a document (such as images in a word document and similar).
My apache setup uses Digest authentication with the following config;
    Alias /group /home/webdav/group
    <Location /group>
            DAV On
            AuthType Digest
            AuthName "group"
            AuthUserFile /home/webdav/users/group-password
            Require valid-user
    </Location>

I don't think the config is the reason for this odd behavior, but more that windows is unable to automatically respond to requests for login credentials (and in the situation with the machines running Vista and lower that they can't even save them for some odd reason).

A: May be mapping to a network drive can help?
net use x: "http://server.net:80/folder" /persistent:yes /User:<user> <password>

Note, that Windows XP doesn't support mapping to root directly, only to subfolders

A: Credential Manager did not work for me, but this registry setting worked in my case (Alfresco with Kerberos Auth):
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WebClient\Parameters\AuthForwardServerList
Create this entry as MULTI_SZ (Multi-String Value) and populate it with your webdav URL. In my case I added:
https://server.domain
https://server.domain/*
server.domain
Avoid using wildcards, if possible, because you are deactivating a security feature for given URLs. More Infos: https://support.microsoft.com/en-us/help/943280

A: Manually adding the credentials to Credential Manager has worked for me in the past, on Vista and XP systems, when the system 'loses' credentials on a logoff/reboot. Windows 7 seems to do a much better job of automagically caching them, which may explain why the problem isn't observed there.
XP: KB306541
Vista/7: http://windows.microsoft.com/en-US/windows7/What-is-Credential-Manager
If you want something scriptable, you can try: http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/e91769eb-dbce-4e77-8b61-d3e55690b511/


Q: Differentiability of a function from the plane to the line at the origin Let $f: \mathbb{R}^2 \to \mathbb{R}$ be a function such that $f(x,y) = (x^3 + y^3)^{1/3}$. I want to study the diffrentiability of $f$ at the origin. My claim is that it is not differentiable at the origin.
MY try:
To show this, suppose by contradiction that it is differentiable at the origin. Then, by definition, there exists a linear $T$ such that
$$ T(x,y) = \lim_{h \to 0} \frac{f(0 + h) - f(0)}{||h|| } =_{h = (x,y)}  \lim_{(x,y) \to 0} \frac{f(h)}{||h||} = \lim_{(x,y) \to 0} \frac{ (x^3+y^3)^{1/3}}{(x^2+y^2)^{1/2}}$$.
Notice, $T(1,0) = T(0,1) = 1$. But $T(1,1) = 2^{-1/6}$. Hence, $T$ cannot be linear. This is a contradiction, and hence $f$ cannot be differentiable at the origin.
Is this correct? Any other way to solve this problem?

A: Your idea is more or less correct, but you might want to made that rigorous. Note that $f$ is differentiable at $(0,0)$ if there is a linear map $T: \mathbb R^2 \to \mathbb R$ such that
$$f(x, y) = f(0,0) + T(x, y) + o(\sqrt{x^2+ y^2})\ .$$
That is
$$(x^3 + y^3)^{\frac{1}{3}} = ax + by + o(\sqrt{x^2 + y^2})\ .$$
By putting $y=0$ and $x=0$, we have $a=b=1$. By setting $x=y$, we have
$$2^{\frac{1}{3}} x = 2 x + o(|x|)\ .$$
Divide by $x$ and take $x\to 0$, we have $2^{\frac{1}{3}} = 2$, which is impossible. This shows that $f$ is not differentiable at $(0,0)$.

A: You could also look at the function’s directional derivatives at the origin:
If $\mathbf u=(\cos \theta,\sin \theta)$, then $$D_{\mathbf u}(0,0) = \lim_{h \to 0} \frac{f(h\cos \theta,h\sin \theta) - f(0,0)}{h}=(\cos^3\theta+\sin^3\theta)^{1/3}$$
But if $f$ is differentiable, then we must also have $D_\mathbf u=\nabla f\cdot \mathbf u=\cos \theta+\sin \theta$ at the origin (since $f_x(0,0)=f_y(0,0)=1$).


Q: ZOOM-IN & ZOOM-OUT 2D graphics C# i have  to ZOOM-IN & ZOOM-OUT specific portion of  2D-graphics like (line, Rectangle, circle) which i have drawn on winform.
I am not used any picture box, panel.
I crated simple program to draw circle & on button click try to zoom
but it showing error "parameter is not valid"
in method Drawing() @ Line- DeviceContexct.Transform = mainViewTransform;
public Graphics DeviceContexct;
  public Matrix mainViewTransform = new Matrix();

    private void ScalingCircle_Paint( object sender, PaintEventArgs e )
            {
                Pen myPen = new Pen(Color.Blue, 1);
                e.Graphics.DrawRectangle(myPen, 50, 50, 100, 100);
                mainViewTransform.Scale(3, 2);
                DeviceContexct = e.Graphics;
            }
     private void Drawing(Graphics gr)
            {
                Pen myPen2 = new Pen(Color.Red, 1);
                DeviceContexct.Transform = mainViewTransform;
                DeviceContexct.DrawRectangle(myPen2, 50, 50, 100, 100);
            }
       private void button1_Click( object sender, EventArgs e )
            {
                Drawing(DeviceContexct);

            }

A: I prefer to draw into Bitmaps with System.Drawing.Graphics object.
Then you can use your graphics object with "go.DrawImage(...)" to draw the bitmap directly into your winforms and actually give it a scale.
https://msdn.microsoft.com/en-us//library/ms142040(v=vs.110).aspx

A: I got the solution, thanks for your help.
I only need to call refresh/invalidate etc on button click.
public partial class ScalingCircle : Form
{
    public Graphics DeviceContexct;
    // current transformation matrix of main view (offset & scaling)
    public Matrix mainViewTransform = new Matrix();

    public int scale = 1;

    public ScalingCircle()
    {
        InitializeComponent();
        DeviceContexct = Graphics.FromHwnd(this.Handle);
        DeviceContexct = this.CreateGraphics();
    }

    public void ScalingCircle_Paint(object sender, PaintEventArgs e)
    {
        DeviceContexct = e.Graphics;
        DeviceContexct.PageUnit = GraphicsUnit.Pixel;
        DeviceContexct.Transform = mainViewTransform;
        ScalingCircle1(scale);
    }

    private void ScalingCircle1(int x )
    {
        Pen myPen2 = new Pen(Color.Black, 1);
        DeviceContexct.Transform = mainViewTransform;

        Rectangle myRectangle = new Rectangle(50, 50, 100 * x, 100 * x);
        DeviceContexct.FillRectangle(new SolidBrush(Color.BurlyWood), myRectangle);
    }

    private void ScalingCircle_Load( object sender, EventArgs e )
    {
        this.ResizeRedraw = true;
      }

    private void button1_Click( object sender, EventArgs e )
    {
        scale += 5;
        this.Refresh();
    }

    private void button2_Click( object sender, EventArgs e )
    {
        if (scale > 1)
        {
            scale -= 5;
            this.Refresh();
        }
    }
}

A: You can use transformations for that. The graphics object you use for painting things has a Transformation property of type System.Drawing.Drawing2D.Matrix.
Graphics also has the ScaleTransform method.
I haven't used it myself, but that is how microsofts Chart does it.
https://msdn.microsoft.com/de-de/library/system.drawing.drawing2d.matrix(v=vs.110).aspx
https://msdn.microsoft.com/de-de/library/system.drawing.graphics.scaletransform(v=vs.110).aspx


Q: End processing a stream using event-stream I am reading a large JSON file using JSONStream and I want to call a method when the whole stream is processed.
var JSONStream = require('JSONStream'), es = require('event-stream');

es.pipeline(
  fs.createReadStream('file.json'),
  JSONStream.parse(['features', true]),
  es.map(function (data) {
    console.log("Added data");
  })
);

How can I do that?

A: I used 'event-stream' for processing of ~200kB files contain JSONs inside and got the issue when 'end' Event was never called when using 'event-stream', if I put .on('end') after event-stream pipes. But when I put it Before pipes - everything works just ok!
stream.on('end',function () {
            console.log("This is the End, my friend");
     }).on('error',function (err) {
                console.error(err);
     }).pipe(es.split())
       .pipe(es.map(function (line, cb) {
                //Do anything you want here with JSON of line
                return cb();
            }));

nodejs,  event-stream

A: Sorted. Save the read stream in a variable and pipe an on('end', function) on that read stream.


Q: python getting many to many from model mixin returning None I have a model:
class Employee(models.Model, MyMixin):
    full_name = models.CharField(max_length=255)
    items = models.ManyToManyField(Item, blank=True)

and a mixin class:
class MyMixin(object):

    def my_m2m(self, field):
        field_value = getattr(self, field)
        print(field_value)
        // do something with many to many field

emp = Employee()
emp.my_m2m("items")

It gives me the result like employee.Item.None while printing emp.my_m2m("items")
 on console.
If I do emp.items.all() it gives me the result but I cant get it by name.
Why is it not giving the list of item associated with it ?
Am I missing anything ?

A: As you say, adding .all() gives the result, so you need to add that to your dynamic lookup:
field_value = getattr(self, field).all()


Q: "NetworkError: 404 Not Found - http://localhost/magento2/pub/media/"? i run magento2 get error

"NetworkError: 404 Not Found -
  http://localhost/magento2/pub/media/"

i tried run php -f bin/magento setup:upgrade
get
missing permissions magento2/pub/media

how do fix it. nay help?

A: Although it might work temporarily in development, you should not use 777 permissions. Magento will write new files with a different set of permissions next time it runs.
We recommend 770/660 permissions with ownership split between a local user and the web server user.
Magento file system owner documentation
Recommended file ownership and permissions

A: give 777 permission to pub/static folder and var folder then run below command to regenerate all css and js file in pub/static folder if you changed code directly in pub folder then you will loss that data because it dynamically generated  files
bin\magento sampledata:deploy


Q: Where does Identity Server 4 stores client's code verifier I have setup Identity Server 4 with EF & Angular client (OIDC JS library) with Authorization Code with PKCE grant. I see the code challenge & method being passed in the /authorize url. As per specification, auth server stores code challenged passed by client on auth server to be verified later when client sends code verifier.
Where does identity server 4 stores the code challenge in database?

A: It depends on how it is implemented, one common way is to store them in a database table called PersistedGrants. The Authorization Codes are also stored in this table, however they are deleted as as soon as they are used.
The image shows what it can look like in this table.

The Code_challenge is stored together with the access-code in the database and you can see the code where they pack it all together and then store it as an encrypted blob in the database.

*

*AuthorizeResponseGenerator.cs (look at the end of the file)

The authorization code is stored in the database as the image below shows:

The actual payload is encrypted and protected, at it looks like this:
{
  "PersistentGrantDataContainerVersion": 1,
  "DataProtected": true,
  "Payload": "CfDJ8OFLAj3iVVVHvhgvjcKB19Z7-Hms4IIQobGgGl7VnJQCtKiB-Inr3h-mcWCxxD8dJ4QNTbuVeywbT6ROsaf13EpaIQDWtLgbnSPvCDTLQeWTO_vP0UtDwJ7TTCc5aTvKEp_9hX9S1b3l685bmBMlTIcZFqGGM2VfK0qasWCqKSQcTxeN6cgJygZEQNMgAG4ipqr..."
}


Q: How to Fetch Child BU Name Currently, I'm fetching Job ID, Subscriber key of a subscriber who clicks on the landing page.
Code in the Email,
%%[ SET @Sub = _subscriberkey SET @CloudPageID = 1646]%%

Code in the landing page
%%[

set @Subs = AttributeValue('_SubscriberKey')
 set @JobId = AttributeValue('jobID')
 set @memberid = AttributeValue("memberid")
 set @member_busname = AttributeValue('member_busname')

 Set @lookUp = LookupRows('Page Visits','Subscriber Key', @Subs,'jobid', @jobid)

 IF RowCount(@lookUp) == 0 THEN
 InsertData('Page Visits','Subscriber Key', @Subs,'jobid', @jobid,'memberid', @memberid, 'member_busname', @member_busname , 'Event Date', NOW())
ENDIF
 ]%%

Using member_busname, it is fetching the Parent BU Name even though if I send the email from the child BU, Is there a way to get the child BU name?

A: member_busname is the Enterprise Business Name, not the name of the BU which is why it's all the same across the child BUs. The BU name is not available as a personalization string. There are SOAP objects that could be useful ("BusinessUnit", "Account"), but I don't think they are retrievable from the child BUs. You could use the memberid and an IF statement on your landing page to set the MID name, presumably the BU name will not change often. If you have a large number of BUs, you could create a Data Extension to contain all the BU names (perhaps in Shared DEs folder for easy access across BUs), and do a lookup from the landing page using the MID.

A: You could probably grab it via the MID using WSProxy on the 'BusinessUnit' object.
Something like:
<script runat="server">

Platform.Load("Core","1.1.1");

  var prox = new Script.Util.WSProxy();

  //This will cause an error if the memberid attribute does not exist.
  //May want to set try/catch or similar error handling on this to prevent 500 error
  var mid = Platform.Variable.GetAttributeValue('memberid');

  /* Set ClientID */
  prox.setClientId({ "ID": mid }); //Impersonates the BU

  var cols = ["Name"];
  var filter = {
      Property: "ID",
      SimpleOperator: "equals",
      Value: mid
  };
  var res = prox.retrieve("BusinessUnit", cols, filter);

  var buName = res.Results[0].Name;

</script>

Then buName would equal the stored name inside the SOAP object of your Business Unit.
As noted in the comments in the code, you will want to put some sort of error handling on the defining of the mid variable though as if the page is accessed outside of the ClougPagesURL() function (which passes the memberid) then that attribute does not exist, which causes the GetAttributeValue() function to error, throwing a 500 error.

EDIT
As @JoshdeBlank commented, this is currently only functional in the parent BU. To account for that, I would recommend adjusting the above SSJS to grab all the MID and BU Name and push that into a shared DE. Then turn this into a script activity and have it run daily (or at whatever interval) to collect most recent BU MID and name into the DE.  You can then use a lookup to that DE with the memberid to grab the name on your page.

A: I've created a new DE with all the Child BU names and MID's and used lookup and get the data from it. It is working for me.
%%[

set @Subs = AttributeValue('_SubscriberKey')
 set @JobId = AttributeValue('jobID')
 set @memberid = AttributeValue("memberid")

 Set @lookUp = LookupRows('Page Visits','Subscriber Key', @Subs,'jobid', @jobid)

SET @lookupvalue = LookupRows('BU Details','memberid', @memberid)

IF Rowcount(@lookupvalue) >0 THEN
   SET @BURow = Row(@lookupvalue, 1)
   Set @BUName = Field(@BURow, 'BUName')
ENDIF

 IF RowCount(@lookUp) == 0 THEN
 InsertData('Page Visits','Subscriber Key', @Subs,'jobid', @jobid,'memberid', @memberid, 'BUName', @BUName , 'Event Date', NOW())
ENDIF
 ]%%


Q: c++ syntax using inheritance I'm having trouble with the syntax of an inherited classes and constructors and methodes in them.
I want to implement a class date and a child class date_ISO that would set a given day, month, year in a specific order and through a method write it into string.
I thing my base class date works fine, but I'm having problems with the derived date_ISO
How do I use correct syntax to inherite a constructor like Date, and how do I implement and execute it?
code for class Date:
#ifndef DATE_HPP
#define DATE_HPP
#include <sstream>
#include <string>
#include <iostream>

class Date
{

    private:
    short day;
    short month;
    short year;

    public:
    std::string getDD(short day);
    std::string getMM(short month);
    std::string getYear(short year);

    Date(short day, short month, short year);

    virtual std::string format() =0;
    virtual ~Date() =0;

};

        std::string Date::getDD(short day)
    {
        std::stringstream s_day;

        if(day < 10)
        {
        s_day << '0' << day;
        }
        return s_day.str();
    }

    std::string Date::getMM(short month)
    {
        std::stringstream s_month;
        if(month < 10)
        {
        s_month << '0' << month;
        }
        return s_month.str();
    }

    std::string Date::getYear(short year)
    {
        std::stringstream s_year;
        s_year << year;
        return s_year.str();
    }

    Date::Date(short day, short month, short year) : day(day), month(month), year(year){}

#endif

code for class Date_iso:
#ifndef DATEISO_HPP
#define DATEISO_HPP
#include "Date.hpp"
#include <sstream>
#include <string>
#include <iostream>

class DateISO : public Date
{
    public:
    std::string format();
    DateISO(short day, short month, short year);
};

    std::string DateISO::format()
    {
        std::stringstream ss;
        ss << this->getYear() << this->getMM() << this->getDD();
        return ss.str();
    }

    DateISO::DateISO(short day, short month, short year){}

    Date::~DateISO()
    {
    }

#endif

Followup question:
I have written a small code with the tips i got here and I don't use it properly. I'm trying to have a polymorphic pointer that would help create a few objects of the derived class but firstly I wanted to check what happends when I create a simple objekt of the derived class. It doesnt compile and I get a "undefined referance" error to all my get methods.
I add the new code (old code no longer relevant but is still there for comparison).
code for class Date:
#ifndef DATE_HPP
#define DATE_HPP
#include <sstream>
#include <string>
#include <iostream>

class Date
{

    private:
    short day;
    short month;
    short year;

    public:
    std::string getTT(short day);
    std::string getMM(short month);
    std::string getYear(short year);

    Date(short day, short month, short year);

    virtual std::string format() =0;
    virtual ~Date() =0;

};

        std::string Date::getTT(short day)
    {
        std::stringstream s_day;
        this->day = day;
        if(day < 10)
        {
        s_day << '0' << day;
        } else {
        s_day << day;
        }
        return s_day.str();

    }

    std::string Date::getMM(short month)
    {
        std::stringstream s_month;
        this->month = month;
        if(month < 10)
        {
        s_month << '0' << month;
        } else {
        s_month << month;
        }
        return s_month.str();
    }

    std::string Date::getYear(short year)
    {
        this->year = year;
        std::stringstream s_year;
        s_year << year;
        return s_year.str();
    }

    Date::Date(short day, short month, short year) : day(day), month(month), year(year)//prueft die Attribute
    {
        //some code
    }

#endif

code for class dateISO:
#ifndef DateISO_HPP
#define DATEISO_HPP
#include "Date.hpp"
#include <sstream>
#include <string>
#include <iostream>

class DateISO : public Date
{
    public:
    std::string getTT();
    std::string getMM();
    std::string getYear();

    std::string format();
    DateISO(short day, short month, short year);
    ~DateISO();
};

    std::string DateISO::format()
    {
        std::stringstream ss;
        ss << DateISO::getYear() << DateISO::getMM() << DateISO::getTT();
        return ss.str();
    }

    DateISO::DateISO(short day, short month, short year) : Date(day, month, year){}

    DateISO::~DateISO()
    {
        //some code
    }

#endif

and code for the test main:
#include "DateISO.hpp"
//#include "DateDE.hpp"
#include "Date.hpp"
#include <sstream>
#include <string>
#include <iostream>

int main()
{
    DateISO date_iso(5,9,2017);
    std::cout << date_iso.format();

return 0;
}

How do I use a polymorphic pointer to create and manage objekts?
what is wrong with the object that I created (that gives me an error)?
I am sorry for the long question and am thankful for any help.

A: You already know how to use a constructor initializer list as you do it in the Date constructor.
You "call" a parent class constructor just the same way. In your case
DateISO::DateISO(short day, short month, short year)
    : Date(day, month, year)  // "Call" the parent constructor
{}

A: In addition to Some Programmer Dude's answer, it is also possible to inherit a constructor with 'using' like so:
class DateISO : public Date
{
    using Date::Date;
};

This will redeclare all the base classes constructors in the child class, and all arguments will be forwarded to the base constructor, so this probably wouldn't be suitable if your base class had multiple constructors and you only wanted to inherit one of them, nor if your child class has additional members which must be initialised, but for your case where all members are in the base class and the child class only adds methods this should be okay. See the section on 'Inheriting Constructors' for more information.


Q: Method for converting float to integer after checking I am trying to perform multiple operations on two numbers (say A and B). These two numbers are getting inputted via a single string. So I am converting them into Double values and performing an operation on them.
The poblem is that the output is always double. I would like to have the answer to be an integer answer if the result is an integer, say, 2 instead of 2.0.
Cases:

*

*A= 2 and B= 2 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4

*A= 2.0 and B= 2.0 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4.0
I looked it up and it wasn't much help. As such questions either deal with conversion or precision. Links to any similar/helping questions that I might have missed will work too. I know how to convert from float to int, but looking for optimum way to check if a number can be represented in int or not. And get result accordingly.
Thank you

A: You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below.
double num1 = 20.0;
double num2 = 5.0;

if (num1%num2 == 0) {
    System.out.println((long) (num1/num2));
} else {
    System.out.println(num1/num2);
}


Q: Change div value based on  option Using this great plugin
http://exodecreations.com/jQuery/jqDropDown.html
My Jquery code:
jQuery(function() {
  jQuery('#list4').jqDropDown({
    optionChanged: function(){
      jQuery("#firmos").html('My New Text');
    },
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

My php code:
<form action="#">
  <select id="list4" name="invoices">
    <option>Aspen</option>
    <option>Tokyo</option>
    <option>Cannes</option>
    <option>Capetown</option>
    <option>Paris</option>
    <option>Nice</option>
    <option>Geneva</option>
  </select>
</form>

Based on the option selected i would like the div with id #firmos to change its value.
My current example changes the div text to a single value but i will need a different value for each option..
Any efficient ideas? The list of cities will be around 50.. maybe define an attribute within each <option> ?

A: I believe this may work.
jQuery("#firmos").html($(this).val());

In your document ready function it would look like this.
jQuery(function() {
  jQuery('#list4').jqDropDown({
    optionChanged: function(){
      jQuery("#firmos").html($(this).val());
    },
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

Edited
Actually if you want to redisplay the option in another element this control has a parameter called place holder
you could do this.
jQuery(function() {
  jQuery('#list4').jqDropDown({
    placeholder: '#firmos',
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

Edited Again
If you want a custom value you can do something like this
jQuery(function() {
  jQuery('#list4').jqDropDown({
    optionChanged: function(){
      jQuery("#firmos").html((function (currentElement) {
        switch (currentElement.val())
        {
          case "someval":
            return "somethingSpecial1";
            break;
          case "someval2":
            return "somethingSpecial2";
            break;
          /// more case statements.
        }
      })($(this)));
    },
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

A: Well, I looked that this plugin just replicates a select element in a list <li> and seems not possible to get the exact changed value from the select because it doesn't change if you see the DOM (that makes me assume that the onchange event from that plugin is used just to trigger something when your list changes).
So, it seems you need to do some tricky thing to get the selected value implementing an onchange event recreation.
Like this:
Live Demo: http://jsfiddle.net/oscarj24/nuRKE/
$(function () {

    var firmos = $('#firmos');

    $('#list4').jqDropDown({
        direction: 'up',
        defaultStyle: false,
        containerName: 'theContainer',
        toggleBtnName: 'awesomeToggleClass',
        optionListName: 'thisListIsRocking',
        effect: 'fade',
        effectSpeed: 300
    });

    //This will be your new 'onchange' event when using 'jqDropDown' plugin.
    $('ul .ddOption').on('click', function(e){
        var selected = $.trim($(e.target).text());
        switch (selected)
        {
          case 'Aspen':
            firmos.html('You selected Aspen.');
            break;
          case 'Tokyo':
            firmos.html('You selected Tokyo.');
            break;
          //Do the same for other options.
        }

    });
});


Q: Problem with SSD MobileNet V2 FPNLite 320x320 conversion for Coral AI TPU I'm trying to run Tensorflow model lite on Rasperry PI with Coral TPU.
Model is SSD Mobile Net 2. It works fine on PC after conversion either fully quantized or with float I/O.
However when I run it on Coral TPU I got a lot of wrong result. Usually it is false positive class 0 (mapped to person).
Could somebody help me, I run out ideas how to fix it?
Tensorflow version: 2.5.0
Tensorflow Lite version: 2.5.0
Steps I did:

*

*Download the model: http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz

*I changed input resize layer to 320x320, but the result is the same as original 300x300.

*I converted saved model to tf lite friendly format:

python3 object_detection/export_tflite_graph_tf2.py --pipeline_config_path /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-init/pipeline.config --trained_checkpoint_dir /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-init/checkpoint --output_directory /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-fixed-input

*Model convertion to TF Lite format, model_path points to the previous step output, I tried quantize True/False and the commented part of the code below:

 converter = tf.lite.TFLiteConverter.from_saved_model(model_path)
    if quantize:
        # converter.optimizations = [tf.lite.Optimize.DEFAULT]
        # converter.representative_dataset = representative_data_gen
        # converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
        # converter.inference_input_type = tf.uint8
        # converter.inference_output_type = tf.uint8

        converter.representative_dataset = representative_data_gen
        converter.optimizations = [tf.lite.Optimize.DEFAULT]
        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]
        converter.inference_input_type = tf.uint8
        converter.inference_output_type = tf.uint8
        converter.allow_custom_ops = True

        print(converter.experimental_new_quantizer)  # outputs True
        print(converter.experimental_new_converter)  # outputs True
    else:
        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
        converter.optimizations = []

    tflite_model = converter.convert()

    with open(lite_model_path, 'wb') as f:
        f.write(tflite_model)

Data provider, used code from step 5:
def representative_data_gen():
    from cocodataset import CocoDataSet
    coco = CocoDataSet(input_size, input_size)
    images = coco.get_calibration_dataset(500)
    for img in images:
        yield [img]

*Repressentative data set - Coco 2017 valuation data - 500 samples.

 class CocoDataSet:
  ...
    def get_calibration_dataset(self, limit: int):
        with open(self.annotation_file, 'r') as f:
            annotations = json.load(f)
        image_info = annotations['images']
        random.shuffle(image_info)
        image_info = image_info[:limit]
        image_paths = []
        for img in image_info:
            image_path = self.image_dir + img['file_name']
            image_paths.append(image_path)

        print(f"{limit} images will be returned")
        images = []
        fl = True
        for i, path in enumerate(image_paths):
            print(f"Loading {i}/{len(image_paths)}:" + path)
            image = cv.imread(path)
            image = cv.cvtColor(image, cv.COLOR_BGR2RGB)

            tensor = np.zeros((self.input_height, self.input_width, 3), dtype=np.uint8)
            _, _, channel = tensor.shape

            h, w, _ = image.shape
            scale = min(self.input_width / w, self.input_height / h)
            w, h = int(w * scale), int(h * scale)
            image = cv.resize(image.copy(), (w, h), interpolation=cv.INTER_LINEAR)

            reshaped = image
            margin_x = (self.input_width - w) // 2
            margin_y = (self.input_height - h) // 2
            tensor[margin_y:h + margin_y, margin_x:w + margin_x] = reshaped

            tensor = np.expand_dims(tensor, axis=0)

            tensor = tensor.astype(np.float32) - 127.5
            tensor = tensor * 0.007843

            images.append(tensor)

        return images

*Coral AI compilation:

edgetpu_compiler ssd_mobilenet_v2_coral.tflite

*Inference with Coral AI (Rpi). It works fine with SSD2 Mobile Net provided in Coral AI SDK.

   x, y, scale = self.set_image_input(self.interpreter, region)

   self.interpreter.invoke()

   detection_boxes = self.get_output_tensor(self.interpreter, 0)
   detection_classes = self.get_output_tensor(self.interpreter, 1, np.int)
   detection_scores = self.get_output_tensor(self.interpreter, 2)
   count = self.get_output_tensor(self.interpreter, 3, np.int)

8.Input image, scaled and centered:
def set_image_input(self, interpreter: tflite.Interpreter, image: np.ndarray) -> (int, int, float):
        self.did = self.did + 1
        width, height = (self.input_height, self.input_width)
        stretch = False
        if stretch:
            h, w, _ = (self.input_height, self.input_width, 1)
        else:
            h, w, _ = image.shape

        cv.imwrite(f"{self.logs_dir}/image{self.did}.png", image)
        scale = min(width / w, height / h)
        w, h = int(w * scale), int(h * scale)
        tensor = self.input_tensor(interpreter)
        tensor.fill(0)
        _, _, channel = tensor.shape

        image = cv.resize(image.copy(), (w, h), interpolation=cv.INTER_LINEAR)

        reshaped = image
        if tensor.dtype == np.float32:
            reshaped = reshaped * (1.0/255) - 1
        margin_x = (self.input_width - w) // 2
        margin_y = (self.input_height - h) // 2
        tensor[margin_y:h + margin_y, margin_x:w + margin_x] = reshaped

        return margin_x, margin_y, scale

*Getting output tensor:

 def get_output_tensor(self, interpreter: tflite.Interpreter, index: int, result_type=np.float):
    output_details = interpreter.get_output_details()[index]
    quantization = output_details['quantization']
    dtype = output_details['dtype']
    tf_index = output_details['index']
    tensor = np.squeeze(interpreter.get_tensor(tf_index))
    if quantization != (0, 0):
        input_scale, input_zero_point = quantization
        tensor = (tensor.astype(np.float32) - input_zero_point) * input_scale
    if tensor.dtype != result_type:
        tensor = tensor.astype(result_type)
    return tensor

What I noticed that the results differs a little when I run the conversion a couple of times - the representative data is randomly obtained from the set. The differences are much more visible on Coral AI compiled model, that that I run on PC.

A: The accuracy quantized SSD model is slightly lowered than the float model, you can probably try the efficient-det model: https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/object_detector

A: It looks that the newest update of Coral compiler and RaspberryPI runtime solved the issue.
RPI runtime after update: 2.5.0.post1
Edge CPU compiler after update: 16.0.384591198
Some example detections (class, score):
Coral:
[(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7428985834121704), (1, 0.8485066890716553), (24, 0.6919153332710266)]

TF Lite - CPU:
[(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7356152534484863), (1, 0.8412233591079712), (24, 0.7028403282165527)]

TF CPU:
[(0, 0), (1, 0.75359964), (0, 0), (1, 0.7409908), (1, 0.7797077), (1, 0.8114069), (24, 0.750371)]


Q: Upgrading Ghost Broke My Website My ghost blog was running fine and i've just tried to upgrade it using the guide posted here. I am using Digital Ocean as the web host by the way.
After upgrade it's showing some problems, I've looked at the error log and it's showing a bunch of errors like this:
2015/09/07 13:22:50 [error] 3987#0: *23 connect() failed (111: Connection refused) while connecting to upstream, client: (IP HIDDEN), server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:2368/favicon.ico", host: "HOST HIDDEN", referrer: "http://URL HIDDEN/"

I've removed IPs and what not

A: Since nobody has answered it I might as well post what worked for me. I was able to start the blog manually with npm start it was just the service ghost start that reported [OK] but didn't actually start it.
First I was able to find the error in /var/log/nginx/errors.log
2016/02/08 21:18:27 [error] 601#0: *2086 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:xxxx/favicon.ico", host: "mydomain.com", referrer: "http://example.com/path-to-post/"
I had to recursively change the owner of /ghost directory like this:
chown -R ghost:ghost ghost/*

I executed it from /var/www
thanks to @BrettDeWoody for his post


Q: redirect to a action that expects value in other controller I have a controller StepOfIdea,and this controller has a action like this :
 StepOfIdeaRepository objStepOfIdearepository=new StepOfIdeaRepository();
        public ActionResult Index(int ideaId)
        {
            return View(objStepOfIdearepository.FindBy(i=>i.IdeaId==ideaId));
        }

So i have another controller named idea and this controller has a view named index
@model IEnumerable<DomainClass.Idea>

@{
    ViewBag.Title = "Index";
}

لیست

    @if (User.IsInRole("User"))
    {

            @Html.ActionLink("ایده جدید", "Create", new {step = 1})

    }

        @if (User.IsInRole("Admin"))
        {

            @Html.DisplayNameFor(model => model.User.Name)

        }

            @Html.DisplayNameFor(model => model.IdeaPersion)

            @Html.DisplayNameFor(model => model.IdeaEnglish)

            @Html.DisplayNameFor(model => model.IdeaResult)

            @Html.DisplayNameFor(model => model.Date)

@foreach (var item in Model) {

         @if (User.IsInRole("Admin"))
        {

            @Html.DisplayFor(modelItem => item.User.Name) @Html.DisplayFor(modelItem => item.User.Name)

        }

            @Html.DisplayFor(modelItem => item.IdeaPersion)

            @Html.DisplayFor(modelItem => item.IdeaEnglish)

            @Html.DisplayFor(modelItem => item.IdeaResult)

            @Html.DisplayFor(modelItem => item.Date)

            @Html.RenderAction("ویرایش","index", stepofidea, new { id=item.Id }) |

            @Html.ActionLink("ویرایش", "Edit", new { id=item.Id }) |
            @Html.ActionLink("نمایش", "Edit", new { id=item.Id }) |
            @Html.ActionLink("حذف", "Delete", new { id=item.Id })

}

In this line
    @Html.RenderAction("ویرایش","index", ????, new { id=item.Id }) |

I want to redirect to index action of  stepOfIdea controller and pass a value .But the above line doesn't work .

A: I think you confused some terms in translation to English, and what you are actually looking for is to create an Link that also passes a variable.
You can do this very simply, by:
@Html.ActionLink("ویرایش", "Index", "StepOfIdea", new { id = item.Id }, null)

This will create the HTML:
ویرایش


Q: Why does content size of UITableView Change I have a UITableView that I am loading my data in 3 blocks. I load the latest 10 records and when user pulls up using the UIRefreshControl, I load the preceding 10 and show the last row from the previous block. I store the previous content size right before I load the new set from database
previousContentSizeHeight = tableView.contentSize.height

and then when data comes and update my array, I use previous to calculate the new content size of table
let difference = tableView.contentSize.height -
     previousContentSizeHeight - MinimumCellHeight

self.messageTableView.setContentOffset(CGPoint(x: 0, y: difference), animated: false)

This works for the most part. It behaves correctly after the viewDidAppear when loading the first set and when loading the 2nd set, but in the third set it starts changing in content size. It gets decreased! My understanding is if I am adding data to it (not deleting anything), the content size should only grow.
I have in multiple places in my code readings of the table content size like this event:
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print("tableView.contentSize.height is: \(tableView.contentSize.height)")
}

as I am scrolling up and down, I see the number decrease and sometimes increase and decrease
Why does content size changes in size!?
NOTE: I want to stick to using the content offset. I have more luck with it than IndexPath.
UPDATE #1
@Sohil R. Memon: I tried your suggestion. Per screenshot, I added a print statement and as you can see the viewDidLayoutSubviews is still not executing. i tried inside the endDisplaying with self.messageTableView and just tableView

A: Once the cell are displayed and didEndDisplaying is called, there are more things to process and when you scroll cellForItem calls again and that gives you different sizes.
In order to get the exact contentSize of UITableView once all the cells are displayed, you can get it from below method. Just write the below method in your UIViewController class.
override func viewDidLayoutSubviews() {
    print(tableView.contentSize.height) //Exact Content Size of UITableView
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tableView.layoutIfNeeded()
}

Hope this helps!


Q: First problems from text on number theory
Express $635,318,657$ as sum of two fourth powers in two different ways. It is the smallest number with this property?

and

$1105$ can be expressed as the sum of two squares in 4 different ways. Find them.

The solution to these problems wouldn't be of any help but how to think about such problems and what tools to use?
Source: "Elementary Numebr Theory with applications" by Thomas Koshy

A: Question $3$ is the only one that is connected to long-established theory.
Note that
$1105=5 \times 13\times 17$, and that each of $5$, $13$, and $17$ is easily seen to be a sum of two squares.
By an identity that is a special case of Brahmagupta's Identity, the product of two sums of two squares is itself a sum of two squares. The identity is
$$(a^2+b^2)(c^2+d^2)=(ac-bd)^2+(ad+bc)^2=(ad-bc)^2 +(ac+bd)^2.$$
You can use the above identity to generate the representations of $1105$ as a sum of squares.  Do it!
The identity is interesting in many ways, and is less "magic" than it looks.
Let $p+qi$ be a complex number.  Then $|p+qi|^2$, the square of the norm of $a+bi$, is precisely $p^2+q^2$.
The Brahmagupta Identity then can be interpreted as saying that
$$ |(a+bi)(c+di)|^2 =|a+bi|^2|c+di|^2$$
(the square of the norm of a product is the product of the squares of the norms, or, taking square roots, the norm of a product is the product of the norms.)
Expressing  $1105$ as a sum of two squares can be thought of as finding all the ways to express
$$(2-i)(2+i)(3-2i)(3+2i)(4-i)(4+i)$$
in the form $(a-bi)(a+bi)$, where $a$ and $b$ are integers.
There is a quite thoroughly worked out theory of sums of two squares, that you can find in most books on Elementary Number Theory. For example, a prime of the form $4k+1$ can be expressed in essentially one way as a sum of two squares.  This is a result of Fermat.  The proof, though "elementary", is not all that easy.

A: Nowadays, the best (anyway, most efficient) way to solve the first problem is to type the number into Google to see what turns up. Alternatively, type it into the search window at the Online Encyclopedia of Integer Sequences, and it will lead you to http://oeis.org/A018786 which has some useful citations.


Q: Connect to sftp server with host key fingerprint using python 3.0 on Windows I am trying to connect to an sftp server using python on Windows. I cannot connect to the server without a hostkey. A lot of options, especially with pysftp ask for hostkey files which apparently aren't generated on Windows.
From what I can see is that I have 3 options:
1) [Most preferred] use a string to generate the required key through python code. But that's always producing errors - some of the code using StringIO doesn't work on Python 3 and the possible workarounds don't seem to work for me. Apparently I am not able to decode the key properly and I have no idea how to check for that. I have tried to generate PKey but I am not sure what I am doing wrong.
2) get the right format of known_hosts file (I have no idea what it should look like and couldn't find any samples online) - and put or add the hostkey there. That way I'd (hopefully) be able to use cnopts to connect to the server.
3) This is a fallback option, if the above two don't work: use python to call powershell script that does the work - I have been successful at this but would like to pass arguments from python script to powershell and then get results/status from powershell back to python.
The most relevant options that I have tried out:
Python - pysftp / paramiko - Verify host key using its fingerprint
Embedding public key as string in Paramiko Application
Using python pysftp package, getting a "SSHException: Bad host key from server" error
What I'd like is a sample string (that would look like the actual thing) and the steps around creating a key from it. Or a sample file that I can use to just plugin the details and run the code.


Q: В чем заключается ошибка в поисках координат view? Друже, выручайте, ей богу 3тий день колочусь , ничего не могу понять.
В кратце. Нужно узнать x,y кнопок на Лаяуте, проблема в том, что выдает 0.0. Но, я бы мог подумать, что нерабочий метод и т.д, но самое интересное это то, что скопировав данный метод и применив на другую активность  - все работает. Скоро сдавать работу, не имею малейшего понятия куда двигаться. Новичок в Android. Выручайте, братцы, кто чем может.
Код активности, где не работает :
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_graps_);
    Intent intent = getIntent();
    String textWindowS = intent.getStringExtra("editTextS");
    visibleGraph(textWindowS);
    drawGraph();
}

private void visibleGraph(String textWindows) {
    ......
        }

    }
}

private void drawGraph() {
    Button btA = (Button) findViewById(R.id.bt_A);
    Button btB = (Button) findViewById(R.id.bt_B);
    Button btC = (Button) findViewById(R.id.bt_C);
    Button btD = (Button) findViewById(R.id.bt_D);
    Button btE = (Button) findViewById(R.id.bt_E);
    Button btF = (Button) findViewById(R.id.bt_F);
    Button btG = (Button) findViewById(R.id.bt_G);
    Button btH = (Button) findViewById(R.id.bt_H);
    Button btJ = (Button) findViewById(R.id.bt_J);
    Button btK = (Button) findViewById(R.id.bt_K);
    Button btL = (Button) findViewById(R.id.bt_L);
    Button btM = (Button) findViewById(R.id.bt_M);
    Button btN = (Button) findViewById(R.id.bt_N);
    Button btO = (Button) findViewById(R.id.bt_O);
    drawingImageView = this.findViewById(R.id.drawingImageView);
    Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
           .getDefaultDisplay().getWidth(), (int) getWindowManager()
           .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
   drawingImageView.setImageBitmap(bitmap);

    Paint paint = new Paint();
    paint.setColor(Color.DKGRAY);
    paint.setStrokeWidth(3);

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

  //  canvas.drawLine(x1, y1, 100, 100, paint);

     //
     // вот тут отправляется view в метод, где должны определиться координаты, но возвращается всегда 0
    Point point = getCenterPointOfView(btA);
    System.out.println(point.x + " " + point.y);

}

private Point getCenterPointOfView(View view) {
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    int x = location[0] + view.getWidth() / 2;
    int y = location[1] + view.getHeight() / 2;
    return new Point(x, y);
}

А вот точно такой же Активити, решил я попробывать туда вставить точно такую же операцию, результат - верный.
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void continue_bt (View view){
    EditText editText = (EditText) findViewById(R.id.mainWindowText);
    String editTextS = editText.getText().toString();
   // тут отправляю view в метод и результат - верный
    Point point = getCenterPointOfView(editText);
    System.out.println(point.x + " " + point.y);
    Intent intent = new Intent(this,Graps_Activity.class);
    intent.putExtra("editTextS",editTextS);
    startActivity(intent);

}
private Point getCenterPointOfView(View view) {
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    int x = location[0] + view.getWidth() / 2;
    int y = location[1] + view.getHeight() / 2;
    return new Point(x, y);
}

}

A: Если вам нужно получить координаты View элемента, то это рано делать в методе onCreate(). Для этого можно использовать ViewTreeObserver. Это такой колбэк который срабатывает когда view уже имеет конкретные координаты.
Например:
    ViewTreeObserver vto = view.getViewTreeObserver(); // view для которого будут определены координаты

    vto.addOnGlobalLayoutListener (new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int x  = (int) view.getX();
            int y = (int) view.getY();
            Log.d("log", "X view: " + x);
            Log.d("log", "Y view: " + y);

        }
    });


Q: Not able to update reducer state in redux On change of select I want to save the value in reducer. But How can I pass the value into state.
below is the code I am using.
container/header/index.js
const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

const mapDispatchToProps = (dispatch) => ({
  setCloud: () => {
    dispatch(setCloud('sf'));
  },
})

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);

component/header/index.js
setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud('this.state.value');
    });
  }

render(){
    return(
    <select onChange={this.setCloudClick} value={this.state.value}>
        <option value="zscaler.net">zscaler.net</option>
        <option value="zscalerOne.net">zscalerOne.net</option>
        <option value="zscaler.net">ZscalerTwo.net</option>
        <option value="Zscaler Private Access">Zscaler Private Access</option>
    </select>
);
}

reducer.js
function reducer(state, action) {
  switch (action.type) {
    case 'SET_CLOUD' :
      alert(action.text);
      return state;
    default :
      return state;
  }
}
export default reducer;

A: From the callback, you need to pass the value and not the string
setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud(this.state.value);  // pass this.state.value here
    });
  }

However, when you are storing value in store, you need not store it locally. You can dispatch the value like
index.js
setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud(this.state.value);
    });
  }

render(){
    return(
         <select onChange={this.setCloudClick} value={this.state.value}>
            <option value="zscaler.net">zscaler.net</option>
            <option value="zscalerOne.net">zscalerOne.net</option>
            <option value="zscaler.net">ZscalerTwo.net</option>
            <option value="Zscaler Private Access">Zscaler Private Access</option>
        </select>
    );
}

container/header/index.js
const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

const mapDispatchToProps = (dispatch) => ({
  setCloud: (value) => {
    dispatch(setCloud(value));
  },
})

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);


Q: How to show html form using shortcode in wordpress? I want to show html form using shortcode. Here is my code:
add_shortcode('sms_order_form', 'sms_order_form_html');

function sms_order_form_html(){?>
'<form>

        0<input type="range" id="range" value="0" min="0" max="100"/>100
        0

</form>
<?php } ?>

But this doesn't print the form. but if I replace the HTML form by echo 'hello'; it prints hello. Is there any way to show any HTML using shortcode.
N.B.: shortcode is placed using elementor.

A: Shortcode should return a string:
<?php
add_shortcode( 'sms_order_form', 'sms_order_form_html' );

function sms_order_form_html() {
    ob_start();

    ?>
    <form>

            0<input type="range" id="range" value="0" min="0" max="100"/>100
            0

    </form>
    <?php

    return ob_get_clean();
}

A: Shortcode functions need to return the output in form of a string as opposed to outputting HTML right away. You can use output buffering to return your code like so:
add_shortcode('sms_order_form', 'sms_order_form_html');

function sms_order_form_html() {
  ob_start();
?>
<form>

        0<input type="range" id="range" value="0" min="0" max="100"/>100
        0

</form>
<?php
  return ob_get_clean(); // clear the output buffer, and return as string
}