text:
Q: Coupon Collector Problem - expected number of draws for some coupon to be drawn twice Suppose that there are $n$ different coupons, equally likely, from which coupons are being randomly drawn with replacement. Find the expected number of draws for some coupon to be drawn twice.
I've attempted to solve this from the basic definition of expectation. If $N$ is a randomly variable for the number of draws for some coupon to be drawn twice, then $1\lt N\le n+1$ and
$$
E[N]=\sum_{i=2}^{n+1} n*Pr(N=n)\\
=2*\left(\frac{1}{n}\right)+3*\left(\frac{n-1}{n}\right)\left(\frac{2}{n}\right)+4*\left(\frac{n-1}{n}\right)\left(\frac{n-2}{n}\right)\left(\frac{3}{n}\right)+...
$$
(Sorry for not finishing the equation, hopefully you get the idea, it goes up to $n+1$, my latex maths is pretty crap.)
Is this correct? How do I evaluate this sum or is there a closed-form solution to this sum? Is there a better way to solve this?

A: \begin{align}
E[N]&=\sum_{k=0}^n\textsf{Pr}(N\gt k)\\
&=\sum_{k=0}^n\frac{n!}{(n-k)!n^k}\\
&=\sum_{k=0}^n\frac{n!}{k!n^{n-k}}\\
&=\frac{n!}{n^n}\sum_{k=0}^n\frac{n^k}{k!}\\
&\sim\frac{n!}{n^n}\frac{\mathrm e^n}2\\
&\sim\sqrt{\frac{\pi n}2}\;,
\end{align}
where the first approximation takes the terms of the exponential series to be approximately symmetric about its maximum at $k=n$, and the second approximation is Stirling's. According to Wikipedia, the next term in the expansion in terms of $\sqrt n$ is $-\frac13$.


text:
Q: View and complex query count distinct locations employee stayed in SQL I have a view which looks like this view_1:
id      Office              Begin_dt    Last_dt    Days
1       Office1            2019-09-02   2019-09-08  6
1       Office2            2019-09-09   2019-09-30  21
1       Office1            2019-10-01   2019-10-31  30
5       Office3            2017-10-01   2017-10-16  15
5       Office2            2017-10-17   2017-10-30  13
5       Office2            2017-11-01   2017-11-31  30

I want to find the office where employee stayed for max time and also the number of Distinct Office locations he stayed in.
Expected output
id      Max_time_in_Office Days      Distinct_office_locations
1       Office1            36             2
5       Office2            43             2

So id 1 spends 6 and 30, overall 36 days in office 1. Max time is spent in office 1 by him. Distinct locations are 2.
id 5 spends 13 and 30 , 43 days in office. Max time is spent in office 2. Distinct locations are 2.
Code tried
select v.*
from (select v.id, v.office, sum(days) as Max_time_in_Office, count(Office) as Distinct_office_locations,
      rank() over (partition by id order by sum(days) desc) as seqnum
      from view_1 v
      group by id, office
     ) v
where seqnum = 1;

Output obtained
id      Max_time_in_Office Days      Distinct_office_locations
1       Office1            36             1
5       Office2            43             1

So I am getting wrong output. Can someone pls help

A: Close.  You want a window function:
select v.*
from (select v.id, v.office, sum(days) as Max_time_in_Office,
             count(*) over (partition by id) as Distinct_office_locations,
             rank() over (partition by id order by sum(days) desc) as seqnum
      from view_1 v
      group by id, office
     ) v
where seqnum = 1;

Basically the window function is counting the number of rows returned after the aggregation -- and there is one row per office.

A: You could use the apply operator to achieve that:
select  V.Id,
        T.Max_Time_Office,
        T.Days,
        Distinct_office_locations = count(distinct V.Office)
from view_1 V
Cross apply
(
    Select  top 1   Id,
                    Max_Time_Office = Office,
                    Days = sum(Days)
    From view_1 VG
    where V.Id = VG.Id
    group by VG.Id, VG.Office
    order by sum(Days) desc
) T
group by V.Id, T.Max_Time_Office, T.Days

Basically, you are getting the Office with most days in the order by sum(Days) desc inside the Cross apply, and using that in the outer expression. I then just did a count(distinct V.Office) to get the distinct offices.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Link that runs code to expand flash object fullscreen without refreshing I want to have a flash game with a link at the bottom that says "Fullscreen" and when you click it as though it was a link it will scale a flash object to be as big as your screen without stretching it, or refreshing it. My blog can be found at bestjavascriptgames.blogspot.com The link for fullscreen is NOT there right now because I don't want people asking about it. Also I have been trying out different display techniques so right now the menu only has 4 games available. It normally has more but for now it has 4.

A: As long as the link is within the Flash object, this is easily achieved:
stage.scaleMode = StageScaleMode.NO_SCALE;

fullscreenBtn.addEventListener(MouseEvent.CLICK, goFullscreen);
function goFullscreen(e:MouseEvent):void
{
    stage.displayState = StageDisplayState.FULL_SCREEN;
}

A: Given what you have said, I will assume for the duration of my answer that the knowledge you desire is needed in the form of HTML.
Rather than a "link" (an ), to prevent reloading what you need is a  or  (without an href.. not technically valid HTML) which has only an onclick attribute and any styling your site needs.
That onclick should run JavaScript that interfaces with your flash object, calling it's internal full-screen'ing routine(s). This comes without penalty of any reloading. I leave the rest as a research project on how to call into flash objects - there are plenty of examples on the web which you can adapt to your needs and I prefer not to guess at how to go about this for your particular flash object.


text:
Q: TypeError: Cannot read property 'name' of undefined - Fetching data from restcountries API I am building an app following the Rest Countries API challenge from frontendmentor. I have run into a problem. When trying to find the border countries full name using the alpha3code, I get the error :
TypeError: Cannot read property 'name' of undefined.
import React, { useState, useEffect } from "react";
import axios from "axios";
import {Link} from "react-router-dom";
import {CountryDetailStyles, ImgContainer, CountryInfo, CountryInfoDetails, CountryDetailsWrapper, CountryInfoDetailsInner, CountryBorders, LinkWrapper} from "../styles/CountryDetailStyles";

function CountryDetail({match}) {
  useEffect(() => {
     fetchItem();

  }, []);

  useEffect(() => {
     setBorderCountries();
  }, []);

  const [item, setItem] = useState([]);
  const [allCountries, setAllCountries] = useState([]);

  const fetchItem = async () => {
    const response = await axios.get(`https://restcountries.eu/rest/v2/name/${match.params.name}?fullText=true`);
    setItem(response.data)
  }

  const setBorderCountries = async () => {
    const response = await axios.get(`https://restcountries.eu/rest/v2/all`);
    setAllCountries(response.data)
  }

  // get borders full name using alpha3code
  const getBorderCountryName = (allCountries, border) => {
    const matchingCountry = allCountries.find(country => {
      return country.alpha3Code === border;
    })

    return matchingCountry.name;
  }

  return (
       <CountryDetailStyles>
           <Link className="country-links" to={"/"}>
             <LinkWrapper>

Go Back

             </LinkWrapper>
             </Link>
           {item.map(i => (
               <CountryDetailsWrapper>
               <ImgContainer flag={i.flag}>
               </ImgContainer>
               <CountryInfo>

{i.name}

                   <CountryInfoDetails>
                       <CountryInfoDetailsInner>

Native Name: {i.nativeName}

Population: {i.population.toLocaleString()}

Region: {i.region}

Sub Region: {i.subregion}

Capital: {i.capital}

                       </CountryInfoDetailsInner>
                       <CountryInfoDetailsInner className="second">

Top Level Domain: {i.topLevelDomain}

Currencies: {i.currencies[0].name}

Languages: {i.languages.map(lang => lang.name).join(", ")}

                       </CountryInfoDetailsInner>
                   </CountryInfoDetails>
                   <CountryBorders>

Border Countries:

                    {i.borders.map(border =>{
                      const borderName = getBorderCountryName(allCountries, border);
                      return (<Link to={`/country/${borderName}`}><button>{borderName}</button></Link>)
                    })}
                   </CountryBorders>
               </CountryInfo>
               </CountryDetailsWrapper>
           ))}
        </CountryDetailStyles>
  )
}

export default CountryDetail;

A: The issue is here:
{item.map(i => (

you are getting this response from an axios call and setting in state which is this:
const response = await axios.get(`https://restcountries.eu/rest/v2/name/${match.params.name}?fullText=true`);
    setItem(response.data)

on first render item doesn't have any data as axios call will take some time to complete and when there is no data an you try to iterate it then it will throw such error. So try this:
{
  ( item && item.length > 0 )  // conditional rendering or such type of check is neede before iteration
  ?
  // Iterate here
  :
  null // do nothing
}


text:
Q: How to pass warning messages from t-sql procedure? I call the procedure in C# code. Is it possible somehow pass warning messages from the procedure to caller, like this raiserror calls or somehow else?
try
{
   if (connection.State != ConnectionState.Open) connection.Open();

   var cmd = connection.CreateCommand();
   cmd.CommandTimeout = cfg.CmdTimeout;
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.CommandText = "dbo.test";

   var ParamReturn = cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
   ParamReturn.Direction = ParameterDirection.ReturnValue;
   cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message, "Test");
}

CREATE PROCEDURE test
AS
BEGIN
    SET NOCOUNT ON;
    RAISERROR(N'Kuku1',0,0) WITH NOWAIT
    select @@VERSION as '@@VERSION'
    RAISERROR(N'Kuku2',0,0) WITH NOWAIT
    select @@LANGID as '@@LANGID'
    RAISERROR(N'Pisec',0,0) WITH NOWAIT
    return @@CONNECTIONS
END
GO

A: You can read the messages (sent via PRINT, or RAISERROR with severity 10 or less) via the InfoMessage property of the connection:
using (var command = new SqlCommand(query, connection))
{
    command.CommandTimeout = 0;
    var infoCaptureHandler = new SqlInfoMessageEventHandler((sender, args) =>
        {
            if (!String.IsNullOrWhiteSpace(args.Message))
            {
                Console.WriteLineLine(args.Message);
            }
        });

    connection.InfoMessage += infoCaptureHandler;
    try
    {
        command.ExecuteReader();
    }
    finally
    {
        connection.InfoMessage -= infoCaptureHandler;
    }
}


text:
Q: HTML 5 - frame by frame animation I have a frame by frame animation that I want to recreate in HTML 5.
I have for example, one element, like a ball, for example, and keyframes like this:
var x = new Array(102,130,140,200);
var y = new Array(52,120,240,400);
var opacity = new Array(0,0.2,0.5,0.3); // I am assuming opacity goes from 0 to 1

these four positions represents x, y and opacity of the ball position on keyframes 1, 2, 3 and 4.
Each keyframe is to be called, for example, every 1/30 second. The element to be animated, the ball in this example, is a png image.
How do I animate that ball on the canvas?
I found this code:
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #myCanvas {
        border: 1px solid #9C9898;
      }
    </style>
    <script>
      window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1 / 30);
        };
      })();

      function animate() {
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");

        // update stage

        // clear stage
        context.clearRect(0, 0, canvas.width, canvas.height);

        // render stage

        // request new frame
        requestAnimFrame(function() {
          animate();
        });
      }

      window.onload = function() {
        animate();
      };

    </script>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
  </body>
