text:
Q: Solving $\int_{-1}^{1}\int_0^{\sqrt{1 - y^2}} \int_{x^2 + y^2}^{\sqrt{x^2 + y^2}} xyz \, dz \, dx \, dy$ I am trying to solve the following integral:
$$\int_{-1}^{1}\int_0^{\sqrt{1 - y^2}} \int_{x^2 + y^2}^{\sqrt{x^2 + y^2}} xyz \, dz \, dx \, dy$$
I think that the best approach is to use cylindrical coordinates, But I'm now sure how to do that since this is one of the first exercises I make with cylindrical coordinates. How can I solve this?

A: Remarks:
You would first need to change the variables of integration to cylindrical coordinates using $ \ dx \ dy \ dz  = r  \ dr \ d\theta \ dz $.
Then you would also need to convert the function inside the integral to cylindrical coordinates using $x = r \cos\theta$, $y=r\sin\theta$, and $z = z$.
Finally, you will need to figure out the bounds for $r$, $\theta$, and $z$ in cylindrical coordinates for the region you are integrating over.
Solution:
First note that $x = r \cos\theta$, $y=r\sin\theta$, and $z = z$.
$I = \int_{y=-1}^{y=1} \int_{x=0}^{x=\sqrt{1-y^2}} \int_{z= x^2+y^2}^{z=\sqrt{x^2+y^2}} xyz  \ dz \ dx \ dy$
Let's try to simplify the bounds of the integral using the conversion from cartesian to cylindrical coordinates.
$\int_{y=-1}^{y=1} \int_{x=0}^{x=\sqrt{1-y^2}} \int_{z=r^2}^{z=r}$.
Now, the bounds $\int_{y=-1}^{y=1} \int_{x=0}^{x=\sqrt{1-y^2}}$ strongly hint that the region they enclose is a semicircle in the x-y plane with equation $x = \sqrt{1-y^2}$ for $-1 \le y \le 1$. In cylindrical/polar coordinates this is $0 \le r \le 1$ and $-\frac{\pi}{2} \le \theta \le \frac{\pi}{2}$.
So, overall the bounds become $\int_{\theta=-\frac{\pi}{2}}^{\theta=\frac{\pi}{2}} \int_{r=0}^{r=1} \int_{z=r^2}^{z=r}$.
Finally, we need to convert the argument of the integral into cylindrical coordinates using $x = r \cos\theta$, $y=r\sin\theta$, and $z = z$ and $ \ dx \ dy \ dz = r \ dr  \ d\theta \ dz$.
So $I = \int_{-1}^1 \int_{0}^{\sqrt{1-y^2}} \int_{x^2+y^2}^{\sqrt{x^2+y^2}} xyz \ dz \ dx \ dy = \int_{\theta=-\frac{\pi}{2}}^{\theta=\frac{\pi}{2}} \int_{r=0}^{r=1} \int_{z=r^2}^{z=r} r^3z \cos\theta \sin\theta \ dz \ dr \ d\theta$.
So the integral simplifies to $I = \int_{\theta=-\frac{\pi}{2}}^{\theta=\frac{\pi}{2}} \int_{r=0}^{r=1} \int_{z=r^2}^{z=r} r^3z \cos\theta \sin\theta \ dz \ dr \ d\theta$


text:
Q: passing arguments in function expression (function() {
    var theArg;
     google = function(arg) {
        theArg = arg;
        alert(theArg);
     }

     yahoo = function() {
       alert(theArg);
     }
})();

google("hello");

I am not getting the alert in yahoo function. What i am missing here and what is going wrong.

A: You're defining a function called yahoo, but nowhere are you calling it - hence I wouldn't expect you to see this alert.

A: You never call the yahoo function.
This does as you would expect:
google("hello");
yahoo();

A: Giving a quick example to the comments in the main question.
Script
(function(exports) {

    var theArg, google, yahoo;

    google = function(arg) {
        theArg = arg;
        alert(theArg);
    }

    yahoo = function() {
        alert(theArg);
    }

    exports.yahoo = yahoo; // This is now available to the window

})(window);

// This will set initial value of
google("Hello World");

HTML Page
<!-- This should now alert Hello World! -->
<button onclick="yahoo()">Yahoo</button>

In my experience if you call this without assigning to window it will not alert anything as the function will be undefined. As mentioned in comments, this is a scope issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import 'schema.sql' file into PHPMyAdmin I'm moving a site from one server to another and have successfully moved the files over and setup a new mySQL database. I've then imported the old database into the new one and that all works fine.
I also have another file that I was supplied and I am having trouble importing it. It is a 'schema.sql' file. Could someone please explain what this is and how I would go about importing it into/alongside my other database? Many thanks!

A: In phpMyAdmin
1. Databases -> Create Database -> Set name and correct collation -> Create

2. Choose newly created database in left pane

3. Import -> File to import -> Choose file -> Click Go


text:
Q: Server date and IIS date format different The server where I publish my Website, the format is M/d/yyyy (eg: 2/25/2016)
But in the website, the date format is d/M/yyyy (eg: 25/2/2016). I want the date format in the website to be M/d/yyyy (like the server format).
Date: <%=now()%>

in .asp page, above code will return current date with d/M/yyyy.
I checked a few questions here in stackoverflow but none of them provided a solution for me. I changed the server date format, still no change. I change the culture setting in web.config (see code below) and restarted the IIS service and the server twice. Also the date still in d/M/yyyy format.
<globalization uiCulture="en-US" culture="en-US" enableClientBasedCulture="false" />

Any suggestions?

A: In file GLOBAL.ASA, in Sub Session_OnStart, put Session.LCID = 1033
List of LocaleID could be found at https://msdn.microsoft.com/en-us/goglobal/bb964664.aspx
Date format will be: 8/2/2016 11:16:18 AM

A: The functions Date() and Now() in VBScript are controlled but the regional settings defined on the server they are running. Looking at the documentation it's quite clear:

From VBScript Language Reference - Now Function
Returns the current date and time according to the setting of your computer's system date and time.

Also for future reference the globalization config section is directly related to ASP.Net and not Classic ASP. Setting the value of the globalization config section will have no effect on a Classic ASP Web Application.
You however have options for controlling the string representation of a date / time value in VBScript, which is already detailed here - Format current date and time.
Or as @Zam has already suggested you do have some minor control of the format by using the
Session.LCID = 1033

Bear in mind that this will change the entire locale to en-US (which I assume is what you are trying to do with the globalization settings in web.config).


text:
Q: Where did the apple that Altair hides in the library come from? I've just finished my first play-through revelations yesterday, and something is bothering me since.

 It's about the apple which Altair hides in the library with him. Where did it come from? It can't be the same one from the previous games, because this one is still there when Ezio opens the library (I think). And if there are many apples, then why didn't the templars found them?

Is there something that I've missed? (It's not impossible, as I was already quite tired and sleepy by the end).

A: This whole answer is chock full of spoilers about the AC universe and story.  Hopefully you already knew this from the huge spoiler tag in the question.  :)
There are multiple Pieces of Eden in the Assassin's Creed universe.  The Templars are searching for them in the first game, which is why they're curious about Desmond's memories of Altair - at the end of the first game he holds the Piece of Eden and it displays a globe with locations marked.  These are the locations of other Pieces of Eden.
In some of the "secret" memories that you can use to unlock "The Truth" in the series, you're told that Pieces of Eden have influenced or allowed great leaders from history to rise to power.  The Templars plan to use many Pieces of Eden, in concert with a vast amplification network, to extend their control over the entire world at once.
The Piece of Eden that Ezio locates in Assassin's Creed 2 is different from the one Altair had - this one the Templars have already recovered from wherever it had been previously hidden or kept.  Ezio takes it from the Templars twice, and finally hides it for Desmond and the Assassin team to recover later in AC: Brotherhood.  (This is the piece Desmond takes right before stabbing Lucy)
At the end of Revelations, Ezio recovers Altair's Piece of Eden, which Altair had possessed from the end of the events of the first game until his death.  The memories that Ezio recovers from the library keys tell the story of how this device effected the assassin brotherhood in the years following the original game.


text:
Q: Add a schema or create a new instance? Not to much a complex question as usual.
I've been just asked to give some opinion on possible impacts of stuffing more schemas in the same Oracle (10g) instance we have our production system running currently.
That's not exactly a problem. The server isn't overloaded or anything and it will get the proper additional resources it might need for supporting the new schemas.
My observations are of the sort "well, you are going to share resources assigned to that instance", "when one backup kicks in, both systems will be down".
Wonder what I'm missing. When would be absolutely recommended to get separated instances. What would be a normal convention for that? or other tips you guys might have.
Just so you guys know, we are talking about a memory and processor intensive application, with pretty much no I/O for long periods. In a nutshell, we are comparing huge data tables all the time.
Highly appreciate your thoughts.
f.

A: If you have more than one instance on a single server, you will have some hard time troubleshooting performance issues because the Oracle tools won't be able to see each other's performance logs.
This is why on busy production systems my advice would be "one instance at most per server". I don't have much experience with virtualization in production but if you have the resource to deal with a virtualized environment, you could have one instance per logical server.
On an unrelated note, why would you take the DB offline to perform a backup, especially if it is not an IO intensive system?


text:
Q: How to select all records from one table that exactly match another table in SQL Server? I have a tricky question about select: I have this table structure:
declare @one as table (serviceid int null)

declare @two as table (id int null, serviceid int null)

insert into @two
values (15,195),(15,84),(16,195),(16,84),(16,NULL),(17,195),(17,84),(17,8)

I need get exactly matching @two.ID (that matches the serviceid and count intable @two )
Scenario 1:
insert into @one values (195),(84)

I need get only ID- 15, because all serviceid is matching and record count in table @one is 2.
Scenario2:
Insert into @one values (195),(84),(8)

I need get only ID- 16 and 17, 17: because all serviceid is matching and record count in table @one is 3. , 16 : because two services are matching,record count in table @one is 3 and NULL means 'Don't Matter'(whoever)
Do you have any idea?

A: declare @one as table (serviceid int null)

declare @two as table (id int null, serviceid int null)

insert into @two values (15,195),(15,84),(16,195),(16,84),(16,NULL),(17,195),(17,84),(17,8);
--insert into @one values (195),(84);
Insert into @one values (195),(84),(8)

select distinct t.id
from @two t
where exists (select * from @one o where t.serviceid = o.serviceid)
      and (select count(*) from @one) = (select count(*) from @two t1 where t1.id = t.id);

A: I am afraid, that the answer you accepted is wrong (as you noticed in comment). Here is working query:
-- tables declaration ---------------------------------------------------------------------
declare @one as table (serviceid int null)
declare @two as table (id int null, serviceid int null)
-- values insert --------------------------------------------------------------------------
insert into @two values (15,195),(15,84),(16,195),(16,84),(16,NULL),(17,195),(17,84),(17,8)
insert into @one values (195),(84)
-- actual query ---------------------------------------------------------------------------
select id from (
select id,
       --check, where we have null records in @one caused by null values in @two, which is acceptable (assifgned value when acceptable = 0)
       case when ([ONE].serviceid is not null and [TWO].serviceid is not null) or ([ONE].serviceid is null and [TWO].serviceid is null) then 0 else 1 end [IsMatched]
from (
    select *, COUNT(*) over (partition by id) as [idCount] from @two
) [TWO] left join (
    select serviceid, COUNT(*) over (partition by (select null)) [idCount] from @one
) [ONE] on ([TWO].idCount = [ONE].idCount and [TWO].serviceid = [ONE].serviceid)
) [a] group by id
having SUM(IsMatched) = 0


