text:
Q: Centering a button on a background image I'm trying to display a "link button" on top of a div (ccontainer) with a background image. It works with a position:absolute but with a position:relative it disappears. I'm wondering why that is as I would like the button to be relative to the div.
My other question is how can I make my "scontent" div come after (below) my "contnent" div. I made my background image transparent and can see the "scontent" grey background color overlapping from behind.

body
{
 margin: 0;
 padding: 0;
 background-color: #999;
}

.header
{
 z-index:3;
 position:fixed;
 background-color:#2B193E;
 border:0px solid #ffffff;
 height:70px;
 left:0;
 width:100%;
 top:0;
 /*Opacity start*/
    -ms-filter:             "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=80);
    -moz-opacity: 0.80;
    -khtml-opacity: 0.8;
    opacity: 0.7;
    /*Opacity end*/
}

.hcontainer
{
 position: relative;
 width:100%;
}

.headingtext
{
 color: #ffffff;
 text-align: center;
 width: 100%;
}

.content
{
 z-index:1;
 position: absolute;
 top:0;
 left:0;
 height: 100%;
 width: 100%;
 padding:0px 0px;
}

.ccontainer
{
 height: 100%;
 width: 100%;
 background:url(my.jpg);
 background-position: center center;
 background-repeat: no-repeat;
 background-attachment: fixed;
 opacity: 0.9;
 background-size: 100% 100%;
}

.scontent
{
 width: 100%;
 height: 2000px;
 padding:0px 0px;
}
.sccontainer
{
 width: 100%;
 height: 100%;
 background-color: #444444;
}

.footer
{
 z-index:2;
 background: #2B193E;
 position: fixed;
 bottom:0;
 height:5em;
 width: 100%;
 padding: 0em 0em;
 /*Opacity start*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=80);
    -moz-opacity: 0.80;
    -khtml-opacity: 0.8;
    opacity: 0.7;
    /*Opacity end*/
}

.fcontainer
{
 position:relative;
 color: #fff;
 text-align: center;
 top: 40%;
}

.btn
{
 position: absolute;
 width: 150px;
   margin-left:-75px;
   left: 50%;
   bottom:200px;
 display: inline-block;
  padding: 5px;
 color: #ffffff;
 border: 2px solid #fff;
 border-radius: 5px;
 text-align: center;
 outline: none;
 text-decoration: none;
 transition: background-color 0.2s ease-out,
               color 0.2s ease-out;
}

.btn:hover, .btn:focus, .btn:active {
 background-color: #fff;
 color: #000;
 transition: background-color 0.3s ease-in,
       color 0.3s ease-in;
}

Poise for victory!

       Submit!

      MADE in USA

*Edit: Here are some images illustrating what I mean. The left is how I wish to have the layout and the one on the right is how it is right now. The second image shows how the gray background overlaps the background image from behind. Also I'm using z-index to keep the header and footer over the 2 contents.
http://imgur.com/a/5uHlK

A: Position absolute, listens to the first parent element, having its position set to something other than it's default value of "static".
So, if you add a position fixed / absolute / relative to the div containing the link, it should allow you to use position absolute in the link element to position it relative to the parent element.
Also, if you use position relative on an element, and not set any position values, for left / top, it does nothing to its behavior.
for more info:
https://developer.mozilla.org/en-US/docs/Web/CSS/position

A: Is this what you wanted?????
Not sure where the grey is coming in also.
If you want to see this correctly click 'full page' after selecting run code snippet. it adjust to the smaller sized box it is in.

body
{
 margin: 0;
 padding: 0;
 background-color: red;
}

.header
{
 z-index:3;
 position:fixed;

    /*Opacity Being done with RGBA */
 background-color:RGBA(51, 37, 65, 0.7);

 border:0px solid #ffffff;
 height:70px;
 left:0;
 width:100%;

}

.hcontainer
{
 position: relative;
 width:100%;
}

.headingtext
{
 color: #ffffff;
 text-align: center;
 width: 100%;
}

.content
{
 z-index:1;
 position: absolute;
 top:0;
 left:0;
 height: 100%;
 width: 100%;
 padding:0px 0px;
    background-image: url('http://www.liveurlifehere.com/wallpaper/uploads/liveurlifehere-wallpaper1431009496.jpg');
  background-size: 100% 100%;

}

.ccontainer
{
 height: 100%;
 width: 100%;
 background:url(my.jpg);
 background-position: center center;
 background-repeat: no-repeat;
 background-attachment: fixed;
 opacity: 0.9;
 background-size: 100% 100%;
}

.scontent
{
 width: 100%;
 height: 2000px;
 padding:0px 0px;
}
.sccontainer
{
 width: 100%;
 height: 100%;
 background-color: #444444;
}

.footer
{
 z-index:2;
 background: #2B193E;
 position: fixed;
 bottom:0;
 height:5em;
 width: 100%;
 padding: 0em 0em;
 /*Opacity start*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=80);
    -moz-opacity: 0.80;
    -khtml-opacity: 0.8;
    opacity: 0.7;
    /*Opacity end*/
}

.fcontainer
{
 position:relative;
 color: #fff;
 text-align: center;
 top: 40%;
}

.btn
{
 position: absolute;
 width: 150px;
   margin-left:-75px;
   left: 50%;
   bottom:200px;
 display: inline-block;
  padding: 5px;
 color: #ffffff;
 border: 2px solid #fff;
 border-radius: 5px;
 text-align: center;
 outline: none;
 text-decoration: none;
 transition: background-color 0.2s ease-out,
               color 0.2s ease-out;
  z-index: 1;
}

.btn:hover, .btn:focus, .btn:active {
 background-color: #fff;
 color: #000;
 transition: background-color 0.3s ease-in,
       color 0.3s ease-in;
}

Poise for victory!

       Submit!

      MADE in USA

A: Thanks for the help. The problem was my positioning of the elements. Now I only use the "static" default and relative positioning. This site also helped not only with z-indexing but normal layouts. The html stayed the same but the css is shown below for reference. I also added 100% width and height to the html and body which helped a lot.

html, body {
 height: 100%;
 width: 100%;
 margin: 0;
 padding: 0;
/* font: 1em/1.2 "Helvetica Neue", Helvetica, Arial, Geneva, sans-serif;
*/
}

.header {
 position:fixed;
 height:5em;
 width:100%;
 z-index:3;
 background-color:#2B193E;
 /*Opacity start*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=80);
    -moz-opacity: 0.80;
    -khtml-opacity: 0.8;
    opacity: 0.7;
    /*Opacity end*/
}

.hcontainer {
 height: 100%;
}

.headingtext {
 position: relative;
 top: .5em;
 text-align: center;
 color: #ffffff;
}

.content {
 height: 100%;
 background:url(http://www.minimit.com/images/picjumbo.com_IMG_6648.jpg) no-repeat center center fixed;
 background-size: 100% 100%;
}

.ccontainer {
 border: 1px dashed #669966;
 position: relative;
 width:40%;
 height:40%;
 left:30%;
 top:50%;
}

.scontent {
 height: 1500px;
 background:url(mypicture.jpg) no-repeat center center fixed;
 opacity: 0.4;
 background-size: 100% 100%;
}

.sccontainer {
 height: 100%;
 width: 100%;
}

.footer {
 position: fixed;
 height:3em;
 width: 100%;
 bottom:0em;
 z-index:2;
 background: #2B193E;
 padding: 0em 0em;
 /*Opacity start*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=80);
    -moz-opacity: 0.80;
    -khtml-opacity: 0.8;
    opacity: 0.7;
    /*Opacity end*/
}

.fcontainer {
 position: relative;
 top:1em;
 text-align: center;
 color: #ffffff;
}

/* -----------------------
Single styles
------------------------*/
.infotable {
 position: relative;
 border: 1px dashed #ffffff;
 width: 70%;
 margin-bottom:0px;
 top: 50%;
 left:15%;

}

.btn {
 border: 20px dashed #000000;
 position: relative;
 left:50%;
  top:-50%;
 width: 150px;
  margin-left:-75px;

 display: inline-block;
  padding: 5px;
 color: #ffffff;
 border: 2px solid #ffffff;
 border-radius: 5px;
 text-align: center;
/* outline: none;*/
 text-decoration: none;
 transition: background-color 0.2s ease-out,
               color 0.2s ease-out;
}

.btn:hover, .btn:focus, .btn:active {
 background-color: #fff;
 color: #000;
 transition: background-color 0.3s ease-in,
       color 0.3s ease-in;
}


text:
Q: Updating SQL Table Data In Android Applcation I'm trying to update my local android app database data , I used the update query:
public void addQTY(String changedQTY, String changedPNAme) {
    String addQuery = "UPDATE" + SQLITE_TABLE +
            "SET" + qty + "='" + changedQTY + "'" +
            "WHERE" + PRODUCT_NAME + "='" + changedPNAme + "';";
    mDb.execSQL(addQuery);
}

the app is crashing whenever I use this method

A: Give space after WHERE and UPDATE cause
String addQuery = "UPDATE " + SQLITE_TABLE +
        " SET "+ qty+"='"+ changedQTY +"'" +
        " WHERE " +PRODUCT_NAME + "='" + changedPNAme + "';

OR
ContentValues values = new ContentValues();
values.put("qty", changedQTY);
mDb.update(SQLITE_TABLE , values, PRODUCT_NAME + "='" + changedPNAme + "'", null);

redpajama_set_name: RedPajamaStackExchange


text:
Q: ......no availabe ...........i
how to
nihas zero answers
has only one answer, but that answer has no upvoteshas zero answers
has only one answer, but that answer has no upvoteshas zero answers
has only one answer, but that answer has no upvotes

A: I wont show you how to answer the whole problem. But you seem confused primarily regarding the random part. Here is how you do that.
Random rand = new Random();
int i = 582; // some arbitrary integer to act as the input
int randInt = rand(5) + 5; // random value from 5 - 9 inclusive
int j = i + randInt; // add the random value to the output integer

i is your integer from the input file and j is your output integer.


text:
Q: How to pass an array of Pointer types to RttiMethods.Invoke in Delphi Using Delphi 10.2 with latest update
I have a procedure (actual code):
PyObject = packed record ... end;
PPyObject = ^PyObject
PPyObjectArray = array of PPyObject;

procedure invokeMethod (methodName : string; args : PPyObjectArray);
var  ctx: TRttiContext;
     rt : TRttiType;
     mt : TRttiMethod;
     py : TPyArithmetic;
     tv : array of TValue;
begin
   py := TPyArithmetic.Create;
   ctx := TRttiContext.Create;
   try
     rt := ctx.GetType(TPyArithmetic);
     mt := rt.GetMethod (methodName);

    setlength (tv, 1);
    tv[0].From(args);
    mt.Invoke(py, tv);
  finally
    ctx.Free;
  end;
end;

The code itself is spread out within invokeMethod onto multiply lines for debugging reasons.  The purpose of the procedure is to call the method methodName with the argument array args. However I have been unable to successfuly get the arguments across to the invoked method. Although the correct function is invoked the arguments at entry to the invoked method are garbled. My question is how should I pass an array of T to the invoke method?
I also tried calling invoke using
mt.Invoke(py, [args]);
but I get the compile error:
E2250 There is no overloaded version of 'Invoke' that can be called with these arguments.
Tried
mt.Invoke(py, [@args]);
but I get the runtime error:
EInvalidCast with message 'Invalid case typecast', tried to trace the call but didn't succeed in figuring out why I got the error.
The code on the invoked side is:
class function TPyArithmetic.add (args : PPyObjectArray) : double;
begin
   result := TArithmetic.add (GetPythonEngine.PyFloat_AsDouble (args[0]), GetPythonEngine.PyFloat_AsDouble (args[1]));
end;

Any suggestions?

A: TValue.From is a function that returns a new value. A this code is wrong:
tv[0].From(args);

Nothing is ever assigned to tv[0]. You need to do that like so:
tv[0] := TValue.From(args);

Simpler though is to remove the dynamic array and use an open array constructor:
mt.Invoke(py, [TValue.From(args)]);

And the code that creates and destroys the RTTI context is spurious also. It works fine your way but it could equally be:
procedure invokeMethod(methodName: string; args: PPyObjectArray);
var
  ctx: TRttiContext;
  rt: TRttiType;
  mt: TRttiMethod;
  py: TPyArithmetic;
begin
  py := TPyArithmetic.Create;
  rt := ctx.GetType(TPyArithmetic);
  mt := rt.GetMethod (methodName);
  mt.Invoke(py, [TValue.From(args)]);
end;

FWIW, it looks like your code leaks py.


text:
Q: Check for disabled button fails with selenium I have a simple assertion on a disabled button within my selenium test that fails. The method expects the button to be disabled but when I run the test it fails stating that the button is actually enabled.
I use Ruby/Rspec and this is the code used to check that button is disabled. I've removed the references to the class and page object but the button object locator used is by :id.
expect(Page.btn.enabled?).to be false
Here is the html of the page for the disabled button I am testing:
<input type="submit" name="ctl00$bodyContentPlaceHolder$btnContinueToAddress" value="Next" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$bodyContentPlaceHolder$btnContinueToAddress", "", true, "", "", false, false))" id="ctl00_bodyContentPlaceHolder_btnContinueToAddress" class="btn btn-primary btn-block disabledContent">
I would expect the selenium test to pass as the button IS disabled on the page, but the rspec results show:
expected false
     got true
Is the locator used incorrect and the :id is actually enabled? Is there something I'm missing? Thanks in advance.


text:
Q: d3.js donut chart select option onchange isn't updating the chart I have donut chart that's working fine except for it doesn't automatically update the chart when I select the option from drop down menu. so I have to refresh the page every-time after an option is changed from dorp down menu
following is code
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 70);