</html>

but this code does not shows how I would include an object animating there...
I appreciate any help. Thanks.

A: First of all you need to create an object representing the ball, then - from my point of view - the best practice is to add some properties like x and y coordinates, velocity, mass etc. You can define these either using object literals or by assigning each property separately. It's up to you. This way you have the base for future re-usability.
This is one of the possibilities you can build up your code. I slightly modified the original one by separating the rendering function from the initialization. This is only for optimization concernings.
function Ball(ctx, x, y, rad) {
    this.x = x;
    this.y = y;
    this.rad = rad;
    this.vx = 0;
    this.vy = 0;
    this.mass = 0;

    this.createBall = function() {
        ctx.fillStyle = '#rgba(38,85,139,1)';
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.rad, 2*Math.PI, false);
        ctx.closePath();
        ctx.fill();
    };

    this.update = function() {
        context.clearRect(0, 0, canvas.width, canvas.height);

        if (this.x > canvas.width) {
            this.x = canvas.width - 1;
            this.vx *= -1;
        }
        //...
    };
}

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

function init() {
    var numBalls = 100;
    var ballPool = [];
    var width = canvas.width;
    var height = canvas.height;
    var ball = new Ball(context, Math.random() * width, Math.random() * height,
                        (Math.random() * 10 - 5) + 2);

    for (var i = 0; i < 100; i++)
        ballPool.push(ball);
      }
}

function animate() {
    var len = ballPool.length;
    var ball = null;

    for (var i=0; i < len; i++) {
        ball = Ball(ballPool[i]);
        ball.update();
    }
}

window.onload = init();
requestAnimFrame(animate);

Note
I didn't tested the code, i make it only to got the idea. One side-note: i didn't constructed my code to use keyframes, but it's possible to use keyframes too, only you need a big pool of coordinates for a smoother transition.


text:
Q: Can List values be validated using JSR 303 field validations I am validating a bean with JSR 303 specifications, it has a parameter that contains list of string. I want to validate each string in this list as this is the request object. I already have a pattern for matching each string, but i am not able to apply if recursively for each entry in the list.
@NotEmpty(message = "phoneNumber must not be null or empty")
@Valid @Pattern(regexp = REGEX_PHONENUMBER, message = "Not a valid phoneNumber")
private List<String> phoneNumber;

A: A custom validator need to be implemented to make it possible using JSR 303
@PhoneNumbers
private List<String> phoneNumber;

It's supported out of the box in Bean Validation 2.0 / JSR 380:
List<@NotEmpty @Pattern(regexp = REGEX_PHONENUMBER) String>


text:
Q: How can I implement and activate search in a Windows 8 app? I want to allow my app to use the Windows 8 search charm and despite going through the extensive search documentation on MSDN I seem to be missing the first step. Firstly, I have already declared that I wish to use search in the Project Manifest, and I have added the code in my header to link my default.htmlwith the searchResults.js file.
The documentation then suggests that using system search should just 'work'. How this does not happen for me, when I do a search it does not open my app on the default, blank search results page. I have tried adding the following to my default.js page, but to no avail:
  // When the user submits a search query
Windows.ApplicationModel.Search.SearchPane.getForCurrentView().onquerysubmitted =
    // Call the function
    function (eventObject) {

        winJS.log && WinJS.log("User submitted the search query: " + eventObject.queryText, "sample", "status");
};

What am I missing? How do I get the search charm to actually activate my app and display the results page?
Thanks.

A: I have search working for a C# project. I created a startup js project and search was working within 2 mins. Here's what I did
Add a search contract,
Click Add New -> Search Contract
by default the js file is called searchResults.js
On your home page or default.html page add a reference to the searchResults.js
Here's what mine looks like
<head>
    <meta charset="utf-8" />
    <title>App4</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- App4 references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
    <script src="/searchResults.js"></script>
</head>

Finally in the app manifest Declarations, select Search for supported Declarations. The properties on the right are empty in my case.
and that's it!
I put a break point in the onQuerySubmitted function. I run the app, call the search charm (Windows Key + Q)
start typing text and on pressing enter it should hit the breakpoint!
appModel.Search.SearchPane.getForCurrentView().onquerysubmitted = function (args)
{
    nav.navigate(searchPageURI, args); // put breakpoint here
};

Hope this helps.


text:
Q: Need to use body onload event, but third party JavaScript library has hijacked it I'm using Simile to draw dynamic timelines. I am also using an in-house library to add a comment blog. Our in-house library uses the body element's onload event to initialize.
<body onload="initComments('myID')">

But Simile seems to have hijacked the onload for their own purpose so that initComments('myID') never executes.
Short of changing the Simile code, how could I get my initializer to run?
I would prefer not to add another library (i.e. jQuery) just to solve the problem.

A: First off, as a general rule, you want to stay away from embedding JavaScript in your HTML as tag attributes.
Secondly, Simile is likely overwriting the onload (using it the same way you are).  So, you'll want to add your onload event after you've included Simile.
Using jQuery:
<script src="/js/blah/simile.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        initComments('myID');
    });
</script>

Using no library (found here):
<script src="/js/blah/simile.js" type="text/javascript"></script>
<script type="text/javascript">
  function addOnloadEvent(fnc){
    if ( window.addEventListener ) {
      window.addEventListener( "load", fnc, false );
    } else if ( window.attachEvent ) {
      window.attachEvent( "onload", fnc );
    }
    else {
      var oldOnload = window.onload || function() {};
      window.onload = function(e) {
        oldOnload(e);
        window[fnc](e);
      };
    }
  }

  addOnloadEvent(function() { initComments('myID'); });
</script>

A: Use jQuery's $(document).ready event, which lets you add an arbitrary number of handlers (unlike onload).

A: Apart from the aforementioned jQuery solution (I however highly recommend to use it, it's great) here's the plain vanilla JS solution (as you didn't mention anything about jQuery in your question):
// Add this to top of your script.
window.onload = function () {
    for (var i = 0; arguments.callee.functions.length > i; i++) {
        arguments.callee.functions[i]();
    }
};
window.onload.functions = [];

// Now for every onload function you want to add, do:
window.onload.functions.push(initComments('myID'));

A: Add in jQuery and use
$(document).ready(function(){
  // Your code here...
});

There are a couple of other ways to write this in jQuery, but I find this is the most explanatory.
If you're doing any kind of JavaScript development, you need to be looking at jQuery. It's totally sweet!

A: By hijacked, you mean, Simile loads after your code and overwrites onload? In that case, make sure you get behind it (as Justin says), and before you overwrite it yourself, store the value of onload somewhere, so it still gets called (from your own handler).
That is, if you don't use jQuery.

A: If you look here you will see a solution that is what jQuery uses, I believe, or a modification of it, but it should work for your needs.
http://dean.edwards.name/weblog/2006/06/again/
// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
/*window.onload = init; */

You will see that the last line is commented out. In the event it gets that far either you will clobber them (uncomment) or your code won't run, but this will work for the major browsers.


text:
Q: Meaning of complex trigonometric ratios I have encountered about finding trigonometric ratios of complex arguments (a+ib) those can be computed via series expansion and Euler formula. But my question is what is the definition of these trigonometric ratios as i have learnt these ratios where defined via triangles and for real arguments. It's also said that cosine and sine both have periods 2nπ for both complex and real arguments. What's the justification for all these as these where defined and found for real arguments only,how do we extend this to complex numbers. Also i want to know the meaning of these ratios as a real trigonometric ratios have meaningful meaning. Any help please. Thank you

A: There are relations between trigonometric and hperbolic functions. For example
$$\sin(ix)=i \, \sinh(x)$$
$$\cos(ix)=\cosh(x)$$
$$\tan(ix)=i \, \tanh(x)$$
Suing the classical expansions, then
$$\sin(a+ib)=\sin (a) \cosh (b)+i \cos (a) \sinh (b)$$
$$\cos(a+ib)=\cos (a) \cosh (b)-i \sin (a) \sinh (b)$$


text:
Q: Spark Random Forests: Different results with same seed When running Spark's RandomForest algorithm, I seem to get different splits in the trees on different runs even when using the same seed. Could anyone kindly explain if I am doing something wrong (likely), or the implementation is buggy (which I believe to be unlikely)? Here is the scheme of my run:
//read data into rdd
//convert string rdd to LabeledPoint rdd
// train_LP_RDD is RDD of LabeledPoint
// call random forest
val seed = 123417
val numTrees = 10
val numClasses = 2
val categoricalFeaturesInfo: Map[Int, Int] = Map()
val featureSubsetStrategy = "auto"
val impurity = "gini"
val maxDepth = 8
val maxBins = 10
val rfmodel = RandomForest.trainClassifier(train_LP_RDD, numClasses, categoricalFeaturesInfo,
                        numTrees, featureSubsetStrategy, impurity, maxDepth, maxBins,seed)
println(rfmodel.toDebugString)

On two different runs, the output of this snippet is different. For example, a diff on two results shows the following:
sdiff -bBWs run1.debug run2.debug

If (feature 2 <= 15.96)             |         If (feature 2 <= 16.0)
Else (feature 2 > 15.96)            |         Else (feature 2 > 16.0)
If (feature 2 <= 15.96)             |         If (feature 2 <= 16.0)
Else (feature 2 > 15.96)            |         Else (feature 2 > 16.0)
If (feature 2 <= 33.68)             |         If (feature 2 <= 34.66)
Else (feature 2 > 33.68)            |         Else (feature 2 > 34.66)
If (feature 1 <= 17.0)              |         If (feature 1 <= 16.0)
Else (feature 1 > 17.0)             |         Else (feature 1 > 16.0)

A: Can't tell without more context (and not enough rep to comment), but as Shaido suggested, one cause could be that train_LP_RDD is not deterministic.  E.g. if you're doing something like
train_LP_RDD = sc.textFile(path).sample(withReplacement=False, fraction=0.5)

Then you're going to get different samples each time you run trainClassifier, even if you're not re-defining train_LP_RDD.


text:
Q: How to enable alpha blending on DirectX? How to do this in DirectX?
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);

Somehow i just cant seem to get it work. Im using code:
d3ddev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR);
d3ddev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, 1);
d3ddev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
d3ddev->SetRenderState(D3DRS_ALPHAREF, (DWORD)50);
d3ddev->SetRenderState(D3DRS_ALPHATESTENABLE, 1);