text:
Q: Where should I put my initialisation code? I have written a programme in java for command line. Now to convert it to gui I used Netbeans GUI Builder. The problem is I do not know where to put my initialisation codes(from the old main class).
  There is a main in gui but I do not think I can put there all those codes. Even then I do not think it would not be a good idea. So how can I run my initialisation codes from old main class?

A: I believe you would have the beginnings of this from Netbeans, correct?
/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    ... some stuff here automatically created by Netbeans (leave it).

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
               //enter initialization code here
            Main mainWindow = null;
            try {
               //enter more initialization code here
                mainWindow = new Main();
            } catch (IOException ex) {
                System.exit(1);
            }
            //enter even more initialization code here
            mainWindow.setVisible(true);
        }
    });
}

Of course, edit as you like.  I would highly recommend that you DO use Netbeans automated features, especially if you're new at creating your own GUIs.  Copy and paste your code from your command line app right into this automated main.  Hope that helps.


text:
Q: How to draw stack and queue data structure? I need to draw a stack data structure to explain it in first concept course as well  as queue.
\begin{tikzpicture}[draw, minimum width=1cm, minimum height=0.5cm]
\node[draw] (in) at (-1,2) {};
\node[draw] (out) at (1,-2) {};
\matrix (queue)[matrix of nodes, nodes={draw, nodes={draw}}, nodes in empty cells] { \\ \\ \\ \\ };
\draw[-latex] (0.25,-1) .. controls (0.25,-1.25) and (1,-1.25) .. (out.north);
\draw[-latex] (in.south) .. controls (-1, 1.5) and (-0.25,1.5) .. (-0.25,1);
\end{tikzpicture}

A: To give you a start (anyway I am now in freetime :))
\documentclass[tikz,margin=1]{standalone}
\usetikzlibrary{arrows.meta}
\tikzset{
    queue element/.style={
        draw,very thin,rounded corners,
        fill=yellow!30,
        minimum width=1cm,minimum height=.5cm,
        font=\sffamily\footnotesize
    },
    >={[scale=0.8]Triangle}
}
\begin{document}
\begin{tikzpicture}
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick,>->] (-.6,.35) -- (5.1,.35);
\draw[green,thick,>->] (-.6,-.35) -- (5.1,-.35);
\foreach \i/\name in {1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {front};
\draw[<-] ([yshift=.2cm]C.north) -- ++ (0,.5) node[above] {rear};
\path (6,0) node[right] {before};
\node[queue element] (D) at (-2,1) {D};
\draw[->,very thick] (D.south) to[out=-90,in=180] (-.7,0);

\scope[yshift=-3cm] % queue after
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick,>->] (-.6,.35) -- (5.1,.35);
\draw[green,thick,>->] (-.6,-.35) -- (5.1,-.35);
\foreach \i/\name in {0/D,1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {front};
\draw[<-] ([yshift=.2cm]D.north) -- ++ (0,.5) node[above] {rear};
\path (6,0) node[right] {after};
\endscope
\end{tikzpicture}
\end{document}

A little modification and you will have dequeue() instead of enqueue().
\documentclass[tikz,margin=1]{standalone}
\usetikzlibrary{arrows.meta}
\tikzset{
    queue element/.style={
        draw,very thin,rounded corners,
        fill=yellow!30,
        minimum width=1cm,minimum height=.5cm,
        font=\sffamily\footnotesize
    },
    >={[scale=0.8]Triangle}
}
\begin{document}
\begin{tikzpicture}
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick,>->] (-.6,.35) -- (5.1,.35);
\draw[green,thick,>->] (-.6,-.35) -- (5.1,-.35);
\foreach \i/\name in {0/D,1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {front};
\draw[<-] ([yshift=.2cm]D.north) -- ++ (0,.5) node[above] {rear};
\draw[->,very thick] (5.2,0) to[out=0,in=90] ++ (1,-1);
\path (6,0) node[right] {before};

\scope[yshift=-3cm] % queue after
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick,>->] (-.6,.35) -- (5.1,.35);
\draw[green,thick,>->] (-.6,-.35) -- (5.1,-.35);
\foreach \i/\name in {0/D,1/C,2/B}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]B.north) -- ++ (0,.5) node[above] {front};
\draw[<-] ([yshift=.2cm]D.north) -- ++ (0,.5) node[above] {rear};
\path (6,0) node[right] {after};
\endscope
\end{tikzpicture}
\end{document}

With the same technique, you can also illustrate stack data structure :)
\documentclass[tikz,margin=1]{standalone}
\usetikzlibrary{arrows.meta}
\tikzset{
    queue element/.style={
        draw,very thin,rounded corners,
        fill=yellow!30,
        minimum width=1cm,minimum height=.5cm,
        font=\sffamily\footnotesize
    },
    >={[scale=0.8]Triangle}
}
\begin{document}
\begin{tikzpicture}
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick] (-.6,.35) -- (5.1,.35) |- (-.6,-.35);
\foreach \i/\name in {1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {rear};
\draw[<-] ([yshift=.2cm]C.north) -- ++ (0,.5) node[above] {front};
\path (6,0) node[right] {before};
\node[queue element] (D) at (-2,1) {D};
\draw[->,very thick] (D.south) to[out=-90,in=180] (-.7,0);

\scope[yshift=-3cm] % stack after
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick] (-.6,.35) -- (5.1,.35) |- (-.6,-.35);
\foreach \i/\name in {0/D,1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {rear};
\draw[<-] ([yshift=.2cm]D.north) -- ++ (0,.5) node[above] {front};
\path (6,0) node[right] {after};
\endscope
\end{tikzpicture}
\end{document}

\documentclass[tikz,margin=1]{standalone}
\usetikzlibrary{arrows.meta}
\tikzset{
    queue element/.style={
        draw,very thin,rounded corners,
        fill=yellow!30,
        minimum width=1cm,minimum height=.5cm,
        font=\sffamily\footnotesize
    },
    >={[scale=0.8]Triangle}
}
\begin{document}
\begin{tikzpicture}
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick] (-.6,.35) -- (5.1,.35) |- (-.6,-.35);
\foreach \i/\name in {0/D,1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {rear};
\draw[<-] ([yshift=.2cm]D.north) -- ++ (0,.5) node[above] {front};
\draw[->,very thick] (-.7,0) to[out=180,in=90] ++ (-1,-1);
\path (6,0) node[right] {before};

\scope[yshift=-3cm] % stack after
\fill[green!20] (5.1,.35) rectangle (-.6,-.35);
\draw[green,thick] (-.6,.35) -- (5.1,.35) |- (-.6,-.35);
\foreach \i/\name in {1/C,2/B,3/A}
    \node[queue element] (\name) at (1.5*\i,0) {\name};
\draw[<-] ([yshift=.2cm]A.north) -- ++ (0,.5) node[above] {rear};
\draw[<-] ([yshift=.2cm]C.north) -- ++ (0,.5) node[above] {front};
\path (6,0) node[right] {after};
\endscope
\end{tikzpicture}
\end{document}

A: A little variation on JouleV's solution.
I've used a matrix of nodes to declare the queue which can be also used for an horizontal or vertical stack. The matrix node can be used as background area and no external rectangle is needed for it.
Internal nodes are conveniently labelled as front and rear to avoid using particular names.
\documentclass[tikz,margin=2mm]{standalone}
\usetikzlibrary{arrows.meta, matrix, positioning}
\tikzset{
    queue element/.style={
        draw,very thin,rounded corners,
        fill=yellow!30,
        minimum width=1cm,minimum height=.5cm,
        font=\sffamily\footnotesize
    },
    >={[scale=0.8]Triangle},
    queue/.style={matrix of nodes,
        nodes in empty cells,
        nodes={queue element, anchor=center},
        fill=green!20,
        column sep=5mm,
        row sep=2mm,
    },
}
\begin{document}
\begin{tikzpicture}

\matrix[queue] (Q1) {
|(rear)| D & C & B &|(front)| A\\};
\draw[green,thick,>->] (Q1.north west) -- (Q1.north east);
\draw[green,thick,>->] (Q1.south west) -- (Q1.south east);
\draw[<-] ([yshift=.2cm]front.north) -- ++ (0,.5) node[above] {front};
\draw[<-] ([yshift=.2cm]rear.north) -- ++ (0,.5) node[above] {rear};
\draw[->,very thick] (Q1.east) to[out=0,in=90] node[pos=.6, above right] (aux) {before} ++ (1,-1);

\scope[yshift=-2cm] % queue after
\matrix[queue] (Q1) {
|(rear)| D & C &|(front)| B &|[fill=none, draw=none]| \\};
\draw[green,thick,>->] (Q1.north west) -- (Q1.north east);
\draw[green,thick,>->] (Q1.south west) -- (Q1.south east);
\draw[<-] ([yshift=.2cm]front.north) -- ++ (0,.5) node[above] {front};
\draw[<-] ([yshift=.2cm]rear.north) -- ++ (0,.5) node[above] {rear};
\node at (aux|-Q1) {after};
\endscope
\end{tikzpicture}

\begin{tikzpicture}

\matrix[queue] (Q1) {
|[fill=none, draw=none]| \\
|(front)| C\\
B\\
|(rear)| A\\};
\draw[green,thick,-] (Q1.north west) |-(Q1.south)-| (Q1.north east);
\draw[<-] ([xshift=.2cm]front.east) -- ++ (0:.5) node[right] {front};
\draw[<-] ([xshift=.2cm]rear.east) -- ++ (0:.5) node[right] {rear};
\draw[<-,very thick] (Q1.north) to[out=90,in=190] ++ (1,1) node[right, queue element] (D) {D};
\node[below=3mm of Q1.south east] {before};

\scope[xshift=3.5cm] % queue after
\matrix[queue] (Q1) {
|(front)| D \\
 C\\
B\\
|(rear)| A\\};
\draw[green,thick,-] (Q1.north west) |-(Q1.south)-| (Q1.north east);
\draw[<-] ([xshift=.2cm]front.east) -- ++ (0:.5) node[right] {front};
\draw[<-] ([xshift=.2cm]rear.east) -- ++ (0:.5) node[right] {rear};
\node[below=3mm of Q1.south east] {after};
\endscope
\end{tikzpicture}
\end{document}

A: \documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{backgrounds,fit,chains}
\begin{document}
\begin{tikzpicture}[lazy/.style={rounded corners,fill=gray!30,draw=gray!50,
minimum width=3em,minimum height=4ex},arr/.style={very thick,-stealth},
arr2/.style={very thick,stealth-},font=\sffamily]
 \begin{scope}[start chain=going left,node distance=1em,nodes={lazy,on chain}]
  \node[lazy] (A2){A};
  \node[lazy] (B2){B};
  \node[lazy] (C2){C};
  \node[lazy] (D2){D};
 \end{scope}
 \begin{scope}[on background layer]
 \node[fit=(A2) (D2),top color=gray!20,bottom color=gray!10,inner sep=1em](F2){};
 \end{scope}
 \foreach \X in {north,south}
 {\draw[arr,gray!50]  (F2.\X\space west) -- (F2.\X\space east);}
 \begin{scope}[yshift=3cm,start chain=going left,node distance=1em,nodes={lazy,on chain}]
  \node[lazy] (A1){A};
  \node[lazy] (B1){B};
  \node[lazy] (C1){C};
 \end{scope}
 \begin{scope}[on background layer]
  \node[fit=(A1) (D2.west|-A1),top color=gray!20,bottom color=gray!10,inner sep=1em](F1){};
 \end{scope}
 \foreach \X in {north,south}
 {\draw[arr,gray!50]  (F1.\X\space west) -- (F1.\X\space east);}
 \node[left=2em of F1.north west,lazy] (D1) {D};
 \draw[arr,black] (D1.south) to[out=-60,in=180] (F1);
 \draw[arr2] (A2|-F2.north) -- ++ (0,1em) node[above]{Front};
 \draw[arr2] (D2|-F2.north) -- ++ (0,1em) node[above]{Rear};
 \draw[arr2] (A1|-F1.north) -- ++ (0,1em) node[above]{Front};
 \draw[arr2] (C1|-F1.north) -- ++ (0,1em) node[above]{Rear};
\end{tikzpicture}
\end{document}


text:
Q: How to put r- and theta-labels plus units on a polar Matplotlib plot (wedge diagram)? I have plotted a wedge-diagram, but can not seem to figure out how to get labels on the axis and units on the values. The r-axis has to be Dec and the theta-axis has to be RA, both with units of degrees.
Here is my code, hope you can help:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

theta = (np.pi/180)*np.array([340.555906,3.592373,32.473440,33.171584,35.463857,44.268397,339.362504,345.211906,346.485567,346.811945,348.672405,349.180736,349.370850,353.098343])
r = np.array([-32.906663,-33.842402,-32.425917,-32.677975, -30.701083,-31.460307,-32.909861,-30.802969,-33.683759,-32.207783,-33.068686,-33.820102,-31.438195,-31.920375])

colors = 'black'

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
c = ax.scatter(theta, r,marker='.', c=colors, cmap='hsv', alpha=0.75)

ax.set_thetamin(55)
ax.set_thetamax(-45)

fmt = lambda x, pos: "{:g}".format(np.degrees(x if x >= 0 else x + 2 * np.pi))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmt))