var pie = d3.layout.pie()
 .sort(null)
 .value(function(d) { return d.population; });
var svg = d3.select("body").append("svg")
 .attr("width", width)
 .attr("height", height)
 .append("g")
 .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var loadData = function() {
var metric = document.getElementById('metric').value;
 var dataFile = 'data_' + metric + '.csv'
 d3.csv(dataFile, function(error, data) {

data.forEach(function(d) {
 d.population = +d.population;
 });

var g = svg.selectAll(".arc")
   .data(pie(data))
   .enter().append("g")
   .attr("class", "arc");

g.append("path")
   .attr("d", arc)
   .style("fill", function(d) { return color(d.data.age); });

}); }

loadData()
can you please let me know what can be done to update the donut chart upon selection..
Thank you


text:
Q: Dependent dropdown getting ids not name I am trying to get user selection from php form but instead of name I am getting id of elements. instead of ids I want to get names. Please help
here is the url
http://efinancec.com/d/drop4/index.php
and here is the code
   <form action="../form/form1.php" method="post" enctype="multipart/form-data">

Training:

<select name="training" id="training-list" class="demoInputBox" onChange="getCourse(this.value);">
<option value="">Select Training</option>
<?php
foreach($results as $training) {
?>
<option value="<?php echo $training["id"]; ?>"><?php echo $training["training"]; ?></option>
<?php
}
?>
</select>

Course:

<select name="course" id="course-list" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Course</option>
</select>

Country:

<select name="country" id="country-list" class="demoInputBox" onChange="getCity(this.value);">
<option value="">Select Country</option>
</select>

City:

<select name="city" id="city-list" class="demoInputBox" onChange="getDates(this.value);">
<option value="">Select City</option>
</select>

Dates:

<select name="dates" id="dates-list" class="demoInputBox" onChange="getPrice(this.value);">
<option value="">Select Dates</option>
</select>

Online Onsite Price:

<select name="price" id="price-list" class="demoInputBox">
<option value="">Select Online or Onsite</option>
</select>

            <input id="submit" name="submit" type="submit" value="Submit">

        </form>

and this is how I am getting the values from sql database
    <?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["training_id"])) {
    $query ="SELECT * FROM course WHERE training_id = '" . $_POST["training_id"] . "'";
    $results = $db_handle->runQuery($query);
?>
    <option value="">Select Course</option>
<?php
    foreach($results as $course) {
?>
    <option value="<?php echo $course["id"]; ?>"><?php echo $course["course"]; ?></option>
<?php
    }
}
?>

A: Change this line:
 onChange="getCourse(this.value);">

To this :
 onChange="getCourse(this.text);">

You are passing id of the course as the value of dropdown and calling that value which is fine but you need to call the text of select option to get the course name.

A: I changed this.value to this.text as suggested and created the new page and it stoped working at all now it is not pulling the records from database except the first one. Here is the link
http://efinancec.com/d/drop4/index1.php
where as my earlier page is still working fine.
http://efinancec.com/d/drop4/index.php
I think I could not convey my problem earlier. My depended dropdown is working fine but when a user submits the form in the email I receive the ids instead of name. Thats the problem.
For example I myself made some selections on index.php and submitted form Here is the email I got
training: 1
 course : 101
 country: 1001
 city: 5005
Basically I am getting the the respective ids instead of name.


text:
Q: count the occurence of values in a column in tableau I have a data set with 900 000 rows. There's a column "event_id". I want to create a table of occurences of event_id.
occured once = 63K
occured twice = 114K
occured thrice = 54k

and so on.
How can I do this in Tableau?

A: step_1 = drag event_id to rows
step_2 = drag filename.csv(count) to TEXT.


text:
Q: Phoenix simple auth testing logged in user From this Simple authentication tutorial
I am looking to test routes of the app inside the :login_required pipeline (which simply checks if the client has called Guardian.Plug.sign_in(conn, user))
As the user_path show action needs to have been piped through the :login_required pipeline, I would have thought that to test this route I would simply need to write the following:
Auth.login_by_email_and_pass(conn, user.email, @password)
and then pipe the conn that comes out of that into:
get conn, user_path(conn, :show, user.id)
and check that I get a 200 status code.
But I can't get past the Auth.login_by_email_and_pass(conn, email, password) line and get the error:
session not fetched, call fetch_session/2
Where should I fetch the session?
I have tried bypass_through(conn, [:browser, :with_session])
I would have thought that the :browser pipeline invokes fetch_session which would have solved this issue.
I have also tried as calling fetch_session before and after, but still get the same error

A: You can use Plug.Test.init_test_session/2 to initialize the session. Since you don't need to put any data, you can pass an empty map as the second argument.
conn = conn
  |> init_test_session(%{})
  |> Auth.login_by_email_and_pass(user.email, @password)


text:
Q: MERN app works locally but breaks on Heroku I am trying to deploy this MERN GitHub project to Heroku. Heroku builds it fine and the site is live here. However, the code on the Heroku site has a whole bunch of problems that don't occur when I run my site locally on my computer.
I think the problem might be the proxy server I set up (setupProxy.js):
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

I can't think of anything else that could be causing all the bugs on Heroku. I would really appreciate any assistance that can be given, since I've been dealing with this issue for some time now (I gave up on fixing it last year but have returned to it) and it's been very frustrating. Thank you for your time.


text:
Q: spring aop - chaining multiple aspects i have two aspects, one for acquiring a lock @Around a call, another one for debouncing method calls. the aspects look like this:
@Pointcut("execution(public * * (..))")
private void anyPublicMethod() {}

@Around("anyPublicMethod() && @annotation(lock)")
public Object all(ProceedingJoinPoint proceedingJoinPoint, Lock lock) throws Throwable {
   // acquire lock, then proceed()
}

and the other one looks like this:
@Pointcut("execution(public * * (..))")
private void anyPublicMethod() {}

@Around("anyPublicMethod() && @annotation(debounce)")
public Object all(ProceedingJoinPoint proceedingJoinPoint, Debounce debounce) throws Throwable {
    // debouncing as described in
    // http://stackoverflow.com/questions/4742210/implementing-debounce-in-java

}

the full code:
https://github.com/rmalchow/debouncer-aspect/blob/master/src/main/java/com/skjlls/aspects/debounce/impl/DebounceAspect.java
and
https://github.com/rmalchow/lock-aspect/blob/master/src/main/java/com/skjlls/aspects/lock/impl/LockAspect.java
when i put both my @Debounce and my @Lock on a method, i get this exception:
Required to bind 2 arguments, but only bound 1 (JoinPointMatch was NOT bound in invocation)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.argBinding(AbstractAspectJAdvice.java:584)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)

it seems to be related to spring aop not being able to figure out the next thing to call in line is another aspect, not the actual target, and i have seen other reports from spring aop 2 and 3 ... but i am using:
spring 4.1.1.RELEASE

A: sorry for my poor English.
did you ordered the Aspect Class? if you didn't,this problem may happend
you could try this for example:
@Aspect
@Order(1)
public class FirstAspect(){}

@Aspect
@Order(2)
public class SecondAspect(){}

the value is lower ,the priority is higher


text:
Q: FormView not displaying PagerTemplate when only 1 item in DataSource I have a FormView control with a custom PagerTemplate with my own paging LinkButtons. All works great until the dataset that I load only contains one record/item and hides the PagerTemplate completely. I've searched online and found several answers to simply add:
protected void fvAppHMDA_PreRender(object sender, EventArgs e)
    {
        if (fvAppHMDA.TopPagerRow != null)
            fvAppHMDA.TopPagerRow.Visible = true;
    }

However, this is not making one bit of difference. It seems that when there is only one record in the data set, the FormView.TopPagerRow is always null. It seems that there needs to be a way to intercept this but I've tried doing it in both OnPreRender and OnDataBound events but still no dice.
Below is sample of my code if that helps:
ASPX
<asp:FormView ID="fvAppHMDA" runat="server" AllowPaging="True" DefaultMode="Edit" DataSourceID="dsLoanApplication" Width="100%" onpageindexchanging="fvAppHMDA_PageIndexChanging" OnDataBound="fvAppHMDA_DataBound" OnPageIndexChanged="fvAppHMDA_PageIndexChanged" OnItemCreated="fvAppHMDA_ItemCreated" DataKeyNames="ApplicationID" OnPreRender="fvAppHMDA_PreRender">
<PagerTemplate>

        <asp:LinkButton ID="lnkMoveFirst" runat="server"
            ToolTip="Move to the First Application" CommandName="Page"
            CommandArgument="First"></asp:LinkButton>
        <asp:LinkButton ID="lnkMovePrevPage" runat="server"
            ToolTip="Move to the Previous Page" CommandName="Page"
            onclick="lnkMovePrevPage_Click" Enabled="False"></asp:LinkButton>
        <asp:LinkButton ID="lnkMovePrevApp" runat="server"
            ToolTip="Move to the Previous Application" CommandName="Page"
            CommandArgument="Prev"></asp:LinkButton>