But it will render my polygon with some sort of ghosted method, i can see through all my polygons! i just want to make the texture with alpha channel to show through those fully transparent pieces of texture. this works with alphatest, but it still shows black edges, so i guess the blending isnt enabled, even though i have set D3DRS_ALPHABLENDENABLE ! What im doing wrong?

A: instead of SRCCOLOR i needed to use SRCALPHA:
d3ddev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3ddev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);


text:
Q: Make private branches with git I'm somewhat new to Git.
So, my task is to make 3 branches, for 3 developers, that would connect only to their branch and work only with their own branch.
Something like this:
developer 1 == branch 1
developer 2 == branch 2

Any help or tutorials will be helpful.

A: All branches created with Git are initially private, and trunk is essentially a branch. What you are describing is the default behaviour of Git.
Take a look at this article on how branch handling differs in Git. Also, this tutorial is useful for people migrating from Subversion to Git.

A: Git doesn't contain any access control by itself.
Gitolite is a Git server, which offers access control including setting access for distinct branches.

A: They just should do this:

developer 1: git checkout branch1

developer 2: git checkout branch2

developer 3: git checkout branch3

So they will use their own branches. push will be only to branches that they are checkouted.

But they can use another branch, if they want. So, if you want to deny them to use another branch, just create separate repository for every developer.

A: I suggest you read up on git workflow, either in http://progit.org or in http://sethrobertson.github.com/GitBestPractices
As seanhodges suggested, by default when each developer clones the upstream repo, they will have a private version of the branches, eg master.  They can do whatever they want locally. When they are ready to share with other people, they push/pull/etc.  There is no particular reason why they need to be on a branch named "dev1".  If other people want to look at their stuff, they can by adding the dev's repo as a remote and then they can look at dev1/master.
If you want to do it they way you suggested, you of course can.  Just git checkout $USER.  People find it more useful to make feature branches (a branch for a particular feature) than user branches.
If you are talking access control, then sure gitolite is probably the best bet as mentioned in the other answer, but really there is no reason why you need to bother except in the most formal circumstances.  If a user screws something up, you can always blow those changes away or restore to an earlier state.


text:
Q: filter swift array of objects to remove objects who have the same value in one or more of their properties I have a Swift array of coreData objects.  The objects have three properties.  I would like to filter the array to remove objects that share the same value for 2 of these properties.
Object properties are object.name, object.age, object.id
All properties are of type String.
I want to filter the array to return an array removing duplicate cases where object.name AND object.age are the same.

A: You could do it with a set:
var uniqueValues = Set<String>()
objectsArray = objectsArray.filter{ uniqueValues.insert("\($0.name)|\($0.age)").inserted}

You could also generalize the approach to cover other combinations by extending the Array type:
extension Array
{
   func filterDuplicate<T>(_ keyValue:(Element)->T) -> [Element]
   {
      var uniqueKeys = Set<String>()
      return filter{uniqueKeys.insert("\(keyValue($0))").inserted}
   }
}

objectsArray = objectsArray.filterDuplicate{ ($0.name,$0.age) }

A: Although Alain's solution is very nice, here's somewhat more swifty way which benefits from KeyPaths:
extension Array {
    func filterDuplicates(by keyPath: PartialKeyPath<Element>) -> Self {
        var uniqueKeys = Set<String>()

        return self.filter { uniqueKeys.insert("\($0[keyPath: keyPath])").inserted }
    }
}

Now you can use it like this:
yourArr.filterDuplicates(by: \YourClass.propertyName)
And if you want to use multiple properties to determine uniqueness, here's the solution for that:
extension Array {
    func withRemovedDuplicates(by keyPaths: PartialKeyPath<Element>...) -> Self {
        var uniqueKeys = Set<String>()

        return self.filter { element in
            uniqueKeys.insert(keyPaths.map { "\(element[keyPath: $0])" }.joined()).inserted
        }
    }
}

Use is this way:
yourArr.filterDuplicates(by: \YourClass.propertyOneName, \YourClass.propertyTwoName)

A: this is the solution that seems to work for me.  maybe not the most elegant but simple enough.
objects is the array of coreData objects.  The second array objectsArray is an empty array which is populated in the nested iteration with non age/name duplicate items.
var objects = [Object]()
//initialize the above array objects and fill with core data objects
objects = populateObjectsArrayWithCoreDataObjects()
//create a new empty array called objectsArray
var objectsArray = [Object]()
for index in 0..<self.objects.count {
    let object = objects[index]
    var isDuplicate = false
    for index2 in (index + 1)..<self.objects.count {
        let object2 = objects[index2]
        if object.name == object2.name && object.age == object2.age {
            isDuplicate = true
        }
    }
    if isDuplicate == false {
        objectsArray.append(item)
    }
}
objects = objectsArray


text:
Q: How can I assign a key to an array of values to pass to an API? Im using Angular with pure JS. I have an array like this:
arr = [1, 2, 5, 32];

But I need to POST this to an API in JSON. I'm trying to achieve this:
{'reportIDs': [1, 2, 5, 32]}

Is there an easy way to do this in Angular?

A: Wherever it is that you need this value, you can create that object almost exactly as in your question:
var obj = {'reportIDs': arr};

You don't need the ', but they don't do any harm.
But if you really need to send JSON, your example isn't JSON. In JSON, property names must be in double quotes. The simplest way to create valid JSON is to use JSON.stringify:
var json = JSON.stringify({reportIDs:arr});

If you're sending that somewhere, you'd use that value as the data in a $http call.
You might want to use angular.toJson instead of using JSON.stringify directly, as it skips some internal Angular prooperties.

A: You need to sent an Ajax request to the server
If you want to keep the json code, insert it as a string
$http.post("the_url_to_sent_data",
   {'json' : JSON.stringify({'reportIDs': arr})}
).then(function (response) {
    // Hey, i got a responce
    return response;
});

Then get the json parameter's value and parse it.
Or just send the data and let the library parse them
$http.post("the_url_to_sent_data",
   {'reportIDs': arr}
).then(function (response) {
    // Hey, i got a responce
    return response;
});


text:
Q: up arrow image in xml drawable: Android I have a listactivity it should look like the following (ie listview with border and an arrow pointing upwards at right side of the listview),

So far i have the listview with border and rounded corners. But i have no idea how to add upward arrow at top right side.
My code:
list_border.xml
    <?xml version="1.0" encoding="UTF-8" ?>
     <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
        <item>
            <shape android:shape="rectangle" >
                <solid android:color="#CCCCCC" />

                <padding
                    android:bottom="3dp"
                    android:left="3dp"
                    android:right="3dp"
                    android:top="3dp" />

                <corners android:radius="5dp" />
            </shape>
        </item>
    </layer-list>

listborder.axml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="325dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:background="@drawable/notification_list_border"
        android:layout_height="300dp">
        <ListView
            android:id="@android:id/list"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"
            android:cacheColorHint="#00000000" />
    </LinearLayout>

I tried to add arrow image in xml. But it isnt working
    <item android:right="10dp">
            <bitmap
                android:src="@drawable/up_icon"
                android:gravity="top|right" />
        </item>

Please help,
Thanks.


text:
Q: Process ends before expected Python I am writing a simple Python program in Pycharm that imports a csv database to a Mongodb, shows a progress bar while importing and, after being imported all documents, run some other functions...
Since I use a subprocess instruction to run mongoimport command I must do some waiting for the other functions not to be executed before the mongimport.
Here comes the issue: if I use subprocess.wait() the progress bar stops updating until the mongoimport ends, else if I use sleep() the same happens...
So I tried to run mongoimport subprocess and the functions that updates the progress bar in the same process. Then I use an "empty" while loop checking if process.is_alive() so the main program does nothin, while the process is importing and updating the progress bar...  BUT it exits the loop before expected! Long before the mongoimport neither the progress bar function end.
Here is the code:
def mainFunction(self):
    process1 = Process(target=self.execc())
    process1.start()

    while process1.is_alive():
        print("IM IN PROCESS 1")

    # THIS IS PRINTED BEFORE "execc()" ENDS
    print("IM OUT!")

    # other functions
    self.toISO()
    self.createFrec()
    self.sort()

