text:
Q: Collision Block Movement i have problem with blocking movement i already read question on Blocking Movement On Collision
but i dont have any idea for my own problem.
if you can give me the logic i will try to solve my own problem.
i hope you can help me
this my player class update
:EDIT: thanks for Kai Hartmann for reply
my problem is for 2D graphic and i want to know how to stop movement when object1 collision with object2
public void Update(GameTime gameTime)
{
    // Ani Test
    up_ani.Update(gameTime);
    down_ani.Update(gameTime);
    left_ani.Update(gameTime);
    right_ani.Update(gameTime);

    position += velocity;

    if (Keyboard.GetState().IsKeyDown(key.MoveUp) && prevState.IsKeyUp(key.MoveDown) && prevState.IsKeyUp(key.MoveRight) && prevState.IsKeyUp(key.MoveLeft))
    {
        currentFace = FacePosition.Up;
        velocity.Y = -3;
    }
    else if (Keyboard.GetState().IsKeyDown(key.MoveDown) && prevState.IsKeyUp(key.MoveUp) && prevState.IsKeyUp(key.MoveRight) && prevState.IsKeyUp(key.MoveLeft))
    {
        currentFace = FacePosition.Down;
        velocity.Y = 3;
    }
    else if (Keyboard.GetState().IsKeyDown(key.MoveRight) && prevState.IsKeyUp(key.MoveDown) && prevState.IsKeyUp(key.MoveUp) && prevState.IsKeyUp(key.MoveLeft))
    {
        currentFace = FacePosition.Right;
        velocity.X = 3;
    }
    else if (Keyboard.GetState().IsKeyDown(key.MoveLeft) && prevState.IsKeyUp(key.MoveDown) && prevState.IsKeyUp(key.MoveRight) && prevState.IsKeyUp(key.MoveUp))
    {
        currentFace = FacePosition.Left;
        velocity.X = -3;
    }
    else
    {
        //currentFace = FacePosition.Down;
        velocity = Vector2.Zero;
    }

    prevState = Keyboard.GetState();
}

and this my collision
public void IntersectWithScore(Vector2 vector1, Vector2 vector2, Texture2D object1, Texture2D object2, int doSomethingToScore, bool isIncrease)
{
    if (vector1.X + object1.Width < vector2.X || vector1.X > vector2.X + object2.Width ||
    vector1.Y + object1.Height < vector2.Y || vector1.Y > vector2.Y + object2.Height)
    {

    }
    else
    {
        player1.Velocity = Vector2.Zero;
    }
}

A: No need for a collision check Method as far as I'm concerned :) I've written this code really quickly but should work okay?(ish). I've assumed you want to check if something is in the player's way and also assumed that there are more than one objects that could be in your players way so to do this I suggest making a class for the 'Solid' object and giving it a position, width and height. Then make a list of this class to contain the multiple 'solid' objects.
// collidable object's Class name = SolidBlock
SolidBlock newSolidBlock;
List<SolidBlock> solidBlocksList = new List<SolidBlock>();

// This will create 10 'solid' objects and adds them all to a list
// This would preferably go in the Load() function so you can set the positions of
// the blocks after creating them (after the loop)
int i = 0;
while (i < 10)
{
    newSolidBlock = new SolidBlock(Vector2, position) // Assuming width and height
                                                      // are set within class
    solidBlocksList.Add(newSolidBlock);
    i++;
}

// It doesn't matter how you create them, the important lines here are the creation of a
// newSolidBlock and then the line adding it to the list of blocks.

solidBlocksList[0].position = new Vector (20, 50); // < for example this is how you would set
                                                   // a block's position.

Then in your players update function you refer to this list of objects.
// Input a list of the objects you want your player to collide with
// this is a list in case you have multiple object2s you want to check
// for collision.
// An Object2 should have a position, height, and width, yes?

public void Update(GameTime gameTime, List<Object2> object2List)
{
    // Ani Test
    up_ani.Update(gameTime);
    down_ani.Update(gameTime);
    left_ani.Update(gameTime);
    right_ani.Update(gameTime);

    position += velocity;

    if (Keyboard.GetState().IsKeyDown(key.MoveUp) && prevState.IsKeyUp(key.MoveDown) &&      prevState.IsKeyUp(key.MoveRight) && prevState.IsKeyUp(key.MoveLeft))
    {
        foreach (Object2 o in object2List)
        {
            if (position.Y <= o.position.Y + o.height)
            {
                velocity.Y = 0;
            }
            else
            {
                velocity.Y = -3;
            }
        }
        currentFace = FacePosition.Up;
    }
    else if (Keyboard.GetState().IsKeyDown(key.MoveDown) && prevState.IsKeyUp(key.MoveUp) &&     prevState.IsKeyUp(key.MoveRight) && prevState.IsKeyUp(key.MoveLeft))
    {
        foreach (Object2 o in object2List)
        {
            if (position.Y + playerWidth >= o.position.Y)
            {
                velocity.Y = 0;
            }
            else
            {
                velocity.Y = 3;
            }
        }
        currentFace = FacePosition.Down;
    }
    else if (Keyboard.GetState().IsKeyDown(key.MoveRight) && prevState.IsKeyUp(key.MoveDown) && prevState.IsKeyUp(key.MoveUp) && prevState.IsKeyUp(key.MoveLeft))
    {
        foreach (Object2 o in object2List)
        {
            if (position.X + playerWidth >= o.position.X)
            {
                velocity.X = 0;
            }
            else
            {
                velocity.X = 3;
            }
        }
        currentFace = FacePosition.Right;
    }
    else if (Keyboard.GetState().IsKeyDown(key.MoveLeft) && prevState.IsKeyUp(key.MoveDown) && prevState.IsKeyUp(key.MoveRight) && prevState.IsKeyUp(key.MoveUp))
    {
        foreach (Object2 o in object2List)
        {
            if (position.X <= o.position.X + o.width)
            {
                velocity.X = 0;
            }
            else
            {
                velocity.X = -3;
            }
        }
        currentFace = FacePosition.Left;
    }
    else
    {
        velocity = Vector2.Zero;
    }

    prevState = Keyboard.GetState();
}

Sorry if this isn't much help, especially the first block of code, that was very much an example of how you could create multiple object2s.


text:
Q: С какой литературы лучше всего стоит начать изучать Hibernate и Spring для Java? С какой литературы лучше всего стоит начать изучать Hibernate и Spring для Java? Желательно на русском если есть.

A: С официальной документации на английском. Особенно хорош reference для Spring.

redpajama_set_name: RedPajamaStackExchange


text:
Q: django: build a class based view that set a session object and call another view is possible to build a class based view that set a session object and call another view? I did this with a form, but I need to set a session object just calling a url.
Now my files are:
url.py
  urlpatterns += [
    path('test/<int:pk>/set', views.testv, name='testset'),
  ]

views.py
def testv(request, pk):
    request.session["test"] = pk
    return render(request, "test_01.html")

This works, called through "test/01/set" and render the test_01.html page. I need to call tha same link but call another class after setted  the request.session["test"] object.
Thanks


text:
Q: Integrated Windows Authentication for Multiple Domains I have Asp.net website for domain A users with the Integrated Windows Authentication.
Now users from domain B need to access the website.
But Domain B users receive pop-up window to input the authenticated information when they access the website
My question is:
How to configure the IIS or Windows Server to allow Domain B users to access the website without the pop-up windows for authentication, just like the users from Domain A.

A: *

*Check that you have a trust configured

Verify this by trying to add domains users from domain B to the file system where your IIS site is located.

*

*Verify that the correct user group from domain B has access to file system where your IIS site is located. ( if not using domain users from domain B ).

*Verify that the user that is testing from domain B has the correct group memberships.
And if running Kerberos authentication.
Check on client where the user is if you have a kerberos ticket by using command
    "klist tickets"


text:
Q: Load many images from php file sometimes throw 500 internal server error I'm loading a gallery of many images from the root of the server ("behind" public_html).
For this job I use a php file which, obtained the name with $_GET, find the image and print it like in the code.
Nothing strange, if not that when the images are many, I get an highly variable number of 500 internal server error.
I'm doing this because I wanted to dynamically manipulate their width/height and maybe adding a watermark. But at the moment I'm not doing that, first I need to solve this problem.
My doubt is:
- Is the problem that I load all of them with the same file and I overload the php?
- The images loaded in this manner, are correctly cached by the browser?
- If I don't want the user for directly access the images, what should I do?
- Should I just surrender and upload normally the images on public_html?
header('Content-Type: '.mime_content_type($filepath));
readfile($filepath);

A: I "found the solution".
There is no solution. The classic route is hundred times faster than putting PHP in the middle of it.
Theres no way around if the images are many.


text:
Q: Determining semi-open subsets of Cantor Space The Cantor space is the product of $\mathbb{N}$ many copies of $\{0,1\}$ which is $\mathcal{C}=\{0,1\}^{\mathbb{N}}$.
Definition: A subset $A$ of a space $X$ is said to be semi-open if $A\subset cl(int(A))$ where cl and int denotes closure and interior operator. It is clear that every open set is semi open. Denote the product topology and $\mathcal{C}$ by $\tau$ and class of all semi open sets of $\mathcal{C}$ is $SO(\mathcal{C})$.
I was confused about determining the class of semi open subsets of $\mathcal{C}$. Since the interior of product does not always imply the product of interiors, It became challenging to determine. Is there any semi open subset of $\mathcal{C}$ which is not open? Or $\tau=SC(\mathcal{C})$? I could not go now, any hint or help would be greatly appreciated.

A: As already mentioned in my above comment, a metric, non-discrete space $X$ always contains a semi-open set, which is not open:
Since $X$ is metric, not discrete, there exists a sequence $(x_n)_{n \in \mathbb{N}}$ of pairwise distinct elements converging to $x \in X$, such that $x_n \neq x$ for all $n \in \mathbb{N}$. Then an easy proof shows that
(*) there exist paiwise disjoint, open sets $U_n$, $n \in \mathbb{N}$ s.t. $x_n \in U_n$ for all $n$.
Let
$U := \bigcup_{n \in \mathbb{N}} U_{2n}$ and
$V := \bigcup_{n \in \mathbb{N}} U_{2n+1}$.
Then $U, V$ are open and disjoint, $x \in \overline{U} \cap \overline{V}$. Hence $\overline{U}$ is semi-open, but not open.  (If $\overline{U}$ was open, then $\overline{U} \cap V \neq \emptyset$, hence $U \cap V \neq \emptyset$.)
Here is a concrete realization in $\mathcal{C}$, which avoids (*):
Let $U_n := \{(x_k)_{k \in \mathbb{N}}: x_1 = \dots = x_n = 0, x_{n+1} = 1\}$. Then $U_n$ is open and $(U_n)_{n \in \mathbb{N}}$ pairwise disjoint.
Let $U, V$ be defined as above. Then $(0, 0, \dots) \in \overline{U} \cap \overline{V}$. Hence $\overline{U}$ is semi-open, but not open.