<asp:TextBox ID="txtMoveNumber" runat="server" Text="0" Columns="5"></asp:TextBox> of <asp:Label ID="lblMoveTotal" runat="server" Text="0"></asp:Label>

        <asp:LinkButton ID="lnkMoveNextApp" runat="server"
            ToolTip="Move to the Next Application" CommandName="Page"
            CommandArgument="Next"></asp:LinkButton>
        <asp:LinkButton ID="lnkMoveNextPage" runat="server"
            ToolTip="Move to the Next Page" CommandName="Page"
            onclick="lnkMoveNextPage_Click" Enabled="False"></asp:LinkButton>
        <asp:LinkButton ID="lnkMoveLast" runat="server"
            ToolTip="Move to the Last Application" CommandName="Page"
            CommandArgument="Last"></asp:LinkButton>

</PagerTemplate>
<PagerSettings Mode="NextPreviousFirstLast" Position="Top" />
<EditItemTemplate>

</EditItemTemplate>

Codebehind
protected void fvAppHMDA_PreRender(object sender, EventArgs e)
{
if (fvAppHMDA.TopPagerRow != null)
    fvAppHMDA.TopPagerRow.Visible = true;
}

protected void fvAppHMDA_DataBound(object sender, EventArgs e)
{
if (fvAppHMDA.DataItemCount != 0)
{
    // Update Current and Total Page
    ((Label)fvAppHMDA.TopPagerRow.FindControl("lblMoveTotal")).Text = fvAppHMDA.PageCount.ToString();
    ((TextBox)fvAppHMDA.TopPagerRow.FindControl("txtMoveNumber")).Text = (fvAppHMDA.PageIndex + 1).ToString();

    // Enable/Disable Page buttons based on Current Page
    if (fvAppHMDA.PageIndex + 1 == fvAppHMDA.PageCount)
    {
        ((LinkButton)fvAppHMDA.TopPagerRow.FindControl("lnkMoveLast")).Enabled = false;
        ((LinkButton)fvAppHMDA.TopPagerRow.FindControl("lnkMoveNextApp")).Enabled = false;
    }
    else if (fvAppHMDA.PageIndex == 0)
    {
        ((LinkButton)fvAppHMDA.TopPagerRow.FindControl("lnkMoveFirst")).Enabled = false;
        ((LinkButton)fvAppHMDA.TopPagerRow.FindControl("lnkMovePrevApp")).Enabled = false;
    }

    if (fvAppHMDA.PageIndex + 10 <= fvAppHMDA.PageCount - 1)
    {
        ((LinkButton)fvAppHMDA.TopPagerRow.FindControl("lnkMoveNextPage")).Enabled = true;
    }
    if (fvAppHMDA.PageIndex - 10 > -1)
    {
        ((LinkButton)fvAppHMDA.TopPagerRow.FindControl("lnkMovePrevPage")).Enabled = true;
    }

    fvAppHMDA.TopPagerRow.Cells[0].Visible = true;
}

if (fvAppHMDA.TopPagerRow != null)
    fvAppHMDA.TopPagerRow.Visible = true;
}

thanks!

A: Tried this http://forums.asp.net/t/1016811.aspx/1 and it worked fine for me.  If you want a top pager row, I guess HeaderTemplate would also work.
"In the markup for the FormView I set:
AllowPaging="true"
PagerSettings-Visible="false"
Then I put all of my controls for paging in the FooterTemplate of the FormView. By doing it this way I was still able to handle all of the paging events and always have the "Pager Row" visible even when there was only one record being returned in the datasource."


text:
Q: Red Hat Yum not working out of the box? I have a server runnning Red Hat Enterprise Linux v5.6 in the cloud.  My project constraints do not allow me to use another OS.
When I created the cloud server, I was able to SSH into it and access the shell.  I next ran the command:
sudo yum update

But the command failed.  About a month ago I created another server with the same machine image and didn't have that error.  Why is it failing now?  The following is the terminal output
sudo yum update
Loaded plugins: security
Repository rhel-server is listed more than once in the configuration
Traceback (most recent call last):
  File "/usr/bin/yum", line 29, in ?
    yummain.user_main(sys.argv[1:], exit_code=True)
  File "/usr/share/yum-cli/yummain.py", line 309, in user_main
    errcode = main(args)
  File "/usr/share/yum-cli/yummain.py", line 178, in main
    result, resultmsgs = base.doCommands()
  File "/usr/share/yum-cli/cli.py", line 345, in doCommands
    self._getTs(needTsRemove)
  File "/usr/lib/python2.4/site-packages/yum/depsolve.py", line 101, in _getTs
    self._getTsInfo(remove_only)
  File "/usr/lib/python2.4/site-packages/yum/depsolve.py", line 112, in _getTsInfo
    pkgSack = self.pkgSack
  File "/usr/lib/python2.4/site-packages/yum/__init__.py", line 662, in <lambda>
    pkgSack = property(fget=lambda self: self._getSacks(),
  File "/usr/lib/python2.4/site-packages/yum/__init__.py", line 502, in _getSacks
    self.repos.populateSack(which=repos)
  File "/usr/lib/python2.4/site-packages/yum/repos.py", line 260, in populateSack
    sack.populate(repo, mdtype, callback, cacheonly)
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 168, in populate
    if self._check_db_version(repo, mydbtype):
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 226, in _check_db_version
    return repo._check_db_version(mdtype)
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 1233, in _check_db_version
    repoXML = self.repoXML
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 1406, in <lambda>
    repoXML = property(fget=lambda self: self._getRepoXML(),
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 1398, in _getRepoXML
    self._loadRepoXML(text=self)
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 1388, in _loadRepoXML
    return self._groupLoadRepoXML(text, ["primary"])
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 1372, in _groupLoadRepoXML
    if self._commonLoadRepoXML(text):
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 1208, in _commonLoadRepoXML
    result = self._getFileRepoXML(local, text)
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 989, in _getFileRepoXML
    cache=self.http_caching == 'all')
  File "/usr/lib/python2.4/site-packages/yum/yumRepo.py", line 826, in _getFile
    http_headers=headers,
  File "/usr/lib/python2.4/site-packages/urlgrabber/mirror.py", line 412, in urlgrab
    return self._mirror_try(func, url, kw)
  File "/usr/lib/python2.4/site-packages/urlgrabber/mirror.py", line 398, in _mirror_try
    return func_ref( *(fullurl,), **kwargs )
  File "/usr/lib/python2.4/site-packages/urlgrabber/grabber.py", line 936, in urlgrab
    return self._retry(opts, retryfunc, url, filename)
  File "/usr/lib/python2.4/site-packages/urlgrabber/grabber.py", line 854, in _retry
    r = apply(func, (opts,) + args, {})
  File "/usr/lib/python2.4/site-packages/urlgrabber/grabber.py", line 922, in retryfunc
    fo = URLGrabberFileObject(url, filename, opts)
  File "/usr/lib/python2.4/site-packages/urlgrabber/grabber.py", line 1010, in __init__
    self._do_open()
  File "/usr/lib/python2.4/site-packages/urlgrabber/grabber.py", line 1093, in _do_open
    fo, hdr = self._make_request(req, opener)
  File "/usr/lib/python2.4/site-packages/urlgrabber/grabber.py", line 1202, in _make_request
    fo = opener.open(req)
  File "/usr/lib64/python2.4/urllib2.py", line 358, in open
    response = self._open(req, data)
  File "/usr/lib64/python2.4/urllib2.py", line 376, in _open
    '_open', req)
  File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain
    result = func(*args)
  File "/usr/lib64/python2.4/site-packages/M2Crypto/m2urllib2.py", line 82, in https_open
    h.request(req.get_method(), req.get_selector(), req.data, headers)
  File "/usr/lib64/python2.4/httplib.py", line 810, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib64/python2.4/httplib.py", line 833, in _send_request
    self.endheaders()
  File "/usr/lib64/python2.4/httplib.py", line 804, in endheaders
    self._send_output()
  File "/usr/lib64/python2.4/httplib.py", line 685, in _send_output
    self.send(msg)
  File "/usr/lib64/python2.4/httplib.py", line 652, in send
    self.connect()
  File "/usr/lib64/python2.4/site-packages/M2Crypto/httpslib.py", line 47, in connect
    self.sock.connect((self.host, self.port))
  File "/usr/lib64/python2.4/site-packages/M2Crypto/SSL/Connection.py", line 174, in connect
    ret = self.connect_ssl()
  File "/usr/lib64/python2.4/site-packages/M2Crypto/SSL/Connection.py", line 167, in connect_ssl
    return m2.ssl_connect(self.ssl, self._timeout)
M2Crypto.SSL.SSLError: certificate verify failed

A: You should read the message. It says Repository rhel-server is listed more than once in the configuration. So delete the duplicate entry and then go ahead.
Delete the one with the failing SSL certificate (untrusted or compromised source).

A: The "Repository is listed more than once in the configuration" error message could some times be caused due to a bug in the yum-rhn-plugin package which yum relies on. I once had the same issues and was able to resolve it by downgrading yum-rhn-plugin to a previous version.
rpm -Uvh --oldpackage yum-rhn-plugin-0.5.2-3.el5.noarch.rpm


text:
Q: How to check Only Credit card number is valid not Debit card..? im using this code for checking credit card number valid or not. But in this code checking both number credit and debit.
I want only credit card number checking.
private bool IsValidNumber(string number)
    {
        int[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 };
        int checksum = 0;
        char[] chars = number.ToCharArray();
        for (int i = chars.Length - 1; i > -1; i--)
        {
            int j = ((int)chars[i]) - 48;
            checksum += j;
            if (((i - chars.Length) % 2) == 0)
                checksum += DELTAS[j];
        }

        return ((checksum % 10) == 0);
    }

Thanks, Kaushik.

A: I think you are going to have to define how you know a number is a credit card number vs a debit card number. To my knowledge there is no way to see from the number it self what kind of card it is only the banks know. However this may be different across banks and countries.


text:
Q: Cannot get ColorThief to work correctly in Angular, library methods are not found? I am trying to use the Library ColorThief(https://lokeshdhakar.com/projects/color-thief/) in an Angular 12 project but have had no success getting it to work.  I started by doing $ npm i --save colorthief and then in my desired component .ts file:
const ColorThief = require('colorthief');.
Everything compiles correctly but some of the methods are not recognized when they are triggered in the browser.
I have also tried adding the script tag to my index.html file, with no success.
My Component TS file:
import { Color } from '../shared/model/color';
const ColorThief = require('colorthief');
//import ColorThief from 'angular-colorthief';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, AfterViewInit {
...
autoGeneratePalette(numColors:number) {
    this.userPalette = [];
      this.paletteCounter = 0;
    //var ColorThief:any = new ColorThief();
      ColorThief.getPalette(this.imgToUse, numColors)
      .then((palette: any) => {
      for(var i = 0; i < palette.length; i++) {
        var color = new Color(0,0,0,0);
        color.red = palette[i][0];
        color.green = palette[i][1];
        color.blue = palette[i][2];
        color.index = i;
        this.userPalette.push(color);
      }
    })
    .catch((err: any) => {console.log(err)});
    }
}