def execc(self):

    p = subprocess.Popen(['mongoimport', '-d', 'tfg', '-c', 'myCol', '--type', 'csv', '--file', './myFile.csv', '--headerline'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # shows and updates the progress bar while mongoimpor
    self.showProgress()

# RECURSIVE FUNCTION
# updates the progress bar every 200ms
def showProgress(self):
    bytes = self.db.command('collStats', self.coll_name.get())
    self.pBar['value'] = bytes['size']

    if bytes['size'] < self.maxbytes:
        self.pBar.after(200, self.showProgress)

A: I don't think you need a multiprocessing approach to handle this case.
Instead you can simply use Popen.poll to check whether the subprocess has terminated. I think something like this should work
p = subprocess.Popen(['mongoimport', '-d', 'tfg', '-c', 'myCol', '--type', 'csv', '--file', './myFile.csv', '--headerline'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while p.poll() is None:

    # shows and updates the progress bar while mongoimpor
    self.showProgress()

if p.returncode != 0:
    raise Exception("mongoimport terminated with exit code {}".format(p.returncode))


text:
Q: How to wait browser on protractor e2e test? I have a flaky test. Its about my loading screen. I use
await browser.wait(EC.invisibilityOf(...)); // It contains parameters.

await browser.sleep(2000);

But still sometimes it is work , it is not. I have a button. My test try button click on Loading screen therefore it fail. It must wait when loading screen was gone.(I tried using wait and sleep )
How I do resolve the problem. I need help.

A:
It must wait when loading screen was gone

*

*Create a while loop.

*Check if the loading screen is gone

*

*if true then do your thing

*else wait

*Let the loop gets executed until the condition returns true

and by

if the loading screen is gone

You can check the CSS of the element of the loading screen. It can be
display: none;

or
visibility: hidden;

depends on how it is hidden.

A: Just because your loading screen is invisible does not mean the the next page has is ready to interact with. You can try waiting for the visibility of an element on the next page or try changing your sleep to await browser.driver.sleep(2000).
I would probably take an element from the page you expect to be loaded and try
await browser.wait(EC.presenceOf(reqElement), 5000,
   'reqElement not displayed on page after 5 seconds, loading screen may still be visible'
)


text:
Q: CSS - Undesired div staggering and text wrapping I have an events listing page where the date is wrapped in a div for styling purposes. If the following code is left as is, the divs become staggered. Also, if the p content after the div is longer than a few lines, it wraps around the div. Is there an easy way to prevent this without encasing each listing in a div?
HTML:

Mar 28

Lorem ipsum dolor sit amet

Mar 29

Lorem ipsum dolor sit amet

Apr 6

Lorem ipsum dolor sit amet

CSS:
.date {
float: left;
width: 42px;
height: 40px;
padding-top: 2px;
font-size: 12px;
text-align: center;
text-transform: uppercase;
background-color: #ccc;
margin-right: 10px;
}
.date span {
display: block;
font-size: 24px;
}

There are problems with a few solutions:
Adding .date + p { height: 42px } means long lines of p content will overflow.
Adding .date + p { min-height: 42px } doesn't account for the text wrapping.
Adding .date + p { margin-left: 50px } would work if I didn't have a mobile version of the site which puts the p content underneath the div.
I also made a fiddle for this.
http://jsfiddle.net/9t48g/

A: For the 'staggering' problem, add clear: left to the CSS for .date - that will make each entry drop below the preceding floated content.
(Using margin-left to solve the wrapping problem seems very sensible - surely there's a way you can use that but omit it from your mobile site?  A media query, or a class on the body?)

A: .date {
    clear:left;
}
.date + p {
    overflow:hidden;
    min-height:40px;
}

http://jsfiddle.net/aber100/qs8WC/
That should work if you can't change the html. Otherwise, I would use Nicole Sullivan's media object html/css for this layout.


text:
Q: Why is the data displayed using D3.js looks cutoff? I am using D3.js to draw some circles inside a div but for some reason no data is displayed in the bottom third of the did even though the specified size of the canvas is equivalent to the size of the of the div.
var data = d3.csv('circles.csv', function(data){
    var canvas = d3.select('.cell').append("svg");

    canvas.selectAll("circles")
            .attr("width", 300)
            .attr("height", 250)
            .data(data)
            .enter()
            .append("circle")
            .attr("cx", function(d){return (+d.x)})
            .attr("cy", function(d){return (+d.y)})
            .attr("r", function(d){return (+d.radius)})
            .attr("fill", "green");
});

A: I set a code snippet for what it looks like if no svg size specified. So if ur case is like this, the data point at the bottom may be just go out the SVG viewport area.

var canvas = d3.select('.cell').append("svg")
                // if u did not specify size
                //.attr("width", 400).attr("height", 400);

canvas.selectAll("circle").data([0])
//  .attr("width", 300)
//  .attr("height", 250)
//  .data(data)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return 150;
  })
  .attr("cy", function(d) {
    return 125;
  })
  .attr("r", function(d) {
    return 125;
  })
  .style("fill", "green");


text:
Q: Is it possible to create a php based iphone/android app with PhoneGap or Appcelerator? I want to be able to make an iphone and android app using php. I have looked at phonegap and appcelerator and it seems like only html and javascript can be used. These frameworks want to make it easy to make apps using web technologies and PHP i would argue is one of the biggest web technologies, but I'm not seeing much (if any) support. I am new, so I could be wrong on multiple levels. So please enlighten me and let me know if what I am trying to achieve is possible.
Thanks in advance.

A: Yes and no. There is no reason why you cannot have PHP running on your own server computer that returns HTML or XML that gets consumed by your mobile application, but to the best of my knowledge, there is currently no way to have PHP running on the mobile phone, itself (although even if you could, PHP is typically a server-side technology and not a client-side technology, so that would be unusual).
I should add that most mobile applications are merely thin clients for web services. You are best off first implementing the web service (using whatever language you find most appropriate), and then creating  mobile phone application that simply provides a UI for invoking the service and displaying the results.

A: Yes, HTML and PHP are seamless when used in a web setting. You can directly modify content in your HMTL with PHP and Javascript to plug into PhoneGap.
Although I have never seen the PhoneGap SDK, I'm sure you could fit PHP in there somewhere.


text:
Q: Making multidimensional slice from multidimensional array does not work as expected I'm trying to create a multidimensional slice from a multidimensional array and some strange things are happening (at least for me). I created a multidimensional array ma and made three slices s1, s2, s3 from it. The code below shows this:
package main

import (
    "fmt"
)

func main() {
    var ma [4][3]int32 = [4][3]int32{
        {10, 20, 30},
        {50, 60, 70},
        {80, 90, 100},
        {110, 120, 130},
    }

    var s1 [][3]int32 = ma[:]       // expected

    var s2 [][3]int32 = ma[:][:]    // ????

    var s3 [][]int32 = ma[0:2][0:2] // ????
}

var s1 [][3]int32 = ma[:] behaves as expected. ma[:] creates a slice of [3]int32 arrays, so we have an underlaying array with each element of type [3]int32 array. Tottally expected behaviour for me.
Problems arise when defining s1 and s2. It's not behaving as I expected. var s2 [][3]int32 = ma[:][:] gives the same result as var s1 [][3]int32 = ma[:]. I expected it to make a slice of slices, not a slice of arrays. How is it possible? How can the two give the same result?
Additionally, I expect var s3 [][]int32 = ma[0:2][0:2] to create a slice of slices as well. Instead it gives the error "cannot use ma[0:2][0:2] (value of type [][3]int32) as [][]int32 value in variable declaration compiler". So somehow, with ma[0:2][0:2] it gives the type [][3]int32, not [][]int32. How?
I hope I have explained what is not clear to me.

A: The expression ma[:][:] parses as (ma[:])[:].  The expression evaluates to a slice expression on the result of the slice expression on ma.  The outer slice expression is a noop.
Go does not have multidimensional slice expressions.


text:
Q: How change body's friction when contact with ground has begun? I making platformer character controls, something like this ->BOX2D platformer
I'm using ContactListener interface.
My problem is(friction) with these lines from code in the link ->
if(!grounded) {
    playerPhysicsFixture.setFriction(0f);
    playerSensorFixture.setFriction(0f);
} else {
    if(!Gdx.input.isKeyPressed(Keys.A) && !Gdx.input.isKeyPressed(Keys.D) && stillTime > 0.2) {
        playerPhysicsFixture.setFriction(100f);
        playerSensorFixture.setFriction(100f);
    }
    else {
        playerPhysicsFixture.setFriction(0.2f);
        playerSensorFixture.setFriction(0.2f);
    }
}

I can't figure how to change friction when feet already in touch with ground. When I change the friction in onUpdate() method of my character, the friction of conact that already is started isn't changed. Can somebody help me with this issue?

A: From b2Fixture:
// Set the coefficient of friction. This will _not_ change the friction of
// existing contacts.
void SetFriction(float32 friction);

So you are completely correct. In a recent version of Box2D they added Contact.setFriction() to accompensate for that behaviour. I'm not sure in which version of libGDX this version of Box2D was added, but at least in the nightlies of libGDX these new methods are available.
So set the friction on the Contact in your ContactListener.


text:
Q: Is it a bad idea to not use module.exports? I use browserify which enables me to include nodejs modules in my javascript files, which can then be used by the browser.
If I write my own js file and require it like so (in functions.js):
require('./_menu');

and here is that menu file:
var $ = require('jquery');

$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 100) {
        $(".js-navigation").addClass("navigation--nav-color-two");
    } else {
        $(".js-navigation").removeClass("navigation--nav-color-two");
    }
});

Then you will notice I haven't used module.exports and everything still works with no problems. If I use module.exports, then everything continues to work in the same way. Is there any point therefore in using module.exports here? Or would I just want to do it in a larger file with lots of different functions available?

A: You aren't exporting anything....so no, it's not a bad idea.
Generally, you only use module.exports if you are creating a reusable piece of code in a separate file, e.g.:
    //MyClass.js
    var MyClass = function() {

    };

    MyClass.prototype.methodOne = function() {

    };

    module.exports = MyClass;

    //main.js
    var MyClass = require('MyClass.js');
    var myInstance = new MyClass();

     myInstance.methodOne();

A: if i understand your question correctly , maybe change your code like this :
var $ = require('jquery');

module.exports  = function(window){
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 100) {
            $(".js-navigation").addClass("navigation--nav-color-two");
        } else {
            $(".js-navigation").removeClass("navigation--nav-color-two");
        }
    });
}

when you want to require it :
var scroll = require('./_menu');
scroll(window);


text:
Q: Json Records returns only one rows of records from database via django I have three records in database but json response returns only just one records.
I need to display database records via json by instantiating a variables so that instead of using database coulmn name
firstname and lastname, I can use something like fname and lname respectively when outputing json records from database.
To this effect, I have created the following code below
views.py
def read(request):
    response_data = {}
    for members in Member.objects.all():
    #members = Member.objects.all()

        response_data['fname']=members.lastname
        response_data['lname']=members.firstname
        print("successful....")
        jsondata = json.dumps([response_data])
        #jsondata = json.dumps(list([response_data]))
        return HttpResponse(jsondata, content_type='application/json')