plt.show()

EDIT: I have tried setting the lables with:
ax.text(0,-29.9,s='RA')
ax.text(2,-29.5,s='Dec')

Which sort of works, but I can still not get units (degrees) on my values. I think the problem might have something to do with my limits, which has to go around zero, but I am not sure.


text:
Q: how we send email in jsp it is my code but it is not work proper please help me.please provide any relevant code or guid. thank you

         <form class="form-group" style=" margin-right:200px; padding: 30px 0px 0 25px;  background-color:white">

Sending Email

                <input type="email" class="form-control" placeholder="To" required name="to" style="width:300px" />

                <input type="email" class="form-control" placeholder="From" required name="from" style="width:300px" />

                <input type="text" class="form-control" placeholder="subject:" required name="subject" style="width:300px" />

                <textarea placeholder="body" required name="body" cols="32" rows="7" style="border:1px gray solid;border-radius:5px;"></textarea>

                <input type="submit" value="send" name="btn"   style="width: 300px; height: 35px; border: 1px solid gainsboro; border-radius: 4px; background-color:limegreen; color: white"/>

    <%
         String from=request.getParameter("from");
          String to=request.getParameter("to");
           String bod=request.getParameter("body");
        String subject=request.getParameter("subject");
try{
  Session mailSession = Session.getInstance(System.getProperties());
  Transport transport = new SMTPTransport(mailSession,new URLName("smtp.gmail.com"));
  transport.connect("smtp.gmail.com",465,null,null);
  MimeMessage m = new MimeMessage(mailSession);
  m.setFrom(new InternetAddress(from));
  Address[] toAddr = new InternetAddress[] {
  new InternetAddress(to)
  };
  m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
  m.setSubject(subject);
  m.setSentDate(new java.util.Date());
  m.setContent(bod, "text/plain");
  transport.sendMessage(m,m.getAllRecipients());
  transport.close();
  out.println("Thanks for sending mail!");
}
catch(Exception e){
  out.println(e.getMessage());
  e.printStackTrace();
}
%>

it show error is:Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1


text:
Q: TypeScript internal module usage I have a class named BMW defined in BMW.ts as follows:
///<reference path="../Thing.ts"/>

module Entities.Cars {

    import e = Entities;

    export class BMW extends Vehicle {

        public series: string;

         constructor ( model : string, series : string) {
            super("BMW", model)
            this.series = series;
        }

         drive() {
             alert("driving a bimmer is a different kind of feeling");
         }

         toString() : string
         {
             return this.getName() + " " + this.series + " " + this.getType();
         }
    }
}

In another file Thing.ts, I have Vehicle and Thing classes defined as follows:
module Entities {

    // Class
    export class Thing {

        private _name: string;
        private _type: string;

        // Constructor
        constructor (public name: string, public type: string) {
            this._name = name;
            this._type = type;
         }

        getName(): string { return this._name; }
        setName(name: string) { this._name = name; }

        getType(): string { return this._type; }
        setType(name: string) {
            this._type = name;
        }

        toString() : string
        {
            return "Entities.Thing";
        }
    }

    export class Vehicle extends Thing {

        public cargoCapacity: number;
        public fuelType: string;
        public owner: string;

        constructor (make: string, model : string) {
            super(make, model)
        }

        drive() {
        }

        toString(): string {
            return "Entities.Vehicle";
        }
    }
}

When I attempt to execute the following code after referencing Thing and BMW TypeScript files:
var car = new Entities.Cars.BMW("335i", "E90");
car.drive();

I get an exception with the following error "   Microsoft JScript runtime error: Unable to get value of the property 'BMW': object is null or undefined".   The generated Javascript for BMW has an error.  What is wrong with my above snippet?

A: There is nothing wrong with your code so it seems like your import order for the generated javascript files is wrong. The specification says the following:

Initialization order of the source files that make up the global module ultimately depends on the order in which the generated JavaScript files are loaded at run-time (which, for example, may be controlled by  tags that reference the generated JavaScript files).

I have generated a file app.ts as follows:
///<reference path='Things.ts'/>
///<reference path='bmw/BMW.ts'/>
var car = new Entities.Cars.BMW("335i", "E90");
car.drive();

At this point you have two options:

*

*Let the compiler determine the correct order for executing the files by generating a single output file
tsc --out app.js app.ts
Then you only have to source app.js.

*Specify the correct order manually. For me, the following is the only order that works without throwing errors.
<html>
    <head>
        <script src="Things.js"></script>
        <script src="bmw/BMW.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
    </body>
</html>

A: Your code is fine.
My guess is that you are not placing script tags in your head element properly(wrong order, or ommitting some).
The simplest way to solve this, and to not have to remember about proper declaration  sequence is to use single .js output file from tsc compiler by setting --out option.
EDIT: Depending on which js scenario you are working on(WSH, web app or some other js environment), you need to link js source files differently.
With wsh for instance, you could use FileSystemObject to read a source file, then evaluate it.
Or you could use AMDs...