Anyone have any ideas what I am doing wrong? Or someone that has successfully used ColorThief in Angular?

A: import ColorThief from 'colorthief'

ngOnInit(){

    const img = document.querySelector('img');

    const colorThief = new ColorThief();

    if (img.complete) {
     // colorThief.getColor(img);
      this.mopl = colorThief.getColor(img)
    } else {
      img.addEventListener('load', () => {
       // colorThief.getColor(img);
        this.mopl = colorThief.getColor(img)
      });
    }
}


text:
Q: flatMap on a sequence of tuples Given the following code :
def flatMap2[A, B, C](s:Seq[(A, B)])(f: B => Seq[C]) : Seq[(A, C)] =
  s.flatMap { case (a, b) => f(b).map((a, _)) }

Is there a better way to code that (maybe something exit in scalaz) ?
Can you help me to find a better name ?
Is there a more generic abstraction to use (Iterable, TraversableOnce) ?

A: How about this:
import scala.collection.GenTraversable
import scala.collection.GenTraversableLike
import scala.collection.GenTraversableOnce
import scala.collection.generic.CanBuildFrom

implicit class WithMapFlatMapValues[A, B, Repr <: GenTraversable[(A, B)]](val self: GenTraversableLike[(A, B), Repr]) extends AnyVal {
  def flatMapValues[C, That](f: B => GenTraversableOnce[C])(implicit bf: CanBuildFrom[Repr, (A, C), That]) = {
    self.flatMap { case (a, b) => f(b).toIterator.map(a -> _) }
  }
}

So you can do:
Vector("a"->1, "b"->2).flatMapValues(Seq.fill(_)("x"))
// res1: Vector[(String, String)] = Vector((a,x), (b,x), (b,x))

Set("a"->1, "b"->2).flatMapValues(Iterator.tabulate(_)(_+"x"))
// res2: Set[(String, String)] = Set((a,0x), (b,0x), (b,1x))

And you can do it with Iterator too (so you have all of TraversableOnce covered):
implicit class WithMapFlatMapValuesItr[A, B](val self: Iterator[(A, B)]) extends AnyVal {
  def flatMapValues[C](f: B => GenTraversableOnce[C]) = {
    for { (a, b) <- self; c <- f(b).toIterator } yield (a -> c)
  }
}

val i1 = Iterator("a"->1, "b"->2).flatMapValues(Seq.fill(_)("x"))
// i1: Iterator[(String, String)] = non-empty iterator
i1.toVector
// res6: Vector[(String, String)] = Vector((a,x), (b,x), (b,x))

A: Looks little better:
def flatMap2[A, B, C](List[(A, B)])(f: B => Seq[C]) : List[(A, C)] =
   for((a,b) <- s; bb <- f(b)) yield a -> bb

But things you're trying to do here is more like about multi-map (with preserving order) than just sequence of tuples:
def flatMap2[A, B, C](s: ListMap[A, List[B]])(f: B => List[C]) : Map[A, List[C]] =
   s.mapValues(_.flatMap(f))

scala> flatMap2(ListMap(2 -> List("a"), 1 -> List("c")))(x => List(x + "a"))
res4: scala.collection.immutable.Map[Int,List[String]] = Map(2 -> List(aa), 1 -> List(ca))

ListMap saves original order here. mapValues returns view on ListMap, which also will preserve the order.
Scalaz's monoids could help you with adding elelements to such Map:
yourListMap |+| ListMap(key -> List(value))

scala>  val map = ListMap(2 -> List("a"), 1 -> List("c"))
map: scala.collection.immutable.ListMap[Int,List[String]] = Map(2 -> List(a), 1 -> List(c))

scala> (map: Map[Int,List[String]]) |+| ListMap(1 -> List("b"))
res11: scala.collection.immutable.Map[Int,List[String]] = Map(2 -> List(a), 1 -> List(c, b))

You can use Seq instead of List, but then you won't have implicit conversion to the semigroup.

A: The question may be unclear, at this point I would say:
// s1: Seq[(A, B)], f: B => C
val s2: Seq[(A, C)] = s1.map((a, b) => a -> f(b))


text:
Q: Event Date Asc Not Right how to do this right
Select DATE_FORMAT(EventDate, '%b %d, %Y')
from details
Order by STR_TO_DATE(EventDate, '%d-%m-%y')

sample records,
Oct 24, 2012
Oct 27, 2012
Oct 28, 2012
Oct 20, 2012
Dec 22, 2012
Jan 11, 2013
Jan 19, 2013
Nov 24, 2012
Dec 29, 2012

A: What about this:
Select DATE_FORMAT(EventDate, '%b %d, %Y') from details Order by EventDate

A: Order by STR_TO_DATE(EventDate, '%d-%m-%y')

So we start with EventDate which you say is a DATE and we feed it as first argument to STR_TO_DATE(). Such function expects a string, so MySQL casts your date as string possibly using the default format (YYYY-MM-DD). Then it tries to cast the string to date using DD-MM-YYYY as format but your string is not in that format. Do you understand where I want to go?
To sum up: you don't need to cast a date to date--it's already a date!
Order by EventDate


text:
Q: How to persist a Map with the JPA I have an Class in Java an their instances are JPA-@Enitit[ies], but they cannot be persisted, because I get a MappingException, because I have a map:
private Map<Account, Boolean> doneTask;

And I do not know how to persist a Boolean like a boolean.
What can I do?

A: Did you use ElementCollection?
Something like:
@ElementCollection
@JoinTable(name="TASKS", joinColumns=@JoinColumn(name="ID"))
@MapKeyColumn (name="ACCOUNT")
@Column(name="DONE_FLAG")
private Map<Account, Boolean> doneTask;


text:
Q: Data having commas creating problem in json I am developing a web applications where users are allowed to enter some text. To create profile, I am using the text entered by users which is saved in database. Problem is, if the data entered by user contains a comma, it is spoiling my page as a json string can't contain a comma. Is there any encoding function in php for supporting commas in json.
Note:
Am using zend framework's zend encoding function to encode json.
Solved:
I got the solution of this problem, json encoding function of zend framework have some issues with encoding decimal data and comma and that was the reason it was creating problem. I used php's own json encode function.

A: Did you try json_encode ?
Works well for me:
<?php

$str = "my string.";

$json_str = json_encode($str);

echo $json_str . "\n";

Gives:
"my string."

A: Yes it can use any character.
$json = json_encode($your_array_or_string);

A: I'd say that as long as you encapsulate your data with either ' or ", it won't parse the , as an actual separator. Use json_encode() as @Patrik MARIE stated above, and you won't be in the need of manually quoting everything!


text:
Q: Python Popen wait/poll blocking execution I need to execute a exe file with arguments which reads a file, makes some calculations and generates 3 new files. Using subprocess.Popen works fine. But in order to check it's execution, I'm using wait(). But when wait() is used, the process doesn't work and no files are generated. I even checked in task manager. It generally takes 5 seconds for the process to complete, but if wait() is used, the process ends within a second. Can anyone help me out?
process = subprocess.Popen(span_command, shell=True)

The above snippet when used alone works fine, but if used with process.wait(), the process stops.

A: More information regarding executed program is needed.
I think that yours program ends when it's stdin is closed.
For example date on windows expects input and finishes when it receives some input.
p2 = subprocess.Popen(["date"], stdout=subprocess.PIPE ,shell=True)
print(p2.returncode)
time.sleep(10)
print(p2.returncode)
print(p2.wait())
print(p2.returncode)

This could be solution for you. Wait some time before calling wait.
But it would be better to know how that program reacts on different inputs and run with stdin=subprocess.PIPE and p2.communicate("some expected input").
Check output of program you are running.
p2 = subprocess.Popen(["date"], stdout=subprocess.PIPE, stderr=subprocess.PIPE ,shell=True)
print(p2.wait())
print(p2.stdout.readlines())
print(p2.stderr.readlines())

It's not solution, it's debugging process.
There is no reason not to work in code you have given.
So it's something you didn't show us. First suspect is program you are running.


text:
Q: Why does Map work but Apply raises ValueError I'm trying to get more comfortable with various ways of using Pandas, and I'm struggling to understand why Map, Apply, and Vectorization are relatively interchangeable with functions that return non-booleans, but Apply and Vectorization sometimes fail when the function being applied returns a boolean. This question will focus on Apply.
Specifically, I wrote the very simple little code to illustrate the challenge:
import numpy as np
import pandas as pd

# make dataframe
x = range(1000)
df = pd.DataFrame(data = x, columns = ['Number'])

# simple function to test if a number is a prime number
def is_prime(num):
    if num < 2:
        return False
    elif num == 2:
        return True
    else:
        for i in range(2,num):
            if num % i == 0:
                return False
    return True

# test if every number in the dataframe is prime using Map
df['map prime'] = list(map(is_prime, df['Number']))
df.head()

The following gives the output I'd expect:

So here's where I no longer understand what's going on: when I try to use apply, I get a ValueError.
in: df['apply prime'] = df.apply(func = is_prime, args = df['Number'], axis=1)
out: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What am I missing?
Thank you!
p.s. I know there are more efficient ways to test for primes. I purposefully wrote an inefficient function so I could test how much faster apply and vectorization really were than map, but then I ran into this challenge. Thank you.

A:
So here's where I no longer understand what's going on: when I try to
use apply, I get a ValueError.

df.apply(..., axis=1), pass pd.Series(...).
i.e. df['apply prime'] = df['Number'].apply(func = is_prime) should work.

Given that apply is ostensibly faster than map, and vectorization
faster still.

In addition pd.DataFrame.apply(...), doesn't use any type of vectorization, just a simple C for loop (ex. cython), so believe that map(...) should be asymptotically faster.

Update
You might need to  figure that,  .apply(...), method passes the values of a given axis=x to the function and returns Y, which could be any data type, In case of pd.DataFrame (multiple keys).
Suppose that df.shape = (1000, 4), if we are intend to move along axis=1, i.e. df.shape[1], it's means your apply function going to be called 1000 times, each run it's got (4, ) element of a type pd.Series, you could use there keys inside the function itself, or just pass the keys as an arguments, pd.DataFrame.apply(..., args=[...]).

import numpy as np
import pandas as pd

x = np.random.randn(1000, 4)
df = pd.DataFrame(data=x, columns=['a', 'b', 'c', 'd'])

print(df.shape)

df.head()

def func(x, key1, key2):

  # print(x.shape)

  if x[key1] > x[key2]:

    return True

  return False

df.apply(func, axis=1, args=['a', 'b'])


text:
Q: Redis scan does not iterate all over the set I want to divide a large redis set into batches by scanning through it. The cursor becomes 0 after iterating some elements of the set. Assume the set length is 250000, sscan paginates about 70000 elements of the set and it comes to end.
Does anyone know why?

A: As @Niloct said, There are some conditions which guarantees full iteration:
https://redis.io/commands/scan#scan-guarantees

A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration

When you iterate a large set which has expiration time, you should control the speed of iteration with count number. If you pass small number for count, the iteration takes much more time and by this, some elements in the set may have been expired, so you miss them.