My Issue:
My problem is that each time the code above is run, it displays only just one records from database via json.
Eg. Here
[
{"fname": "Thorr", "lname": "Odinson"}
]

My Requirements:
How do I make it to loop more and display all the three records from database via json
Eg.
 [
    {"fname": "Thorr", "lname": "Odinson"},
    {"fname": "Ann", "lname": "bell"},
    {"fname": "Jon", "lname": "Han"}
    ]

A: Your error is that you are returning a response within your loop. Instead create the response data first and the send it.
def read(request):
    response_data = [{'fname': m.lastname, 'lname': m.firstname} for m in Members.objects.all()]
    jsondata = json.dumps(response_data)
    return HttpResponse(jsondata, content_type='application/json')

Also, your logic seems to be flipping first and last names. I kept this logic to align with your code but you may want to reverse the fname and lname args.


text:
Q: Firebird database schema/data difference tool RedGate makes a tool for Microsoft SQL Server that allows you to snapshot the difference between two databases. It generates the scripts needed to update the database schema while preserving the data.
I need to find a tool like this for the Firebird database. We use Firebird in an embedded fashion, and would like to push out schema updates to remote machines with as little hassle as possible.

A: I don't know of a tool for Firebird that does exactly the same.
However, FlameRobin allows you to extract the metadata for single database objects or the complete database. It can also create scripts to recreate a certain database object including its dependencies. So you could either diff two database creation scripts and save the differences as the starting point (which may still need some changes), or you could use the recreation scripts for a single object and its dependencies.

A: This list contains a couple of comparison tools

A: As @devio suggsted, I took a look at the large list of administration tools listed on the IBPhoenix site. Of the tools on the list, the only two that generate scripts to migrate schema and data changes are XCase and Database Workbench.
Does anyone have experience with these tools? Are there others that I may have missed?

A: Embarcadero Change Manager will add support for InterBase and Firebird in the fall. Read all about it here. Change Manager includes schema archive compare and synchronizations, data compare, sync, and masking, and configuration management.

A: see IBExpert, it have a command line tool too where you can run scripts in a propietary language.  You can compare two db and get the script to update the target db, it does a great job with dependecies, like views, it drops every dependency where the view is used, alter the view and then recreate the dropped objects. This can be done in GUI too, and a lot of other nice things

A: Migration tools for Firebird on IBPhoenix site are on a separate link Contributed Downloads - Migration Tools

A: Try SchemaCrawler link

SchemaCrawler is an open-source Java
  API that makes working with database
  metadata as easy as working with plain
  old Java objects.
SchemaCrawler is also a command-line
  tool to output your database schema
  and data in a readable form. The
  output is designed to be diff-ed with
  previous versions of your database
  schema.

As it requires a JDBC driver, you would also need the following: Firebird JDBC Driver


text:
Q: Why does no three-scalar parameterization of 3d orientation exist that doesn't contain singularities? I'm reading a magazine article on 3d orientation and want to know what the mathematical issue is and where to read about it, preferably a theorem title that I can google or a topic and textbook:

It's possible to prove that no three-scalar parameterization of 3D
  orientation exists that doesn't suck, for some suitably mathematically
  rigorous definition of "suck." I haven't done this proof (I think it
  uses some pretty high-end group theory, which I haven't learned yet),
  so I can't tell you exactly how it works, but I believe the gist of
  the proof is that no minimal parameterization exists that doesn't
  contain singularities. These singularities can take different forms —
  depending on how you allocate the three degrees of freedom — but
  according to the math, it's impossible to get rid of them.


text:
Q: Is the Royal Mail website secure? In the UK our postal service drops cards through our mailbox when there is a fee to pay on a item of mail. On this card it gives us a URL to visit to pay the fee, after following the links you get to this site:
http://www.royalmail.com/portal/rm/esurcharge

In the top right corner of the page it says "This page is secure", in fact this link goes to a FAQ which includes the following text:

All details are taken over a secure
  network and held in compliance with
  all required UK security and data
  protection standards.  To help keep
  your details secure, please do not
  share your password with anyone.

Am I missing something:

*

*The site doesn't use HTTPS (SSL).

*Adding the "s" after http re-directs back to the non-SSL site.

*There appears to be nothing in either FireFox or IE that indicates it has even made an attempt to use SSL.

*Starting from royalmail.com and working my way through I still get a non-SSL site.

I don't intend to put my credit card details in there, however I am slightly at a loss as why such a large company would mess up in this way. I can't quite believe it, could this be something else?
EDIT: You can register on the site (which is secure), and enter credit/debit card details which is also secure. However on most of the secure pages the "This page is secure" link is missing... go figure.

A: Well, you typically don't use your credit card details until you log in. The log in process is indeed secure with AES-256 encryption, and I assume anything past that is too.

A: FYI some sites in the past (Yahoo from memory) have used Javascript to encrypt the form details before transmitting them over http. Apparently it increases the load on the server to use https. I don't know if anyone still uses this technique however.


text:
Q: Duplicate nodes in umbraco content tree Currently i am working on a website, which is made in Umbraco cms. I am facing a problem of duplicate nodes creation. If i create a node and publish that node, then a new duplicate node gets created. This duplicate node is visible after i reload all nodes. It is a multilingual website. I am attaching an image for more clear explanation.

A: If you have NOT setup multiple root nodes to handle multiple languages you should remove this file:   AppCode/CopyDocumentToRelatedOnPublish.cs from the project per the package instructions:
http://our.umbraco.org/projects/website-utilities/multi-language-tools
That package will create duplicate content nodes.


text:
Q: TFS - issue with go online , once worked in offline mode We are working in Visual Studio with TFS.
We are facing one issue in it. if we work offline for, and then go online, then rather than showing conflicts on files which have been changes, it asks to checkout all files or it will show confilit in all files.
Can any body have idea if this behaviour. How to resolve it??


text:
Q: Does C++14 and above allow default parameters for Lambda functions? If so how? Does lambda functions changes to accept default arguments in c++ 14?
This example doesn't work on C++ 11:
int main() {

    int i = 34;
    auto RectSurf = [i](int length = 0, int width = 0){ return length * width;};
    cout << RectSurf(10) << endl;

    std::cout << std::endl;
}

But it works fine on C++ 14 and above. So is it correct or not? Because C++ prime 5ed said that: "Passing Arguments to a Lambda
As with an ordinary function call, the arguments in a call to a lambda are used to initialize the lambda's parameters. As usual, the argument and parameter types must match. Unlike ordinary functions, a lambda may not have default arguments (§ 6.5.1, p. 236). Therefore, a call to a lambda always has as many arguments as the lambda has parameters. Once the parameters are initialized, the function body executes.
As an example of a lambda that takes arguments, we can write a lambda that behaves like our isShorter function:" From C++ Prime 5ed.
But the same code on C++14 and above works fine! But Also I've read here in S.O That lambda functions can have a default parameter on condition that no variable has been captured in Lambda's capture list.

A: Default Arguments in Lambda Expressions were explicitly added to the Standard with C++14, and were not permitted in C++11. You can see this if you run the code against two different compiler flags in GCC, one for C++11, one for C++14, and compile using the -Wpedantic flag, you'll see that when compiled for C++11, the compiler issues a warning (GCC still supports it, but tells you it's not standard-compliant) whereas in C++14, there's no warning.
So yes. In C++14 and later, Default Arguments in a Lambda Expression are valid.


text:
Q: preventing user from entering certain characters while allowing others using jquery Please help me with this problem... oddly enough it works up until:
if (key < 48 || key > 57){ //if it is not a number ascii code
        //Prevent default action, which is inserting character
        if (e.preventDefault) e.preventDefault();
            e.returnValue = false;
    }

Which prevents the user from entering any value that isn't a number. The code following that is attempting to allow the user to use characters such as tab and delete. For some reason it isnt working and it seems like it should logically..
Please Help or provide me with a more up to date answer/good guide on how to achieve this..
Thanks,

<title>Registration</title>
<link href="style.css" rel="stylesheet" type="text/css">

<form action="registration.php" method="post" name = "register" >

Register

<button style = "width:100px;float:right;display:inlineblock;"onclick="goBack()">Go Back</button>

Please fill in this form to create an account.

    Username:
    <input type="text" placeholder="Username" name="username" pattern="[^-,]+" onKeyDown="ValidateName()" >

    First Name:
    <input type="text" placeholder="Enter First Name"  pattern="[^-,]+" name="fname">

    Last Name:
    <input type="text" placeholder="Ender Last Name" pattern="[^-,]+" name="lname">

    Date of Birth
    <input type="date" placeholder="" name="dob" pattern="[^-,]+">

    In Game Name:
    <input type="text" placeholder="Enter In Game Name" name="ingame" pattern="[^-,]+">

    Email
    <input type="text" placeholder="Enter Email" name="email" pattern="[^-,]+">

    Password
    <input type="password" placeholder="Enter Password" name="pw" pattern="[^-,]+">

    Confirm Password
    <input type="password" placeholder="Repeat Password" name="confpw" pattern="[^-,]+">

By creating an account you agree to our Terms & Privacy.

    <button onclick="" name="register" type="submit" class="register">Register</button>

  <div

Already have an account? Sign in (unfinished).

</form>

© Copyright 2019 Daniel Violante except where noted
Privacy Policy | Terms of Service
Endless Online © Copyright Vult-r Studios

A:

$("input").on("input", function(){
 $(this).val($(this).val().replace(/[^0-9]/g, ''));
})
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

 <input type="text">

This will replace non-numeric characters with nothing.
How this works
Add a event listener to input area. This will be triggered when user makes an input, including paste.
When this is triggered, function will get the value from target input, and replace with user input, but only numeric characters. Any characters which is not numeric will be deleted.


text:
Q: Shouldn't internal input resistance of a transistor be almost zero? I am absolute beginner in electronics and the whole transistor thing is not looking very intuitive to me. Suppose this problem, in active region input terminal voltage almost remains constant with change in input current for a transistor. So, in terms of h-parameters, shouldn't \$h_i\$ (i.e. short circuit input impedance) be almost zero instead of a significant (typical 600-900 ohm) value?

A:
So, in terms of h-parameters, shouldn't \$h_{i}\$ be almost zero

Consider that the input to a BJT (in a common emitter configuration) is basically just driving a forward biased diode. Here's what a 1N4148 looks like just as an example. BJTs will be a little different in terms of collector voltage influences but well-within the same ball-park: -