text:
Q: Create PDF of whole webview Android Currently attempting to include a PDF export feature for my application. This involves populating a HTML template, putting that into a WebView, then writing the contents of that WebView to a PDF using adapted code from here: How to create PDF from webView, which is hidden? - however when the PDF is generated I am only getting the visible area of the  WebView, so information off-screen is being cut off.
Here is my code, is there a way I can capture the data from the whole WebView?
public void createPDF() {
    PdfDocument doc = new PdfDocument();
    PdfDocument.PageInfo inf = new PdfDocument.PageInfo.Builder(A4_width, A4_height, 1).create();
    PdfDocument.Page page = doc.startPage(inf);
    Canvas c = page.getCanvas();
    int webWidth = htmlViewer.getWidth();
    float scale = A4_width / (float) webWidth;
    c.save();
    c.scale(scale, scale);

    htmlViewer.draw(c);
    c.restore();
    doc.finishPage(page);

    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    String name = requestID + ".pdf";
    try {
        FileOutputStream fos = null;
        try {
            File file = (new File(dir, name));
            if(!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            doc.writeTo(fos);
            doc.close();
            Log.d(TAG, "PDF made");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) { fos.close(); }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}


text:
Q: Do var fn = function() {...} and var fn = function foo() {...} ever differ? When you're assigning a function to a variable, does it make any difference at all if you use a named instead of an anonymous function. The following generates an error that "foo() is not defined".
var fn = function foo(){...};
foo();

Can anyone clear up what's going on here?

A: You're creating a named function expression.
Except in IE, the name is only visible inside the function.

A: Because it (foo) is not defined ;-)
In this context, function is a function-expression ("FunctionExpression") and not a function-statement ("FunctionDeclaration") -- there are two different productions in the grammar. Only the function-statement form [magically] assigns (and hoists the assignment) of the function name to the appropriate variable. Even functions created with a function-expression can have a name, it just happens to be optional, but there is no implicit assignment as with the other form.
[Edit: Apparently this is more quirky then I imagined. In any case, the above cases hold for a properly conforming browser. For instance Gecko has the "function statement extension, which is non-conforming, and IE/JScript exhibits different behavior, which is also non-conforming. Both of these are incorrect implementations according to the grammar specification.]
Consider the following, which should hopefully show why a ([more] conforming implementation) will sanely throw an exception:
// `function` is just an expression here -- there is no good reason for it to
// cause an implicit side-effect. And, according to the specification, it will not.
(function foo () {}).name // "foo", at least in FF
foo // undefined

On a side note: Any function production which is not a top-level statement or a statement directly inside a function block is a function-expression. The behavior of the following is quirky across browsers:
foo() // works in IE (this should never work)
if (true) {
   // this is an INVALID GRAMMAR production, although it is accepted in browsers,
   // with different operational semantics
   function foo () {
   }
}
foo() // works in FF and IE (this should never work)

Happy coding.

A little trip to the ECMAScript specification to talk about the grammar. The "rules" can be equally found there, although I find Ed. 5 to be written in the most confusing manner possible. (It misses for forest for all the trees...)
Grammar for FunctionExpression:
// There is a silly long expression tree to get here.
// Look it up if you want :)
FunctionExpression : function Identifier [optional] ( FormalParameterListopt ) { FunctionBody }

Grammar for FunctionDeclaration (what I refer to as a function-statement above), and associated "chain":
 FunctionBody : SourceElements [optional]
 Program : SourceElements [optional]
 SourceElements : SourceElement
                  SourceElements SourceElement
 SourceElement : Statement
                 FunctionDeclaration
 FunctionDeclaration : function Identifier ( FormalParameterListopt ) { FunctionBody }

Note that there is no grammar rule for the "INVALID GRAMMAR" noted. The only way to get to a FunctionDeclaration is through a SourceElement which is only valid inside a FunctionBody or Program (which does not include other blocks like if). "Normal expressions", as a FunctionExpression are restricted, as per below:

An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

...and an apt note from the spec:

Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable difference, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations.

A: In your example, the variable fn is accessible in the current scope, but foo is only accessible in the functions scope. For example:
var bar = function foo() {
    document.write("Internally, Foo is " + typeof foo + "
");
    document.write("Internally, Bar is " + typeof bar + "
");
};

document.write("Foo is " + typeof foo + "
");
document.write("Bar is " + typeof bar + "
");

bar();

Will produce:
Foo is undefined
Bar is function
Internally, Foo is function
Internally, Bar is function

http://jsfiddle.net/robert/TEnjb/

A: Technically, fn is a function pointer pointing to "foo", but you don't really see this in Javascript. You should really just write:
function foo() {
  /* ... */
}

foo();

As others have pointed out, your assignment makes the foo function "live" only in the scope of fn, so when fn goes out of scope, the function object could in principle be cleaned up. If you have a really compelling reason to do that then use the function pointer, but otherwise you can just keep the function global.

A: On some versions of IE this will work, but only because they are non-conforming.
var fn  // declares a variable named fn
    = function  // initializes fn
      foo  // declares a name foo that is only visible within the function body.
      (){
        ...  // foo is visible here.
      };
foo();  // foo is not defined here (except on IE 6 and earlier)
fn();  // works just fine.

A: Note also that although it's often said that:
function foo() {
};

is just syntactic sugar for:
var foo = function() {
};

it's actually not quite true.
In the former case the named function is immediately available when the script is parsed regardless of the order of definitions in the file.
In the latter, the anonymous function body is parsed immediately, but its assignment to a locally scoped variable doesn't happen until that line of code is executed.  This means that you can't call foo() in any code executed before then.

A: Depending on the scope and how you define the function it can be a Function Declaration, Function Expression, or Function Statement. These three function types are treated and loaded differently. Among them, only function declarations require a name. So two other types can be defined without a name. These three types are also different in they way they are assigned to a variable with the function name.

*

*Function Declaration : is defined in the top scope and is not used in another expression/statement (e.g., it is not assigned to a variable)
 function foo(){}

The function object is assigned to the variable foo in the global scope.

*Function Expression : is defined in another expression/statement.
 var bar = function foo(){}

The function object is assigned to the variable foo but in the inner scope (i.e., the scope inside the function)

*Function Statement : they are allowed to be anywhere where plain Statements are allowed.
if (true) {
  function foo(){ }
}

The function object is assigned to the variable foo in the outer scope (i.e., the scope contains the function definition).
For more information look at this address: http://kangax.github.com/nfe/


text:
Q: Polymorphic relationship confusion So I'm confused about how ActiveRecord is handling this, and hoped someone could give me some insight.
I have a table that has a polymorphic relationship.  We'll call it table choices.  In there I have defined:
belongs_to :chooseable, polymorphic: true

I have two models, let's call one movies, and the other plays.  In there, I have:   has_many :choices as: chooseable, dependent: destroy
In the model with the polymorphic relationship I have two scopes:
  scope :with_movies, -> {
    includes(:movies)
      .where("chooseable_type": "Measure")
  }
  scope :with_shows, -> {
    includes(:shows)
      .where(shows: { hidden: false })
  }

What is confusing to me, is, if I say users.choices.with_movies, and I leave out the chooseable_type where condition, AR balks at me and says:
Unknown column 'choices.chooseable_type' in 'where clause': SELECT `movies`.* FROM `movies` WHERE `choices`.`chooseable_type` = 'Movie' AND `movies`.`id` IN (728)

Yet, in the second scope with_shows, I don't need to define chooseable_type - it works fine.  The even more confusing thing is, if I remove the where clause, with_shows, doesn't work as well.
I really don't understand why the where clause in the second scope allows a proper query to be generated, yet without it, it falls on its face.

A: The problem is that Rails tries to do it's best building the resulting complicated query for you, and it resolves
.where("chooseable_type": "Measure")

to it's best assumption, which is the main table for this query. Help it to not fail, specify the table name explicitly:
.where("movies.chooseable_type": "Measure")


text:
Q: Unable to Connect to any Servers Error on Cassandra Seed Host In my Cassandra 3-node setup, all the seed nodes are working fine. However, I am unable to connect to the seed host.
I get the following error:
Connection error: ('Unable to connect to any servers', {'127.0.0.1':
  error(111,"Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

Please help.

A: NOTE: As you haven't specified which version of Cassandra you are running, or how you are attempting to connect to your cluster (cqlsh, Java client driver, etc...) I am going to make some assumptions here.  For the future, that's good information to provide.
My guess is that if you were to run a nodetool status from one of your nodes, that you wouldn't see "127.0.0.1" in the list.  Example:
$ nodetool status | grep 192.168 | awk '{ print $2 }'
192.168.1.1
192.168.1.2
192.168.1.3

My point, is that even if I am on 192.168.1.1, cqlsh 127.0.0.1 or cqlsh (without the IP) won't work.  I need to specify the (non-localhost) IP address, which is probably going to be the value of your listen_address or rpc_address.


text:
Q: Q: ValueError: substring not found pygame 2.1.2 (SDL 2.0.18, Python 3.8.0)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 192, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85,
in _run_code
    exec(code, run_globals)
  File "c:\Users\Dell\.vscode\extensions\ms-python.python-2022.6.2\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\Users\Dell\.vscode\extensions\ms-python.python-2022.6.2\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 444, in main
    run()
  File "c:\Users\Dell\.vscode\extensions\ms-python.python-2022.6.2\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 285, in run_file
    runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 262, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 95,
in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85,
in _run_code
    exec(code, run_globals)
  File "c:\Users\Dell\Documents\My beatMaker\My beats app.py", line 228, in <module>
    exit_button, loading_button, delete_button, load_rectangle = draw_load_menu()
  File "c:\Users\Dell\Documents\My beatMaker\My beats app.py", line 157, in draw_load_menu
    name_index_start = saved_beats[beat].index('name: ') + 6
ValueError: substring not found

Hi, I am coding a drum machine. I am making it through pygame in python.
I am learning pygame through freecodecamp.org.
I don't know where this error came from. It says 'substring not found'. See if there is problem.
There is my code -
import pygame
from pygame import mixer
pygame.init()

WIDTH = 1300
HEIGHT = 650

black = (0, 0, 0)
white = (255, 255, 255)
gray = (128, 128, 128)
dark_gray = (50, 50, 50)
green = (0, 255, 0)
gold = (212, 175, 55)
blue = (0, 255, 255)

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Beat Maker")
label_font = pygame.font.Font("Roboto-Bold.ttf", 32)
medium_font = pygame.font.Font("Roboto-Bold.ttf", 24)

fps = 60
timer = pygame.time.Clock()
beats = 8
instruments = 5
boxes = []
clicked = [[-1 for _ in range(beats)] for _ in range(instruments)]
active_list = [1 for _ in range(instruments)]
bpm = 240
playing = True
active_length = 0
active_beat = 0
beat_changed = True
save_menu = False
load_menu = False
saved_beats = []
file = open('saved_beats.txt', 'r')
for line in file:
    saved_beats.append(line)
beat_name = ''
typing = False

# load in sounds
hi_hat = mixer.Sound('sounds\hi hat.wav')
snare = mixer.Sound('sounds\snare.wav')
drum = mixer.Sound('sounds\kick.wav')
crash = mixer.Sound('sounds\crash.wav')
clap = mixer.Sound('sounds\clap.wav')
pygame.mixer.set_num_channels(instruments * 3)

def play_notes():
    for i in range(len(clicked)):
        if clicked[i][active_beat] == 1 and active_list[i] == 1:
            if i == 0:
                hi_hat.play()
            if i == 1:
                snare.play()
            if i == 2:
                drum.play()
            if i == 3:
                crash.play()
            if i == 4:
                clap.play()

def draw_grid(clicks, beat, actives):
    left_box = pygame.draw.rect(screen, gray, (0,0, 206, HEIGHT - 150), 4)
    bottom_box = pygame.draw.rect(screen, gray, (0, HEIGHT - 150, WIDTH, 150), 4)
    boxes = []
    colors = [gray, white, gray]

    hi_hat_text = label_font.render('Hi Hat', True, colors[actives[0]])
    screen.blit(hi_hat_text, (30, 40))

    snare_text = label_font.render('Snare', True, colors[actives[1]])
    screen.blit(snare_text, (30, 145))

    drum_text = label_font.render('Bass Drum', True, colors[actives[2]])
    screen.blit(drum_text, (30, 240))

    crash_text = label_font.render('Crash', True, colors[actives[3]])
    screen.blit(crash_text, (30, 340))

    clap_text = label_font.render('Clap', True, colors[actives[4]])
    screen.blit(clap_text, (30, 435))

    for i in range(instruments):
        pygame.draw.line(screen, gray, (0, (i*100)+1), (200, (i*100)+1), 3)

    for i in range(beats):
        for j in range(instruments):
            if clicks[j][i] == -1:
                color = gray
            else:
                if active_list[j] == 1:
                    color = green
                else:
                    color = dark_gray
            rect = pygame.draw.rect(screen, color,
                                                  ((i * ((WIDTH-200) // beats) + 200), (j*100),
                                                   ((WIDTH-200) // beats), ((HEIGHT-150)//instruments)
                                                  ), 0, 3
                                   )
            pygame.draw.rect(screen, gold,
                                          ((i * ((WIDTH-200) // beats) + 200), (j*100),
                                          ((WIDTH-200) // beats), ((HEIGHT-150)//instruments)
                                          ), 5, 5
                                   )
            pygame.draw.rect(screen, black,
                                                  ((i * ((WIDTH-200) // beats) + 200), (j*100),
                                                   ((WIDTH-200) // beats), ((HEIGHT-150)//instruments)
                                                  ), 2, 5
                                   )
            boxes.append((rect, (i, j)))

        active = pygame.draw.rect(screen, blue, (beat*((WIDTH-200)//beats)+200, 0, ((WIDTH-200)//beats), instruments*100), 5, 3)
    return boxes

def draw_save_menu(beat_name, typing):
    pygame.draw.rect(screen, black, (0, 0, WIDTH, HEIGHT))
    menu_text = label_font.render('SAVE MENU: Enter a Name for Current beat', True, white)
    saving_btn = pygame.draw.rect(screen, gray, (WIDTH//2 - 166, HEIGHT*0.75, 400, 100), 0, 5)
    saving_txt = label_font.render('Save beat', True, white)
    screen.blit(saving_txt, (WIDTH//2-50, HEIGHT*0.75+30))
    screen.blit(menu_text, (400, 40))
    exit_btn = pygame.draw.rect(screen, gray, (WIDTH-200, HEIGHT-100, 180, 90), 0, 5)
    exit_text = label_font.render('Close', True, white)
    screen.blit(exit_text, (WIDTH-150, HEIGHT-70))
    if typing:
        pygame.draw.rect(screen, dark_gray, (400, 200, 600, 200), 0, 5)
    entry_rect = pygame.draw.rect(screen, gray, (400, 200, 600, 200), 5, 5)
    entry_text = label_font.render(f'{beat_name}', True, white)
    screen.blit(entry_text, (430, 250))
    return exit_btn, saving_btn, entry_rect

def draw_load_menu():
    pygame.draw.rect(screen, black, (0, 0, WIDTH, HEIGHT))
    menu_text = label_font.render('LOAD MENU: Select a Beat a Load', True, white)
    loading_btn = pygame.draw.rect(screen, gray, (WIDTH//2 - 166, HEIGHT*0.87, 400, 100), 0, 5)
    loading_txt = label_font.render('Load beat', True, white)
    delete_btn = pygame.draw.rect(screen, gray, ((WIDTH//2)-600, HEIGHT*0.87, 200, 100), 0, 5)
    delete_text = label_font.render('Delete Beat', True, white)
    screen.blit(delete_text, ((WIDTH//2)-583, HEIGHT*0.87+30))
    screen.blit(loading_txt, (WIDTH//2-50, HEIGHT*0.87+30))
    screen.blit(menu_text, (400, 40))
    exit_btn = pygame.draw.rect(screen, gray, (WIDTH-200, HEIGHT-100, 180, 90), 0, 5)
    exit_text = label_font.render('Close', True, white)
    screen.blit(exit_text, (WIDTH-150, HEIGHT-70))
    loaded_rectangle = pygame.draw.rect(screen, gray, (190, 90, 1000, 450), 3, 5)
    for beat in range(len(saved_beats)):
        if beat < 10:
            beat_clicked = []
            row_text = medium_font.render(f'{beat + 1}', True, white)
            screen.blit(row_text, (200, 100 + beat * 50))
            name_index_start = saved_beats[beat].index('name: ') + 6
            name_index_end = saved_beats[beat].index(', beats:')
            name_text = medium_font.render(saved_beats[beat][name_index_start:name_index_end], True, white)
            screen.blit(name_text, (240, 100 + beat * 50))
    return exit_btn, loading_btn, delete_btn, loaded_rectangle

run = True
while run:
    timer.tick(fps)
    screen.fill(black)

    boxes = draw_grid(clicked, active_beat, active_list)
    # lower menu buttons
    play_pause = pygame.draw.rect(screen, gray, (50, HEIGHT-100, 200, 100), 0, 5)
    play_text = label_font.render('Play/Pause', True, white)
    screen.blit(play_text, (70, HEIGHT-80))
    if playing:
        play_text2 = medium_font.render('Playing', True, dark_gray)
    else:
        play_text2 = medium_font.render('Paused', True, dark_gray)
    screen.blit(play_text2, (70, HEIGHT-40))
    # bpm stuff
    bpm_rect = pygame.draw.rect(screen, gray, (300, HEIGHT - 100, 250, 100), 5, 5)
    bpm_text = medium_font.render('Beats Per Minute', True, white)
    screen.blit(bpm_text, (330, HEIGHT-80))
    bpm_text2 = medium_font.render(f'{bpm}', True, dark_gray)
    screen.blit(bpm_text2, (330, HEIGHT-40))
    bpm_add_rect = pygame.draw.rect(screen, gray, (560, HEIGHT-100, 45, 45), 0, 5)
    bpm_sub_rect = pygame.draw.rect(screen, gray, (560, HEIGHT-50, 45, 45), 0, 5)
    add_text = medium_font.render('+5', True, white)
    sub_text = medium_font.render('-5', True, white)
    screen.blit(add_text, (565, HEIGHT-89))
    screen.blit(sub_text, (567, HEIGHT-40))

    # beats stuff
    beats_rect = pygame.draw.rect(screen, gray, (700, HEIGHT - 100, 250, 100), 5, 5)
    beats_text = medium_font.render('Beats Per Loop', True, white)
    screen.blit(beats_text, (730, HEIGHT-80))
    beats_text2 = medium_font.render(f'{beats}', True, dark_gray)
    screen.blit(beats_text2, (730, HEIGHT-40))
    beats_add_rect = pygame.draw.rect(screen, gray, (960, HEIGHT-100, 45, 45), 0, 5)
    beats_sub_rect = pygame.draw.rect(screen, gray, (960, HEIGHT-50, 45, 45), 0, 5)
    add_text2 = medium_font.render('+1', True, white)
    sub_text2 = medium_font.render('-1', True, white)
    screen.blit(add_text2, (965, HEIGHT-89))
    screen.blit(sub_text2, (967, HEIGHT-40))

    # instruments rects
    instruments_rects = []
    for i in range(instruments):
        rect = pygame.rect.Rect((0, i * 100), (200, 100))
        instruments_rects.append(rect)

    # save and load stuff
    save_button = pygame.draw.rect(screen, gray, (1050, HEIGHT-100, 200, 40), 0, 5)
    save_text = label_font.render('Save Beat', True, white)
    screen.blit(save_text, (1077, HEIGHT - 100))
    load_button = pygame.draw.rect(screen, gray, (1050, HEIGHT-50, 200, 40), 0, 5)
    load_text = label_font.render('Load beat', True, white)
    screen.blit(load_text, (1077, HEIGHT - 50))

    # clear board
    clear_button = pygame.draw.rect(screen, gray, (570, HEIGHT - 150, 200, 40), 0, 5)
    clear_text = label_font.render('Clear', True, white)
    screen.blit(clear_text, (635, HEIGHT-147))

    if save_menu:
        exit_button, saving_button, entry_rectangle = draw_save_menu(beat_name, typing)
    if load_menu:
        exit_button, loading_button, delete_button, load_rectangle = draw_load_menu()

    # sounds stuff
    if beat_changed:
        play_notes()
        beat_changed = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            for i in range(len(boxes)):
                if boxes[i][0].collidepoint(event.pos) and not save_menu and not load_menu:
                    coords = boxes[i][1]
                    clicked[coords[1]][coords[0]] *= -1
        if event.type == pygame.MOUSEBUTTONUP and not save_menu and not load_menu:
            if play_pause.collidepoint(event.pos) and playing:
                playing = False
            elif not playing:
                playing = True
            elif bpm_add_rect.collidepoint(event.pos):
                bpm += 5
            elif bpm_sub_rect.collidepoint(event.pos):
                bpm -= 5
            elif beats_add_rect.collidepoint(event.pos):
                beats += 1
                for i in range(len(clicked)):
                    clicked[i].append(-1)
            elif beats_sub_rect.collidepoint(event.pos):
                beats -= 1
                for i in range(len(clicked)):
                    clicked[i].pop(-1)
            elif clear_button.collidepoint(event.pos):
                clicked = [[-1 for _ in range(beats)] for _ in range(instruments)]
            elif save_button.collidepoint(event.pos):
                save_menu = True
            elif load_button.collidepoint(event.pos):
                load_menu = True
            for i in range(len(instruments_rects)):
                if instruments_rects[i].collidepoint(event.pos):
                    active_list[i] *= -1
        elif event.type == pygame.MOUSEBUTTONUP:
            if exit_button.collidepoint(event.pos):
                save_menu = False
                load_menu = False
                playing = True
                beat_name = ''
                typing = False
            elif entry_rectangle.collidepoint(event.pos):
                if typing:
                    typing = False
                elif not typing:
                    typing = True
            elif saving_button.collidepoint(event.pos):
                file = open('saved_beats.txt', 'w')
                saved_beats.append(f'\nname: {beat_name}, beats: {beats}, bpm: {bpm}, selected: {clicked}')
                for i in range(len(saved_beats)):
                    file.write(str(saved_beats[i]))
                file.close()
                save_menu = False
                typing = False
                beat_name = ''
        if event.type == pygame.TEXTINPUT and typing:
            beat_name += event.text
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE and len(beat_name) > 0 and typing:
                beat_name = beat_name[:-1]

    beat_length = 3600 // bpm

    if playing:
        if active_length < beat_length:
            active_length += 1
        else:
            active_length = 0
            if active_beat < beats - 1:
                active_beat += 1
                beat_changed = True
            else:
                active_beat = 0
                beat_changed = True

    pygame.display.flip()

pygame.quit()

This code is 113 lines long. See if there is anything wrong. If you find an anwer, please answer me that.
Thanks

A: This seems like an obscure issue.  Without knowing the contents of the
file, it seems as if by the following lines:
saved_beats.append(f'\nname: {beat_name}, beats: {beats}, bpm: {bpm}, selected: {clicked}')
for i in range(len(saved_beats)):
    file.write(str(saved_beats[i]))

You have an f-string that has the \n at the beginning, which would turn when written to a file, would produce something along the lines
of:

name: foo, beats: 3, bpm: 10, selected: bar
name: foo, beats: 3, bpm: 10, selected: bar
name: foo, beats: 3, bpm: 10, selected: bar
.
.
.

Notice the empty line at the beginning.
You can either move the \n to the end of the line.
saved_beats.append(f'name: {beat_name}, beats: {beats}, bpm: {bpm}, selected: {clicked}\n')

or if you have to keep that particular format:
Change:
if beat < 10:
    beat_clicked = []
    row_text = medium_font.render(f'{beat + 1}', True, white)
    screen.blit(row_text, (200, 100 + beat * 50))
    name_index_start = saved_beats[beat].index('name: ') + 6
    name_index_end = saved_beats[beat].index(', beats:')
    name_text = medium_font.render(saved_beats[beat][name_index_start:name_index_end], True, white)
    screen.blit(name_text, (240, 100 + beat * 50))

to
if beat < 10:
    beat_clicked = []
    if saved_beats[beat].startswith("name:"):
        row_text = medium_font.render(f'{beat + 1}', True, white)
        screen.blit(row_text, (200, 100 + beat * 50))
        name_index_start = saved_beats[beat].index('name: ') + 6
        name_index_end = saved_beats[beat].index(', beats:')
        name_text = medium_font.render(saved_beats[beat][name_index_start:name_index_end],
                                       True, white)
        screen.blit(name_text, (240, 100 + beat * 50))

This would skip all screen changes if the line doesn't start with
name:.
You could also change the if condition to something like:
if len(saved_beats[beat].strip()) > 0:


text:
Q: pandas convert a nested dictionary to mutiIndex rows and columns I have a nested dictionary and i want to make it to a multiIndex rows and colums like below. But my data is lost in table somehow.
    test= {12: {'Category 1': {'TestA': {'att_1': 1, 'att_2': 'whatever'}, 'TestB': {'att_1': 3, 'att_2': 'spring'}}, 'Category 2': {'TestA': {'att_1': 23, 'att_2': 'another'}, 'TestB': {'att_1': 9, 'att_2': 'summer'}}}, 15: {'Category 1': {'TestA': {'att_1': 10, 'att_2': 'foo'}, 'TestB': {'att_1': 29, 'att_2': 'fall'}}, 'Category 2': {'TestA': {'att_1': 30, 'att_2': 'bar'}, 'TestB': {'att_1': 36, 'att_2': 'winter'}}}}
columns=pd.MultiIndex.from_arrays([['TestA','TestA','TestB','TestB'],['att_1','att_2','att_1','att_2']])

The format I want:
              TestA       TestB
              att_1 att_2 att_1 att_2
12 Category 1   NaN   NaN   NaN   NaN
   Category 2   NaN   NaN   NaN   NaN
15 Category 1   NaN   NaN   NaN   NaN
   Category 2   NaN   NaN   NaN   NaN

And I did
    pd.DataFrame(test,index=pd.MultiIndex.from_arrays([[12,12,15,15],['Category 1','Category 2','Category 1','Category 2']]),columns=pd.MultiIndex.from_arrays([['TestA','TestA','TestB','TestB'],['att_1','att_2','att_1','att_2']]))

My data is lost as below:
             TestA       TestB
              att_1 att_2 att_1 att_2
12 Category 1   NaN   NaN   NaN   NaN
   Category 2   NaN   NaN   NaN   NaN
15 Category 1   NaN   NaN   NaN   NaN
   Category 2   NaN   NaN   NaN   NaN

If I have only multiIndex rows, it would work, but I want both multiIndex rows and colums.
     pd.DataFrame.from_dict({(i,j): test[i][j]
                           for i in test.keys()
                           for j in test[i].keys()},
                       orient='index')

                                           TestA                             TestB
12 Category 1  {'att_1': 1, 'att_2': 'whatever'}   {'att_1': 3, 'att_2': 'spring'}
   Category 2  {'att_1': 23, 'att_2': 'another'}   {'att_1': 9, 'att_2': 'summer'}
15 Category 1      {'att_1': 10, 'att_2': 'foo'}    {'att_1': 29, 'att_2': 'fall'}
   Category 2      {'att_1': 30, 'att_2': 'bar'}  {'att_1': 36, 'att_2': 'winter

A: You can get the required data frame as:
import pandas as pd
import numpy as np

test= {12: {'Category 1': {'TestA': {'att_1': 1, 'att_2': 'whatever'}, 'TestB': {'att_1': 3, 'att_2': 'spring'}}, 'Category 2': {'TestA': {'att_1': 23, 'att_2': 'another'}, 'TestB': {'att_1': 9, 'att_2': 'summer'}}}, 15: {'Category 1': {'TestA': {'att_1': 10, 'att_2': 'foo'}, 'TestB': {'att_1': 29, 'att_2': 'fall'}}, 'Category 2': {'TestA': {'att_1': 30, 'att_2': 'bar'}, 'TestB': {'att_1': 36, 'att_2': 'winter'}}}}

# Row indexes
row_index = [[12,12,15,15],['Category 1','Category 2','Category 1','Category 2']]

# Column indexes
col_index = [['TestA','TestA','TestB','TestB'],['att_1','att_2','att_1','att_2']]

# Values row wise
values =[1,'whatever',3,'spring',23,'another',9,'summer',10,'foo',29,'fall',30,'bar',36,'winter']

# Convert the list of values to numpy array
value = np.array(values)

# Reshape the value as (4,4) array as the matrix/dataframe is of shape (4,4)
value = value.reshape(4,4)

# Get your required data frame
pd.DataFrame(value, index=row_index, columns=col_index)


text:
Q: Fastest way to concatenate slices of numpy array I have a large number of small numpy arrays (groups) of different sizes, and I want to concatenate an arbitrary subset of these groups as fast as possible. The solution I originaly came up with is to store these groups as np.array of np.arrays and then access a subset of groups with list indexing:
groups = []
for i in range(100000):
    size = np.random.randint(3) + 1
    groups.append(np.random.randint(1000000, size=size))
groups = np.array(groups)  # dtype=np.object
indices = np.random.randint(len(groups), size=1000)

%%timeit
np.concatenate(groups[indices])
>>> 204 µs ± 395 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

However, this solution is inefficient in terms of memory consumption as groups are small (2 elements on average) and I have to store a numpy array structure for each group, which is almost 100 bytes (too much for me).
To make the solution more efficient I've decided to concatenate all groups and store array boundaries in a separate array
data = np.concatenate(groups)
offsets = np.cumsum([0] + [len(group) for group in groups])
# ith group is data[offsets[i]: offsets[i + 1]]

But then concatenation is not obvious at all. Something like this:
%%timeit
np.concatenate([data[offsets[i]: offsets[i + 1]] for i in indices])
>>> 1.02 ms ± 44.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Works 5 times slower than the original solution. I think this is because of two things. First, iteration over numpy array indices (python wraps c-int into object for each index). Second, python creates numpy structure for each slice/index. I think it's impossible to reduce concatenation time for this case in pure python, so I've decided to come up with a cython solution.
%%cython
import numpy as np
ctypedef long long int64

def concatenate(data, offsets, indices):
    cdef int64[::] data_view = data
    cdef int64[::] indices_view = indices
    cdef int64[::] offsets_view = offsets

    size = np.sum(offsets[indices + 1]) - np.sum(offsets[indices])
    res = np.zeros(size, dtype=np.int64)
    cdef int64[::] res_view = res

    cdef int64 i, l = 0, r
    for i in indices_view:
        r = l + offsets_view[i + 1] - offsets_view[i]
        res_view[l: r] = data_view[offsets_view[i]: offsets_view[i + 1]]
        l = r
    return res

%%timeit
concatenate(data, offsets, indices)
>>> 277 µs ± 89.8 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

This solution is faster than the previous, but still a little slower than the original. But the biggest problem is that I don't know the data type in advance. I've used int64 in the example, but it could be any number type, e.g. float32. Because of that, I cannot use typed memory views as I did. In theory, I only need to know the size of the type (4/8 bytes) and if I have pointers to the data and result arrays, I can use memcpy or something similar to copy slices. But I don't know how to do it in cython. Is there a way to do it?

A: Here's my pure numpy-only solution, adv_concatenate() function. It gives 15x-47x times speedup (different on different machines) compared to regular np.concatenate().
NOTE: There is also a second faster solution going after the code of first one.
For time measurement for used pip module timerit, install it once by python -m pip install timerit. For timings two types of machines were used - first machine is Windows-based, it is same for all tests, it is my home laptop, second machine is Linux-based, it is different machine for every test (so different speed between different tests, but same speed inside one run/test), it is machine of repl.it site that I used to test my code too.
The idea of algorithm was to use numpy's cumulative sum function (.cumsum()):

*

*We create array of just 1s, size of array equal to total resulting concatenated data array size. This array will hold indexes of all data elements to be fetched to create resulting data array.

*Inside this array at starting postitions of each block (small sub-array) we change values to in such a way that after running cumsum() on whole resulting array this starting values are transformed to starting offsets into data array. The remaining values remain 1s.

*To this array we apply .cumsum(). Now all values will hold correct indexes of data elements to be fetched.

*We form resulting fetched data array by just indexing data with formed above array of indexes.

This algorithm can be potentially boosted even more if we pre-compute some values like offsets[1:] - offsets[:-1] or offsets[:-1] + 1 and use them inside adv_concatenate() function.
Try it online!
# Needs: python -m pip install numpy timerit
from timerit import Timerit
import numpy as np
np.random.seed(0)
Timerit._default_asciimode = True

groups = []
for i in range(100000):
    size = np.random.randint(3) + 1
    groups.append(np.random.randint(1000000, size = size))
groups = np.array(groups)  # dtype=np.object
indices = np.random.randint(len(groups), size = 1000)

data = np.concatenate(groups)
offsets = np.cumsum([0] + [len(group) for group in groups])

timer = lambda: Timerit(num = 600, verbose = 1)

print('np.concatenate(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        ref = np.concatenate([data[offsets[i] : offsets[i + 1]] for i in indices])
tref = tim.mean()

def adv_concatenate(data, offsets, indices):
    begs, ends = offsets[indices], offsets[indices + 1]
    lens = ends - begs
    clens = lens.cumsum()
    ix = np.ones((clens[-1],), dtype = offsets.dtype)
    ix[0] = begs[0]
    ix[clens[:-1]] = begs[1:] - ends[:-1] + 1
    ix = ix.cumsum()
    return data[ix]

print('adv_concatenate(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        adv = adv_concatenate(data, offsets, indices)
tadv = tim.mean()
assert np.array_equal(ref, adv) # Check that our solution is correct

print('speedup:', round(tref / tadv, 3))

Outputs:
On first machine (Windows):
np.concatenate(): Timed best=3.129 ms, mean=3.225 +- 0.1 ms
adv_concatenate(): Timed best=191.137 us, mean=208.012 +- 20.7 us
speedup: 15.504

On second machine (Linux):
np.concatenate(): Timed best=1.666 ms, mean=2.314 +- 0.4 ms
adv_concatenate(): Timed best=35.596 us, mean=48.680 +- 15.4 us
speedup: 47.532

Second solution is even more faster than first one giving 40x-150x times speedup (different on different machines) compared to regular np.concatenate(). But second solution uses Numba JIT LLVM-based compiler, that needs to be installed via python -m pip install numba.
Although it uses extra numba package still central function adv_concatenate_indexes_numba() is very simple, same amount of lines of code as in first solution. Also algorithm is much simpler just, two simple loops.
Current solution works for any data type, because central function just computes resulting indexes, hence doesn't work with data's dtype at all. Also current solution can be boosted by 10%-90% more if instead of computing indexes numba function will compute straight resulting data array, but this is only possible for quite simple data types that are supported by numba, including all number types. Here is the code (or here) for this improved solution which achieves up to 250x speedup! Timings for this improved version on second machine (Linux):
np.concatenate(): Timed best=1.640 ms, mean=3.403 +- 1.9 ms
adv_concatenate_numba(): Timed best=12.669 us, mean=17.235 +- 6.9 us
speedup: 197.46

More generic (only-indexes-computing) solution's code is going next:
Try it online!
# Needs: python -m pip install numpy numba timerit
from timerit import Timerit
import numpy as np, numba
np.random.seed(0)
Timerit._default_asciimode = True

groups = []
for i in range(100000):
    size = np.random.randint(3) + 1
    groups.append(np.random.randint(1000000, size = size, dtype = np.int64))
groups = np.array(groups)  # dtype=np.object
indices = np.random.randint(len(groups), size = 1000, dtype = np.int64)

data = np.concatenate(groups)
offsets = np.cumsum([0] + [len(group) for group in groups], dtype = np.int64)

timer = lambda: Timerit(num = 600, verbose = 1)

print('np.concatenate(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        ref = np.concatenate([data[offsets[i] : offsets[i + 1]] for i in indices])
tref = tim.mean()

@numba.njit('i8[:](i8[:], i8[:])', cache = True)
def adv_concatenate_indexes_numba(offsets, indices):
    tlen = 0
    for i in range(indices.size):
        ix = indices[i]
        tlen += offsets[ix + 1] - offsets[ix]

    pos, r = 0, np.empty((tlen,), dtype = offsets.dtype)
    for i in range(indices.size):
        ix = indices[i]
        for j in range(offsets[ix], offsets[ix + 1]):
            r[pos] = j
            pos += 1

    return r

def adv_concatenate2(data, offsets, indices):
    return data[adv_concatenate_indexes_numba(offsets, indices)]

adv_concatenate2(data, offsets, indices) # Once pre-compile Numba
print('adv_concatenate2(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        adv = adv_concatenate2(data, offsets, indices)
tadv = tim.mean()
assert np.array_equal(ref, adv) # Check that our solution is correct

print('speedup:', round(tref / tadv, 3))

Output:
On first machine (Windows):
np.concatenate(): Timed best=3.201 ms, mean=3.356 +- 0.1 ms
adv_concatenate2(): Timed best=79.681 us, mean=82.991 +- 6.7 us
speedup: 40.442

On second machine (Linux):
np.concatenate(): Timed best=1.541 ms, mean=2.220 +- 0.7 ms
adv_concatenate2(): Timed best=12.012 us, mean=14.830 +- 4.8 us
speedup: 149.716

Inspired by Cython code of @pavelgramovich answer I've also decided to implement my simplified version with loop (func concatenate1()) instead of memcpy() version (func concatenate0()), simplified version appeared to be 1.5-2x faster than memcpy version for current test data. Full code comparing both versions down below:
Try it online!
# Needs: python -m pip install numpy timerit cython setuptools
from timerit import Timerit
import numpy as np
np.random.seed(0)
Timerit._default_asciimode = True

groups = []
for i in range(100000):
    size = np.random.randint(3) + 1
    groups.append(np.random.randint(1000000, size = size, dtype = np.int64))
groups = np.array(groups)  # dtype=np.object
indices = np.random.randint(len(groups), size = 1000, dtype = np.int64)

data = np.concatenate(groups)
offsets = np.cumsum([0] + [len(group) for group in groups], dtype = np.int64)

timer = lambda: Timerit(num = 600, verbose = 1)

def compile_cy_cats():
    src = """
import numpy as np
cimport numpy as np
cimport cython
from libc.string cimport memcpy

@cython.boundscheck(False)
@cython.wraparound(False)
def concatenate0(np.ndarray data, np.ndarray offsets, np.ndarray indices):
    data = np.ascontiguousarray(data)
    start_offsets = np.ascontiguousarray(offsets[indices], dtype=np.int64)
    end_offsets = np.ascontiguousarray(offsets[indices + 1], dtype=np.int64)
    cdef np.int64_t[::1] coffsets = start_offsets
    cdef np.int64_t[::1] csizes = end_offsets - start_offsets

    cdef np.int64_t i, total_size = 0
    for i in range(csizes.shape[0]):
        total_size += csizes[i]
    res = np.empty(total_size, dtype=data.dtype)

    cdef np.ndarray cdata = data
    cdef np.ndarray cres = res

    cdef np.int64_t itemsize = data.itemsize
    cdef np.int64_t res_offset = 0
    for i in range(csizes.shape[0]):
        memcpy(cres.data + res_offset * itemsize,
               cdata.data + coffsets[i] * itemsize,
               csizes[i] * itemsize)
        res_offset += csizes[i]

    return res

@cython.boundscheck(False)
@cython.wraparound(False)
def concatenate1(np.int64_t[:] data, np.int64_t[:] offsets, np.int64_t[:] indices):
    cdef np.int64_t tlen = 0, pos = 0, ix = 0, ixs = indices.size, i = 0, j = 0

    for i in range(ixs):
        ix = indices[i]
        tlen += offsets[ix + 1] - offsets[ix]

    r = np.empty(tlen, dtype = np.int64)
    cdef np.int64_t[:] cr = r, cdata = data

    for i in range(ixs):
        ix = indices[i]
        for j in range(offsets[ix], offsets[ix + 1]):
            cr[pos] = cdata[j]
            pos += 1

    return r
    """

    srcb = src.encode('utf-8')

    import hashlib, os, glob, importlib
    srch = hashlib.sha256(srcb).hexdigest().upper()[:8]

    if len(glob.glob(f'cy{srch}*')) == 0:
        with open(f'cys{srch}.pyx', 'wb') as f:
            f.write(srcb)

        import sys
        from setuptools import setup, Extension
        from Cython.Build import cythonize
        import numpy as np

        sys.argv += ['build_ext', '--inplace']
        setup(
            ext_modules = cythonize(
                Extension(f'cy{srch}', [f'cys{srch}.pyx']), language_level = 3, annotate = True,
            ),
            include_dirs = [np.get_include()],
        )
        del sys.argv[-2:]

    print('Cython module:', f'cy{srch}')
    return importlib.import_module(f'cy{srch}')

cy_cats = compile_cy_cats()
concatenate0, concatenate1 = cy_cats.concatenate0, cy_cats.concatenate1

print('np.concatenate(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        ref = np.concatenate([data[offsets[i] : offsets[i + 1]] for i in indices])
tref = tim.mean()

concatenate0(data, offsets, indices) # Maybe pre-heat
print('cy_concatenate0(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        adv0 = concatenate0(data, offsets, indices)
tadv0 = tim.mean()
assert np.array_equal(ref, adv0) # Check that our solution is correct

print('speedup:', round(tref / tadv0, 3))

concatenate1(data, offsets, indices) # Maybe pre-heat
print('cy_concatenate1(): ', end = '', flush = True)
tim = timer()
for t in tim:
    with t:
        adv1 = concatenate1(data, offsets, indices)
tadv1 = tim.mean()
assert np.array_equal(ref, adv1) # Check that our solution is correct

print('speedup:', round(tref / tadv1, 3))

Output:
First machine (Windows):
Cython module: cy0BEBA0C8
np.concatenate(): Timed best=3.184 ms, mean=3.263 +- 0.1 ms
cy_concatenate0(): Timed best=119.767 us, mean=128.688 +- 10.7 us
speedup: 25.354
cy_concatenate1(): Timed best=86.525 us, mean=93.699 +- 20.5 us
speedup: 34.821

Second machine (Linux):
Cython module: cy0BEBA0C8
np.concatenate(): Timed best=1.630 ms, mean=2.215 +- 0.5 ms
cy_concatenate0(): Timed best=21.839 us, mean=28.930 +- 8.4 us
speedup: 76.578
cy_concatenate1(): Timed best=11.447 us, mean=15.263 +- 5.1 us
speedup: 145.151

A: I found a way to concatenate slices of an array of arbitrary dtype with cython. There is a c-counterpart of a python numpy.ndarray class. It contains a pointer data to the beginning of an underlying c-array and attribute itemsize, which stores the size of a single element in bytes. With that, it becomes possible to concatenate slices using memcpy.
import numpy as np
cimport numpy as np
cimport cython
from libc.string cimport memcpy

@cython.boundscheck(False)
@cython.wraparound(False)
def concatenate(np.ndarray data, np.ndarray offsets, np.ndarray indices):
    data = np.ascontiguousarray(data)
    start_offsets = np.ascontiguousarray(offsets[indices], dtype=np.int64)
    end_offsets = np.ascontiguousarray(offsets[indices + 1], dtype=np.int64)
    cdef np.int64_t[::1] coffsets = start_offsets
    cdef np.int64_t[::1] csizes = end_offsets - start_offsets

    cdef np.int64_t i, total_size = 0
    for i in range(csizes.shape[0]):
        total_size += csizes[i]
    res = np.empty(total_size, dtype=data.dtype)

    cdef np.ndarray cdata = data
    cdef np.ndarray cres = res

    cdef np.int64_t itemsize = data.itemsize
    cdef np.int64_t res_offset = 0
    for i in range(csizes.shape[0]):
        memcpy(cres.data + res_offset * itemsize,
               cdata.data + coffsets[i] * itemsize,
               csizes[i] * itemsize)
        res_offset += csizes[i]

    return res

%%timeit
concatenate(data, offsets, indices)
>>> 21.1 µs ± 24.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)


text:
Q: Pympler behaves strangely Pympler is used to find memory leaks in python but when I run this program:
from pympler import muppy

for i in range(10):
    objs = muppy.get_objects()
    print(len(objs))

the output is:
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712

In every iteration, the number of objects has increased! If I run it for a long time, I would run out of memory! What is happening? Does pympler have memory leak itself?!

Update:
The same thing happens with the following program:
import gc

for i in range(10):
    objs = gc.get_objects()
    print(len(objs))

A: I think I figured out what's going on:
The increasing number indeed comes from the objs collection itself.
When the loop is called the second (!) time, the objs object from the last iteration is still in scope. Therefore, it will be not removed by GC. Thus, the collection of objects objs now also contains the (older) objs object itself, leading to the count being incremented.
If you call del objs or objs = None or anything else before calling gc.get_objects()/muppy.get_objects(), you will get the same count on each iteration:
import gc

for i in range(10):
    objs = None
    objs = gc.get_objects()
    print(len(objs))

Gives 7063 on each iteration (on my system).


text:
Q: Why am I getting 'object is not a function' on this form? When I submit this form, I'm quickly getting an "object is not a function" error (in Chrome), while the form submits. What's my bug?
I'm sure it's something silly, but for the life of me I don't understand what's wrong here.

A: I just changed your function name validate() to formVal(), and now it's working just fine - it's because you have an element with id of validate.
Change the function name to formVal() (or anything apart from validate()), then change the form tag to say this:
<form onSubmit='return formVal();'>

It now comes up saying "Valid!" in a heading tag below the form. There is also no error.

A: You have function 'validate' and submit button has got id 'validate'. Change one of them.

A: The other answers are correct, but you can avoid all this hassle by using jQuery more properly.
Instead of inline JavaScript inside the form tag, add ID to the form then have such code:
$(document).ready(function() {
    $("#myform").bind("submit", validate);
});

The form now should look like this:
<form id="myform">

And don't forget to add the return false; to the function itself to prevent submission.
When inside the function, JS will treat validate properly as a function - when inline inside the form tag, it looked first in the form elements and found the button - hence the error you got.


text:
Q: Adding a method to an object that is inside of a function in js Hi this is from a challenge I was working on. Is there any way i can add the introduce method to the personStore object without using the keyword this. Any insight is greatly appreciated.

Using Object.create
Challenge 1/3
Inside personStore object, create a property greet where the value is a  function that logs "hello".
Challenge 2/3
Create a function personFromPersonStore that takes as input a name and an age. > When called, the function will create person objects using the Object.create  method on the personStore object.
Challenge 3/3
Without editing the code you've already written, add an introduce method to the personStore object that logs "Hi, my name is [name]".
Side Curiosity
As a side note, was curious if there was a way to add the introduce method to the person object that sits inside of the personFromPersonStore function.

my solution:
var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;
};

personStore.introduce = function () {
  console.log('Hi, my name is ' + this.name)
}

//Challenge 3 Tester
sandra.introduce(); // -> Logs 'Hi, my name is Sandra

A: You can, but using this is a lot simpler.
This code passes the name property as an argument, but as the property is already accessible to the introduce function as an internal property via this, it is a bit wasteful.

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;
};

personStore.introduce = function (nm) {
  console.log('Hi, my name is ' + nm)
}

person1=personFromPersonStore('Fred',21);
person1.introduce(person1.name);

A: You can write it like this:
personFromPersonStore("whatevername","whateverage").name

instead of this.


text:
Q: CSS transition not working in ASP.NET Web Forms CSS3 transition works fine in an HTML page, but not in a .aspx page.  Is there a way to overcome this?  I'd like to do the app in Web Forms as it makes designing the forms much easier.  Any input would be appreciated.
Here is the .aspx page:
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="CMSWebForms.Index" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!DOCTYPE html>

    <title>test</title>
    <link rel="stylesheet" type="text/css" href="Content/jquery-1.10.2.min.js" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/bootstrap-combined.min.css" rel="stylesheet" />
    <link href="Content/font-awesome.min.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="Content/test.css"/>

CMS

            Sales

Customers

                    Pricing

A

B

C

D

E

Quotes

Orders

Pricing

Reports

            Manufacturing

One

Two

Three

Four

Five

                        <button id="sidebarToggle" class="btn btn-primary btn-lg">

                        </button>

                           Log in

                CMS

Hello Beautiful!

                    Name:
                    <asp:TextBox ID="TextBox1" runat="server" Width="248px"></asp:TextBox>
                    Address:
                     <asp:TextBox ID="TextBox2" runat="server" Width="248px"></asp:TextBox>

©2016 Apiron Technologies, Inc.

</asp:Content>

Here is the CSS:
#sidebar{
  background: #000;
  color: #999999;
  border-radius: 0;
  padding: 0;
  height: 100%;
  width: 200px;
  margin-top: 0;
  transition: .25s;
}

#sidebar.dropdown-menu.text-right.hide-sidebar{
    left: -200px !important;
    transition: .25s;
}

.navbar.navbar-inverse{
    border-radius: 0 !important;
    background: #1536b6 !important;
}

.navbar-inverse
.navbar-inverse .nav>li>a {
    color: #fff !important;
}

.btn-info{
    color: #fff !important;
}

.navbar.navbar-inverse.navbar-fixed-bottom{
   margin-left: 200px !important;
}

#page-content-wrapper {
    margin-left: 200px;
    transition: .25s;
}

#page-content-wrapper.hide-sidebar{
    margin-left: 0;
    transition: .25s;
}

.dropdown-menu {
 border-radius: 0;
 padding: 0;
}

.dropdown-menu li a {
  background: #000;
  color: #999999;
  display: block;
  text-decoration: none;
  outline: none;

}

.dropdown-menu li a:hover,
.dropdown-menu li.active {
  color: #fff;
  background: rgba(255,255,255,0.2);
  text-decoration: none;
}

.dropdown-menu.text-right li a {
  background: #000;
  color: #999999;

  display: block;
  text-decoration: none;
  outline: none;

}

.dropdown-menu.text-right li a:hover,
.dropdown-menu.text-right li.active {
  color: #fff;
  background-color: #333131 ;
  text-decoration: none;
}

.dropdown-submenu.pull-right{
  background: #000;
  display: block;
  width: 100%;
}

#myId  {
    color: aqua;

}

and here is the JS:
 (function () {

    var $sidebarAndWrapper = $("#sidebar,#page-content-wrapper");
    var $icon = $("#sidebarToggle i.fa");

    $("#sidebarToggle").on("click", function () {
        $sidebarAndWrapper.toggleClass("hide-sidebar");
        if ($sidebarAndWrapper.hasClass("hide-sidebar")) {
            $icon.removeClass("fa-angle-left");
            $icon.addClass("fa-angle-right");
        }
        else {
            $icon.removeClass("fa-angle-right");
            $icon.addClass("fa-angle-left");
        }
    });

})();

A: What browser are you checking in? Try using another browser.
Once i had a same problem. Resetting IIS site fixed the issue. You can also try prefixing CSS.
Cheers


text:
Q: VB.NET Compiler : got stuck with "replace" My code is below : (It was quite long)
Module Module1

    Sub EndFunction(Optional ByVal NL As Integer = 0)
        If NL = 1 Then
            Console.WriteLine(Environment.NewLine)
        Else
            Console.WriteLine()
        End If
    End Sub

    Sub HandleCompile(ByVal FileLine As String())

        Dim CurrentLine As String
        Dim CurrentPara() As String
        Dim CurrentUserReadLine As String = ""

        For i As Integer = 0 To FileLine.Length - 1

            CurrentLine = FileLine(i)
            CurrentPara = CurrentLine.Split(" ")

            Select Case CurrentPara(0)
                Case "write"
                    For Count As Integer = 1 To CurrentPara.Length - 1
                        If (CurrentPara(Count).Contains("$readvalue")) Then
                            CurrentPara(Count).Replace("$readvalue", CurrentUserReadLine)
                        End If
                        Console.Write(CurrentPara(Count) + " ")
                    Next
                    EndFunction(1)
                Case "read"
                    CurrentUserReadLine = Console.ReadLine()
                    EndFunction()
                Case "clean"
                    Console.Clear()
                Case Else
                    Console.WriteLine("ERROR : NO SUCH FUNCTION")
                    EndFunction()
            End Select

        Next

    End Sub

    Sub Main()

        Dim UserInput As String
        Dim Para() As String
        Dim UserReadLine As String = ""
        Dim FullFile As String
        Dim FileLine() As String

GetInput:
        UserInput = Console.ReadLine()
        Para = UserInput.Split(" ")
        Para(0) = Para(0).ToLower

        For i As Integer = 1 To Para.Length - 1
            If (Para(i).ToLower.Contains("$readvalue")) Then
                Para(i) = Para(i).Replace("$readvalue", UserReadLine)
            End If
        Next

        Select Case Para(0)
            Case "write"
                For Count As Integer = 1 To Para.Length - 1
                    Console.Write(Para(Count) + " ")
                Next
                EndFunction(1)
            Case "read"
                UserReadLine = Console.ReadLine()
                EndFunction()
            Case "clean"
                Console.Clear()
            Case "compile"
                If My.Computer.FileSystem.FileExists(Para(1)) Then
                    FullFile = My.Computer.FileSystem.ReadAllText(Para(1))
                    FileLine = FullFile.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
                    HandleCompile(FileLine)
                Else
                    Console.WriteLine("Cannot Find File : " + Para(1))
                End If
                EndFunction()
            Case Else
                Console.WriteLine("ERROR : NO SUCH FUNCTION")
                EndFunction()
        End Select

        GoTo GetInput

    End Sub

End Module

In HandleCompile(FileLine), I wish to get every parameter's $readvalue to be replaced to CurrentUserReadLine. Which means if I wrote such a code in file C:\easy.txt :
read
write $readvalue

And I ran this in the compiler :
compile C:\easy.txt

What I have expected is :

*

*The compiler reads the user's input;

*It prints out $readvalue, which is the same as the user's input.

However when I try the code above what I get is :
(Line 1 is User Input)
abc
$readvalue

But I want to see
abc
abc

I had no idea what's going on. Any answer or comment would be appreciated.

A: You forgot to save the result of your replace back into CurrentPara(Count).
CurrentPara(Count) = CurrentPara(Count).Replace("$readvalue", CurrentUserReadLine)


text:
Q: How to recover from segmentation fault on C++? I have some production-critical code that has to keep running.
think of the code as
while (true){
   init();
   do_important_things();  //segfault here
   clean();
}

I can't trust the code to be bug-free, and I need to be able to log problems to investigate later.
This time, I know for a fact somewhere in the code there is a segmentation fault getting thrown, and I need to be able to at least log that, and then start everything over.
Reading here there are a few solutions, but following each one is a flame-war claiming the solution will actually do more harm than good, with no real explanation. I also found this answer which I consider using, but I'm not sure it is good for my use case.
So, what is the best way to recover from segmentation fault on C++?

A: I suggest that you create a very small program that you make really safe that monitors the buggy program. If the buggy program exits in a way you don't like, restart the program.
Posix example:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <cstdio>
#include <iostream>

int main(int argc, char* argv[]) {
    if(argc < 2) {
        std::cerr << "USAGE: " << argv[0] << " program_to_monitor <arguments...>\n";
        return 1;
    }

    while(true) {
        pid_t child = fork();          // create a child process

        if(child == -1) {
            std::perror("fork");
            return 1;
        }

        if(child == 0) {
            execvp(argv[1], argv + 1); // start the buggy program
            perror(argv[1]);           // starting failed
            std::exit(0);              // exit with 0 to not trigger a retry
        }

        // Wait for the buggy program to terminate and check the status
        // to see if it should be restarted.

        if(int wstatus; waitpid(child, &wstatus, 0) != -1) {
            if(WIFEXITED(wstatus)) {
                if(WEXITSTATUS(wstatus) == 0) return 0; // normal exit, terminate

                std::cerr << argv[0] << ": " << argv[1] << " exited with "
                          << WEXITSTATUS(wstatus) << '\n';
            }
            if(WIFSIGNALED(wstatus)) {
                std::cerr << argv[0] << ": " << argv[1]
                          << " terminated by signal " << WTERMSIG(wstatus);
                if(WCOREDUMP(wstatus)) std::cout << " (core dumped)";
                std::cout << '\n';
            }
            std::cout << argv[0] << ": Restarting " << argv[1] << '\n';
        } else {
            std::perror("wait");
            break;
        }
    }
}


text:
Q: Can't use $_post value as table name for mysql in php I'm working on a blog right now that aims to display messages to only people it belongs to, so I have a select in html where people can select a person and then it sends it to that table in MySQL.
What I now have in the index.html:
<form action="post.php" method="post">
                Naam:
                <input type="text" name="name" placeholder="Naam" class="form-control">
                Voor wie is dit bericht bestemd?
                <select name="portal" class="form-control">
                    <option id="0">Selecteer</option>
                    <option id="1">Leerlingen</option>
                    <option id="2">Docenten</option>
                    <option id="3">Ouders</option>
                    <option id="4">Bedrijven</option>
                </select>

                Email:
                <input type="email" placeholder="Email" class="form-control">
                Onderwerp:
                <input type="textarea" class="form-control" placeholder="Onderwerp" name="subject"/>

                Korte informatie:
                <input class="form-control" type="textarea" name="short"/>
                Volledige informatie
                <textarea class="form-control" rows="4" cols="50" name="long"></textarea>

                <button class="btn btn-default">Verstuur!</button>
            </form>

and this in my post.php:
<?php
    $servername = "localhost";
    $username = "a1070rik";
    $password = "";
    $dbname = "portals";
    $title = '$_POST[subject]';
    $by = '$_POST[name]';
    $short = '$_POST[short]';
    $long = '$_POST[long]';
    $portal = '$_POST[portal]';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO $portal (id, title, by, short, long)
VALUES ('', $title, $by, $short, $long)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

When I try to run it it gives me this vague error:
Error: INSERT INTO $_POST[portal] (id, title, by, short, long) VALUES ('', $_POST[subject], $_POST[name], $_POST[short], $_POST[long])
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[portal] (id, title, by, short, long) VALUES ('', $_POST[subject], $_POST[name],' at line 1

Thanks
EDIT:
Thanks everyone that helped,
this code eventually worked for me:
<?php
    $servername = "localhost";
    $username = "a1070rik";
    $password = "";
    $dbname = "portals";
    $title = $_POST['subject'];
    $by_information = $_POST['name'];
    $short = $_POST['short'];
    $long_information = $_POST['long'];
    $portal = $_POST['portal'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO  $portal (`id`, `title`, `info_bys`, `info_shorts`, `info_longs`) VALUES ('', '$title', '$by', '$short', '$long')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

A: Dont use variables as strings. Keep it organized and fool proof:

<?php
    $servername = "localhost";
    $username = "a1070rik";
    $password = "";
    $dbname = "portals";
    $title = $_POST['subject'];
    $by = $_POST['name'];
    $short = $_POST['short'];
    $long = $_POST['long'];
    $portal = $_POST['portal'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$portal = $mysqli->real_escape_string($portal);
$title = $mysqli->real_escape_string($title);
$by = $mysqli->real_escape_string($by);
$short = $mysqli->real_escape_string($short);
$long = $mysqli->real_escape_string($long);

$sql = "INSERT INTO `".$portal."` (id, title, by, short, long) VALUES ('', '".$title."', '".$by."', '".$short."', '".$long."')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

A: $_POST works like an array So you will need to get values from $_POST by his indexs i.e in your case subject,name etc. So Remove ' while assigning the values to variable.
$title = $_POST['subject'];
$by = $_POST['name'];
$short = $_POST['short'];
$long = $_POST['long'];
$portal = strtolower($_POST['portal']);

NOTE : The names 'by,long' are MySQL reserved keywords. So Change them.
Update your SQL from
 $sql = "INSERT INTO $portal (id, title, by, short, long) VALUES ('', '$title', '$by', '$short', '$long')";

TO
 $sql = "INSERT INTO  $portal (`id`, `title`, `info_bys`, `info_shorts`, `info_longs`) VALUES ('', '$title', '$by', '$short', '$long')";

Your sql is vulnerable So use
// prepare and bind
$stmt = $conn->prepare("INSERT INTO  $portal (`title`, `info_bys`, `info_shorts`, `info_longs`) VALUES (?, ?, ?, ?)");
$stmt->bind_param($title, $by, $short, $long);
$stmt->execute();


text:
Q: Time series forecasting with decision making I want to do forecasting for wind power generation but the problem with it is that when the wind speed is below 4 m/s the power output is zero. RNN based models do best when these type of conditions are not there. But with these consitions the RNN is not able to forecast properly. Look at the forecasting results below:

As one can see most of the time I got negative results which is not possible.
I tried to using Gradient boosting regression which gave the following results.

Still I'm not able to get those peak values and zero values. I don't think a single model would be able to do prediction here. So, my question is which models should I combine to get those decision making ability and regression ability?


text:
Q: Logout redirect to wrong page When I click on the logout why it redirect me to wrong page. I'm using locahost to develop my page but when I click logout it will redirect me to xampp page, it suppose redirect me to admin page.
     case 'logout':
        log_activity('user logout', $curr_path);
        system_user_stopsession();
        header("Location: http://".$_SERVER["HTTP_HOST"].$web_path);
        break;

A: You're missing a / between the host and path:
header("Location: http://".$_SERVER["HTTP_HOST"]."/".$web_path);