text:
Q: ORA-06550: line 15, column 1: PLS-00103: Encountered the symbol "LOOP" when expecting one of the following:
I get following error:
LOOP
*
ERROR at line 15:
ORA-06550: line 15, column 1:
PLS-00103: Encountered the symbol"LOOP" when expecting one of the following: . ( % ; for
The symbol "; was inserted before "LOOP" to continue.
ORA-06550: line 39, column 1:
PLS-00103: Encountered the symbol "CLOSE"

DECLARE

CURSOR C1
IS
select B.PTN_STATUS,B.SUBSCRIBER_NO,A.PTN from DVC_REFRESH_Q_TEMP A, subscriber_rsource B where A.PTN=B.PTN;

ptn_sts DVC_REFRESH_Q_TEMP.PTN_STATUS%TYPE;
ptn DVC_REFRESH_Q_TEMP.PTN%TYPE;
subs_no DVC_REFRESH_Q_TEMP.SUBSCRIBER_NO%TYPE;

BEGIN

OPEN C1

LOOP
FETCH C1 into ptn_sts,subs_no,ptn;

EXIT when C1%notfound;

update DVC_REFRESH_Q_TEMP set PTN_STATUS=ptn_sts where PTN=ptn;

if ptn_sts='A' then

update DVC_REFRESH_Q_TEMP set SUBSCRIBER_NO=subs_no where PTN=ptn;

else

dbms_output.put_line('Subscriber number will be empty');

end if;

INSERT into dvc_refresh_q(dvc_name,subscriber_no,nms_ftr_ref,sys_update_date,operator_id,application_id,status)
select dvc_name,subscriber_no,nms_ftr_ref,sysdate,87952,'DRFSCR',null from dvc_refresh_q_temp where PTN_STATUS='A';

END LOOP;

CLOSE C1;

END;

/

A: I think you just forgot the ; after OPEN C1.


text:
Q: How to avoid application crashing when download file using WebClient(); I'm using C# WebClient(); to download a file from a server. The problem is when I don't have internet or  the server is not responsive, my application crashes trying to download this file.
What is the best practice to avoid crashing, to abort and give a notification that connection with a server failed?

A: Just handle the exceptions returned by WebClient.DownloadFile:
try
{
    WebClient.DownloadFile(uri, myPath);
}
catch(WebException webEx)
{
     // There was an exception due to network or path problems...
     // Notify the user?
}

A: A server not being responsive is an exceptional situation that is best dealt with using proper exception handling with a try/catch block.
The exception to handle for WebClient request is a WebException. You can inspect the exception object for further details. The Status property will contain a status value giving you further information what actually went wrong.
Check the samples in MSDN:
try
{
    WebClient client = new WebClient();

    byte[] pageData = client.DownloadData("http://www.contoso.com");
    string pageHtml = Encoding.ASCII.GetString(pageData);
    Console.WriteLine(pageHtml);

    client.DownloadFile("http://www.contoso.com", "page.htm");
}
catch (WebException webEx)
{
    Console.WriteLine(webEx.ToString());
    if(webEx.Status == WebExceptionStatus.ConnectFailure)
    {
        Console.WriteLine("Are you behind a firewall?  If so, go through the proxy server.");
    }
}

A: If it's interactive, then yes that would be the best thing to do upon catching the relevant exception. Whether you aborted everything or gave a message (and whether that message was modal or non-modal) would depend on your overall UI. Generally, aborting is more acceptable in the command line or in a web app (with appropriate response for each), aborting just that operation with an error message is more appropriate for a GUI app.
If it was something running as a service etc. you would want to log the exception and go on to the next operation, possibly with some degree of back-off (two exceptions in a row, wait for a bit as the network might be down entirely; another exception, wait longer this time).
In either case you should explicitly catch WebExceptions (and perhaps IOException from the attempt to save the file failing) and let other exceptions (which are more likely to be from bugs in the application) be caught by your overall exception handling strategy.


text:
Q: Moving elements between Twitter Bootstrap lists with different entry stile I have 2 Twitter Bootstrap lists of elements:

*

*One is a list of available elements which can be dragged to the second list (its like a shop)

*The other list stores copies of elements from the first list (like a shopping cart)

There is an additional difference between both tables: Entries on the "shopping cart list" have a badge (to indicate the amount of each item) and a delete button.
HTML:

list1 (cart)

Item1 5

Item2 -3

list2 (shop)

Item1

Item2

Item3

JS:
// Create list of instances
var list1_element = document.getElementById("list1");
var list1 = new Sortable(list1_element, {
    group: {
        name: "my_group",
        pull: true,
        put: true
    },

    // Called by any change to the list (add / update / remove)
    onSort: function (event) {
        console.log('Change performed to list1');
    },
});

// Create list 2
var list2_element = document.getElementById("list2");
var list2 = new Sortable(list2_element, {
    group: {
        name: "my_group",
        pull: 'clone',
        put: false
    },
    sort: false
});

// Configure click action over the badges
jQuery(".badge").click(function () {
    console.log('Clicked badge');
});

// Configure click action over the remove buttons
jQuery(".icon-remove").click(function () {
    console.log('Clicked remove button');
    $(this).closest("li").remove();
});

The problem is that initial items do have the badge and the delete button, but items dragged from the "shop list" are stored at the other list without badge or delete button.
I made a JSFiddle to show current status.
Any idea of how to fix it?
BONUS: I'm still figguring out how to make the delete icon appear at the right of the badge and better centered in height. Any idea for that?

A: You need to update the element that you have dragged with your custom HTML, to show the badge and the remove icon.
UPDATED
After you created the new i element, you need to bind the click() for it.
I've updated my FIDDLE.
  ...
  onSort: function (event) {
    ///add the badge
    var span = document.createElement("span");
    span.innerHTML = span.innerHTML +"1";
    span.className = span.className + " badge";
    event.item.appendChild(span);

    ///add remove icon
    var i = document.createElement("i");
    i.style.color='red';
    i.className = i.className + " fa fa-remove fa-2x pull-right";
    event.item.appendChild(i);

    //bind the new icon element
    jQuery(i).click(function () {
            console.log('Clicked the new remove button');
            $(this).closest("li").remove();
     });

    //in event you have a lot of information see it in the console
    console.log(event);
  }
  ...


text:
Q: Delete elements from array javascript Maybe by title seems a easy question, but I didn´t know how to do the shortest title for my question.
I want to delete elements from array on javascript, yes, but what I am looking for exactly is delete from array mismatched elements with other array on javascript (maybe it could be title, but too large).
For example:
Array A=> [a, b, c, d]
Array B=> [b,d]
Array C = deleteMismatchedElements(A,B)
Array C (after function)-> [b,d]

I suppose that using a nested foreach loop it could be possible, but I wonder if there is a better way, something as a "native" implemented method that could be called, or similar...
Thank you very much.

A: var C = [];
for(var i = 0; i < B.length; i ++){
    if(A.indexOf(B[i]) > -1){
        C.push(B[i]);
    }
}

What this does is

*
*Creates array C
*Runs through each item in B
*if B[i] is in A, add it to C


text:
Q: Kotlin-anko Relative Layout params problem Just started to learn kotlin with anko lib. Created a class for UI and got some problem with relative layout. Need to set below property for textView, but when i do that? its just ruins all UI. Here some pice of code. Whats wrong ?
relativeLayout {
    val image : ImageView = imageView(R.mipmap.ic_launcher).lparams {
        gravity = left
        padding = dip(8)
    }
    val u_name: TextView=textView {
        textSize = 20F
        text = "user name"
    }.lparams { margin = dip(5)
        below(image)
    }
}

A: Solved a problem by using id's insted of variables


text:
Q: $_POST not working I cannot get my $_POST to work for some reason..Here is the code:
*Javascript that gets called from href onClick event:*
function feedVote(postId, vote) {
    if(vote == "1") {
        document.getElementById('voteUpSpan' + postId).innerHTML = "Thank you for voting!";
        document.getElementById('voteDownSpan' + postId).innerHTML = "";
        var i = new Image();
        var d = new Date();
        i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
    }
}

So it spoofs a image and runs my voteUp.php page passing the parameters without changing the current page.
<?php
    $id = $_POST['postId'];
    $con = mysql_connect("localhost", "username", "password");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("database", $con);

    $update = mysql_query("UPDATE posts SET upvote = upvote + 1 WHERE id = '$id'");

    mysql_close($con);
    echo "$id";
?>

The echo "$id"; returns nothing so its obviously not even putting a variable in $id which is why my sql statement is not being run but why...
When I run the code in Google Crome, I use the network tracking feature under Inspect source code and this is the url it fires off when it runs my spoof image.
test.com/voteUp.php?time=1327644851907&postId=35
**I editted some of the information out like my database name and username/password and website url.

A: Those parameters are known as GET params, not POST.
Use the $_GET super global (use it in the same way as $_POST) to access them.

A: If you want post, do some jquery ajax post, like this:
Instead of:
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;

change it with this:
$.ajax({
    url: "voteUp.php",
    cache: false,
    type: 'POST',
    data: {time: d.getTime(), postId: postId},
    success: function(data){}
});

Note: you need jquery on that webpage!

A: Variables that appear in the query string of the URL (i.e. after the ? character) are accessed using the $_GET array rather than $_POST.


text:
Q: Issue related to textfield and datepicker I have an issue related to hide and show the datepicker view when click on textfield...Actually I have 2 textfields..Here is my problem image...
Problem
datepicker show and hide when click on textfiled...it should show on begin editing and hide on end editing...

At 1st time when we click on "textfield 1" its working good, but as soon as it resignFirstResponder and make 2nd field to respond, the problem occurs.
CODE
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    self.datepicker.alpha = 0.0
    self.datepicker.hidden = false
    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.datepicker.alpha = 1.0
        self.conDateHeight.constant = 100.0
        self.datepicker.addTarget(self, action: Selector("dataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
    })
    return true
}

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        UIView.animateWithDuration(0.3, animations: {
        self.datepicker.alpha = 0.0
        }, completion: {
            (value: Bool) in
            self.conDateHeight.constant = 0.0
            self.datepicker.hidden = true
        })
    return true
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    if textField == self.txtToDate {
        txtToDate.resignFirstResponder()
        txtFromDate.becomeFirstResponder()
    }
    else if textField == self.txtFromDate {
        txtFromDate.resignFirstResponder()
        txtToDate.becomeFirstResponder()
    }
    return true
}

When I hide keyboard after 1st textfield and then enter in second textfield its ok...otherwise the problem is as it is

A: Batter to use date picker as input view
UIView *viewDateInput = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 200)];
[viewDateInput setBackgroundColor:[UIColor whiteColor]];
self.pickerDate = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, viewDateInput.frame.size.width, viewDateInput.frame.size.height)];
self.pickerDate.datePickerMode = UIDatePickerModeDate;
[viewDateInput addSubview:self.pickerDate];
[self.pickerDate addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
[self.txtDate setInputView:viewDateInput];

Function For date Change
- (void)dateChanged:(id)sender
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTime = [dateFormatter stringFromDate:self.pickerDate.date];
self.txtDate.text = currentTime;
}


text:
Q: Find the maximum value in a drop-down list using jQuery? I have a drop-down list with numerical values:
<select name="a">
   <option value="1">asdsadas</option>
   <option value="1">wqecsdc</option>
   <option value="10">nmnmbn</option>
   <option value="16">assadsa</option>
   <option value="12">uuyuyuy</option>
   <option value="60">xzXz</option>
   <option value="55">vbbnbnm</option>
   <option value="13">eerrt</option>