So if you looked at the slope of the graph you could calculate dynamic input resistance versus forward voltage. At 0.8 volts the forward current is approximately 10 mA. At maybe 0.75 volts in, the current is about 8 mA. This means the dynamic input impedance is (0.8 - 0.75)/0.002 = 25 ohms.
At about 0.6 volts, the forward current is about 1 mA and if the voltage reduced to 0.55 volts, the current would be about 0.8 mA. Thus the dynamic resistance is now about 250 ohms.

A: The resistance you're thinking of, called dynamic resistance or small signal resistance or differential resistance is the derivative \$dV/dI\$.
For a diode (which is what the base of a BJT looks like), \$V = kT/q \space\text{ln}(I/I_s)\$, so \$dV/dI = kT/q \cdot 1/I\$
kT/q is about 25 mV so if the base current is 10 microamps, dV/dI = 2500 ohms.


text:
Q: android third party app I am new to android. I want to install an unreleased third party android apk file into my device  from a windows pc or mac osx machine without having to install Android SDK and going the whole nine yards. Can it be done? Appreciate any help/pointers.

A: Easily. copy the apk to sdcard, then run some file manager installed on your phone(for example ASTRO) and launch the apk from it.

A: You will also need to a File browser program such as "ASTRO" to locate the APK file and execute.  In additio, you will also need to enable 3rd party applications within the settings of the phone.  To enable 3rd party apps, just tap the HOME key then menu key, and select Settings.  Tap applications from the settings list and check the box labeled "Unknown Sources".  This will allow you to install apk files from "ASTRO" or any other file browsing program that you installed from the app store.  The installation will prform the same as it would from the app store.

A: Additionally, you can use the "sideload wonder machine" to install apps in the manner of the sdk without installing the sdk.  On a phone without the 3rd party apps setting, only this mechanism is available.


text:
Q: What is the difference between Fix, Mu and Nu in Ed Kmett's recursion scheme package In Ed Kmett's recursion-scheme package, there are three declarations:
newtype Fix f = Fix (f (Fix f))

newtype Mu f = Mu (forall a. (f a -> a) -> a)

data Nu f where
  Nu :: (a -> f a) -> a -> Nu f

What is the difference between those three data types?

A: Mu represents a recursive type as its fold, and Nu represents it as its unfold. In Haskell, these are isomorphic, and are different ways to represent the same type. If you pretend that Haskell doesn't have arbitrary recursion, the distinction between these types becomes more interesting: Mu f is the least (initial) fixed point of f, and Nu f is its greatest (terminal) fixed point.
A fixed point of f is a type T an isomorphism between T and f T, i.e. a pair of inverse functions in :: f T -> T, out :: T -> f T. The type Fix just uses Haskell's built-in type recursion to declare the isomorphism directly. But you can implement in/out for both Mu and Nu.
For a concrete example, pretend for a moment that you can't write recursive values. The inhabitants of Mu Maybe , i.e. values :: forall r. (Maybe r -> r) -> r, are the naturals, {0, 1, 2, ...}; the inhabitants of Nu Maybe, i.e. values :: exists x. (x, x -> Maybe x), are the conaturals {0, 1, 2, ..., ∞}. Think about the possible values of these types to see why Nu Maybe has an extra inhabitant.
If you want to get some intuition for these types, it can be a fun exercise to implement the following without recursion (roughly in increasing order of difficulty):

*

*zeroMu :: Mu Maybe, succMu :: Mu Maybe -> Mu Maybe

*zeroNu :: Nu Maybe, succNu :: Nu Maybe -> Nu Maybe, inftyNu :: Nu Maybe

*muTofix :: Mu f -> Fix f, fixToNu :: Fix f -> Nu f

*inMu :: f (Mu f) -> Mu f, outMu :: Mu f -> f (Mu f)

*inNu :: f (Nu f) -> Nu f, outNu :: Nu f -> f (Nu f)
You can also try to implement these, but they require recursion:

*

*nuToFix :: Nu f -> Fix f, fixToMu :: Fix f -> Mu f
Mu f is the least fixed point, and Nu f is the greatest, so writing a function :: Mu f -> Nu f is very easy, but writing a function :: Nu f -> Mu f is hard; it's like swimming against the current.
(At one point I was meaning to write a more detailed explanation of these types, but it might be a little too long for this format.)


text:
Q: filter out TreeId if the area equals to zero in r I am trying to remove treeId if the area is equal to zero. When i print the treeID i can see the area been zero but how can i filter out this point. I cannot find the attribute area anywhere in the header.
> las_x
class        : LAS (v1.4 format 6)
memory       : 5.9 Kb
extent       : 368538.2, 368538.3, 5807601, 5807601 (xmin, xmax, ymin, ymax)
coord. ref.  : WGS 84 / UTM zone 33N
area         : 0 m²
points       : 3  points
density      : 0 points/m²

A: It is computed on the-fly when printed. You can use st_area() or area() to get the area. Be careful: 0 m² is likely a rounded value, maybe the actual value is 0.0001 or any very small number.