A: If $U$ is open (in any space $X$) and $U \subseteq A \subseteq cl(U)$ then $A$ is semi-open. So we just want to find a $U$ in $\mathcal C$ with an $A$ that is not open. $\mathcal C$ has the topology generated by the lexiographical ordering. If (a,b) is a no-empty open interval in that ordering then $\overline{(a,b)} \subseteq [a,b]$ but it can be open. But if $a$ and $b$ are specified to be sequences which are not eventually constant, then $\overline{(a,b)} = [a,b]$ and $[a,b],[a,b)$ and $[a,b]$ are all semi-open but not open.


text:
Q: Django FileField save the url instead of the path in the database I have a FileField on my form.
I like the way it behaves, writes the file to MEDIA_ROOT, etc.
I'd like to change what it writes to the database.

If I look in the database I see the path.. /home/user/media/path/to/file.txt what I would like it to write is the URL path without the domain /media/file.txt
Is there an argument to pass into the ModelForm, or Model?
If not, which class do I override?
Seems like bad practice to write absolute path's to a database. I need to be able to dynamically change MEDIA_ROOT & MEDIA_URL. And possibly share this database with other non django applications that would only need the URL of the media.

A: I don't see a way to save the URL in the database, but you can save a relative path in the database. I suppose you have set upload_to to an absolute path. You can change that to a path relative to your MEDIA_ROOT, for example `upload_to="path/to/". See also the official Documentation on that matter.


text:
Q: To visualise Schematic Intersections of Sections over Parts Assume you have Parts

*

*Eggs

*Bars

Some of Eggs belong too to Bars.
I can visualise this by a venn diagram, however I would like show this kind of structure in colours too.
Assume you have items which belong to Eggs and Bars or any combination
Eggs

*

*Kinder

Bars

*

*Mars

*Fazer

*Kinder

The structure of my text (note this is old example of code so You do not need to use this - this is only a dummy example about Tikz how possibly visualize the situation by it)
\documentclass{article}
\usepackage[framemethod=tikz]{mdframed}

%%%%%%%%%%%%%%%%%%%%%%%% Counter Section %%%%%%%%%%%%%%%%%%%%%%
\makeatletter
  \def\@part[#1]#2{%
    \ifnum \c@secnumdepth >\m@ne
      \refstepcounter{part}%
    \fi
    \addcontentsline{toc}{part}{#1}%
    {\parindent \z@ \raggedright
     \interlinepenalty \@M
     \normalfont
     \LARGE \bfseries #2%
     \markboth{}{}\par}%
    \nobreak
    \vskip 3ex
    \@afterheading}
\@addtoreset{section}{part}
\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}
% Start yellow bar on the left-hand-side margin for the Eggs
\part{Eggs}
\section{Mars}
....
% Start red bar on the left-hand-side margin to sign for Bars
\part{Bars}
\section{Kinder}
...
\section{Fazer}
...
% End Red bar on the margin for Bars
% End yellow bar on the margin for Eggs

tikz package comes to my mind only fro this visualisation.
However, there can be better solutions.
Having keyword-list about other groups of the species
\section{Kinder in Eggs}
Lorem ipsun.
Groups: Bars, Eggs. % Notice here. % autogenerate this by checking the applicable groups of Kinder and add them to the end of the section.

section{Fazer in Bars}
Lorem ipsun.
Groups: Bars. % have this although topic in Bars

Visualising this thing with tikz
Above example with any applicable visualization.
I am not sure how to do this.
Some ideas which I have seen elsewhere

*

*use colors or some specific markers to make it that this item belongs to other group too

*use group Cloud to visualise the connections i.e. generate a picture where you can see which items belong to which groups

How would you do the visualisation of the body and mark intersections?
I remember of seeing an elliptical curve visualisation for Table of Contents, where the writer added tag words to specific sections and then finally it created 2D elliptical curve visualisation about the relationships in the body.
However, I cannot remember by which package he did it.

A: Here's one idea using the changebar package to insert colorized bars in the outer margins; if an element belongs to more than one category, you can nest changebar environments with different width to have superimposed bars with the color associated to each category:
\documentclass{article}
\usepackage[framemethod=tikz]{mdframed}
\usepackage[outerbars,color]{changebar}
\usepackage{lipsum}