</select>

I need to find the highest numerical value within this list. (In this case, it's 60.)
I was thinking of looping using .each, but is there a shorter way?

A: This works fine for me, pretty straight forward:
$('select option:last').val()

edit: misunderstood the question but might become handy for others, in most cases you have the options in the select element ordered desc or asc.

A: Something like this should work:
function findMaxValue(element) {
    var maxValue = undefined;
    $('option', element).each(function() {
        var val = $(this).attr('value');
        val = parseInt(val, 10);
        if (maxValue === undefined || maxValue < val) {
            maxValue = val;
        }
    });
    return maxValue;
}

alert(findMaxValue($('select[name=a]')));

A: This would work..!!
var temp=0;

var currentValue, maxValue;

$('select option').each(function(){

currentValue = $(this).val();

maxValue = Math.max(temp, currentValue);

temp=currentValue;

});

console.log(maxValue);

A:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="aktivite_type" id="aktivite_type">
  <option value="1">A</option>
  <option value="6">B</option>
  <option value="10">C</option>
  <option value="11">D</option>
  <option value="8">E</option>
  <option value="9">F</option>
  <option value="7">F</option>
</select>

<button onclick="JSF__selectLastTypeValue()">Select Value</button>

<script>

function JSF__selectLastTypeValue()
    {
    var temp=0;
    var currentValue, maxValue;
    $('#aktivite_type option').each(function(i,v)
        {
        currentValue = v.value;
        maxValue = Math.max(temp, currentValue);
        temp=maxValue;
        });
    $("#aktivite_type").val(maxValue);
    }

   </script>

A: var maxValue = undefined;
$('option', element).each(function() {
  var val = $(this).val();
  val = parseInt(val, 10);
  if(!isNaN(val)) {
    if (maxValue === undefined || maxValue < val) {
      maxValue = val;
    }
  }
});
return maxValue;


text:
Q: Getting two answers to: How many monoalphabetic substitution ciphers of $\{A,B,C,D\}$ are possible in which no letter is fixed? From Combinatorics by Mazur:

I am trying this with $\{A,B,C,D\}$ but I am getting two answers. If I enumerate then I get $9$.
$ABCD,\ ABDC,\ ACBD,\ ACDB,\ ADBC,\ ADCB$
$BACD,\ BADC(1),\ BCAD,\ BCDA(2),\ BDAC(3),\ BDCA$
$CABD,\ CADB(4),\ CBAD,\ CBDA,\ CDAB(5),\ CDBA(6)$
$DABC(7),\ DACB,\ DBAC,\ DBCA,\ DCAB(8),\ DCBA(9)$

However,
$U=4!$
$$|f_A \cup f_B \cup f_C \cup f_D| = |f_A|+|f_B|+|f_C|+|f_D|-|f_A \cap f_B|-|f_A \cap f_C|-|f_A \cap f_D|-|f_B \cap f_C|-|f_B \cap f_D|-|f_C \cap f_D|+|f_A \cap f_B \cap f_C \cap f_D|$$
$$|f_A \cup f_B \cup f_C \cup f_D|=3!+3!+3!+3!-2!-2!-2!-2!-2!-2!+1=13$$
So, $$U-|f_A \cup f_B \cup f_C \cup f_D|=4!-13=11$$
What is wrong?

A: You skipped the terms with $3$ restrictions in the inclusion-exclusion sum. It should end with ${}+1!+1!+1!+1!-0!$ instead.

A: Rather than spot your arithmetic error, perhaps it would help to see an easier derivation of a recursive formula for this number.
Let's denote the number of permutations of $n$ letters which fix no letter as $!n$.
Let's choose where to send $A$, say $A$ goes to $X$. Now $X$ has two options. If $X$ goes to $A$, then we have reduced to the problem of counting $!(n-2)$. If $X$ promises not choose $A$, then we have reduced to the problem of counting $!(n-1)$ (each of the $n-1$ letters have exactly one forbidden choice out of the remaining $n-1$ slots: $X$ has voluntarily forbidden himself to $A$, and the rest are forbidden their own slots).
So $!n=(n-1)(!(n-1)+!(n-2))$
To calculate $!4$ we get:
$!1=0$
$!2=1$
$!3=(3-1)(!(3-1)+!(3-2))=2$
$!4=(4-1)(!4-1)+!(4-2))=3(2+1)=9$
The function you are talking about is known as the subfactorial of $n$, commonly denoted $!n$, and what it counts are the derangements of $n$ letters.


text:
Q: Where should the text in parentheses be placed? In the sentence:

The constant IO::SEEK_CUR assumes that
  the offset is relative to the current
  position (which may be negative).

offset is meant to be negative, not current_position. Is the above sentence correct or is one of the following the correct one:

The constant IO::SEEK_CUR assumes that
  the offset (which may be negative) is
  relative to the current position.

or

The constant IO::SEEK_CUR assumes that
  the offset, which may be negative, is
  relative to the current position.

A: Generally text in parentheses should be immediately following the text it is modifying.  Therefore,

The constant IO::SEEK_CUR assumes that
  the offset (which may be negative) is
  relative to the current position.

would be more appropriate than the first option.  The third option,

The constant IO::SEEK_CUR assumes that
  the offset, which may be negative, is
  relative to the current position.

would be ok as well, but the second most clearly communicates the meaning you're trying to convey.