text:
Q: AngularJS and "this" alias I'm tasked with updating another person's AngularJS (version 1) code.  In a Javascript file, for the app.directive() section's controller function I see a "this" alias:
   app.directive("myDirective", function() {
    return {
        templateUrl: contextPath + "myPath/myDirective.html",
        controllerAs: 'myDirectiveCtrl',
        controller: function($scope, $element, $http, $rootScope) {
            var ctrl = this;
            ...

I understand that "ctrl" is a way for the functions to reliably refer to "this" even after the constructor has completed.  However, later on I see this code:
this.someFunction = function() {
    this.firstProperty = true;
    this.secondProperty = true;
    ...
    ctrl.thirdProperty = [];
    ...

In my understanding the "this." code would be wrong as the function can't guarantee the accuracy of "this.", so I'm tempted to "fix" the code so that all of these properties use "ctrl."
Is my reasoning right?
Thanks,
Jerome.


text:
Q: How to convert SinkRecord to JSON string? Imagine myAPICreate requires a JSON string.
public void put(Collection<SinkRecord> collection) {
        for (SinkRecord record : collection) {
            JSONObject recordJson = toJSON(record.value());
            String recordJsonString = recordJson.toString();

            myAPICreate(recordJsonString);
        }
    }

toJSON is a helper I have defined which just takes the record and returns a JSONObject.
JSONObject json = new JSONObject()
  .put("a", record.getString("a"))
  .put("b", record.getString("b"))
  .put("c", record.getString("c"));

I feel like I might be doing a lot of redundant work here. Is it necessary to have the code in put convert it to JSON or is there a way to use the converters so that record already comes in as JSON or a JSON string? Then I can just pass myAPICreate(record.value().toString()) without having to manually do it?

A: When you create a SinkRecord, you have a key & value schema w/ a key and value Object. Those objects should be Struct instances that must be created with the matching Schema
In the Connector configuration, you would then use JSONConverter (or other converter) to get the serialized output


text:
Q: SharePoint Online Restore Files from Drop Off Library Our retention policy in SharePoint misfired and moved 1000's of files from different libraries into the drop of library.
Is there any way to restore these files back to their original libraries.
We have no clue where to start, any hint or guidance will be much appreciated.

A: Even if there was a golden ticket to give you a seemingly instant restore of the documents, I wouldn't jump right into that. Instead,
Consult Microsoft's support.
Depending on your subscription, you likely are able to get the best available support from them. Also, as we are in the context of SharePoint Online, due to the progression of continuous improvement by Microsoft, I'd rely on a word signed by them in the last hand.
The following is a reference for a guidance of addressing the issue with MS, available in an article of an even worse situation. (How to recover missing, deleted or corrupted items in SharePoint Online and OneDrive for Business):

When you open a request, provide as much additional information as
  possible to describe your issue. For more information, see Contact
  Office 365 for business support. Include the following information in
  your request:

*

*The full URL for the affected site collection or
  library. For example:
  https://contoso.sharepoint.com/sites/<SiteCollectionName>/Shared%20Documents

*The names of several of the affected items.

*For files, include the
  file name extension.

*The date and time when you think the item was
  last in an uncorrupted state.

Refer to the Contact Office 365 for business support - Admin Help article when contacting Microsoft.


text:
Q: Remove duplicate comma separated values from mysql How can I remove duplicate comma separated values returned from database?
I have it in this format:
XL,L,XXL
XL
M,L,XL
L,XL,M

What I tried:
$new_str = array_unique(array_map('trim', explode(',', $srow['size'])));
$string = implode(',', $new_str);

But I still get duplicate values. Is there a better way of doing it?

A: Since your data is stored as comma separated values in the database, you will need to aggregate all the values as you loop over fetching from the database and then remove duplicates e.g.
while ($srow = $result->fetch_assoc()) {
    $sizes[] = $srow['size'];
    // do other stuff with fetched data
    // ...
}
$sizes = array_unique(array_map('trim', explode(',', implode(',', $sizes))));
sort($sizes);
$string = implode(',', $sizes);

Demo on 3v4l.org (with simulated database fetch)


text:
Q: SecureCRT: vim not using maximum terminal window size No matter what the size of the SecureCRT window, vim's screen area remains constant. If I maximize SecureCRT, vim continues to only occupy a portion of the terminal.
I have fiddled with the obvious setting choices but have been unable to get vim to adjust to the width of the terminal window.
It DOES work when using ConEmu.
Any ideas?


text:
Q: Databricks SQL syntax for previous six months in where statement I'm trying to figure out how to look for data in the last six months in the where statement of a SQL query in Databricks, but I'm having a lot of issues with the syntax.
Right now I have:
Select * from table
where datediff(add_months(date_column, -6), date_column) = 1

The query doesn't throw an error, but returns no results.

A: I think you're expecting the wrong thing from datediff. Datediff tells you the number of days between two dates. In your case, you're comparing your date_column to your date_column - 6 months. That's always going to be 6 months or ~180 days.
Try this.
WHERE date_column > DATEADD(MONTH, -6, CURRENT_DATE())

AKA, where your date column is greater than the current date minus 6 months.


text:
Q: How can I find the probability of moving an object on a board, and it landing at the origin after X moves? Imagine $5~ by~ 5$ squares. Your character piece starts in the very middle $(0,0)$.
The rules allow the character to only move up, down, left, or right, and also not to move at all ($5$ total options).
How can I figure the probability of returning to $(0,0)$ after $X$ attempts?
This is assuming I have equal probability of choosing one of the $5$ possible moves.
What is the probability that the character will be touching a wall after $X$ tries?
(If the character is touching the east wall and is told to move east, it will stay in place)
Trying to illustrate this in Java, so formulas will suffice for an answer.

A: Probability For an N x N square:
There exist 5^x different paths can be taken:
A walk consists of of a word of up's (1), down's (-1), left's (-i), rights (i) and waits (0) such that that the sum of the elements in the word = 0 and the word is of length X, (has x elements)
Note that a walk can be broken into two parts: an actionable part and wait part. Actionable parts must have even length, as every decision to take a non-waiting move must eventually be undone at a later stage. The wait part is all the instances when waiting did occurred.
We consider the first case where X is odd:
We can have actionable parts of length  0, 2, 4, 6 ... X -1 respectively:
Each of these actionable parts has a total of 2 * rC2 * 2 * (r-2)C2 * 2 * (r - 4)C2 ... different arrangements which creates r! ways to arrange an actionable part of length r.
Therefore we know there exist 0! 2! 4! 6! ... (x - 1)! actionable parts correspondingly.
This can also be derived as: for an even integer I have r spots for the first move, r - 1 for the next unmove, etc...
Now for each of these actionable parts we must compute the number of ways to take its elements and then place on the x possible locations. That of course can be accomplished in x!/(x-r)! ways for each of the r! possible walks therefore we have:
x!0!/(x-0)! + x!2!/(x-2)! + x!4!/(x-4)! ...+ x!(x-1)!/1! possible ways to arrange actionable parts. The factorial function + while loop + a factorial function can quickly calculate this. For the probability we will denote the above sum as S(x). Simply compute S(x)/5^x to be done.
In the case of X being even, actionable parts can be computed as being either:
0, 2, 4 ... X moves and therefore there exist:
x!0!/(x-2)! + x!2!(x-2)! ... x!x!/0! possible ways to arrange the actionable parts.
Pseudo-code style:
Make a Factorial Method, we'll call it fact(x)
if x is odd then x = x - 1:
else x = x
start a while loop with index at 0
while index <= x - 1:
sum = sum + x!i!/(x-i)!
finally print sum/5^x.
I'm sure this can be optimized. I don't know how atm.

A: A general approach may encompass the usage of Markov-chains which may be used to model the random walk you are talking about. In your case of a 5x5 board, the matrix $\mathbf{A}$ of this model will be from $\mathbb{R}^{25,25}$ as there are 25 states.
When you fill this matrix with all the transition probabilities (each row will have from 3 to 5) non-zero elements (3 for the corner elements, 5 for the elements in the middle).
You can get the probability distribution of the states after one move $p'$ given the probability distribution before this move ($p$) by following formula: $p' = \mathbf{A}p$. As you are interested in the probability of getting back to the $i$-th state starting at the same state after $x$ steps, you can do following calculation: $p' = \mathbf{A}^xp$, where the vector $p$ has all elements zero except the $i$-th one. The probability you are looking for is the $i$-th element of the vector $p'$.
As for the case of touching the wall, you will just focus on other elements in the $p'$ vector.


text:
Q: Template compilation error when executing flush Whenever I execute the ExtentReport.flush() method I get en exception regarding references.
I have downloaded the package using NuGet and I don't have issues compiling the code.
In another test project, it works fine. I copied the test code to the current project and nothing works.

RazorEngine.Templating.TemplateCompilationException HResult=0x80131500
    Message=Errors while compiling a Template.
Please try the following to solve the situation:

*

*If the problem is about missing/invalid references or multiple defines either try to load
  the missing references manually (in the compiling appdomain!) or
  Specify your references manually by providing your own IReferenceResolver implementation.
  See https://antaris.github.io/RazorEngine/ReferenceResolver.html for details.
  Currently all references have to be available as files!

*

*If you get 'class' does not contain a definition for 'member':
  try another modelType (for example 'null' to make the model dynamic).
  NOTE: You CANNOT use typeof(dynamic) to make the model dynamic!
  Or try to use static instead of anonymous/dynamic types.
  More details about the error:

*error: (15, 11) The type or namespace name 'AventStack' could not be found (are you missing a using directive or an assembly reference?)

*

*error: (16, 11) The type or namespace name 'AventStack' could not be found (are you missing a using directive or an assembly reference?)

*error: (17, 11) The type or namespace name 'RazorEngine' could not be found (are you missing a using directive or an assembly reference?)

*error: (18, 11) The type or namespace name 'RazorEngine' could not be found (are you missing a using directive or an assembly reference?)

*error: (21, 65) The type or namespace name 'RazorEngine' could not be found (are you missing a using directive or an assembly reference?)

*error: (21, 101) The type or namespace name 'AventStack' could not be found (are you missing a using directive or an assembly

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System.Configuration;
using System.IO;
using System.Diagnostics;
using AutomationClientProduct;
using AutomationReporter;
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;

static class Program
{

    [STAThread]
    static void Main(string[] args)
    {
        ExtentHtmlReporter reporter = new
        ExtentHtmlReporter(@"C:\TestResults\result.html");
        ExtentReports reports = new ExtentReports();
        reports.AttachReporter(reporter);
        var logger = reports.CreateTest("New test");
        logger.Pass("Success");
        logger.Info("Succeeded test");
        logger = reports.CreateTest("Second Test");
        logger.Fail("test failed");
        reports.Flush();
}


text:
Q: Ansible commands on docker containers? Upto now i had setup my ansible-playbook commands running on AWS EC2 instances.
can i run regular ansible commands like (linefile, apt, pip, etc) on container?
can i add my container-ip to hosts file in container-group and then does the same code works, here if i chanage my main.yml file that has
hosts: ec2-group

to
hosts:contaniers-group

does all commands work?
i am bit  beginner into this..please do confirm me i am actually thinking of making docker-compose files from scratch, and run docker-compose commands using ansible.

A: You can, but it's not really how Docker is designed to be used.
A Docker container is usually a wrapper around a single process.  In the standard setup you create an image that has that application built and packaged, and you can just run it without any further setup.  It's not usually interesting to run a bare Linux distribution container (which won't have an application installed) or to run an interactive shell as the main container process.  Tutorials like Docker's Build and run your image walk through this sequence.
A corollary to this is that containers don't usually have any local state.  In the best case any state a container needs is in an external database; if you can't do that then you store local state in a volume that outlives the container.
Finally, it's extremely routine to delete and recreate containers.  You need to do this to change some common options; in a cluster environment like Kubernetes this can happen outside your control.  When this happens the new container will restart running its default setup, and it won't know about any manual changes the previous container might have had.
So you don't usually want to try to install software directly in a running container, since that will get lost as soon as the container exits.  You can, in principle, get a shell in a container (via docker exec) but this is more of a debugging tool than an administration tool.  You could make the only process a container runs be an ssh daemon, but anything you start this way will get lost as soon as the container exits (and I've never seen a recipe that correctly and securely sets up credentials to access it).
I'd recommend learning the standard Dockerfile system and running self-contained Docker images over trying to adapt Ansible to this rather different environment.


text:
Q: Pass session expression language variable in ELFileBody I encounter an issue using Gatling EL in ELFileBody.
I have the following exec :
exec(myFunction("${myEmail}", otherParameters))

and the function :
def myFunction((email: String) = {
     exec((s: Session) => s.set("email", email))
     .exec(http("MyFunction")
                        .put("/myUrl")
                        .headers(Headers.basic_headers_json)
             .body(ElFileBody("LinkToMyJsonFile"))
                        .asJson
                        .check(status.is(200)))
}

my myEmail is set in session. Yet, when the exec runs myFunction, the variable is replaced in the json by "${myEmail}" instead of beeing evaluated.
Have you an idea how I can resolve it be able to pass myEmail session variable in the exec through myFunction?
Thanks a lot in advance
JF

A: your function takes a string and you are then putting that string into a session variable - so when you pass in "${myEmail}" gatling is putting that string literal into the session var. So when gatling does the substitution in the ELFile body it's using exactly what you've specified.
I'm assuming you already have the email you want in the ${myEmail} session var - why not just edit the file to use ${myEmail} in place of "${email}"?
a more idiomatic approach would be to pass in an Expression[String], validate it and set the result into the ${email} var
def myFunction((email: Expression[String]) = {
 exec((s: Session) => email.apply(s) match {
    case Success(address) => s.set("email", address)
    case Failure(error) => {
        println(s"There was an error: $error")
        s
    }
}
...

This will retrieve the value of ${myEmail} if there is one or just the string literal if that's the case, and put it in the ${email} var. The error would be thrown if you provided a session var for which there was no value


text:
Q: Django CMS icon in menu I am trying to show my uploaded icon on navigation but i guess, i am going through a wrong way.
this is my model that extended
class IconExtension(PageExtension):
    image = models.ImageField(upload_to='icons')

extension_pool.register(IconExtension)

and this is my cms_toolbars.py file
@toolbar_pool.register
class IconExtensionToolbar(ExtensionToolbar):
    # defines the model for the current toolbar
    model = IconExtension

    def populate(self):
        # setup the extension toolbar with permissions and sanity checks
        current_page_menu = self._setup_extension_toolbar()

        # if it's all ok
        if current_page_menu:
            # retrieves the instance of the current extension (if any) and the toolbar item URL
            page_extension, url = self.get_page_extension_admin()
            if url:
                # adds a toolbar item in position 0 (at the top of the menu)
                current_page_menu.add_modal_item(_('Page Icon'), url=url,
                    disabled=not self.toolbar.edit_mode_active, position=0)

and this is my menu.html file
{% load menu_tags %}

{% for child in children %}

    {{ child.get_menu_title }}

    {% if child.children %}

        {% show_menu from_level to_level extra_inactive extra_active template "" "" child %}

    {% endif %}

{% endfor %}

I am not getting why it is not working, I don't see any error even I don't see any image url here, my everything is working fine, only going through problem showing menu icon, can anyone help me in this case?

A: It looks like you're just missing the reference to the object from the page, you're going straight to it's attribute.
I've got a very similar setup with images associated with pages;
class PageImage(PageExtension):
    """ Add images to pages """
    image = models.FileField(
        verbose_name=_("Image"),
        upload_to=upload_to('page_images')
    )

Which in my templates becomes;
{% if request.current_page.pageimage.image %}
    {{ request.current_page.pageimage.image.url }}
{% endif %}

So in your example, if you did this in a template you'd do;
{% if request.current_page.iconextension %}

{% endif %}

Checking if the extension exists is important to avoid attribute errors etc.
In a menu, the child isn't a Page object though, it's a NavigationNode from the menu system. So it doesn't have your extension.
I think the proper solution to this is to setup a navigation Modifier. The docs for this are here; http://docs.django-cms.org/en/latest/how_to/menus.html#navigation-modifiers
Alternatively you could setup a template tag which you pass your child which could then use the reverse_id attribute to query the database for the Page that corresponds to, and return the iconextension of that page. I've used this method before.

A: Based on @markwalker_ answer. I did the job successfully in 3 Steps
Step 1 - Add an FontAwesomeField in a page Extension :
https://docs.django-cms.org/en/latest/how_to/extending_page_title.html
For the record here is my code :
In models.py
from django.db import models

# Create your models here.
from cms.extensions import PageExtension
from cms.extensions.extension_pool import extension_pool

class IconExtension(PageExtension):
    image = models.ImageField(upload_to='icons', null=True, blank=True)
    fontawesomeicon = models.CharField(max_length=100, null=True, blank=True)

extension_pool.register(IconExtension)

In admin.py
from django.contrib import admin
from cms.extensions import PageExtensionAdmin

from .models import IconExtension

class IconExtensionAdmin(PageExtensionAdmin):
    pass

admin.site.register(IconExtension, IconExtensionAdmin)

In cms_toolbars.py
from cms.toolbar_pool import toolbar_pool
from cms.extensions.toolbar import ExtensionToolbar
from django.utils.translation import gettext_lazy as _
from .models import IconExtension

@toolbar_pool.register
class IconExtensionToolbar(ExtensionToolbar):
    # defines the model for the current toolbar
    model = IconExtension

    def populate(self):
        # setup the extension toolbar with permissions and sanity checks
        current_page_menu = self._setup_extension_toolbar()

        # if it's all ok
        if current_page_menu:
            # retrieves the instance of the current extension (if any) and the toolbar item URL
            page_extension, url = self.get_page_extension_admin()
            if url:
                # adds a toolbar item in position 0 (at the top of the menu)
                current_page_menu.add_modal_item(_('Page Icon'), url=url,
                    disabled=not self.toolbar.edit_mode_active, position=0)

Step 2 - Implementing Navigation Modifier
https://docs.django-cms.org/en/latest/how_to/menus.html#navigation-modifiers
In cms_menu.py
from menus.base import Modifier
from menus.menu_pool import menu_pool

from cms.models import Page

class AddIconModifier(Modifier):
    """
    This modifier makes the changed_by attribute of a page
    accessible for the menu system.
    """

    def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb):
        if breadcrumb:
            return nodes
        # Only on last iteration (Voir : https://docs.django-cms.org/en/latest/how_to/menus.html#navigation-modifiers)
        if not post_cut:
            return nodes
        # only consider nodes that refer to cms pages
        # and put them in a dict for efficient access
        page_nodes = {n.id: n for n in nodes if n.attr["is_page"]}
        # retrieve the relevent pages
        pages = Page.objects.filter(id__in=page_nodes.keys())
        # loop over all relevant pages
        for page in pages:
            # take the node referring to the page
            node = page_nodes[page.id]
            if hasattr(page, 'iconextension') and hasattr(page.iconextension ,'fontawesomeicon'):
                node.attr["faicon"] = page.iconextension.fontawesomeicon
            else:
                node.attr["faicon"] = 'fa-arrow-circle-right'

        return nodes

menu_pool.register_modifier(AddIconModifier)

Step 3 - Specific navigation template
In my main template :
{% show_menu 0 100 100 100 "partials/navigation.html" %}

In my navigation template (navigation.html)
{% load cms_tags menu_tags cache %}

{% for child in children %}

        {{ child.get_menu_title }}
        {% if child.children %}

                {% show_menu from_level to_level extra_inactive extra_active template '' '' child %}

        {% endif %}

{% endfor %}


text:
Q: Why does Ubuntu Music Lens display only a few songs and albums? The Ubuntu Music Lens displays just a few songs and albums of my music collections. For example the lens displays just 44 albums but it should be 200 albums.
If I type the name of the song or album in the search bar then the music lens displays the song, but not in the overview.
I edited the ID3 Tags of the songs with Banshee, Rhythmbox or EasyTag but it had no effect.
What could I do, that the lens displays all songs and albums?

A: For Ubuntu 12.04, in particular, the performance of the dash was such that it did not handle displaying hundreds or even thousands of results very well. In addition, it was felt that a user would find it cumbersome to parse hundreds of results visually when it was easier to type terms to narrow down the search, so limiting the number of results displayed was a good trade off.
As such, there was a limit set on the number of results a scope would return to the dash to be displayed (100 when there is no search, 50 for a search in the music lens and 20 for a search from the home lens).  Presumably, in this case, the first 100 songs it finds are spread between 44 albums.
The music lens is written in vala. It should be possible to edit the source and compile  and install a new version with much larger limits.  The limits for the Rhythmbox scope are defined here: http://bazaar.launchpad.net/~unity-team/unity-lens-music/6.0/view/head:/src/rhythmbox-scope.vala#L48


text:
Q: How to add onclick="return false" in php I use javascript code to disable click on link in php

onclick="return false"

but not working
What I have tried so far:
$data .= ''.".$row2->model.".'	';

$data .= ''.".$row2->model.".'	';

A: option 1
Click Here

option 2

option 3 make sure return false is in double quote
click


text:
Q: Differential equation with constant coefficients When we solve differential equation with constant coeffiecients we find out the auxiliary equation, then its roots and proceed further.
But my question is
When for example we have an equation of the type $ay'' +by=0$ auxiliary equation is $ar^2 +b=0$ but what if the differential equation is of the form
$ay''+ by+c=0$ , then how do we write the auxiliary equation

A: A homogenous,  second order differential equation with constant coefficients is of the form $ay'' + by' + cy = 0$, and are solved by solving the characteristic equation and plugging the solutions into $c_1 e^{r_1t} + c_2 e^{r_2t}$ (the formula is a bit different if you have a repeated root). Now, nonhomogenous equations are,  in general,  much more difficult to solve,  even with constant coefficients.  Here is a link to Paul's Notes that goes into the subject if you're interested:
http://tutorial.math.lamar.edu/Classes/DE/NonhomogeneousDE.aspx
Here you'll find that there IS a link between the two,  but you'll have to find a particular solution first.  Since you have a constant on the right this should be fairly trivial.
Since I have some time on my hands,  here is an example. Say we want to solve $y'' - 5y = 2$. We first see that the associated  characteristic equation is $r^2 - 5 + 0 \implies r=\pm \sqrt{5}$ making our complementary solution $c_1 e^{t\sqrt{5}} + c_2 e^{-t\sqrt{5}}$
We now need a particular solution. Since we have a constant on the right side of our original equation our guess will be a constant,  say $A$.  We now plug this into the equation to get $A'' - 5A = 2 \implies 5A = -2 \implies A=-\frac{2}{5}$ (note that the nth derivative of a constant is a zero)
Now that we have found all this,  we use the the fact that the solution set to a non-homogenous equation of this type is the sum of its complementary solution and a particular solution,  which in this case is simply $c_1 e^{t\sqrt{5}} + c_2 e^{-t\sqrt{5}} -\frac{2}{5}$.  At this point you can plug in any initial values,  boundary conditions,  etc.


text:
Q: How does moshi access Private fields? I am having following model class:
class Recipe {

  @Json(name = "name") private String mName;

  public String getName() {
    return mName;
  }
}

and I am parsing Json using following code:
private static final JsonAdapter<List<Recipe>> recipeListAdapter = moshi.adapter(
      Types.newParameterizedType(List.class, Recipe.class));

Flowable.fromCallable(() -> {
      Request request = new Request.Builder()
          .url(URL)
          .build();
      try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
          throw new IOException("Unexpected code " + response);
        }
        return recipeListAdapter.fromJson(response.body().source());
      }
    })
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.
        .subscribe(recipes -> {
          Log.i(TAG, recipes.get(0).getName() + "");
        }, Throwable::printStackTrace);

So here I am able to set private field even if it is private and there is no setter either.
How is this possible?
How is moshi able to set private field?


text:
Q: How can I get phone serial number (IMEI) I want to get phone serial number by programming to registration configuration of my application and number of users and phones that my app has been installed on them.
Can I get that?
and can I get phone model that my app has been installed on them?

A: public String getIMEI(Context context){

    TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
    String imei = mngr.getDeviceId();
    return imei;

}

A: pls refer this
https://stackoverflow.com/a/1972404/951045
 TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  mngr.getDeviceId();

add READ_PHONE_STATE permission to AndroidManifest.xml

A: Here is the code:-
telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

    deviceId = telephonyManager.getDeviceId();
    Log.d(TAG, "getDeviceId() " + deviceId);

    phoneType = telephonyManager.getPhoneType();
    Log.d(TAG, "getPhoneType () " + phoneType);

A: try this
 final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

  String deviceid = tm.getDeviceId();

A: Use below code for IMEI:
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();


text:
Q: Minimal files needed to deploy ASP.NET App to the Web Server I have a ASP.NET project. When compiling this project it will create a DLL.
Let's assume this project does not need any other dlls(references).
I want to know what are the minimal files needed.
I know VB code behind files will be part of this dll and are not needed on server
So question is:
1: Is Web.Config file needed?
2: Is Global.asax needed?
3: Are aspx files needed?

If all of above needed then can't we simply copy them to the we server and don't publish the application?

A: Yes, you can xcopy your web.config, global.asax and all .aspx files to the server, which is essentially what the Publish command in Visual Studio does.
There is also the option to create a new Profile when doing a Publish via Visual Studio and have the files published to a directory so you can see what would have been pushed to an actual server before actually doing it. I use this as part of our deployment process to have a copy of the code that gets deployed to each of our testing environments.