\makeatletter
  \def\@part[#1]#2{%
    \ifnum \c@secnumdepth >\m@ne
      \refstepcounter{part}%
    \fi
    \addcontentsline{toc}{part}{#1}%
    {\parindent \z@ \raggedright
     \interlinepenalty \@M
     \normalfont
     \LARGE \bfseries\textcolor{partcolor}{#2}%
     \markboth{}{}\par}%
    \nobreak
    \vskip 3ex
    \@afterheading}
\@addtoreset{section}{part}
\makeatother

\setlength\changebarwidth{6pt}

\colorlet{eggcolor}{orange}
\colorlet{barcolor}{cyan}

\begin{document}

\colorlet{partcolor}{orange}

\part{Eggs}
\section{Kinder}
\begin{changebar}[2pt]
\begin{changebar}
\cbcolor{eggcolor}
\lipsum[4]
\end{changebar}
\cbcolor{barcolor}
\end{changebar}

\colorlet{partcolor}{cyan}
\part{Bars}

\section{Mars}
\begin{changebar}
\cbcolor{barcolor}
\lipsum[4]
\end{changebar}

\section{Kinder}
\begin{changebar}[2pt]
\begin{changebar}
\lipsum[4]
\end{changebar}
\cbcolor{eggcolor}
\end{changebar}

\section{Fazer}
\begin{changebar}
\cbcolor{barcolor}
\lipsum[4]
\end{changebar}

\end{document}

The result:


text:
Q: SQL percentage of salary by each employee in different location I got some difficulty when I am trying to get the Salary % of each employee that work in different locations, and by using that % to calculate employee salary contribution in each location. I've attached the table structure and expected result below. I am trying to use the following query, but I think I missed something to group them together. There are errors in the query. Can anybody help me with this?

SELECT p.[Period End Date], p.[EE#], p.Department,
(p.[Gross Wages]/ SUM([Gross Wages]))
WHERE [Location] = 'A' AS 'Gross Wages % in Location A',
(p.[Gross Wages]/ SUM[Gross Wages])
WHERE [Location] = 'B' AS 'Gross Wages % in Location B',
b.[Health Insurance]*(p.[Gross Wages]/ SUM[Gross Wages])
WHERE [Location] = 'A' AS 'Health Insurance % in Location A',
b.[Health Insurance]*(p.[Gross Wages]/ SUM[Gross Wages])
WHERE [Location] = 'B' AS 'Health Insurance % in Location B',
c.[Tax]*(p.[Gross Wages]/ SUM[Gross Wages])
WHERE [Location] = 'A' AS 'Tax % in Location A',
c.[Tax]*(p.[Gross Wages]/ SUM[Gross Wages])
WHERE [Location] = 'B' AS 'Tax % in Location B',
FROM [Table A] p
INNER JOIN [Table B] b ON p.[Employee Number] = b.[Employee Number]
INNER JOIN [Table C] b ON p.[Employee Number] = c.[Employee Number]
GROUP BY p.[location]
Order by p.[Employee Number]
    INNER JOIN [Table B] b ON p.[Employee Number] = b.[Employee Number]
    INNER JOIN [Table C] b ON p.[Employee Number] = c.[Employee Number]
    GROUP BY p.[location]
    Order by p.[Employee Number]

Query Edited Update.
Errors:
1. Found Else by expected ')' Line 2
2. Found 'Gross Wages % in Location A' but expected ''. Line 2
3. Found 'Gross Wages % in Location A' but expected ''. Line 2
SELECT p.[Period End Date], p.[EE#], p.Department,
    SUM(CASE WHEN [Location]='A' THEN(p.[Gross Wages]/ SUM([Gross Wages]) ELSE '0' END) AS 'Gross Wages % in Location A'),
    SUM(CASE WHEN [Location]='B' THEN(p.[Gross Wages]/ SUM([Gross Wages]) ELSE '0' END) AS 'Gross Wages % in Location B'),
    SUM(CASE WHEN [Location]='A' THEN(b.[Health Insurance]*(p.[Gross Wages]/SUM([Gross Wages]) ELSE '0' END) AS 'Health Insurance in Location A'),
    SUM(CASE WHEN [Location]='B' THEN(b.[Health Insurance]*(p.[Gross Wages]/ SUM([Gross Wages]) ELSE '0' END) AS 'Health Insurance in Location B'),
    SUM(CASE WHEN [Location]='A' THEN(b.[Tax]*(p.[Gross Wages]/ SUM[Gross Wages]) ELSE '0' END) AS 'Tax in Location A'),
    SUM(CASE WHEN [Location]='B' THEN(b.[Tax]*(p.[Gross Wages]/ SUM[Gross Wages]) ELSE '0' END) AS 'Tax in Location B'),
FROM [Table A] p
INNER JOIN [Table B] b ON p.[EE#] = b.[EE#]
INNER JOIN [Table C] b ON p.[EE#] = c.[EE#]
GROUP BY p.[EE#], p.[location]
ORDER BY p.[EE#]

A: Making a lot of guesses about what is going on but this should be close:
The key thing I'm doing below is to use JOINing to flatten the result and reduce the CASE statements.  Here instead of having to do two case statements and a group by you just have two joins and then use the correct one for the column's calculation.
SELECT
  P.[EE#], P.location,
--  p.[Period End Date],
--  p.[EE#], p.Department,
  (AA.[Gross Wages]/ SUM(AA.[Gross Wages])  AS 'Gross Wages % in Location A',
  (AB.[Gross Wages]/ SUM(AB.[Gross Wages])  AS 'Gross Wages % in Location B',
  BA.[Health Insurance]*(AA.[Gross Wages]/ SUM(AA.[Gross Wages])) AS 'Health insurance Location A',
  BB.[Health Insurance]*(AB.[Gross Wages]/ SUM(AB.[Gross Wages])) AS 'Health insurance Location B'
-- etc something with CA and CB
FROM (SELECT distinct [EE#], location FROM [Table A]) AS P
LEFT JOIN [TABLE A] AA ON p.[EE#] = AA.[EE#] AND BA.Location = 'A'
LEFT JOIN [TABLE A] AB ON p.[EE#] = AB.[EE#] AND BB.Location = 'B'
LEFT JOIN [TABLE B] BA ON p.[EE#] = BA.[EE#] AND BA.Location = 'A'
LEFT JOIN [TABLE B] BB ON p.[EE#] = BB.[EE#] AND BB.Location = 'B'
LEFT JOIN [TABLE C] CA ON p.[EE#] = CA.[EE#] AND CA.Location = 'A'
LEFT JOIN [TABLE C] CB ON p.[EE#] = CB.[EE#] AND CB.Location = 'B'
GROUP BY p.[EE#], p.[location]
Order by p.[EE#]

Also note:
I would expect you would want the following query to get all the EE#s not just the ones in [Table A]:
FROM (
  SELECT distinct [EE#], location FROM [Table A]
  UNION
  SELECT distinct [EE#], location FROM [Table B]
  UNION
  SELECT distinct [EE#], location FROM [Table C]
) AS P

of course if you have an employee table somewhere that would be even better then you could do something like
FROM (SELECT DISTINCT [EE#], location FROM Employee) AS P

Then if you have employees who are not in A, B or C -- they would still show up in your report.


text:
Q: jPlayer playlist title element I have seen similar questions, but no solutions.
I have jPlayer working beautifully except for one thing...
In "playlist" mode, the title element is set to display:none.
Is there a setting in the constructor to override this?
Thanks in advance

A: A solution is to use a jQuery listener and add the title programmatically as it plays...
$("#music").bind($.jPlayer.event.play, function(event)
{
    $.each(player.playlist, function(index, song)
    {
        if(index == player.current)
        {
            $(".songTitle").html(song.title);
        }
    });
});

Where #music is the div you initally attach jplayer too and .songTitle is the class of the element where you want the title displayed.

A: You can force the css to show the title item by adding "important" like this:
div.jp-details {
    display: block !important;
}


text:
Q: how to solve the problem of "import gradio could not be resolved" importing api from gradio quickstart but in terminal it's showing a prblem of "import gradio could not be resolved"
how to make complier accept gradio

A: firstly make sure that you have installed the library using the following command.
pip install gradio

The solution is to select the python3 interpreter inside the bin/ folder of the python installed

click on the enter interpreter path here and choose the python3 inside the bin it will get the import error solved.
in my case i was using a venv so i'm selecting the python3 so that the pylint in the vscode will now the packages.


text:
Q: Not able to load dataset as per the instructions in article I am new to data science field.
I came through this article
https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6
Here I am not able to load diabetes dataset as per the code they have written.
# Load the Diabetes dataset

columns = "age sex bmi map tc ldl hdl tch ltg glu".split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y

I have tried to load data set through csv but in vain.

A: As @DYZ mentioned it is the quotation marks issue, copy paste the below and run
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt

columns = "age sex bmi map tc ldl hdl tch ltg glu".split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y


text:
Q: Android : Facing issue while passing data from fragment to other fragment This might be a very simple issue. But I'am getting difficulty to find the problem where i have done.
I'am passing data from One fragment to other fragment.
This is my code which i have written to pass the data.
Fragment fr = new ProjectFragment();
          Bundle args = new Bundle();
          args.putString("project_id", pro.p_id);
          fr.setArguments(args);

Receiving code.
String project_id = getArguments().getString("project_id");

I'am getting null value in project_id. Please help me to solve this problem.


text:
Q: How to Pass MongoDB error to React from Express I am Working in a MERN application. In one of my model of express.js I have unique email schema like below
email: {
   type: String,
   trim: true,
   required: true,
   minlength: 3,
   unique: true
},

I am checking uniqueness of email address when I am saving a record like below
address.save()
.then(address => {
   //other code
})
.catch(err => {
   console.log(err);
   res.status(500).json({
     message: 'Error Occured',
         error: err
   });
 });

I am getting below error in Terminal.
{ MongoError: E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }
[0]     at Function.create (/home/foysal/Videos/my-app/node_modules/mongodb-core/lib/error.js:43:12)
[0]     at toError (/home/foysal/Videos/my-app/node_modules/mongodb/lib/utils.js:149:22)
[0]     at coll.s.topology.insert (/home/foysal/Videos/my-app/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
[0]     at /home/foysal/Videos/my-app/node_modules/mongodb-core/lib/connection/pool.js:532:18
[0]     at process._tickCallback (internal/process/next_tick.js:61:11)
[0]   driver: true,
[0]   name: 'MongoError',
[0]   index: 0,
[0]   code: 11000,
[0]   errmsg:
[0]    'E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }',
[0]   [Symbol(mongoErrorContextSymbol)]: {} }

I would like to modify this error errmsg:
'E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }', to Email already Exists and pass this to React (front end).
How can I do that ?
UPDATE
I am using below code in express.js
address.save()
    .then( address => {
        // others code
    })
    .catch( err => {
        const errString = err.toString();
        if (errString.includes("E11000")) return res.status(404).json({ err: 'That email is already in use!' });
    });

My React Redux action is like below
export const addAddress = value => dispatch => {
  return Axios.post('/api/address', value)
    .then( response => {
      // other code
    })
    .catch( error => {
      console.log('actionError', error )
    });
};

I am getting below error in console
Error: "Request failed with status code 404"

A: Well, if you look at the Error object being logged, you can observe some stuff like code property.
You could evaluate such property and if that's the case just pass an appropiate custom error message.
address.save()
.then(address => {
   //other code
})
.catch(err => {
   const {code} = err
   console.log(err);
   if (code === 11000) {
     err = new Error('Email already Exists');
   }
   res.status(500).json({
     message: 'Error Occured',
     error: err
   });
 });

A: You have two options: Check if the email already exists before creation (better option) or allow Mongo to throw an error object during user creation, convert it to a string and then check if that string includes E11000.
Working example: https://github.com/mattcarlotta/fullstack-mern-kit (click here to view the code in use as described below; in addition, the code below refers to a User static method which you can find here)

For example (choose one option, you don't need both):
const createUser = async (req, res, done) => {
  const {
    email,
    firstName,
    lastName,
    userName,
    backgroundInfo,
    address,
  } = req.body;

  if (
    !email
    || !firstName
    || !lastName
    || !userName
    || !backgroundInfo
    || isEmpty(address)
  ) return res.status(400).json({ err: "You must include all required fields to create a new user!" }); // checking if the req.body contains all the required user fields

  try {
    const emailTaken = await User.findOne({ email });
    if (emailTaken) return res.status(400).json({ err: "That email is already in use!" }); // checking if the user exists before creation

    await User.createUser(req.body); // createUser is a custom static method placed on the model

    res
      .status(201)
      .json({ message: `Successfully created ${req.body.userName}.` });
  } catch (err) {
    const errString = err.toString();

    if (errString.includes("E11000")) return res.status(400).json({ err: "That email is already in use!" }); // handling the error Mongo throws if the user exists during creation

    return res.status(400).json({ err: errString }); // handling any other misc errors
  }
};

By default axios won't return any error from a server. Instead, you're going to have to create a custom axios configuration: axiosConfig.js.  The most important part of this configuration is changing the error interceptor as shown here. This is specifically looking for an error to come from error.response.data.err. If you don't use err for the API, then you need to update this line.
The purpose of this line is to check if error.response.data.err exists, if it doesn't, then it returns a generic Network Error (error.message) message.
Once you've created this configuration, you'll now need to use it for the entire application (import axios from '../path/to/axiosConfig').
NOTE: Please update the baseURL to your API localhost and it's port. The upside to using this configuration is that any calls you make with axios will be prepended with http://localhost:port/.
For example, instead of:
axios.get("http://localhost:5000/api/user")
it'll be:
axios.get("user")
If you have questions, before asking, please refer to the github repo above as it shows how to integrate everything. If you plan on using this in production, then you'll need to use ENVs (this example utilizes the better-npm-run package, but you can use cross-env or dotenv).


text:
Q: Offers on Razorpay subscriptions I want to ask can we include multiple offers on razorpay subscriptions.
Right now razor pay gives us functionality to create an offer for either UPI or CARD.
In Checkout a user can go for any of payment methods, but we can only send one offer at a time, why?
So if i am giving discount on both CARD and UPI what should we do?
DOCS Refereed - https://razorpay.com/docs/payments/subscriptions/offers


text: Q: Как записать/читать свой класс в qt через WinApi? К примеру у меня есть свой класс noteitem с полями различных типов (QTime, QDatetime, QString, и так далее). Я хочу с помощью WinApiшных функций WriteFile и Readfile произвести запись в файл/чтение из файла массива (вектора) с моими собственными объектами класса noteitem. Вопрос, каким образом можно это сделать? Заранее благодарю


text:
Q: Android Studio loading device button is disabled My Android Studio loading device button is disabled for my cordova project but it is perfectly working for other project.
Things I have tried:

*

*Making sure my SDK path is correct

*Running Android Studio as administrator

Here is the screenshot
Can anyone tell me why it is happening.
Any help is appreciated. Thank you!

A: Problem is due to version of gradle.I have to change the gradle version.
go to file -> Project Structure -> Gradle Version and change the gradle version.


text:
Q: System.Net.Http conflict in Watson speech to text When I build my project, I get the following warning:

Severity  Code    Description Project File    Line    Suppression State
  Warning MSB3243 No way to resolve conflict between "System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Net.Http, Version=1.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". Choosing "System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" arbitrarily.    SliqSpeechToTextCore    C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets   1964

When I run, I get this exception when I try to instantiate the service by calling new SpeechToTextService()

System.IO.FileLoadException: 'Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'

My csproj is
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PackageTargetFallback>dnxcore50;portable-net45+netcore45+wp8+wp81+wpa81;</PackageTargetFallback>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="IBM.WatsonDeveloperCloud.SpeechToText.v1" Version="1.0.0" />
  </ItemGroup>

</Project>

I tried installing System.Net.Http from NuGet but it didn't help. I've found the most common solution for this type of problem is to add a dependentAssembly to the config. Is this solution relevant to .NET Core and if so what file would I edit?


text:
Q: How do I push changes to someone else's repository (I'm a collaborator on), from a submodule of my own repository? So I have my own repository, let's call it "mine", which contains a submodule repository "theirs". I have access to their remote repository, so I can push changes to it directly.
I'm trying to push the changes I've made to "theirs" back to their remote GitHub repository but I can't seem to get it to work. I can push the changes to my remote repository "mine" on GitHub, and there the new commits to "theirs" are visible. But when I visit their GitHub it hasn't added the latest commits.
Aren't submodules supposed to just be regular repositories, inside another with some extra metadata? If so, why does "git push" from within the directory "theirs" not work? I've tried committing and pushing from within "theirs" and then "cd .." and commit/push from within "mine" but it doesn't work either.
I have tried the steps listed here: Git submodule push to no avail. I can only assume that because I'm trying to push to a repository that I don't own, something else needs to be done?
~/Mine$ git remote -v
origin  https://github.com/myUser/Mine.git (fetch)
origin  https://github.com/myUser/Mine.git (push)

~/Mine/Their$ git remote -v
origin  https://github.com/theirUser/Theirs.git (fetch)
origin  https://github.com/theirUser/Theirs.git (push)

A: Once the commits are done push it forked repo (ie "mine"). From your fork open a pull request in the correct branch. Once the pull request is approved and merged you can pull the changes from upstream to your local repo.
Then the changes will get added to "theirs" repository.

A: You are correct:  A submodule is a repository in its own right.  This means you can cd or chdir into the submodule and start using it the same way you would use any other Git repository, including running git fetch, git checkout, git commit, and so on.
What makes a submodule a submodule is the fact that some other Git, positioned somewhere above the submodule, is controlling the submodule, normally by running git checkout hash-id in it.  This puts the submodule into what Git calls detached HEAD mode.  (The controlling Git is the superproject.)
This "detached HEAD" mode is a bit tricky.  You can make new commits in this mode, but when you do, they're not findable by most ordinary means.  They're easily findable for the moment by the special name HEAD, but this special name HEAD will be forcibly adjusted by the superproject, which will chdir into the submodule and run git checkout hash-id again, losing1 the commits you've made.
To send, to some other Git repository, commits you've made in your submodule Git repository, you must give those commits a name in the other Git repository.  Usually, that means giving them a branch name over there.  There's no hard requirement to use a branch name in your repository, as you can run:
git push <remote-or-URL> HEAD:<name>

to send the commit identified in your submodule repository via the name HEAD, to the other Git, and politely ask it to create or update its name name to point to that commit.  But most people don't like working on/with detached HEAD mode.
What this means, in general, is that to do work in the Git repository that is acting as a submodule for some superproject, you should use the following sequence:2

*

*Enter the submodule.  From here through step 3, you'll just work with this as a regular Git repository.

*Exit detached HEAD mode by selecting a branch name to git checkout, or by creating a branch name pointing to the current commit.  Note that if you choose some existing branch name, that may be a different commit from the current commit.  Or it may be the same commit as the current commit.
Remember, the superproject repository earlier told this Git: use this raw commit, by its hash ID to get into detached HEAD mode.  We're now getting out of detached HEAD mode, which requires picking or creating a branch name.  If you pick some existing branch name, you're stuck with whatever commit that branch name chooses.  But if you're developing new commits in the submodule repository, you probably want a branch name to remember them.

*Now, make new commit(s) in the usual way.  Use git push in the usual way.  The commits will, or won't, go to the receiving repository in the usual way that commits do or don't.  If they do make it to the receiving repository, that repository's branch name will be created or updated in the usual way.

*Once everything is done, exit the submodule repository, returning to the superproject repository.  It's now time to make a new commit in the superproject.
I already mentioned, several times, that the superproject Git keeps controlling the submodule Git.  It does a chdir into the submodule Git and runs git checkout hash-id.  The key here comes in two parts:

*

*When does the superproject Git do this to the submodule?

*Where does the superproject Git get the raw hash ID?

The answer to the first question is complicated: git submodule update does it, but not always;3 git checkout --recursive does it (always); various other operations can sometimes do it, depending on options and settings.  That is, it doesn't happen unless and until you ask for it to happen, but it's not always obvious that you are asking for it to happen.  What we're about to do is to make sure we address the second point, before it happens again.
The answer to the second question—where does the superproject Git get the raw hash ID—is that it gets it from commits in the superproject.  But you've made a new commit in the submodule, and delivered it upstream to some other Git repository, so now it's time to make a new commit in the superproject, to record the right hash ID, i.e., the hash ID of the new commit you made in the submodule.
As always, no commit can ever be changed; and as always, Git makes new commits from whatever is in the index (aka staging area).  When you extract some existing commit, Git reads the files from that commit into the index / staging-area.  If the repository is acting as a superproject for some submodule, this step also reads the desired hash ID (in that submodule) from the commit, into the index.  Since that's no longer the desired hash ID, your job is now to put the new hash ID into the index.
The command that does this, in the superproject, is git add.  As always, git add writes stuff into the index.  For a normal file, it writes into the index a copy of that file.4  For a submodule, though, it:

*

*enters the submodule for a moment;

*asks that Git: what is the raw hash ID for the commit identified by your HEAD? (git rev-parse HEAD);

*stuffs the resulting hash ID, whatever it is, into the superproject Git's index, in the slot for that submodule.

This works whether the submodule is in detached HEAD state or not, because git rev-parse HEAD always returns the raw hash ID of the current commit.
So, after git add path/to/submodule, the hash ID of the commit that you selected (and in fact made and pushed) is now recorded in the index in the superproject.  Your next commit will record that raw hash ID.
Assuming everything else is also ready, you can now run git commit to make a new commit in the superproject (which presumably is, and has been all along, in attached-HEAD state, on some branch name).  Once you do make this new superproject commit, you're ready to git push it as usual.
Note the careful ordering of steps here:

*

*Enter the submodule.

*Make the commit(s) in the submodule, on branches for simplicity, but however you make them is OK.

*Send those commits to wherever it is that people clone the submodule from, so that that Git has them.  This step requires setting a branch or tag name in that other Git.

*Now that other people can access that commit in the submodule's origin repository, make and push a commit in the suprerproject that refers to the submodule commit's raw hash ID.

It is possible—because of Git's distributed nature—to make the commit in your submodule but not push it anywhere, then to make the commit in your superproject and push it.  Anyone who gets this new commit gets a commit that refers, by raw hash ID, to a commit they not only don't have, but can't even get.  So step 3 ("make the commit available to everyone") must happen before the push in step 4.  (The "make commit" in step 4 can happen earlier—just be careful not to push it, and to redo it with any updated commit hash, if the submodule commit has to be redone for any reason.)

1Losing here means "make hard to find".  The commits themselves won't vanish right away: they have the same grace period that other lost commits get, and you can use the submodule Git's HEAD reflog to find them, the same way you find lost commits in any repository—because the submodule is just another repository, after all.
2Because Git is a set of tools, not a pre-packaged solution, there are a lot of other ways to accomplish your goal.  This is just one very flexible way.
3In particular, git submodule update has many update modes.  With some arguments, you can direct git submodule update to check out a name in the submodule, resulting in an attached HEAD (not a detached one) in the first place!  That's part of what footnote 2 is referring to.  The detailed workings of git submodule update are quite complicated, so I'm trying to avoid these variants in this answer.
4Technically, it writes out a blob object with the right file contents—or reuses some existing blob object unchanged, if possible—and then writes the blob object's hash ID into the index, rather than the actual file content.  But the effect is as if Git copied the file into the index, as long as you don't get down to the level of git ls-files --stage and git update-index.


text:
Q: How can you use Excel to determine the number of days occurring between several date ranges? Hey hoping someone can help me out, first time posting but I am stuck trying to write a formula in excel to record breaks and the week in which they occurred. Basically I have a list of week ending dates, from time to time a break (or breaks) may occur, what I want is to be able to record the break range (say 8/11/2014-22/11/2014) and have the formula provide a value next to each week that was effected by that break showing how many days in that period were affected.
EG.
WEEK|WEEKEND|BREAK
week 1  10/08/2014  ?
week 2  17/08/2014  ?
week 3  11/08/2014  ?
week 4  18/08/2014  ?
BREAKS
Break 1 11/08/2014-13/08/2014
Break 2 17/08/2014-18/08/2014
Hope that makes sense, I have tried to write it as an IF formula however keep going cross eyed trying to get the ranges right and having it not count above the 7 days in that week. Think I may be approaching it entirely the wrong way.
Thanks in advance!

A: Try the following.  It will not scale -- if you have a lot of breaks a VBA macro may be the way to go (it might also be possible with arrays, but I suspect it would be painful).
The formula in D2 should be as for C2, except with references to row 11 replaced by references to row 12.  In E2, you would use row 13, etc.  Having put formulas in C2->Y2 (or however many you need) you should be able to copy row 2 down.
   A      | B       | C                       | D          | ... | Z
1  WEEK   | WEEKEND | BREAK1                  | BREAK2     | ... | DAYS OUT
2  week 1 | 10/8/14 | = if(and($b$11>($b2-7), | = if(and...| ... | =sum(c2:y2)
                               $b$11<=$b2),
                           if($b2<$c$11,$b2-$b$11+1,$c$11-$b$11+1),
                           if(and($b2-$c$11<7,$b2>=$c$11),$c$11-($b2-6)+1,0))

3  week 2 | 17/8/14 | = if(and($b$11>($b3-7),
                           ...
4 ...
....
10 BREAK  | START   | END
11 Break 1| 11/8/14 | 13/8/14
12 Break 2| 17/8/14 | 18/8/14
13 ...

The formula in C2:

*

*Checks to see if the break starts in the week ending on the weekend

*If it does, it checks to see if it ends in the week as well.  If so, the days out are just the days in the break (break end - break start + 1).  If not so, the days out are the days from the
start of the break to the weekend (weekend - break start + 1)

*If the break does not start in the week ending on the weekend, check to see if the break ends in the week.  If so, the days out are (break end - week start + 1).  Otherwise, there are no days out.


text:
Q: iOS DropBox - browse folders and view files - sample code or tutorial? Inside of my app, I would like the user to be able to log into DropBox, and browse and view his or her files and folders. This seems like a very common task to me, so I'm wondering if there are any tutorials or sample code out there? I haven't been able to find anything on Google.
I believe I could do it myself using a table view and the Core API tutorial from dropbox.com, but I don't want to waste all that time if the code is already out there.

A: if you are looking it on Objective c you can get a demo project from this link. where you can browse the folder of rootdirectory and also you can download the files.
https://github.com/danielbierwirth/DropboxBrowser

A: I had the same problem. It took me so long to find the answer for that, really it was overwhelming because there isn't much info about it. I did this:
I'm sorry for my english, is not my first language.
Install Dropbox Chooser https://www.dropbox.com/developers/chooser#ios
Install SwiftyDropbox
SwiftyDropbox installs Alamofire, we need this to download the file, if not then install it
Dropbox Chooser allow the user select any file from their dropbox account and returns the shared link of the selected file so:
    //Ask SwiftyDropbox if the user is logged in

    if DropboxClientsManager.authorizedClient != nil{

    // Use this from Dropbox chooser to open a view controller that allow the user select the file
    //DBChooserLinkTypeDirect <--- it has to be this parameter, there is another one but is useless for our purpose

    DBChooser.default().open(for: DBChooserLinkTypeDirect, from: self, completion: { (results) in

                //Here starts the completion block of Chooser

                if let resultado = results{ //Obtain the results

                    var d = DBChooserResult() //Create a variable of DBChooserResult type
                    d = resultado[0] as! DBChooserResult //Get the result. Just one result because the user just can select ONE file (in this version just one, it may be more but I don't know how in this moment
                    print(d.name)
                    print(d.link)//The atributte link give us the url to download the file.
    //If you paste it in your browser the download starts right away

                  //Use Alamofire to download the file from the url
                    Alamofire.request(d.link).responseData { response in

         //Get the data from the URL
                        if let data = response.result.value
                        {
                           //Here we have the data to do whatever we want, in my case I show the PDF file in a WebView
                            print("Data de Alamofire \(response.description)")
                            self.desplegarUrlEnWebview(datos: data, url: d.link)
                        }
                    }
                }

            })
        }else{

            //If the user is not logged in we use SwiftyDropbox to log in

            DropboxClientsManager.authorizeFromController(UIApplication.shared, controller: self, openURL: { (url) in

                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            })
        }

A: All of the official resources for the Dropbox API and SDKs can be found on the Dropbox Developer website:
https://www.dropbox.com/developers
Specifically, you're referring to the iOS Core SDK. You already mentioned the tutorial, but the SDK download itself also contains a working sample app:
https://www.dropbox.com/developers/core/sdks/ios
The sample doesn't contain all of the functionality you're looking for though.

A: Well, I've gone ahead and created it. Although it seems to have a problem when trying to view a pdf file. Anyway, here is the code:
https://github.com/danielbierwirth/DropboxBrowser
and for more inforation you can refer to official developer site of dropbox.

A: Use pod 'SwiftyDropbox'.
Configure your project as explained here: http://dropbox.github.io/SwiftyDropbox/api-docs/latest/.
In your Dropbox App console remember to give Permissions that allow your app to view and manage files and folders under Permission tab. You have to regenerate the access token if you make any changes in the permission and remember to change the access token in your code.
Since dropbox doesn't has a redirect url to redirect and view our files & folders after we login, we have to create a table view controller to load our files with the metadata. (Remember, you have to return back to your app from dropbox to view the files).
If you want to use the file for uploading purpose in your app, do it with tableView delegate method 'didSeelectRowAt'.


text:
Q: fatal: unable to access 'https://github.com/CocoaPods/Specs.git/': Could not resolve proxy: proxy-listen-ip My git reports error, when I $ git clone https://github.com/CocoaPods/Specs.git master:

fatal: unable to access 'https://github.com/CocoaPods/Specs.git/': Could not resolve proxy: proxy-listen-ip

How to resolve it?

A: git config --global --unset http.proxy helps as @ASR suggested. Had to do git config --global --unset https.proxy too to get the issue resolved.


text:
Q: How to add individual layer of WMS group layer to ArcMap? I am attempting to add a single WMS layer that is part of a WMS service group layer.  I am writing code to do this using ArcObjects in C# .Net.  So far I have been unsuccessful.  I can either only add the whole group layer, or I can add the individual WMS sub-layer but the full group is also still added.
Here is the code I have tried.  I have allowed the user to select a layer from a list, and this code is trying to only add that selected layer.
    IWMSGroupLayer wmsMapLayer = new WMSMapLayerClass();
    IWMSConnectionName connName = new WMSConnectionNameClass();

    IPropertySet propSet = new PropertySetClass();
    propSet.SetProperty("URL", "http://www.___________________?");

    connName.ConnectionProperties = propSet;

    IDataLayer dataLayer = (IDataLayer)wmsMapLayer;
    dataLayer.Connect((IName)connName);

    IWMSServiceDescription serviceDesc = wmsMapLayer.WMSServiceDescription;
    IWMSLayerDescription groupDesc = serviceDesc.LayerDescription[0];

    for (int i = 0; i < groupDesc.LayerDescriptionCount - 1; i++)
    {
        IWMSLayerDescription layerDesc = groupDesc.LayerDescription[i];

        if (layerDesc.Title == lstWMSLayers.SelectedItem.ToString())//Checking if this is the selected layer
        {
            ILayer newLayer;
            IWMSLayer newWMSLayer = wmsMapLayer.CreateWMSLayer(layerDesc);
            newLayer = (ILayer)newWMSLayer;
            wmsMapLayer.InsertLayer(newLayer, 0);

            IMxDocument mxDoc = (IMxDocument)ArcMap.Application.Document;
            mxDoc.FocusMap.AddLayer((ILayer)wmsMapLayer);
            IActiveView activeView = (IActiveView)mxDoc.FocusMap;
            activeView.Refresh();
        }
    }

In ArcMap I get the following tree of layers

*

*WMS Service Group Layer

*

*Selected WMS Layer

*WMS Group Layer

*

*All the layers that are part of the service...

Any suggestions?

A: You need to clear the WMS Service Group Layer before adding the single WMSMapLayer.
wmsMapLayer.Clear();
wmsMapLayer.InsertLayer(newLayer, 0);

Note that this will remove all group/map layers from the WMS Service Group Layer, so if you're adding more than one, it might be advisable to not call wmsMapLayer.Clear() in the body of your loop. I haven't tested as I'm only adding a single layer, but perhaps instead, loop through groupDesc.LayerDescriptionCount and grab all the layerDesc objects that match your criteria, then Clear() and add the selected WMS layers back in.


text:
Q: Training uNet model the prediction is only black I'm training a uNet model for segmentation. After training the model, the output is all zeros and I can't understand why.
I saw recommendations that I should be using a specific loss function, so I used a dice loss function. This because the black area (0) is way bigger then white area (1).
Am I doing something wrong?
My model is:
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            (None, 80, 80, 1)    0
__________________________________________________________________________________________________
conv2d_1 (Conv2D)               (None, 80, 80, 64)   640         input_1[0][0]
__________________________________________________________________________________________________
conv2d_2 (Conv2D)               (None, 80, 80, 64)   36928       conv2d_1[0][0]
__________________________________________________________________________________________________
max_pooling2d_1 (MaxPooling2D)  (None, 40, 40, 64)   0           conv2d_2[0][0]
__________________________________________________________________________________________________
conv2d_3 (Conv2D)               (None, 40, 40, 128)  73856       max_pooling2d_1[0][0]
__________________________________________________________________________________________________
conv2d_4 (Conv2D)               (None, 40, 40, 128)  147584      conv2d_3[0][0]
__________________________________________________________________________________________________
max_pooling2d_2 (MaxPooling2D)  (None, 20, 20, 128)  0           conv2d_4[0][0]
__________________________________________________________________________________________________
conv2d_5 (Conv2D)               (None, 20, 20, 256)  295168      max_pooling2d_2[0][0]
__________________________________________________________________________________________________
conv2d_6 (Conv2D)               (None, 20, 20, 256)  590080      conv2d_5[0][0]
__________________________________________________________________________________________________
max_pooling2d_3 (MaxPooling2D)  (None, 10, 10, 256)  0           conv2d_6[0][0]
__________________________________________________________________________________________________
conv2d_7 (Conv2D)               (None, 10, 10, 512)  1180160     max_pooling2d_3[0][0]
__________________________________________________________________________________________________
conv2d_8 (Conv2D)               (None, 10, 10, 512)  2359808     conv2d_7[0][0]
__________________________________________________________________________________________________
dropout_1 (Dropout)             (None, 10, 10, 512)  0           conv2d_8[0][0]
__________________________________________________________________________________________________
max_pooling2d_4 (MaxPooling2D)  (None, 5, 5, 512)    0           dropout_1[0][0]
__________________________________________________________________________________________________
conv2d_9 (Conv2D)               (None, 5, 5, 1024)   4719616     max_pooling2d_4[0][0]
__________________________________________________________________________________________________
conv2d_10 (Conv2D)              (None, 5, 5, 1024)   9438208     conv2d_9[0][0]
__________________________________________________________________________________________________
dropout_2 (Dropout)             (None, 5, 5, 1024)   0           conv2d_10[0][0]
__________________________________________________________________________________________________
conv2d_transpose_1 (Conv2DTrans (None, 10, 10, 512)  2097664     dropout_2[0][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate)     (None, 10, 10, 1024) 0           dropout_1[0][0]
                                                                 conv2d_transpose_1[0][0]
__________________________________________________________________________________________________
conv2d_11 (Conv2D)              (None, 10, 10, 512)  4719104     concatenate_1[0][0]
__________________________________________________________________________________________________
conv2d_12 (Conv2D)              (None, 10, 10, 512)  2359808     conv2d_11[0][0]
__________________________________________________________________________________________________
conv2d_transpose_2 (Conv2DTrans (None, 20, 20, 256)  524544      conv2d_12[0][0]
__________________________________________________________________________________________________
concatenate_2 (Concatenate)     (None, 20, 20, 512)  0           conv2d_6[0][0]
                                                                 conv2d_transpose_2[0][0]
__________________________________________________________________________________________________
conv2d_13 (Conv2D)              (None, 20, 20, 256)  1179904     concatenate_2[0][0]
__________________________________________________________________________________________________
conv2d_14 (Conv2D)              (None, 20, 20, 256)  590080      conv2d_13[0][0]
__________________________________________________________________________________________________
conv2d_transpose_3 (Conv2DTrans (None, 40, 40, 128)  131200      conv2d_14[0][0]
__________________________________________________________________________________________________
concatenate_3 (Concatenate)     (None, 40, 40, 256)  0           conv2d_4[0][0]
                                                                 conv2d_transpose_3[0][0]
__________________________________________________________________________________________________
conv2d_15 (Conv2D)              (None, 40, 40, 128)  295040      concatenate_3[0][0]
__________________________________________________________________________________________________
conv2d_16 (Conv2D)              (None, 40, 40, 128)  147584      conv2d_15[0][0]
__________________________________________________________________________________________________
conv2d_transpose_4 (Conv2DTrans (None, 80, 80, 64)   32832       conv2d_16[0][0]
__________________________________________________________________________________________________
concatenate_4 (Concatenate)     (None, 80, 80, 128)  0           conv2d_2[0][0]
                                                                 conv2d_transpose_4[0][0]
__________________________________________________________________________________________________
conv2d_17 (Conv2D)              (None, 80, 80, 64)   73792       concatenate_4[0][0]
__________________________________________________________________________________________________
conv2d_18 (Conv2D)              (None, 80, 80, 64)   36928       conv2d_17[0][0]
__________________________________________________________________________________________________
conv2d_19 (Conv2D)              (None, 80, 80, 2)    1154        conv2d_18[0][0]
__________________________________________________________________________________________________
conv2d_20 (Conv2D)              (None, 80, 80, 1)    3           conv2d_19[0][0]
==================================================================================================

Loss Function
def dice_loss_v2(y_true, y_pred):
    numerator = 2 * tf.reduce_sum(y_true * y_pred, axis=(1,2,3))
    denominator = tf.reduce_sum(y_true + y_pred, axis=(1,2,3))

    return 1 - numerator / denominator

Activation
    model.compile(optimizer='adam',
                  loss=dice_loss_v2,
                  metrics=['accuracy', iou_loss_core])

Predefined Learning Rate is LR=0.001
An extra information:
        datagen = ImageDataGenerator(
                    rotation_range=10,
                    width_shift_range=0.1,
                    height_shift_range=0.1,
                    zoom_range=0.1)
        datagen.fit(X_train)

        model.fit_generator(datagen.flow(X_train, y_train, batch_size=100), steps_per_epoch=len(X_train),
                                        epochs=4, validation_data=(X_test, y_test))

A: The mask may be all black because of the pixels predicting as 0 and 1. As 0 and 1 both are nearly black in color space (0,255). So, Multiply mask by 255 and then try to save/show it (All 1's are converted to 255). You will get required output.


text:
Q: What is the facial feature extraction algorithm of picasa?  I'm researching facial feature extraction algorithms. I have played with several face recognition solutions, but I prefer picasa.
I want to know the facial feature extraction algorithm of picasa.  Can you help me?  Please give me your helpful advice.
Thank you in advance.

A: Google bought two companies working on face detection, Neven Vision in 2006 and Pittsburgh Pattern Recognition or PittPatt in 2011. Neven Vision was most likely used for early versions of Picasa. Hard to say for sure.
Some more information about Neven Vision's algorithms can be found in scholarly articles and their patent filings.

A: Try opencv it seems to have closer face detection...but u will have write your own face recognition algorithm...they have given a formula to do that check out opencv.com
Never use face recognition as means for any authentication.....because even android has a api for that and it has got bad review for image recognition.....likewise a picasa also employs face recognition but it's not that good...
Finally iphoto app apple has achieved it almost to 95 percent perfection...
The iPhoto algorithm is learning based algorithm if u let iphoto know wrong face recgnition images it will learn from that....
But neither iPhoto nor picasa has published this..
Check out the below URLs...
http://www.ratchetup.com/eyes/2009/02/comparing-iphoto-and-google-face-recognition.html
http://arstechnica.com/gadgets/2011/10/first-look-android-40-sdk-opens-up-face-recognition-apis/
http://blog.chron.com/techblog/2011/12/android-4-0s-facial-recognition-is-cool-but-dont-trust-it-yet/


text:
Q: Desinging Test Cases using configurable Commandlines. I currently working with embedded linux with bash shell on it. Write now I am working on a test framework for that system. The way it works now I have 3 linux commands lines (ie 3 linux programs in C) that execute a paticular test.
ie
command1 arg1 arg2 arg3 ...
command2 arg3 arg4 arg5 ...
command3 arg6 arg6 arg7 ...

The thing is that the test case combinations are huge. So assume if I have different databases that hold parameters for the 3 command lines. How could I make it so I can generate different combination from the database with out iterating using for loops.
Thanks

A: What exactly are you asking?
How to create test permutations from a data set?  How to query the database for a representative sampling of test data?  How to invoke the test data from your automated tests?  Something else entirely???
Anyway, here's a good link on test permutations:
http://msdn.microsoft.com/en-us/magazine/cc163513.aspx
'Hope that helps...


text:
Q: How do i print a fetchone() function but get NoneType error? Sqlite3 I am trying to print the fetchone() value but it just gives me the error 'NoneType' object is not iterable, does anyone know why
Here is my code:
def viewemaillook():
        global realusername
        global realpassword
        viewemail = input("Would you like to see/change your email")
        if viewemail == "y" or viewemail == "yes":
            c.execute("SELECT email, * FROM stuffToPlot WHERE username = ?  and password = ?", (realusername,realpassword,))
            grab = c.fetchone()
            for i in grab:
                print(i)
        elif viewemail == "n" or "no":
            print("Okay")
        else:
            print("Invalid option")
            viewemaillook()
    viewemaillook()
else:
    print("Not a valid option")
    change()
change()

A: If your query is not finding any results, then fetchone() will return None. When you try to loop over grab which is equal to None you are getting the error. Try checking if you have a result in grab first.


text:
Q: Bootstrap tabs not displaying correctly when window too small So I have a nav menu using the tabs from bootstrap. It's all good, but when the window is at such width that the tabs (justified) are not yet stacked, it's displaying weirdly (because some tabs are now taking two lines rather than one line), as you can see:
Good:

Bad:

And here's the HTML:

 addition (polaire)

 addition (composantes)

 conversion d'angles

 produit

vecteur unitaire

I think I've found the CSS related to nav-justified in my bootstrap.min.css:
.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}

How can I solve this problem? Thanks!
Edit: So, by playing with the bootstrap.min.css file, I was able to change the @media query to change the tabs to be stacked to 992px rather than 768px (as it would start to be corrupted at 991px). It works, but if someone has a better solution, I am open!

A: Using white-space:nowrap; you can make the tabs always display in a single line, this may be a solution for you:
@media (min-width: 768px){
    #onglets>li>a {
        white-space: nowrap;
    }
}

Demo fiddle


text:
Q: How do i get the state value which I have stored in the Child component to the Parent component in React without button OnClick events? I have a child component which i call from the Parent and within the child component, i set state and get a specific value which is then stored within a state value. Now, how do i get the value from there and read it in the Parent component without using an onClick event ?
Here's my code snippet:
PARENT COMPONENT
import Child from "../Child"
     const Parent = () => {
        ...
        ...

        return(
        ...
        ...
        <Child />
    );
        };
        export default Parent

CHILD COMPONENT
    function Child (props) {
    ...
    ...
    const [query, setQuery] = useState("sample")
    ...
    ...
    return(
    ...
    ...
    );

}
export default Child

As you can see above, I initialize a state variable and assign "sample" to "query"
How can I get this "query" readable within the Parent Component ? I don't want to use an  Onclick event, so please help me.

A: Define the useState in parent and pass it down to child
 const Parent = () => {
   const [query, setQuery] = useState("sample")

    ...
    ...

    return(
    ...
    ...
    <Child query={query} setQuery={setQuery}/>
);

child
 function Child ({query,setQuery }) {


text:
Q: How to load complex views concurrently I have an Android activity that creates custom views, and it is an expensive process. I tried to use a Handler, but when I do, the progress dialog that shows, spins like once every 5 seconds. So I tried to use an AsyncTask. Now the progressDialog spins, but then it crashes, because it isn't allowed to load the UI? How can I do this without getting ANR?
08-10 19:28:21.313: ERROR/AndroidRuntime(1428): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

A:
I have an Android activity that creates custom views, and it is an expensive process.

Use Traceview or other tools to improve your performance. Custom views are not intrinsically expensive to create.

So I tried to use an AsyncTask. Now
  the progressDialog spins, but then it
  crashes, because it isn't allowed to
  load the UI?

You generally cannot do UI-related work in a background thread. With some care, you may be able to construct widgets, but you definitely cannot attach them to the screen (i.e., they can't be referenced as children of whatever is your content view).

How can I do this without getting ANR?

I would focus on fixing your performance problem, using Traceview or other tools to get at the root of where your time is being spent.


text:
Q: Showing that these vector fields commute on the image This was a problem from my final exam I took a few days ago, and after having it graded my solution did not receive full points. The professor seems to be busy grading for other classes he is teaching and I am eager to know why I did not get full credit for it, so I was hoping someone here could help me determine what my solution is missing.
Suppose $M$ is a smooth $n$-manifold and $F: \mathbf{R}^2 \to M$ is a smooth map. Let $X, Y \in \mathscr{X}(M)$ (smooth vector fields on $M$), and suppose that for every $s \in \mathbf{R}$, $t \mapsto F(t, s)$ and $t \mapsto F(s,t)$ are integral curves for $X, Y$ respectively. Show that $[X, Y]=0$ on $F(\mathbf{R}^2)$.
My solution:
By the fundamental theorem on flows (Lee Theorem 9.12) there are a unique smooth maximal flows with infinitesimal generators $X$ and $Y$. Since $t \mapsto F(t, s)$ and $t \mapsto F(s, t)$ are maximal integral curves for $X, Y$, they must be equal to the integral curves for $X, Y$ defined by the flow on all of $M$. Let $\theta$ be the flow of $X$ and $\Psi$ be the flow of $Y$ restricted to $F(\mathbf{R}^2)$. Now given a specific point $p \in F(\mathbf{R}^2)$ there exists $(t_p, s_p) \in \mathbf{R}^2$ such that $F(t_p, s_p) = p$. Let $t_1, t_2 \in \mathbf{R}$. Then $\theta_{t_1}(p) = F(t_p+t_1, s_p)$ and applying $\Psi_{t_2}(\theta_{t_1}(p))$ we obtain $F(t_p+t_1, s_p +t_2)$, and the same argument can be given to show this equals $\theta_{t_1}(\Psi_{t_2}(p))$.
Now by theorem 9.44 of Lee, we have that smooth vector fields commute iff their flows commute (where the flows are defined), and thus we must have that $X, Y$ commute on $F(\mathbf{R}^2)$ and therefore $[X, Y]=0$ on $F(\mathbf{R}^2)$ as desired.

A: There are a couple of problems with your solution. Let me try to explain what they are.

By the fundamental theorem on flows (Lee Theorem 9.12) there are a
  unique smooth maximal flows with infinitesimal generators $X$ and $Y$.
  Since $t \mapsto F(t, s)$ and $t \mapsto F(s, t)$ are maximal integral
  curves for $X, Y$, they must be equal to the integral curves for $X,Y$ defined by the flow on all of $M$.
  Let $\theta$ be the flow of $X$
  and $\Psi$ be the flow of $Y$ restricted to $F(\mathbf{R}^2)$. Now
  given a specific point $p \in F(\mathbf{R}^2)$ there exists $(t_p,s_p) \in \mathbf{R}^2$ such that $F(t_p, s_p) = p$. Let $t_1, t_2 \in \mathbf{R}$. Then $\theta_{t_1}(p) = F(t_p+t_1, s_p)$ and applying
  $\Psi_{t_2}(\theta_{t_1}(p))$ we obtain $F(t_p+t_1, s_p +t_2)$, and
  the same argument can be given to show this equals
  $\theta_{t_1}(\Psi_{t_2}(p))$.

Nothing in the problem statement guarantees that $t\mapsto F(t,s)$ and $t\mapsto F(s,t)$ are maximal integral curves. But they are integral curves. Note that the first paragraph of the proof of Theorem 9.12 in my book shows that any two integral curves for the same vector field with the same initial condition must agree on their common domain (I don't know why I didn't state that as a separate theorem!), and therefore your conclusions in the last sentence above are true.

Now by theorem 9.44 of Lee, we have that smooth vector fields commute
  iff their flows commute (where the flows are defined), and thus we
  must have that $X, Y$ commute on $F(\mathbf{R}^2)$ and therefore $[X,Y]=0$ on $F(\mathbf{R}^2)$ as desired.

Theorem 9.44 doesn't apply in this situation. The context of that theorem (stated at the beginning of the "Commuting Vector Fields" section on page 231) is that we are talking about smooth vector fields defined on a smooth manifold. Because $F(\mathbb R^2)$ is typically not going to be a smooth submanifold of $M$, we can't conclude from Theorem 9.44 that $X$ and $Y$ commute on $F(\mathbb R^2)$ if and only if their flows commute on $F(\mathbb R^2)$. (That approach could be made to work in the special case that $F$ is a smooth embedding, once you show that the vector fields $X$ and $Y$ are tangent to the submanifold $N = F(\mathbb R^2)$ and therefore restrict to vector fields on $N$.)
A better approach to this problem is based on the notion of $\boldsymbol F$-related vector fields. Take a look at Propositions 8.30 (naturality of Lie brackets) and 9.6 (naturality of integral curves), and think about applying them to the vector fields $\partial/\partial x$ and $\partial/\partial y$ on $\mathbb R^2$.


text:
Q: Can redshift be used to create an accurate accelerometer in a phone? Currently, accelerometers use small springs which produce wild fluctuations and inaccuracies.
Because light's speed is limited and compresses when its source moves in the direction it's going, and decompresses when it does the opposite, it seems we could use light as a spring which uses the constraints of space as its medium.
What I'm wondering is if a cross-beam of light were put inside of a device, with receivers constantly reading the frequency of the light to detect its red-shift compared to what the output should be, would this be accurate enough to determine the phone's velocity and acceleration in space?

A: You can measure rotational velocity very accurately with a fiber optic gyroscope. When you are rotating, the path length along one direction "is shorter". Whether you consider that a red shift or a phase shift doesn't really matter - you are using the finite speed of light to determine the rotation.
Measuring absolute velocity in space is of course impossible (because it's dependent on your reference frame). Acceleration could be measured using the same principle as above, but it's not easy.
I found a nice description of an experiment to measure velocity using interference in this paper which claims an accuracy of velocity on the order of µm/s. Unfortunately, they are moving one mirror in their setup relative to the rest of the interferometer - that's a much more favorable setup than a self-contained device (and explains why they are able to measure velocity and not just acceleration).


text:
Q: Preserve data integrity in a database structure with two paths of association I have this situation that is as simple as it is annoying.
The requirements are

*

*Every item must have an associated category.

*Every item MAY be included in a set.

*Sets must be composed of items of the same category.

*There may be several sets of the same category.
The desired logic procedure to insert new data is as following:

*

*Categories are inserted.

*Items are inserted. For each new item, a category is assigned.

*Sets of items of the same category are created.
I'd like to get a design where data integrity between tables is ensured.
I have come up with the following design, but I can't figure out how to maintain data integrity.

If the relationship highlighted in yellow is not taken into account, everything is very simple and data integrity is forced by design: an item acquires a category only when it is assigned to a set and the category is given by the set itself.However, it would not be possible to have items not associated with a set but linked to a category and this is annoying.
I want to avoid using special "bridging sets" to assign a category to an item since it would feel hacky and there is no way to distinguish between real sets and special ones.
So I introduced the relationship in yellow. But now you can create sets of objects of different categories!
How can I avoid this integrity problem using only plain constraints (index, uniques, FK) in MySQL?
Also I would like to avoid triggers as I don't like them as it seems  a fragile and not very reliable way to solve this problem...
I've read about similar question like How to preserve data integrity in circular reference database structure? but I cannot understand how to apply the solution in my case...

A: Interesting scenario. I don't see a slam-dunk 'best' approach. One consideration here is: what proportion of items are in sets vs attached only to categories?

*

*What you don't want is two fields on items. Because, as you say, there's going to be data anomalies: an item's direct category being different to the category it inherits via its set.

*Ideally you'd make a single field on items that is an Algebraic Data Type aka Tagged Union, with a tag saying its payload was a category vs a set. But SQL doesn't support ADTs. So any SQL approach would have to be a bit hacky.

*Then I suggest the compromise is to make every item a member of a set, from which it inherits its category. Then data access is consistent: always JOIN items-sets-categories.

*To support that, create dummy sets whose only purpose is to link to a category.

*To address "there is no way to distinguish between real sets and special ones": put an extra field/indicator on sets: this is a 'real' set vs this is a link-to-category set. (Or a hack: make the set-description as "Category: <category-name>".)
Addit: BTW your "desired logic procedure to insert new data" is just wrong: you must insert sets (Step 3) before items (Step 2).

A: I think I might found a solution by looking at the answer from Roger Wolf to a similar situation here:
Ensuring relationship integrity in a database modelling sets and subsets
Essentially, in the items table, I've changed the set_id FK to a composite FK that references both set.id and set.category_id from, respectively, items.set_id and item.category_id columns.
In this way there is an overlap of the two FKs on items table.
So for each row in items table, once a category_id is chosen, the FK referring to the sets table is forced to point to a set of the same category.
If this condition is not respected, an exception is thrown.
Now, the original answer came with an advice against the use of this approach.
I am uncertain whether this is a good idea or not.
Surely it works and I think that is a fairly elegant solution compared to the one that uses tiggers for such a simple piece of a a more complex design.
Maybe the same solution is more difficult to understand and maintain if heavily applied to a large set of tables.
Edit:
As AntC pointed out in the comments below, this technique, although working, can give insidious problems e.g. if you want to change the category_id for a set.
In that case you would have to update the category_id of each item linked to that set.
That needs BEGIN COMMIT/END COMMIT wrapped around the updates.
So ultimately it's probably not worth it and it's better to investigate the requirements further in order to find a better schema.


text:
Q: How to place div / text inside a highchart I am using a highchart.. depending on the selection people make on the chart, i would like to display different text inside the graph. How can i achieve this?

handleRefresh : function(ChartModel) {
        var chartOptions = new ChartTheme();
.......
.......
var chart = new Highcharts.Chart(chartOptions.options);
}

updateColumnSelection : function(index){
  var data = this.model.getData(index);
  _.each(data.messages, function(msg) {
    //display message
    //pool: yes
    var dataPlacement = $("#messages");
dataPlacement .html('');
    dataPlacement.append(msg);

 }
}

Best way to do is, I don't know if possible, but i would love to have a div (place holder) inside the graph and just update it with every selection.

A: You should take a look the reference, here you can see how to add new elements to the chart. Create the element with an id, so that you can get it using jQuery.
Then you can use the selection event to update the number.
{
    chart: {
        renderTo: #element,
        events: {
            selection: function() {
                // @todo Update message
            }
        }
    }
}


text:
Q: Supplying power to an 5V LED strip I'm working on a project to create an infinity mirror based on an Instructables tutorial. Instead of the larger analogue LED strip that the author uses, I opted for a shorter addressable LED strip that runs on 5V.
I thought I would be able to run it off the 5V port on the Arduino, but that seems not to be the case. I understand that the strip can draw up to 3.3A and the Arduino can only supply ~0.5A, but I thought it would work fine if I only turned a few lights on (each one draws ~0.05A). However many lights I program the Arduino to turn on, I always see ~10 random lights with a bias towards red.
The fact that the lights are usually red and there are ~10 of them working at any one is evidence that it is a power issue (because red is lower power and 10×0.05A = 0.5A).
Does anyone have any ideas how I can either

*

*turn on only a chosen subset of lights at one time, or

*supply the appropriate power to the LEDs (preferably from a battery) ?

Here's the code I'm using below, on the chance I made some stupid mistake:
/* LedStripGradient: Example Arduino sketch that shows
 * how to control an Addressable RGB LED Strip from Pololu.
 *
 * To use this, you will need to plug an Addressable RGB LED strip from Pololu
 * into pin 12.  After uploading the sketch, you should see a pattern on the LED
 * strip that fades from green to pink and also moves along the strip. */

#include <PololuLedStrip.h>

// Create an ledStrip object and specify the pin it will use.
PololuLedStrip<12> ledStrip;

// Create a buffer for holding the colors (4 bytes per color).
#define LED_COUNT 72
rgb_color colors[LED_COUNT];

void setup() {
}

void loop() {
  // Update the colors.
  byte time = millis() >> 2;
  for(uint16_t i = 0; i < LED_COUNT; i++)
  {
    byte x = time - 8*i;
    // colors[i] = (rgb_color){ x, 255 - x, x };
    colors[i] = (rgb_color){ 0, 0, 0 };
  }
  colors[0] = (rgb_color){ 0, 0, 255 };
  colors[1] = (rgb_color){ 0, 255, 0 };
  colors[2] = (rgb_color){ 255, 0, 0 };

  // Write the colors to the LED strip.
  ledStrip.write(colors, LED_COUNT);

  delay(100);
}

Thanks!

A: While it's not possible to turn all the LEDs on max brightness without extra power, the main problem was that I hadn't realized that Pololu sells 2 almost identical 0.5m LED strips, and I was reading the instructions for the other variant.
Now that I'm sending instructions using the correct protocol everything works fine as long as I limit the number of LEDs I turn on.
Sorry for the mistake.


text:
Q: Можно ли как-то извне авторизовать пользователя Laravel? хочу прикрепить свой сайт на PHP к сайту Laravel, но никак не могу поставить пользователю нужную куку для общей сессии. Пробовал и просто ставить и через апи, но ничего не работает. Поэтому вопрос, можно ли всё-таки как-то это сделать?

A: Можно сделать в лоб, чтобы куку ставил сам laravel. Таблица с пользователями у ваших сайтов одинаковая ? В nginx настроен proxy_pass на определённый урл, по которому открывается корень laravel-сайта ?
В laravel-сайте делаете некий роут /laravel/external_auth. Он должен принимать get-параметры user_id (или что-то другое, по чему пользователя можно идентифицировать), sign и redirect_back.
sign - это например md5($user_id.$secret). $secret помещаете в .env в laravel и куда-нибудь на старом сайте
В контроллере проверяете валидность sign логините пользователя штатным ларавеловским образом и делаете редирект на redirect_back, т.е. на урл на старом сайте.
На старом сайте после логина делаете редирект пользователя на ларавеловский /laravel/external_auth с нужными параметрами.
В итоге у пользователя в браузере будет нужная кука.


text:
Q: Create a nested dictionary in Python I have created a Father 'father_dict' dictionary, in which I store list type data, but I am looking for that data to be stored as the key of another dictionary, (ultimately a kind of nested dictionary).
#            SubKey            Key
data_input = [[ 1,     'Col',   1,    'TWO',    450],
              [ 2,     'Col',   1,    'TWO',    450],
              [ 3,     'Col',   1,    'TWO',    450],
              [ 4,     'Col',   2,    'TWO',    400],
              [ 5,     'Col',   2,    'TWO',    400],
              [ 6,     'Col',   2,    'TWO',    400],
              [ 7,     'Col',   3,    'TWO',    300],
              [ 8,     'Col',   3,    'TWO',    300],
              [ 9,     'Col',   3,    'TWO',    300]]
cc_list = []
father_dict = {}

for i in range(len(data_input)):
    if data_input[i][1] == 'Col':
        cc_list.append(data_input[i][2]) #--> key list
flat_list = list(set(cc_list)) #--> Key flat

for j in flat_list:
    father_dict[j] = []

for i in range(len(data_input)):
    if data_input[i][1] == 'Col':
        key = data_input[i][2]
        father_dict[key].append(data_input[i][0])
print('\n', 'Father Dict ')
print(father_dict)

The problem is that when replacing 'father_dict [j] = [] with {}', I get an Attribute error because in dictionaries the append method cannot be applied, I have tried some things like matching 'father_dict [key] = data_input [ i] [0] ', but it doesn't work either.
What I'm looking for is that when printing on screen it returns this:
 Father Dict
{1: {1:, 2:, 3:}, 2: {4:, 5:, 6:}, 3: {7:, 8:, 9:}}

Is there any method that works for these cases, thanks?

A: Yes, you can use a defaultdict. It's like a dictionary, except you can provide a default value for any key that doesn't exist. If you provide "dict" as the default value, then you can easily set keys and the subdictionaries get created on demand.
Here's your code using defaultdict:
from collections import defaultdict
import json

#            SubKey            Key
data_input = [[ 1,     'Col',   1,    'TWO',    450],
              [ 2,     'Col',   1,    'TWO',    450],
              [ 3,     'Col',   1,    'TWO',    450],
              [ 4,     'Col',   2,    'TWO',    400],
              [ 5,     'Col',   2,    'TWO',    400],
              [ 6,     'Col',   2,    'TWO',    400],
              [ 7,     'Col',   3,    'TWO',    300],
              [ 8,     'Col',   3,    'TWO',    300],
              [ 9,     'Col',   3,    'TWO',    300]]
cc_list = []
father_dict = defaultdict(dict)

for i in range(len(data_input)):
    if data_input[i][1] == 'Col':
        cc_list.append(data_input[i][2]) #--> key list
flat_list = list(set(cc_list)) #--> Key flat

for i in range(len(data_input)):
    if data_input[i][1] == 'Col':
        key = data_input[i][2]
        father_dict[key][data_input[i][0]] = None
print('\n', 'Father Dict ')
print(json.dumps(father_dict).replace(" null", "").replace('"', ''))

Printing out the result wasn't as convenient, and there's probably a better way which I was too lazy to find, but hopefully you get the idea.

A: With that change, your father_dict will contain elements which are themselves dictionaries. This means that
father_dict[key]

returns a dictionary, not a list. So, if you want to set something in this dictionary, use
father_dict[key][j] = something

Unfortunately, you can't have a dictionary without a value, as you've printed it, so you have to decide what you want the something to be in the above statement.


text:
Q: QPSQL driver not loaded Qt I have some trouble when I want to add a database.
    _dataBase = QSqlDatabase::addDatabase("QPSQL");

After calling this method I have an error:
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7

I include to PATH variable paths to:
PostgreSQL\9.3\bin
PostgreSQL\9.3\lib
PostgreSQL\9.3\include

Also I copy folder sqldrivers to Debug folder. Also tried to copy dlls drom this folder to Debug. Doesn't work either.

A: Use depends.exe on qsqlpsql.dll and found that this dll need libpq.dll from PostgreSQL\9.3\libfolder. Add libpq.dll to Debug folder and it works:)

A: Add the system variable QT_DEBUG_PLUGINS=1 if you want to get full information of why the QPSQL driver has not been loaded.
Probably you will discover that Qt is not able to find it. Copy and paste the output here to know what exactly happens.

A: I came here googling because I had the same problem in Windows.
In my case to solve the issue I had to install PostgreSQL for Windows 32 bits since my Qt target was MinGW 32 bits.
Additionally, I had to add the PATH to the PostgreSQL bin and lib directories so Qt could find the right .dlls.
@SET PATH=C:\Program Files (x86)\PostgreSQL\9.6\bin\;C:\Program Files (x86)\PostgreSQL\9.6\lib\;%PATH%

The PATH can be set before launching Qt Creator or using the Qt Creator itself via the Build Environment in the Projects pane.

A: Try pip install PyQt5 event if you already installed it using conda or installer. It helped me.

A: I got same problem with deploying Qt application (windeployqt didn't help). I had to copy more .dlls (libcrypto-1_1-x64.dll, libiconv-2.dll, libintl-8.dll, libpq.dll, libssl-1_1-x64.dll, libwinpthread-1.dll) from postgreSQL bin path (c:\Program Files\PostgreSQL\12\bin) next to .exe file (according to dependency walker).


text:
Q: data-loss from using auto-generated serializer I have an xsd file that describes a small schema. I created a C# file with the help of xsd.exe (I ran this command in the developer command prompt: xsd.exe smallSchema.xsd /classes /language:CS) to be able to easily (de-)serialize it. I took an xml file that complies to that schema and tried to deserialize it by using the generated code. But i noticed that data loss occurs!
Can anyone point me to the cause of that data loss?
This is the xml file that I want to deserialize:
<?xml version="1.0" encoding="UTF-8"?>
<top-element>
    <complex-elem type="plain-number">1</complex-elem>
    <top-elem-name>myTopElement</top-elem-name>
</top-element>

The following code will deserialize it, then serialize it again and overwrite the file:
XmlSerializer serializer = new XmlSerializer(typeof(topelement));
string path = ... // path of the file on my disk
topelement rawData = null;
using (FileStream reader = new FileStream(path, FileMode.Open))
{
    rawData = (topelement)serializer.Deserialize(reader);
}
XmlSerializerNamespaces noNamespace
    = new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName("", "") });
    // I use it to prevent adding a namespace during serializing
using (XmlWriter wr = XmlWriter.Create(path))
{
    serializer.Serialize(wr, rawData, noNamespace);
}

But the overwritten file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<top-element>
    <complex-elem />
    <top-elem-name>myTopElement</top-elem-name>
</top-element>

I.e. the data inside complex-elem got lost! Debugging shows that the deserialized content already contains null where it shouldn't (see picture).

This is the xsd schema:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="top-element">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="complex-elem" />
        <xs:element ref="top-elem-name" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:element name="complex-elem">
    <xs:complexType>
      <xs:choice>
        <xs:element ref="plain-number" />
      </xs:choice>
    </xs:complexType>
  </xs:element>

  <xs:element name="plain-number" type="xs:string" />
  <xs:element name="top-elem-name" type="xs:string" />

</xs:schema>

And here is the result of calling xsd.exe (the comments are German):
//------------------------------------------------------------------------------
// <auto-generated>
//     Dieser Code wurde von einem Tool generiert.
//     Laufzeitversion:4.0.30319.42000
//
//     Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
//     der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// Dieser Quellcode wurde automatisch generiert von xsd, Version=4.6.1055.0.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute("top-element", Namespace="", IsNullable=false)]
public partial class topelement {

    private complexelem complexelemField;

    private string topelemnameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("complex-elem")]
    public complexelem complexelem {
        get {
            return this.complexelemField;
        }
        set {
            this.complexelemField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("top-elem-name")]
    public string topelemname {
        get {
            return this.topelemnameField;
        }
        set {
            this.topelemnameField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute("complex-elem", Namespace="", IsNullable=false)]
public partial class complexelem {

    private string itemField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("plain-number")]
    public string Item {
        get {
            return this.itemField;
        }
        set {
            this.itemField = value;
        }
    }
}

A: The XML sample you try to deserialize doesn't validate against the XSD schema you provided.
If you try to validate the XML, you'll get three validation errors:

*

*Cvc-complex-type.3.2.2: Attribute 'type' Is Not Allowed To Appear In Element 'complex-elem'., Line '2', Column '39'.

*Cvc-complex-type.2.3: Element 'complex-elem' Cannot Have Character [children], Because The Type's Content Type Is Element-only., Line
  '2', Column '55'.

*Cvc-complex-type.2.4.b: The Content Of Element 'complex-elem' Is Not Complete. One Of '{plain-number}' Is Expected., Line '2', Column
  '55'.

So either change your XML to the following one:
<?xml version="1.0" encoding="UTF-8"?>
<top-element>
    <complex-elem>
        <plain-number>1</plain-number>
    </complex-elem>
    <top-elem-name>myTopElement</top-elem-name>
</top-element>

... or change your complex-elem schema definition to this one:
<xs:element name="complex-elem">
    <xs:complexType>
        <xs:simpleContent>
            <xs:extension base="xs:string">
                <xs:attribute name="type" type="xs:string" />
            </xs:extension>
       </xs:simpleContent>
   </xs:complexType>
</xs:element>


text:
Q: many whitespaces in string after reading of database I have the a textarea with the following value:

I save this value with php into my mysql database.
The result looks like this via phpmyadmin:

Now, I send a query with php to get the result and to show this text like this, to show it with line breaks:
<? echo nl2br($row->text); ?>

But the result will shown many withspaces. here the source code:

Where is my fault? :/

A:
The result looks like this via phpmyadmin

phpadmin ist a webpage with html, it doesn't show consecutive blanks.

Where is my fault? :/

Somewhere between reading it out of the textarea, writing it into the database and reading it back from there.
Steps to track your problem.
What is transferred from the textarea to the server?
Check how the value is in your database.
Output the length of this string to get a simple idea of what really is in the database.
Then if you know if the string already got wrong into the database or the error occurs only when reading it, you can go on looking at this particular place.


text:
Q: Why doesn't the code "horizontal loop scroll" work on a real browser? I am supposed to make a component which is horizontal loop scroll in both direction.
It is perfectly fine on Codepen but not on a real browser when I put them in a single HTML file. It works fine in up direction but in down direction.
I have tried this on several browsers but the results are the same.
You can see the full source code here:
HTML

Looping Horizontal Scroll

2

3

4

5

Last

Looping Horizontal Scroll

CSS
body{
  overflow-x:hidden;
  color:#FFF;
  font-family:Helvetica;
  font-size:200%;
}
#page {
  overflow:hidden;
  white-space:nowrap;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color:#CCC;
  display:flex;
  flex-wrap:no-wrap;
}
.pane {
  flex:0 0 100vw;
  height:100vh;
  display:flex;
  position:relative;
  align-items:center;
  justify-content:center;
  background-color: #45CCFF;
}

.pane:nth-child(4n+2)  {
  background-color: #49E83E;
}
.pane:nth-child(4n+3)  {
  background-color: #EDDE05;
}
.pane:nth-child(4n+4)  {
  background-color: #E84B30;
}
.pane:last-child {
  background-color: #45CCFF;
}

SCRIPT
var page = document.getElementById('page');
var last_pane = page.getElementsByClassName('pane');
last_pane = last_pane[last_pane.length-1];
var dummy_x = null;

window.onscroll = function () {
  // Horizontal Scroll.
  var y = document.body.getBoundingClientRect().top;
  page.scrollLeft = -y;

  // Looping Scroll.
  var diff = window.scrollY - dummy_x;
  if (diff > 0) {
    window.scrollTo(0, diff);
  }
  else if (window.scrollY == 0) {
    window.scrollTo(0, dummy_x);
  }
}
// Adjust the body height if the window resizes.
window.onresize = resize;
// Initial resize.
resize();

// Reset window-based vars
function resize() {
  var w = page.scrollWidth-window.innerWidth+window.innerHeight;
  document.body.style.height = w + 'px';

  dummy_x = last_pane.getBoundingClientRect().left+window.scrollY;
}

It is supposed to work fine on any browsers.