text:
Q: How to find location of package? I am building an R package (let's call it "pkg"), and would like to write a function that downloads a file from the internet and saves it in the "inst/extdata" directory in my package's directory.
 download_file <- function(link) {
     path <- ... # path to where "pkg" is stored
                 # something along the lines of ....../pkg
     download.file(link, paste(path, "inst/extdata", "newfile", sep = ""))
 }

Could you please help me get the "path"? While developing the package, I can just do "getwd()" -- however, when a user calls my package, her working directory might not be the pkg directory. In which case, how do I get the path to my package's directory?

A: Just run .libPaths() and it will show you the filepath to your library folder. Inside the library folder you can see all your packages.


text:
Q: GCP Documentation - Task Queue bucket_size and rate I read a lot of articles and answers here about Google Task, my doubt is "rate" and "bucket_size" behavior.
I read this documentation:
https://cloud.google.com/appengine/docs/standard/java/configyaml/queue
The snippet is:

Configuring the maximum number of concurrent requests
If using the default max_concurrent_requests settings are not
  sufficient, you can change the settings for max_concurrent_requests,
  as shown in the following example:
If your application queue has a rate of 20/s and a bucket size of 40,
  tasks in that queue execute at a rate of 20/s and can burst up to 40/s
  briefly. These settings work fine if task latency is relatively low;
  however, if latency increases significantly, you'll end up processing
  significantly more concurrent tasks. This extra processing load can
  consume extra instances and slow down your application.
For example, let's assume that your normal task latency is 0.3
  seconds. At this latency, you'll process at most around 40 tasks
  simultaneously. But if your task latency increases to 5 seconds, you
  could easily have over 100 tasks processing at once. This increase
  forces your application to consume more instances to process the extra
  tasks, potentially slowing down the entire application and interfering
  with user requests.
You can avoid this possibility by setting max_concurrent_requests to a
  lower value. For example, if you set max_concurrent_requests to 10,
  our example queue maintains about 20 tasks/second when latency is 0.3
  seconds. However, when the latency increases over 0.5 seconds, this
  setting throttles the processing rate to ensure that no more than 10
  tasks run simultaneously.
queue:
# Set the max number of concurrent requests to 50
- name: optimize-queue
    rate: 20/s
    bucket_size: 40
    max_concurrent_requests: 10

I understood that queue works like this:
The bucket is the unit that determine amount of tasks that are execute.
The rate is amount of bucket are fill to execute per period.
max_concurrent_requests is the max simultaneously can be executed.
This snippet here maybe strange:

But if your task latency increases to 5 seconds, you could easily have
  over 100 tasks processing at once. This increase forces your
  application to consume more instances to process the extra tasks,
  potentially slowing down the entire application and interfering with
  user requests.

Imagine that max_concurrent_requests is not setted.
For me, it is impossible execute more than 100 tasks because the bucket_size is 40. For me, the low tasks would impact on time that tasks will be wait for a empty bucket.
Why the documentation said that tasks can have over 100?
if the bucket is 40, can more than 40 run simultaneously?
Edit
The bucket is fill up just the all tasks were executed or if some bucket is free in next rate will be increase?
Example:
40 buckets are executing.
1 bucket finished.
Imagine that each bucket spend more than 0.5 seconds and some bucket more than 1s.
When 1 bucket is free, this will fill up in next second or the bucket wait all tasks finishing before bucket fill up again?

A: Bucket size is defined more precisely in the doc you link, but one way to think of it is as a kind of initial burst limit.
Here's how I understand it would work, based on the parameters you provided in your question:

*

*bucket_size: 40

*rate: 20/s

*max_concurrent_requests: 10

In the first second (t1) 40 tasks will start processing. At the same time 20 tokens (based on the rate) will be added to the bucket. Thus, at t2, 20 tasks will be primed for processing and another 20 tokens will be added to the bucket.
If there is no max_concurrent_setting, those 20 tasks would start processing. If max_concurrent_setting is 10, nothing will happen because more than 10 processes are already in use.
App Engine will continue to add tokens to the bucket at a rate of 20/s, but only if there is room in the bucket (bucket_size). Once there are 40 tokens in the bucket, it will stop until some of the running processes finish and there is more room.
After the initial burst of 40 tasks is finished, there should never be more than 10 tasks executing at a time.


text:
Q: How to use this function AddToArray? I took from here http://fydo.net/gamedev/dynamic-arrays  the quality of the dynamic array.
But I do not know how to use it and I get this error:
test.c: In function 'main':
test.c:26:25: warning: comparison between pointer and     integer [enabled by default]
test.c:35:39: error: expected expression before 'DATA'
test.c: In function 'AddToArray':
test.c:72:17: warning: implicit declaration of function 'realloc' [-Wimplicit-function-declaration]
test.c:72:30: warning: incompatible implicit declaration of built-in function 'realloc' [enabled by default]

I'm trying to do it like this:
fprintf(stdout, "%d\n", AddToArray(DATA 5));

I read the tutorial and know the syntax of the language, but for some reason they did not teach me that. So tell me how to use this function correctly

A: What you have is syntactically incorrect.  The AddToArray function expects to be passed a variable of type DATA.  What you're doing is passing the name of the type followed by whitespace followed by an integer constant, which is invalid.
Declare a variable of type DATA, populate the fields, then pass that variable to AddToArray.
Also, the compiler is complaining that there is no declaration for realloc.  You need to #include <stdlib.h> to get it.

A: There's an example of how to use the function on the page you linked to:

I've got a little example available right here:
Download Example – (arrays.c – 2kb)

I'd suggest you start with that and modify the code until you understand it and can use it for whatever it is you are intending to do.


text:
Q: How can you change ident, which shows up as ident@hostname.com on ircll? I know the nickname and the real name field can be changed with environment variables such as IRCNICK and IRCNAME. However, the documentation does not tell you how the ident is changed. (The ident is the name that's used when you /whois nickname, and it shows up as part of ident@username.com in the host field, and the bolded part is what I'm trying to figure out how to change)
I'm wondering if this is possible on the ircll client.

A: It sounds like you want IRCUSER.

A: Talk to the machine administrator. It's a system-level thing. IRC uses RFC 1413 to determine the identify of the connections it receives. The client has no control over it. (Except for some Windows clients that have an embedded ident server. That won't work on UNIX though, since you'd need root permissions to listen on the ident port.)

A: If you are running your own server, you can install your own identd to spoof and say whatever you want. See Wikipedia for more info.

A: Since this question still comes up as first on Google search, I will add what works for me.
I am using Irrsi, when I am connected to the IRC server of my choice using /connect, next command I issue:
/set user_name myfavident
/save

Now I restart Irrsi and my /whois will show myfavident@myip.


text:
Q: Cancel action after cancel button on alert is clicked Please, help me. I want to display confirmation box for delete action. If the user click okay then it will proceed. But if the user click cancel, it cancel the delete operation or go back to the same page. I did the code in javascript but it's not working. when I clicked on cancel on confirmation alert it still proceed to delete action.

  function confirmation() {
    if (confirm("Are you sure you want to delete the reservation?"))
      return true;
    else
      return false;
  }

  <a href="updateStaffServlet?action=update&sID=<c:out value=" ${staff.staffID} "/>"class="btn btn-icons btn-rounded btn-light">

  <a onclick="confirmation()" href="deleteStaffServlet?action=delete&sID=<c:out value=" ${staff.staffID} "/>" id="dltbtn" class="btn btn-icons btn-rounded btn-light">

A: this is not the best way but you can pass url to your confirmation function and if user confirmed, redirect him.

  function confirmation(url) {
    if (confirm("Are you sure you want to delete the reservation?"))
      location.replace(url);

  }

  <a href="updateStaffServlet?action=update&sID=<c:out" value=" ${staff.staffID} " class="btn btn-icons btn-rounded btn-light">

update link

  <a onclick="confirmation('deleteStaffServlet?action=delete&sID=<c:out')" value=" ${staff.staffID} " id="dltbtn" class="btn btn-icons btn-rounded btn-light">

delete link

but i recommend you learn basics about ajax and send delete request without redirecting page.


text:
Q: Python automatically extract list index in and append data I don't know how to describe the problem. Given an example:
a=[[1,2],[3,4],[5,6]]
b=[['a','b'],['c','c']]
x=[a,b]

Now I want to append the elements of elements of x to their previous elements, (in this case b's elements on every a's elements), that I can use
t=[]
for i in a:
    for j in b:
        t.append(i+j)

then  my desired result became:
t
[[1, 2, 'a', 'b'],
 [1, 2, 'c', 'c'],
 [3, 4, 'a', 'b'],
 [3, 4, 'c', 'c'],
 [5, 6, 'a', 'b'],
 [5, 6, 'c', 'c']]

In this case I know there are a and b in x, so I can append them. However, if I don't know how many items in x, how could I append the elements?
like x=[a,b,c,d,e,...]
Have tried with loops, but seems not good. I am thinking combination but not sure how to do that.

A: Generate pairwise products and flatten them using itertools' product and chain functions (respectively):
from itertools import chain, product
t = [list(chain.from_iterable(i)) for i in product(a, b)]

print(t)
[[1, 2, 'a', 'b'],
 [1, 2, 'c', 'c'],
 [3, 4, 'a', 'b'],
 [3, 4, 'c', 'c'],
 [5, 6, 'a', 'b'],
 [5, 6, 'c', 'c']]

This solution will generalise to any number of lists:
x = [a, b, c, ...]
t = [list(chain.from_iterable(i)) for i in product(*x)]


text:
Q: Adding roads to SKMaps I was wondering if there was a way to edit Skobbler maps (online or through some kind of software) and then use the resulting map in my project? For example, could I add a trail which is not in currently in OSM? I sent a message to the Skobbler support team, but have not received a reply.
Many thanks

A: By default, Scout SDK uses OpenStreetMap as a map data source – the OSM maps are processed to our proprietary format (.skm). Add your map data that is missing in OSM and this will be picked up when we reprocess our maps (each release contains updated maps)
Another possibility to create a certain trail could be to use the custom routing feature: create a route based on a custom GPX file or by specifying an array of points as input. See more details here:
http://sdkblog.skobbler.com/creating-routes-from-gps-points-gpx-track-navigation/


text:
Q: How can I do git merges in such a way that they are easy to roll back? There is lots of talk about how it's not easy to "undo" a merge in git. Short version: if you undo a merge commit, it also tells git to never merge those changes back in in the future.
Is there something I can do when doing the merge in order to abate this problem? There are plenty of situations where undoing a merge would be really, really useful, just in the normal course of software dev, and more crucially, in controlling the state of a release branch, when changes need to be rolled back.
edit
I have seen the solution in this article and don't really consider it a solution, more of an explanation of the problem. It requires

*

*always use --no-ff

*remember all your undone-merges when you want to bring back in code that depends on them (this could be a few hours, days, week, or months in the future…)

what I want
Here is how it works in Subversion. Let's say I have a branch called "release-candidate", which is what we run on the staging server and where we try out features. Let's say I merge in feature A branch. In Subversion, it's all one changeset, and all history for all files is merged. Let's say we don't like it, so we want to take it out. We just undo that single changeset, and don't have to think about anything else. We can merge feature branch A back in at any time in the future without having to remember that we at one point merged it in and took it out.
I'd like to be able to get as close to that flow as possible. I'd like to optimize for "not having to remember stuff in the future", even if it makes things take more steps along the way somehow. (this might be impossible...)

A: UPDATE:
A workflow that makes it easier to work with branch-per-feature is here: http://dymitruk.com/blog/2012/02/05/branch-per-feature/

(the SVN part of the question has been answered at the end)
Yes, here is how you reintroduce a feature that you unmerged. Consider the following history (assumes you "undid" a merge already):
x---x----x--x---x--M--U--L
     \            /
      x--x--x--x-F

F is the feature branch, M is the merge, U is the opposite when you unmerge that feature, L is the latest commit.
Here are your choices:

*

*revert U (no --force necessary to push):
x---x----x--x---x--M--U--L--^U
    \            /
     x--x--x--x-F

*rebase F onto L (and then merge --ff-only F') (no --force necessary to push):
x---x----x--x---x--M--U--L
     \            /       \
      x--x--x--x-x         x'--x'--x'--x'--F'

*rebase F onto L (and then merge --no-ff F' - preserves your new branch point) (no --force necessary to push):
x---x----x--x---x--M--U--L-------------------M2
     \            /       \                 /
      x--x--x--x-x         x'--x'--x'--x'--F'

*rebase -i head^^ and eliminate U from the list (--force is necessary to push):
x---x----x--x---x--M--L
     \            /
      x--x--x--x-F

*rebase --onto M^1 L^ L to get rid of the merge and unmerge. Now you can remerge F later.
                  L'
                 /
x---x----x--x---x--M--U--L
     \            /
      x--x--x--x-F

To squash all the feature commits, use the --squash modifier on the initial merge. I'll let your imagination do the work on how that would look in history. There is a reason I don't recommend doing this. There is value in knowing how you got a feature working and what steps it took. Subsequent merges will be easier since Git can examine the history of why a certain file looks like it does. Squashing the commits together loses that information.
There are additional drawbacks that may or may not affect your ability to take advantage of rerere history.
What I recommend is always marking what is released with a blank merge in master. This is done via a merge with the --no-ff option. You never work on master and the only commits that are done there are those merges - no code change commits. In the QA branch, you tag the commit that marks the point at which you released. So when you do git merge --no-ff rc-12.2, you will autogenerate a commit comment "merged rc-12.2".
Check out git-flow.
Hope that provides you more detail.


text:
Q: What are the advantages of using a container element for lists in XML? When specifying XML formats that contain a list of items, there is often a choice of at least two distinct styles. One uses a container element for the list, the other doesn't. As an example: if specifying a document with multiple pages, one could do this:
<document>
  <title>...</title>
  <pages>
    <page>...</page>
    <page>...</page>
  </pages>
</document>

Or just this:
<document>
  <title>...</title>
  <page>...</page>
  <page>...</page>
</document>

What are the pros and cons of each approach?
Some I can think of are:

*

*the former allows expressing an explicit empty list (useful if the list itself is a conceptual entity)

*the former is probably slightly better for error recovery (although that shouldn't matter if XSD validation is used)

*the latter is more concise

*the latter doesn't require a distinction between adding the first element or any successive (no management of the container element)

EDIT
To clarify: I am assuming there is no meaning attached to the pages element. There are no other elements inside, no attributes attached and it is hard to find any other name than 'pages', 'pageList' or similar for it.
EDIT 2
I found another entry about the same question. While the answer are all for the container/parent element, it seems to come down to treating the container as actual object or the assumption that it is easier to model a schema by having that extra container element (which I tend to disagree with).

A: In the example you have given the difference is subtle, however the two examples actually represent completely different things:

*

*The second example is of a document which has a title and many pages

*The first example however is of a document with a title and a collection of pages
Like I said, in your example the difference is superfluous and so it is easy to miss, so instead consider the following slight variation:
<document>
  <title>...</title>
  <contents>
    <page>...</page>
    <page>...</page>
  </contents>
  <chapter name="chapterName">
    <page>...</page>
    <page>...</page>
  </chapter>
  <index>
    <page>...</page>
    <page>...</page>
  </index>
</document>

In this case the document has many collections of pages.  (Of course some might argue that you could equally represent this differently):
<document>
  <title>...</title>
  <page section="contents">...</page>
  <page section="chapter1">...</page>
  <page section="index">...</page>
</document>

However you would have had to change the page element, in the above example I'd argue for the worse (why should page have to know about what it is contained in?)
Another subtle consideration is that often the ordering of elements means something:
<document>
  <page>...</page>
  <title>...</title>
  <page>...</page>
  <page>...</page>
</document>

In this example we have (for whatever reason) a page before the title - obviously not possible when using collections.  Another consideration is that each collection might also (for example) have a title.
My point is that they are representing different things - it's not really a case of pro's vs con's so much of a case of choosing the format that most closely matches your data model.

A: It is really a matter of personal choice although the first form is more powerful, IMO. t makes multiple pages, e.g. pages with different name possible. It just depends on your requirement.
<document>
  <title>...</title>
  <pages name="page1">
    <page>...</page>
    <page>...</page>
  </pages>
  <pages name="page2">
    <page>...</page>
    <page>...</page>
  </pages>
</document>

A: If you're following the Venetian Blind style for XSD-validating your XML with collections of direct containerized elements, and if you want those elements to contain key-like attributes unique locally: you will have nowhere to place your xs:key definitions. Those are not allowed to be directly under xs:complexType or xs:complexContent which will be your only direct parent of the collection elements. Purist Venetian Blind style with explicit global polymorphic complex types will be impossible without those extra containers with the element name pluralized. This is not a conceptual, but a tools limitation.


text:
Q: Give Border To Texture - SetPixel I'm trying to dynamically add a border to a texture of mine. So far, I have a border at the top, and at the bottom. But struggling to get a left and right border. This is what I have so far:
var i = image;
var pixels : Color[] = i.GetPixels(0, 0, i.width, i.height, 0);
var br : int = 1;

for(var p = 0; p < pixels.Length; p++){

    var b : int = 30;

    //Bottom
    if(p < i.width * b)
        pixels[p] = new Color(1,0,0,1);

    //Top
    if(p > (i.height * i.width) - (i.width * b))
        pixels[p] = new Color(1,0,0,1);

    //int when a new row of pixels has began
    if(p > i.width * br)
        br++;

}

The pixels are read from bottom left, to top right. I just can't seem to get my head around the maths.
Thanks

A: Probably the easiest way to get x position of a pixel is to use modular operator (%), which returns the remainder.
Here is a code calculating the x position and setting the border based on that:
// Left
if(p % i.width < b)
    pixels[p] = new Color(1,0,0,1);

// right
if(p % i.width > i.width - b)
    pixels[p] = new Color(1,0,0,1);


text:
Q: Shut down after offline updates with PackageKit from command line When PackageKit has updates fetched for installation and you use the Gnome GUI to shut down the machine, it is possible to set a checkbox to install updates before shut down. How can this be accomplished from command line without root? Example purpose: automating the execution of custom commands before shut down.

A: # This will force fetching repository data and updates
pkcon get-updates
pkcon update --only-download

dbus-send --system --type=method_call --print-reply \
  --dest=org.freedesktop.PackageKit \
  /org/freedesktop/PackageKit \
  org.freedesktop.PackageKit.Offline.Trigger \
  string:power-off

if pkcon offline-get-prepared; then
  systemctl reboot
else
  systemctl poweroff
fi

If you remove the dbus-send command and replace the if block by systemctl reboot, the system will reboot instead.


text:
Q: Numpy installation error. (Mingw32CCompiler instance has no attribute 'compile_options') I use python with windows8 / anaconda spyder (2.7)
I'm trying to update Theano up-to-date. When I installing the theano by
"pip install --upgrade theano"

The error happens at numpy installation part.
Though numpy is available to use in anaconda GUI, But is not shown in anaconda terminal. (pip show numpy outputs nothing)
The error is like below (when I try to install numpy, same error happens)
  File "c:\users\user\appdata\local\temp\pip_build_user\numpy\numpy\distutils\command\build_src.py", line 329, in build_extension_sources

    sources = self.generate_sources(sources, ext)

  File "c:\users\user\appdata\local\temp\pip_build_user\numpy\numpy\distutils\command\build_src.py", line 386, in generate_sources

    source = func(extension, build_dir)

  File "numpy\core\setup.py", line 455, in generate_config_h

    rep = check_long_double_representation(config_cmd)

  File "numpy\core\setup_common.py", line 191, in check_long_double_representation

    cmd.compiler.compile_options.remove("/GL")

AttributeError: Mingw32CCompiler instance has no attribute 'compile_options'

----------------------------------------
Cleaning up...
  Removing temporary dir c:\users\user\appdata\local\temp\pip_build_user...
Command C:\Anaconda\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\user\\appdata\\local\\temp\\pip_build_user\\numpy\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\user\appdata\local\temp\pip-nm4fpu-record\install-record.txt --single-version-externally-managed --compile failed with error code 1 in c:\users\user\appdata\local\temp\pip_build_user\numpy
Exception information:
Traceback (most recent call last):
  File "C:\Anaconda\lib\site-packages\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "C:\Anaconda\lib\site-packages\pip\commands\install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "C:\Anaconda\lib\site-packages\pip\req.py", line 1435, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "C:\Anaconda\lib\site-packages\pip\req.py", line 706, in install
    cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
  File "C:\Anaconda\lib\site-packages\pip\util.py", line 697, in call_subprocess
    % (command_desc, proc.returncode, cwd))
InstallationError: Command C:\Anaconda\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\user\\appdata\\local\\temp\\pip_build_user\\numpy\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\user\appdata\local\temp\pip-nm4fpu-record\install-record.txt --single-version-externally-managed --compile failed with error code 1 in c:\users\user\appdata\local\temp\pip_build_user\numpy

A: This is most likely a numpy issue. Unfortunately I could not upgrade theano even after the fix I will suggest, but following a step by step guide like this one might work.
This specific problem occurs because numpy.distutils.misc_util.mingw32() returns False while it shouldn't. See also this discussion and the source
. I decided to set manually the system variable MSYSTEM to MINGW32 which was not defined in my system and which I find unlikely to break any other behavior.
As I said this does not guarantee that the upgrade will work nor that there will be no side effects, but it will solve the issue mentioned here.


text:
Q: Flexible in-app updates download in the foreground rather than the background I have implemented flexible and immediate in-app update flows on my Android app. I fetch the update type from a remote server, and then use if-else to determine which update type to trigger. As of now, I am experiencing two issues.

*

*The flexible update is not providing a background download. Pressing the update button displays a full screen with download progress.

*The immediate update does not restart the app after installation. The user needs to manually open the app.

It is important to note that when I implement only the flexible flow, the flow will work correctly, and the background download will work while the user interacts with the app.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkForInAppUpdate();
}

private void checkForInAppUpdate() {
    try {
        appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
                if (triggerUpdate
                        && appUpdateInfo.updatePriority() > 3
                        && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                    requestImmediateUpdate(appUpdateInfo);
                } else if (triggerUpdate
                        && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                    requestFlexibleUpdate(appUpdateInfo);
                }
            }
        });

        appUpdateInfoTask.addOnFailureListener(Throwable::printStackTrace);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void requestFlexibleUpdate(AppUpdateInfo appUpdateInfo) {
    try {
        appUpdateManager.startUpdateFlowForResult(
                appUpdateInfo,
                AppUpdateType.FLEXIBLE,
                this,
                FLEXIBLE_UPDATE_CODE);
    } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
    }
}

private void requestImmediateUpdate(AppUpdateInfo appUpdateInfo) {
    try {
        appUpdateManager.startUpdateFlowForResult(
                appUpdateInfo,
                AppUpdateType.IMMEDIATE,
                this,
                IMMEDIATE_UPDATE_CODE);
    } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
    }
}

@Override
protected void onResume() {
    super.onResume();

    appUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
        if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
            // If an in-app update is already running, resume the update.
            requestImmediateUpdate(appUpdateInfo);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == IMMEDIATE_UPDATE_CODE && resultCode != RESULT_OK) {
        checkForInAppUpdate(); // if in any case update request is cancelled and failed
    }
}

A: Removing the Immediate update listener from onResume() and moving it inside my custom checkForInAppUpdate method fixed my use case.
private void checkForInAppUpdate() {
    try {
        appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
                if (triggerUpdate
                        && appUpdateInfo.updatePriority() > 3
                        && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                    requestUpdate(appUpdateInfo, AppUpdateType.IMMEDIATE);
                } else if (triggerUpdate
                        && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                    requestUpdate(appUpdateInfo, AppUpdateType.FLEXIBLE);
                } else if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                    requestUpdate(appUpdateInfo, AppUpdateType.IMMEDIATE);
                }
            }
        });

        appUpdateInfoTask.addOnFailureListener(Throwable::printStackTrace);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: Sorting data from .txt file I am running some query's on mysql through python. Once reading the data I would want to sort them by percentage. Any help would be gladly appriciated.
The method I am using to write is:
def mid_critical(controller,code):
critical = 75
mid_critical = 50

cursor = controller.cursor()
cursor.execute(code)    # execute code

with open('report.txt', 'a') as f:
    print("\n******************* Mid Critical: **************", file=f)
    for r in cursor:  #show tables one by one
        if str(type(r[5])) == "<class 'decimal.Decimal'>":
            percent = r[5] / r[2] * 100
            if percent > mid_critical and percent < critical:
                print(r[1],"\nOwner:",r[8],"\nValues:",r[5],"out of", r[2] ,"\nPercent used: %d%% \n" %(percent), file=f)

code is the query that is being ran.
controller is credentials to make a succesful communication.
Once writing to the file is:
POC
Owner: ACE
Values: 45.1 out of 81.5
Percent used: 55%

DESKTOP
Owner: Nan
Values: 231.8 out of 329.2
Percent used: 70%

REGRESSION
Owner: None
Values: 6.6 out of 10.2
Percent used: 64%

For the sake of an example I only show 3, there is houndreds more.
The output I am seeking would be
DESKTOP
Owner: Nan
Values: 231.8 out of 329.2
Percent used: 70%

REGRESSION
Owner: None
Values: 6.6 out of 10.2
Percent used: 64%

POC
Owner: ACE
Values: 45.1 out of 81.5
Percent used: 55%

A: To sort the data, you need to get the data out of the database, sort it, then print it to the file instead of writing to the file after each row. Something like this:
def calc_percent(r):
    return r[5] / r[2] * 100

with open('report.txt', 'a') as f:
    print("\n******************* Mid Critical: **************", file=f)
    rows = []
    for r in cursor:  #show tables one by one
        if str(type(r[5])) == "<class 'decimal.Decimal'>":
            percent = calc_percent(r)
            if percent > mid_critical and percent < critical:
                rows.append(r)
    rows.sort(key=calc_percent)

    for r in rows:
        percent = calc_percent(r)
        print(r[1],"\nOwner:",r[8],"\nValues:",r[5],"out of", r[2] ,"\nPercent used: %d%% \n" %(percent), file=f)

A: BigO.
Maybe you should consider calculating the percentage inside your MySQL Query and using ORDER BY to get the order right.
Then, on python you'll already have the records in the order you intended.
For example:
SELECT * FROM
(
   SELECT Number1,Number2,Number1/Number2 AS Percentage
   FROM Table
) subquery
ORDER BY Percentage

Then do whatever you want with the data

A: Append sections to a list, sort the list of lists by the last element, and then output the list:
from operator import itemgetter

report = []
for r in cursor:  # show tables one by one
    if str(type(r[5])) == "<class 'decimal.Decimal'>":
        percent = r[5] / r[2] * 100
        if percent > mid_critical and percent < critical:
            report.append(
                (
                    str(r[1]),
                    "\nOwner:",
                    str(r[8]),
                    "\nValues:",
                    str(r[5]),
                    "out of",
                    str(r[2]),
                    "\nPercent used: %d%% \n" % (percent),
                )
            )

report.sort(key=itemgetter(-1), reverse=True)

with open("report.txt", "a") as f:
    print("\n******************* Mid Critical: **************", file=f)
    print("\n".join(report))


text:
Q: How to calculate the derivative of a function in $\mathbb{Q}_p$? On Wikipedia it is stated that the function
$$
f:\mathbb{Q}_p\to \mathbb{Q}_p
$$
with $f(x)=(1/|x|_p)^2$ if $x\neq 0$ and $f(0)=0$ is differentiable and its derivative is the zero-function.

How can I see that? More generally, how can I derivate a function of $p$-adic numbers explicitely?

A: By definition (yes, it's the same as in the general real case):
$$f'(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}h=\lim_{h\to 0}\frac{\frac1{|x+h|_p^2}-\frac1{|x|_p^2}}h=$$
$$=\lim_{h\to 0}\frac{p^{2\nu_p(x+h)}-p^{2\nu_p(x)}}h=0$$
Since when $\;h\;$ is very close to zero, clearly both $\;x\;$ and $\;x+h\;$ are divided by the same power of the prime $\;p\;$ (which is what the $\;p-$adic valuation $\;\nu_p(x)\;$ gives) ...