text:
Q: Beginning Phone Applications Development I've been developing applications for a long time now, but now I want to jump into Phone applications development. There are four main candidates:

*

*Nokia's Symbian

*Apple's iPhone

*Google's Android

*Microsoft Windows Mobile Phone

Can anyone suggest one, considering documentation, market, samples and availabilty of emulators, I'm not a millionaire so I can't buy it unless I know it would mean profits!
I don't have much preferences as for languages, but to stay within C# would be nice, however I've been thru Assembler for a long time, so it's hard to scare me :)

A: First, you forgot RIM (Blackberry's OS). You will find this graph usefull to analyzie your audience (I think the graph is for the USA only): Source of the image

Microsoft Phone 7 will soon reach the market with new devices so it is hard to tell what market share they will take. Their IDE for Windows Phone 7 is free and it supports C#.
Can't say much about the other OSs other than the fact that iOS has the most extensive store and fanatic fans that are willing to buy those apps- but that info is only from what I read on the net and see from friends around me.
You may find the beginning-phone-applications-development question helpful as well.

A: If your plan is to create and market Paid apps, versus just free ones, don't forget to also consider and evaluate potential revenues and existing competition, instead of just your development cost of entry.
My local, and not necessarily statistically significant, sample shows a larger number of iPhone developers making more money than Android developers.  The amount of money to be made, if you produce an app just near the top 10% of apps in many categories, may be well over enough to amortize the higher initial costs of a development system, certificates and testing with iOS devices.
However, for iPhone development, you may have to create a stand-out app, as many app niches in the App store are already filled with several dozens of apps.  The absolute number of potential competing apps in the Android store is far lower in many areas.  You will need to evaluate the competition in your area of expertise or interest.

A: Windows Phone 7's API will be based on C#, but most of the other stuff about it is still speculation.
Android has the lowest cost of entry, essentially free - and will use Java (which is very similar to C#).
The iPhone has a higher cost of entry - you need to own a Mac (or somewhat less legally, a hacked together OSX install). Plus once you've devloped your app it costs $99 per year to become a registered developer, allowing you to put the app on actual phones, and sell through the App Store. You'll also need to learn Objective-C, which uses a syntax which is a little different to C# and Java.
On the flip side to this, the iPhone tools are very good, and the market is huge, there are also some good online free courses (including the videos of the Stanford course available on iTunes).
Don't know much about the Nokia toolset, and I wouldn't start developing for old-school Windows Mobile now - it's a dead-end.

A: Some thoughts:

*

*If you have a mac then the choice is certainly the iPhone since all the development tools are free.

*AFAIK the Android SDK is an Eclipse extension and can run on pretty much any environment, and is also free.

*Mirosoft charges for its IDE, and probably has the smallest audience.

I am pretty sure you will find more community support for iPhone or Android development too.

A: There are many factors to consider such as where the biggest market is, and so on.  But ignoring those factors and thinking just about technical and money issues, the clear answer is start with Android.
The Android SDK is totally free.  The iPhone dev tools need a Mac, so if you're not a Mac user, you need to buy a Mac.  If you're not a Mac user, then it's probably a safe bet that you don't already know Objective C, which you'll need for iPhone.  You don't even need a phone, there is an emulator that works wonderfully.  It's very rare that I've made something that works in the emulator but doesn't work or works differently on a real phone.  So the emulator is quite excellent.
Android programming is Java, and is very similar to C#.
Android development is much more approachable and easy for development (for getting started at least) than Objective C and iPhone.
There are many online resources available, but the book "Hello, Android" is actually very good.  It's dated, though, goes back to version 1.5 of the SDK and we're at 2.2 today, but the fundamentals for getting started are pretty much the same.
You may decide to go another way, but in a handful of hours you can be writing your first Hello World program on Android free of charge.  Even if you decide to start on another platform, you can hardly go wrong by giving Android a shot first.
Another thing that's worth noting is that Android is way easier to sell and distribute your apps than iPhone, making it a better place to start.  There is no app approval process with the Android marketplace, so you can have your app posted for sure without wondering whether the powers that be will approve your first app for sale or to give away.
It bears mentioning that if you go the Microsoft route, your C# experience will transfer almost completely, and you'll be amazed at how close the compact SDK is to writing plain Windows apps.  (At least, it was in 2007, the last time I wrote a Microsoft phone app.) But forget I brought this up-- if you want to be a serious phone developer for consumers, I recommend you forget about Microsoft at least for now.

A: There are also cross platform options, such as PhoneGap, which may be worth your consideration.

A: With all technical considerations being roughly equivelant, the most "profitable" platform would have to be the one with the largest untapped consumer base for the particular app(s) you intend to develop.
Two factors come into play which you can assess

*

*Size and growth potential of the market. There are plenty of charts and opinion articles around on this to allow you to make an assessment. If you can't find them, just drop those 4 topics you listed into google alerts and watch the incoming articles to your mailbox for a while.

*Saturation of the app marketplace, in particular in the markets your app addresses. Your own market research would be best at identifying this.
The only other consideration which may apply to specific types of apps would be if there is a fundamental feature your app requires of the platform, and whether respective platforms support it. For example you won't get far making a flash based player on iPhone.


text:
Q: Java Throwing exceptions vs returning response in catch I know a lot has been discussed around exception handling, however I need some advice specific to my situation.
I am currently working on a Spring MVC application with Controller->Services->DAO layers. The service classes catch mainly two kinds of exceptions HibernateException and IOException.
HibernateException because service needs to perform rollback if a transaction did not succeed and IOException since it is an unchecked exception and needs to be caught or thrown and I prefer the first option.
Now what would be a better way of handling these further up in the stack :

*

*Should I rethrow these exceptions to the controller and in the
ExceptionHandler of the controller send a HTTP error-code 500

*Or in the catch block create the normal JSON response object, setting status=failure and the appropriate error message and return this to the Controller?

A: Exception Handling convensions:
There is a saying that, best way of handling Exception is not to handle it!
For Spring's convention of controller<->service<->dao layers, Exception handling mechanism is known as Bubble up. Any exception occurs in the dao or service layer, you should pop it up to the controller layer (by adding throws XXXException in dao and service layer's method signature, is the most common way). Only controller layer should handle Exceptions.
Here is a nice tutorial of how you can handle exceptions for REST with spring.
Send HTTP Status code 500 or JSON object with status:
Sounds like you are writing API with Spring MVC. Look, when you are writing API's you should follow the proper conventions. It is Globally accepted that for internal server errors you send HTTP response with code 500, that means internal server errors.
There are number of causes for what you should not send JSON response in this case. One of the main cause is the implicit assumption of your API client. That is HTTP response with code 200 with a JSON object means every thing went normal. And thus the client side business logic may reflect that assumption which is wrong eventually.
Here you can see some API error code conventions for some well-known organizations:

*

*twitter

*LinkedIn

*Facebook Graph API

A: I assume that you have not come so far yet as to create a client and therefor can pick 100% for yourself.
If so I would also recommend to use 1, for the main reason that using the correct status codes can go a long way in your API, as well as it's a very easy solution to your problem. You can write some neat code for your error handling.
Another major reason why you should use your first point is because you can easily re-use the error handling for other APIs, resources or webapps.
For example an enum with all your errors, and what status code you consider them to be, and you can also include what log level you want them to be.
public enum ExceptionMapping {
IllegalArgumentException(IllegalArgumentException.class, 400, LogLevel.ERROR),

If your goal is to build a neat API for unknown clients I would recommend reading more about REST level 3 (http://martinfowler.com/articles/richardsonMaturityModel.html) where you includes hypermedia links to create an API which allows the client to "browse" your full API. It's more work for the client since they have to be smarter but it can provide you with very nice features such as breaking a large part of your API without the client even noticing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: application of Minkowski's inequality Hi: I'm reading a proof and I don't understand one of the steps. The theorem supposes the following:
$E(X^2_{thi})^{1+\delta} < \triangle < \infty$ for some $\delta > 0 $ and all $h = 1, \ldots p, ~i = 1, \ldots k$, and all $t$.
Then, it starts off the proof by saying the following:
By Minkowski's inequality:
$E \left|\sum_{h=1}^{p} X_{thi} X_{thj}\right|^{1+\delta} \le \left|\sum_{h=1}^{p} (E|X_{thi} X_{thj}| ^{(1+\delta)})^\left(\frac{1}{1+\delta}\right)\right| ^{1+\delta}$
Can someone show or explain how the relation above is obtained from A) the stated assumption and B) Minkowski's inequality ( or any other inequality in case it's a typo and it's using some other inequality ). The rest of the proof makes sense so no need to state the rest.
Minkowski's inequality is :
Let $q \ge 1$. If $E(|Y|^q) < \infty $ and  $E(|Z|^q) < \infty $, then
$\left(E|Y + Z|^{q}\right)^\left(\frac{1}{q}\right) \le E(|Y|^q)^\left(\frac{1}{q}\right) + E(|Z|^q)^\left(\frac{1}{q}\right)$
Thanks.


text:
Q: How to fix "The operator '{0}' can't be unconditionally invoked because the receiver can be 'null'" While trying Dart's Sound Null Safety i came up with a problem:

Some Context
Creating a new Flutter project i found the following (and very familiar) piece code
int _counter = 0;

void _incrementCounter() {
  setState(() {
    // This call to setState tells the Flutter framework that something has
    // changed in this State, which causes it to rerun the build method below
    // so that the display can reflect the updated values. If we changed
    // _counter without calling setState(), then the build method would not be
    // called again, and so nothing would appear to happen.
    _counter++;
  });
}

Now, i changed the variable _counter to be nullable and took off the initialization:
int? _counter;

void _incrementCounter() {
  setState(() {
    _counter++;
  });
}

And as expected, i got the following error in the editor:

The operator '+' can't be unconditionally invoked because the receiver can be 'null'

The Problem
Following the documentation i added the required checking:
if (_counter!=null)
        _counter++;

but to my astonishment, the error kept on showing and suggesting

Try making the call conditional (using '?' or adding a null check to the target ('!'))

even though i explicitly am making the call conditionally... so what is wrong?

A: UPDATE
As suggested in another SO thread, in a further thread in Github Erik Ernst says:

Type promotion is only applicable to local variables... Promotion of an instance variable is not sound, because it could be overridden by a getter that runs a computation and returns a different object each time it is invoked. Cf. dart-lang/language#1188 for discussions about a mechanism which is similar to type promotion but based on dynamic checks, with some links to related discussions.

So, with that explanation, now i see that only local variables can (so far?) be promoted, and thus my problem could be fixed by writing
int? _counter;

void _incrementCounter() {
  setState(() {
    if (_counter!=null)
        _counter = _counter! + 1;
  });
}

For an alternative fix, see my original answer below.

The other Fix
I finally fixed the problem by capturing the value of the instance variable inside the method as follows:
int? _counter;

void _incrementCounter() {
  setState(() {
    var c = _counter;

    if (c!=null)
      c++;

    _counter = c;

  });
}

Why the need to capture the variable?
Well, the whole problem is that

Type promotion is only applicable to local variables... Promotion of an instance variable is not sound, because it could be overridden by a getter that runs a computation and returns a different object each time it is invoked

so in my approach we

*

*capture the value of the instance variable

*then we check for that value to not be null.

*if that value turned out not to be null then we operate on the local variable which through the null check is now correctly promoted.

*finally we apply the new value to the instance variable.

Final observations
I am new to Dart and thus i am not 100% sure, but to me it seems that in general, when working with nullable instace variables, my approach is better that that of using the bang operator to cast away nullity:
By casting away nullity you are overlooking the main problem of promoting instance variables, namely that

it could be overridden by a getter that runs a computation and returns a different object each time it is invoked ...

That exact problem is what is avoided by capturing the value of the instance variable and working with that locally captured value...
If i am wrong kindly let me know...


text:
Q: TypeScript lambda functions with optional parameters I am having problems when defining a lambda function that accepts an optional parameter. The strange part is that if I use the full "function" syntax the anonymous function works, but the lambda shorthand/arrow syntax produces errors such as the following:

*

*The name 'a' does not exist in the current scope

*Supplied parameters do not match any signature of call target

*Expected ')'

Example:
(function (a, b?) => { console.log(a, b); })("a"); // OK
((a, b?) => { console.log(a, b); })("a", "b");     // Errors
((a, b) => { console.log(a, b); })("a", "b");      // OK

A: This is a bug in the compiler and is getting fixed right now [v0.8]. Lambdas currently give error messages with optional and rest parameters. Please use the long function syntax if this is a blocking issue.

A: There's currently a bug with optional parameter annotation in fat arrow lambda expressions.


text:
Q: PHP MySQL and Android connection I'm trying to connect my android app with an online database server that uses MySQL and phpMyAdmin.
But problem I am having is that I'm unable to access my database (which is online) using Java code for android.
It get the following error:

java.sql.SQLException: No suitable driver at java.sql.DriverManager.getConnection(DriverManager.java:187)

I already loaded the driver and external JAR of MySQL but it is still showing this exception.
The code is :
Class.forName("com.mysql.jdbc.Driver").newInstance();

Connection con = DriverManager.getConnection(
        "jdbc:mysql:http://www.demo.com:2082/",
        "usernme", "password"); //username and password of cpanel access
PreparedStatement statement = con
        .prepareStatement("SELECT * FROM users WHERE userName = '"
                + userName + "'");

ResultSet result = statement.executeQuery();

while (result.next()) {
    retrievedUserName = result.getString("username");
    Log.e("data username:", retrievedUserName);
    retrievedPassword = result.getString("password");
}

A: Use the Webservice to make the Connection to Mysql from your android app through json or xml.you can use SQlite database to connect the android app internally by the use of this package android.database.sqlite classes


text:
Q: Integration of looped sin function
At infinity,
i took limits to be L. so L= sin (x+L)
then after integration i am left withL= 2 cosL.
how to get value of L

A: Hint:
Assuming $\lim\limits_{n\to\infty}f_n(x)=f(x)$ the functional equation for $f(x)$ reads:
$$
f(x)=\sin(x+f(x)).\tag1
$$
Instead of trying to resolve the equation (1) wrt $f$ one can easily resolve it (taking into account multivaluedness of $\arcsin$ function) wrt $x$:
$$
x=\begin{cases}
X_1(f)\equiv\arcsin(f)-f,& 0\le x\le\frac\pi2-1\\
X_2(f)\equiv\pi-\arcsin(f)-f,& \frac\pi2-1\le x\le\pi
\end{cases}.\tag2
$$
and compute the integral in question as
$$
\int_0^\pi f(x)dx=\int_0^1[X_2(f)-X_1(f)] df=\int_0^1[\pi-2\arcsin(f)] df=\color{red}2.
$$

Extended hint:
To justify the equation $(2)$ it is necessary that the function $f(x)$ consists of exactly two monotonic branches: one increasing from $0$ to $1$ followed by the other decreasing from $1$ to $0$. The properties of $f(x)$ follow immediately from the equation $(1)$, provided that $g(x)\equiv x+f(x)$ is a monotonic function mapping $[0,\pi]\mapsto[0,\pi]$, and this is
  easy to demonstrate rewriting the equation $(1)$ as:
  $$g(x)=x+\sin(g(x)).$$
Indeed, $g(0)=0$ and $g(\pi)=\pi$ are the only possible solutions of
$$g(0)=\sin(g(0)),\quad\text{and}\quad g(\pi)=\pi+\sin(g(\pi)),$$
  respectively, and
  $$
g'(x)=1+\cos(g(x))g'(x)\Rightarrow g'(x)=\frac1{1-\cos(g(x))}>0.
$$


text:
Q: How to enable SSH X11 forwarding through additional server? I have hosts A,B and C. From host A I can access through ssh only B. From B I can access C.
I want to be able to run X11 programs on C and forward display to A.
I tried this:
A$ ssh -X B
B$ ssh -X C
C$ xclock
Error: Can't open display:

But it doesn't work.

A: This can easily be accomplished using port forwarding:
A$ ssh -NL 2022:C:22 B &
A$ ssh -X -p 2022 localhost
C$ xclock

Port localhost:2022 is forwarded to C:22 via B
SSH to C via localhost:2022
Use X as normal

A: Have you tried with
A$ ssh -Y B
B$ ssh -Y C
C$ xlclock

The -Y flag "Enables trusted X11 forwarding."

A: For newer versions opensshd you have to disable X11UseLocalhost for this to work.
You need to do this on Host C's /etc/ssh/sshd_config and restart sshd for this to work:
X11Forwarding yes
X11UseLocalhost no

A: Assuming the problem is that the middle machine doesn't have X, but it otherwise configured to allow forwarding X11, just install xauth.
on a yum-based system (fedora, redhat, centos):
B$ sudo yum install xauth

on an apt-based system (debian, ubuntu):
B$ sudo apt-get install xauth

A: There are several ways to do this, the one I prefer is to forward the ssh port:
First, connect to machine B and forward [localPort] to C:22 through B
A$ ssh -L [localPort]:C:22 B

Next, connect to C from A through this newly-created tunnel using [localPort], forwarding X11
A$ ssh -X -p [localPort] localhost

Now we can run X11 programs on C and have them display on A
C$ xclock

[localPort] can be any port that you are not already listening to on A, I often use 2222 for simplicity.

A: If you often go from A to C, you can configure B as a proxy:
A:~/.ssh/config:

Host C
  ForwardX11   yes
  ProxyCommand ssh -W %h:%p B

then it's just:
A$ ssh C xclock

A: You could combine -Y/-X command with the -J command line option:
A$ ssh -Y user@C -J user@B
C$ xclock

If you have more Hosts to hop than just do the following:
A$ ssh -Y user@C -J user@B,user@D,...,user@Z
C$ xclock

From man ssh:
-J [user@]host[:port]
     Connect to the target host by first making a ssh connection to
     the jump host and then establishing a TCP forwarding to the
     ultimate destination from there.  Multiple jump hops may be
     specified separated by comma characters.  This is a shortcut to
     specify a ProxyJump configuration directive.

It was introduced in OpenSSH version 7.3 (released in August 2016).

A: You can't forward X11 display if you have X11Forwarding disabled in any sshd you are using.
man sshd_config:
X11Forwarding
  Specifies whether X11 forwarding is permitted. The argument must be "yes"
  or "no".  The default is "no".

You have to make sure X11Forwarding is enabled on destination and all intermediate sshds you are using.
Just a small hint: you should try to use VNC, X11 display forwarding is quite bandwidth consuming.


text:
Q: click event for list group not triggering when clicked I'm new to JQuery so maybe my syntax isn't correct but I can't trigger any click event for a bootstrap list group, when I select something from the list. I don't know if it makes a difference but the list group is inside a bootstrap popover.
I have tried both methods here.

$('#eventList').on('click', '.list-group-item', function(e) {
  e.preventDefault();
  //code here
});

$(".list-group-item").click(function() {
  // code here
});

Events

First item

Second item

Third item

A: That code is correct and works fine.
It's not working in your case because '#eventList' doesn't exist at the time you're adding the listener.
Try this
$(document).on('click', '#eventList .list-group-item', function(e) {

A: Your code is working 100% fine here https://jsfiddle.net/bkf7y6q7/
Are you sure you included the following in your html file:

A:
Demo : http://jsfiddle.net/du92ucfm/1/

This is working , is there anything else you are asking ?
can you provide a specific code related to bootstrap.js
$('#eventList').on('click', '.list-group-item', function(e) {
  console.log('i am clicked 1');
});
$(".list-group-item").click(function() {
 console.log("i am clicked 2");
});


text:
Q: Probability of $X_1 > 2X_2$, where $X_1$ and $X_2$ are independent random variables with exponential distribution functions I have two random variables, $X_1$ and $X_2$, both of which have exponential distributions, and $\lambda_1 = 1$, $\lambda_2 = 2$. The question is then, what is the probability $P(X_1 > 2X_2)$. So I have two distribution functions:
$$f(x_1) = e^{-x_1}$$
$$f(x_2) = 2e^{-2x_2}$$
Looking at the integral I get
$$\int \int_{x_1 > x_2}f_1(x_1)f_2(x_2) dx_1 dx_2$$
Combining this all I come to
$$\int_0^\infty \int_{2x_2}^\infty 2e^{-(x_1 + x_2)}$$
This is my concern. Is the lower limit on my second integral actually $2x_2$ or should it be $2x_1$. To me $2x_2$ makes more sense, and leads to a result of $\frac{1}{2}$. However having a lower limit of $2x_1$ leads to a result of $\frac{1}{5}$ and I have seen this elsewhere. Can anybody perhaps shed some light on my issue and help me out with my confusion?

A: It is
$$\int_0^\infty \int_{2x_2}^\infty 2e^{-(x_1+x_2)}\, dx_1 \, dx_2$$
Let $x_2$ takes value from $0$ to $\infty$. After which, fixing $x_2$, what are the values that $x_1$ can take to satisfy the domain of interest. We want $x_1 >2x_2$, hence the lower limit should be $2x_2$.


text:
Q: Update UI WinForms with multiple tasks I've a basic form application. It displays a list of checkbox and a list of asyn task update CheckBox label :
public partial class Form1 : Form
{
    List<CheckBox> checkedBoxes = new List<CheckBox>();
    public Form1()
    {
        InitializeComponent();
        CreateCheckBoxes();
        Display();
    }

   public void CreateCheckBoxes()
    {

        SuspendLayout();
        for (int i = 0; i < 11; i++)
        {
            checkedBoxes.Add(new CheckBox() {Name = "Combo"+i, Text = "-"+i  });

            flowLayoutPanel1.Controls.Add(checkedBoxes[i]);
        }
        ResumeLayout();
    }

    private async void Display()
    {

        List < Task < LyStruc >> tasks = new List<Task<LyStruc>>();
        for (int i = 0; i < 10; i++)
        {
            tasks.Add(Task.Run(() => { return ProcessMessage(i); }) );
        }

        var wa =  await Task.WhenAll(tasks.ToArray());

        // Doesn't work (few checkbox update label)
        foreach (LyStruc t in wa)
        {
            UpdateCheckBoxLabel(t);
        }

        // Doesn't work either.
        //TaskScheduler taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        //foreach (var item in tasks)
        //{
        //    item.ContinueWith(c =>
        //    {
        //        switch (c.Status)
        //        {
        //            case TaskStatus.RanToCompletion: Test(c.Result); break;
        //            case TaskStatus.Faulted: richTextBox1.Text = c.Exception.ToString(); break;
        //        }

        //    }, taskScheduler);
        // }
    }

    private void UpdateCheckBoxLabel(LyStruc s)
    {
        this.checkedBoxes[s.Id].Text = "Update" + s.Name;
    }

    private LyStruc ProcessMessage(int i)
    {
        return new LyStruc()
        {
            Id = i,
            Name = string.Format( "-Combo {0}", i),
        };
    }

}

Why don't all checkboxes change (just few of them)  ? I get no errors. I expect that each check box update with label CheckBox


text:
Q: Video upload on YouTube - Android I am working on application to upload video on YouTube from android. I know we can not use API on android so we have to send a http post request to YouTube to upload video. Here is my code in which I am getting error Invalid Content-Type x-www-urlencode, code shows i have used Content-Type as application/atom+xml; charset=UTF-8 then why i am getting this type of error, any one can help me in this?
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
pairs.add(new BasicNameValuePair("Email", "xxxx"));
pairs.add(new BasicNameValuePair("Passwd", "xxx"));
pairs.add(new BasicNameValuePair("service", "youtube"));
pairs.add(new BasicNameValuePair("source", "YouTubeApp"));

post.setEntity(new UrlEncodedFormEntity(pairs));

HttpResponse response = client.execute(post);

String textResponse = getResponseBody(response);
String auth = textResponse.substring(textResponse.lastIndexOf("Auth"));

builder.setMessage(auth).show();

String entry = "<?xml version=\"1.0\"?>"
     + "<entry xmlns=\"http://www.w3.org/2005/Atom\""
     + " xmlns:media=\"http://search.yahoo.com/mrss/\""
     + " xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
     + "<media:group>"
     + "<media:title type=\"plain\">Bad Wedding Toast</media:title>"
     + "<media:description type=\"plain\">"
     + "I gave a bad toast at my friend's wedding. Maybe"
     + "</media:description>"
     + "<media:category"
     + " scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">People"
     + "</media:category>"
     + "<media:keywords>toast, wedding</media:keywords>"
     + "</media:group>"
     + "</entry>";

StringBuilder sb = new StringBuilder();
sb.append("--");
 sb.append("Content-Type: application/atom+xml; charset=UTF-8");
sb.append(entry);
 sb.append("--");
 sb.append("Content-Type: video/3gpp");
sb.append("Content-Transfer-Encoding: binary");

               String bodyStart = sb.toString();

               File file = new File("/mnt/sdcard/recordvideooutput.3gpp");
               FileInputStream fIn = new FileInputStream(file);
               byte fileBytes[] = new byte[(int) file.length()];
               fIn.read(fileBytes);

            HttpClient client1 = new DefaultHttpClient();
            HttpPost post1 = new HttpPost("https://uploads.gdata.youtube.com/feeds/api/users/default/uploads");

            List<NameValuePair> pairs1 = new ArrayList<NameValuePair>();
            pairs1.add(new BasicNameValuePair("X-GData-Key", "key=xxxxx"));
            pairs1.add(new BasicNameValuePair("Slug", "/mnt/sdcard/recordvideooutput.3gpp"));
            pairs1.add(new BasicNameValuePair("Content-Type", "application/atom+xml; charset=UTF-8"));
            pairs1.add(new BasicNameValuePair("Content-Length", "" + (bodyStart.getBytes().length + fileBytes.length)));
            pairs1.add(new BasicNameValuePair("Authorization", "GoogleLogin " + auth));

post1.setEntity(new UrlEncodedFormEntity(pairs1));

response = client1.execute(post1);

A: You can convert API to google code for an android application. This link may be useful for you
 Resources for Mobile Development with YouTube


text:
Q: CommonJS - How can I combine jquery and a jquery-plugin into the $ namespace What I'm trying to do is adapt my jQuery-plugin to work with jQuery on Node.js.
From what I understand, CommonJS in it's most basic form requires a library to be wrapped in a closure, and that closure should be made available as a parameter of an 'exports' parameter. That way, the code is neatly contained in its own namespace (via a named variable) and doesn't pollute the global namespace.
jQuery itself should fall under the '$' namespace.
Ala:
var $ = require(jquery);

But my plugin should also fit under the '$' namespace.
Plugin code:
(function( $ ) {
  // plugin code goes here
})(jquery);

exports.jquery = jquery // will this work?

Ex:
var $ = require(jquery);
$ = require(jquery-csv.js); // will this work?

To work in the browser, everything is setup to be callable from the '$' namespace even though my modules are setup as a sub-namespace of '$' (ie '$.csv').
Is there a standard way to do multiple requires on a single namespace? If not, there a viable alternative (ex doing a shallow copy on the plugin code)?
Note: The anonymous function wrapper follows the standard jquery guidelines.
Note: This fix will be applied to the jquery-csv plugin.

A: You should require jQuery inside your plugin:
var $ = require("jquery");

This is also the technique in UMD (Universal Module Definition), a standard for both CommonJS and AMD.
Also see the example for a jQuery plugin with UMD

A: Easiest way I can think of doing something like this would be doing something like the following:
var $ = require("jquery");
require("jquery-csv")($);

That also means you can just do something like this:
module.exports = exports = function (jquery) {
    //You modify the jquery object here.
};

Modification of the $ object should be done in accordance to jQuery plugins recommendations. I will believe you are already aware of them for what you said.
I'm sure someone will come up with a smarter way :) but this should work for now. You could also just return a modified jquery object and then assign it to the $ object on the scope in which you originally included the module.

A: The answer turned out to be simpler than I thought...
var $ = jQuery = require('jquery');
require('./jquery.csv.js');

Calling 'require' without assigning it to a variable/namespace acts the same as a script import (ie it can manipulate objects that exist in the global namespace).
The first line takes care of properly initializing jquery. Once that's done, jquery-csv can modify the existing '$' namespace the same way it does in the browser.
The second assignment 'jQuery' is necessary because that's where jquery-csv grabs the reference to the 'jquery' instance. This could probably be shortened to only assign to '$' but 'jQuery' is the value that the plugin guidelines specify for referencing the library.


text:
Q: ios 8.1 - controller with UIWebView not shown without WiFi connection Few days ago i started receiving user reports that my app is not working. After few hours of investigation i've found that controller is not shown ([self.navigationController pushViewController:terminalController animated:YES];) if it has UIWebView and there is no wifi connection! I did not believe it but i have 2 controllers - one with loading 'about the app' page and another is for showing some built-in app documentation. I'm testing on ios 8.1.2 and ipad 2.
Controller's viewDidLoad just is not invoked and the app just freezes. I've checked few times - if i turn wifi on and relaunch the app controllers are shown!
The problem is that i'm using uiwebview for showing local pages and it does not require wifi connection, so most users are very confused.
Any workaround?
Update: here is how i push controller:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    ASTerminalController *terminalController = [storyboard instantiateViewControllerWithIdentifier:@"ASTerminalController"];
    terminalController.htmlFilename = self.outputFilePath;
    [self.navigationController pushViewController:terminalController animated:YES];

Update2: i've modified the app and now i'm creating UIWebView not in storyboard but in code. Now i can see initWithFrame hangs is there is no internet connection:
self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];

Update 1: probably some 3rd-party code uses UIWebView and somehow blocks it (see semaphore is used):
Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib          0x3aa34540 semaphore_wait_trap + 8
1   libsystem_platform.dylib        0x3aabf431 _os_semaphore_wait + 9
2   libdispatch.dylib               0x01b966f7 0x1b94000 + 9975
3   UIKit                           0x2ff893ef +[UIWebDocumentView initialize] + 39
4   libobjc.A.dylib                 0x3a4024d5 _class_initialize + 533
5   libobjc.A.dylib                 0x3a4022fd _class_initialize + 61
6   libobjc.A.dylib                 0x3a40805b lookUpImpOrForward + 251
7   libobjc.A.dylib                 0x3a407f53 _class_lookupMethodAndLoadCache3 + 31
8   libobjc.A.dylib                 0x3a40e1d7 _objc_msgSend_uncached + 23
9   UIKit                           0x2fe743d1 -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) containerIsBrowserView] + 73
10  UIKit                           0x2fe74353 -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) textDocument] + 35
11  UIKit                           0x2fe74271 -[UITextSelectionView selection] + 41
12  UIKit                           0x2fe74e7f -[UITextSelectionView selectionChanged] + 167
13  UIKit                           0x304f17bb __47-[UITextInputController _setSelectedTextRange:]_block_invoke251 + 223
14  UIKit                           0x2fe74d8b __52-[UITextInputController _coordinateSelectionChange:]_block_invoke + 83
15  UIFoundation                    0x3756bb63 -[NSTextStorage coordinateReading:] + 35
16  UIKit                           0x2fe74d31 -[UITextInputController _coordinateSelectionChange:] + 97
17  UIKit                           0x304f14d3 -[UITextInputController _setSelectedTextRange:] + 599
18  UIKit                           0x2feda6db -[UITextView setAttributedText:] + 391
19  CppCode                         0x0011b925 0xd1000 + 305445
20  CppCode                         0x0011d0cb 0xd1000 + 311499
21  CppCode                         0x00119daf 0xd1000 + 298415
22  CoreFoundation                  0x2c931c5f __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 11
23  CoreFoundation                  0x2c88d6d1 _CFXNotificationPost + 1781
24  Foundation                      0x2d5bf125 -[NSNotificationCenter postNotificationName:object:userInfo:] + 69
25  Foundation                      0x2d5ebe33 -[NSUserDefaults(NSUserDefaults) registerDefaults:] + 71
26  WebKitLegacy                    0x389df8cd +[WebView initialize] + 301
27  libobjc.A.dylib                 0x3a4024d5 _class_initialize + 533
28  libobjc.A.dylib                 0x3a40805b lookUpImpOrForward + 251
29  libobjc.A.dylib                 0x3a407f53 _class_lookupMethodAndLoadCache3 + 31
30  libobjc.A.dylib                 0x3a40e1d7 _objc_msgSend_uncached + 23
31  WebKitLegacy                    0x389df6cf WebKitInitialize + 67
32  UIKit                           0x3009cf97 ___UIApplicationLoadWebKit_block_invoke + 151
33  libdispatch.dylib               0x01b959c5 0x1b94000 + 6597
34  libdispatch.dylib               0x01b9662d 0x1b94000 + 9773
35  libobjc.A.dylib                 0x3a4024d5 _class_initialize + 533
36  libobjc.A.dylib                 0x3a40805b lookUpImpOrForward + 251
37  libobjc.A.dylib                 0x3a407f53 _class_lookupMethodAndLoadCache3 + 31
38  libobjc.A.dylib                 0x3a40e1d7 _objc_msgSend_uncached + 23
39  CppCode                         0x0011182d 0xd1000 + 264237
40  UIKit                           0x2fe3a52b -[UIViewController loadViewIfRequired] + 599
41  UIKit                           0x2fe3a299 -[UIViewController view] + 21
42  UIKit                           0x2ffc3585 -[UINavigationController _startCustomTransition:] + 625
43  UIKit                           0x2fee34d3 -[UINavigationController _startDeferredTransitionIfNeeded:] + 419
44  UIKit                           0x2fee32d9 -[UINavigationController __viewWillLayoutSubviews] + 41
45  UIKit                           0x2fee326d -[UILayoutContainerView layoutSubviews] + 181
46  UIKit                           0x2fe37a6b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 511
47  QuartzCore                      0x2f85fa09 -[CALayer layoutSublayers] + 133
48  QuartzCore                      0x2f85b3e1 CA::Layer::layout_if_needed(CA::Transaction*) + 357
49  QuartzCore                      0x2f85b269 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 13
50  QuartzCore                      0x2f85ac4d CA::Context::commit_transaction(CA::Transaction*) + 221
51  QuartzCore                      0x2f85aa51 CA::Transaction::commit() + 321
52  QuartzCore                      0x2f854929 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 53
53  CoreFoundation                  0x2c93fd93 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 19
54  CoreFoundation                  0x2c93d44f __CFRunLoopDoObservers + 275
55  CoreFoundation                  0x2c93d857 __CFRunLoopRun + 911
56  CoreFoundation                  0x2c88b3bd CFRunLoopRunSpecific + 473
57  CoreFoundation                  0x2c88b1cf CFRunLoopRunInMode + 103
58  GraphicsServices                0x33c200a5 GSEventRunModal + 133
59  UIKit                           0x2fe997ad UIApplicationMain + 1437
60  CppCode                         0x0011f619 0xd1000 + 321049
61  libdyld.dylib                   0x3a981aad start + 1


text:
Q: How can I put a Webview below other views and scroll all views together I'm developing an android application there I have a webview below other views.
The whole content does not fit the screen so I want to enable some scrolling.
My layout file looks like this:
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <TextView .../>
    <TextView .../>
    <TextView .../>
    <TextView .../>

    <WebView
        android:id="@+id/about_detail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:textSize="14sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/contactInformation"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

</android.support.constraint.ConstraintLayout>

Should I use a Scrollview around my ConstraintLayout, or how can I do that?

A: You can try below code:
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView .../>
        <TextView .../>
        <TextView .../>
        <TextView .../>

        <WebView
            android:id="@+id/about_detail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="24dp"
            android:textSize="14sp" />
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>


text:
Q: How can I programmatically get the ABI compatibility level (minor version) of my Ruby installation? I'm trying to figure out a way to determine the ABI compatibility level (i.e. the minor version) of the Ruby installation on any given machine.
I know that I can determine the full version number by running "RUBY_VERSION" in irb - for example, on my machine, it would currently return "2.6.5". But I'm looking for a solution that will tell me just the minor version - so for both 2.6.5 or 2.6.6, I'd simply want "2.6.0" as the output.
Is there a straightforward way to get this info, short of simply trimming the full version and appending a .0?

A: There is no way I know of to get the ABI compatibility level programmatically.
However, given your comments, it seems that you are not actually caring about the ABI compatibility level but about the RubyGems Gem installation path. Since this path can be configured by the user in a configuration file, environment variable or command line argument, I think it would make much more sense to ask RubyGems for the Gem installation path using the Gem::dir method instead of asking Ruby for the ABI compatibility level:
Gem.dir
#=> "/usr/local/lib/ruby/gems/2.7.0"


text:
Q: Как передать id? Здраствуйте! Подскажите, пожалуйста, как мне передать id (div-а) при клике на него (ниже пример)

Папка 3.1

И при выполнении этой функции надо, чтоб "Папка 3.1" залилась светло синим цветом (и параллельно все другие дивы, которые есть очистились от заливки. Ну, я так думаю, надо сначала все дивы от заливки почистить, а после на который кликнули залить. Но вот не могу прописать это.
A:

Палка 3.1

Палка 3.2

Палка 3.3

http://jsfiddle.net/54Awe/2/ я так понял, в конечном счёте такое нужно?
A: Вам достаточно передать в функцию сам div( т.е самого себя ), на котором и произошло событие:

Папка 3.1

A: ппц, не кажется ли что jQuery слишком много для такой задачи?
function Func_Id_Div(obj)
{
return this.id;
}
A: $('.Content').click(function(){
   var id = $(this).attr('id');
   $('.Content').css('background-color','white');
   $(this).css('background-color','blue');
});


text:
Q: Call javascript function through dynamically generated href tag (the js function has one paramter) I need to call getStandards() function from the dynamically generated href tag.All the code is in .js file. I went through many stackoverflow questions but I couldn't find the solution. The function has one parameter(classId) as shown below:

var ul = $('

');
var li = $('

');

for (var i = 0; i < classes.length; i++) {
    var classId = classes[i].classId;
    var html = "";
    html = "
" + classes[i].className + "

";
    li.append(html);
}
ul.append(li);

function getStandards(classId) {

}

Can someone help me !! thank you.

A: Rather than making multiple inline bindings, I would suggest using a data attribute and a delegate event binding for this logic.
var ul = $('

');

ul.append(
  classes.map( aClass => {
    return `

          ${aClass.className}

    `;
  } )
);

ul.on( 'click', '.class-entry', event => {
  let $link = $( event.target );

  getStandards( $link.data( 'classId' ) );
} );

function getStandards(classId) {

}

*

*You can use a template literal to make your html construction more readable

*Mapping all the classes to html and appending them all and once, reduces the number of appends to the ul you are doing

*Attaching a delegate event listener to the ul lets you handle the click for all the children of it, and you can grab the class id from the data attribute

A: I would hazard a guess that you aren't appending your ul to the body and that the classId is a string. With a few modifications this code can work:

Note the appending to the body as well as the extra quotes by the onclick. If you don't have those quotes, it will look like this: onclick="getStandards(id1)" which is invalid since id1 is a string


text:
Q: Ubuntu: how to check when kernel was last updated? How to check when kernel was last updated? I know I can use uname to check kernel version but I am particularly interested in when last update occurred.
I'm using Ubuntu 14.04.
    uname -a
    Linux atp-ome32 3.13.0-51-generic #84-Ubuntu SMP Wed Apr 15 12:08:34 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

A: I'd say this question is kind of off-topic so I'd recommend http://askubuntu.com.
Still, on 10.04, you just had to click System -> Administration -> Synaptic Package Manager -> File -> History
Answered here:
https://askubuntu.com/questions/14328/where-can-i-look-up-my-update-history


text:
Q: pass by reference an object in a static function C++? Can static functions have pointers as parameters?
For example this code:
static void myFunctionName(Object &object1)

Thank you.

A: In your example, it's a reference, not a pointer. But aside from this, a static method can have any parameter that would be legal for a non-static function. There is no difference between the two in that aspect.


text:
Q: Why does file and folder icons disappear when I select vscode-icons extension as my preferred File Icon Theme in Visual Studio Code? I have installed vscode-icons extension. And set this as my preferred File-Icon Theme using File -> Preferences option in Visual Studio Code. All folders and files icons disappear. The extension is installed properly and I could see all the icons in the installed extension folder.
But when I switch back to Set(Visual Studio Code) theme, all the folder and file icons are visible. I have tried all possible options like install and uninstalling packages, libraries, extensions and VS Code itself. Please find below screen shot,

A: I am able to see folder and file icons after installing one more alternative extension called file-icons.file-icons.
Earlier I tried at least 2 extensions. But to my surprise, none of them worked. So I assumed that, something wrong in the VS Code.


text:
Q: Google Calendar - get ics file (without API) I would like to get an ICS file from Google Agenda in a Java project, without using APIs (just getting the content of the ics).
The calendar is set to "public", and I get the public ical address from the paramaters (https://www.google.com/calendar/ical/perrine.lbc62%40gmail.com/public/basic.ics).
If I try this address in a browser, I can download the file (event if i'm not connected).
But if I try to get the content with curl command line for example, or with my Java code, it doesn't work : I can't connect to the URL.
Curl says : curl: (7) couldn't connect to host
Java code is the following :
private ICalendar getICalWithUrl(String url) throws Exception {
    ICalendar iCal = null;
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        throw new Exception("Unable to get content at the url "+url+". Method failed: " + method.getStatusLine());
      }
      // Read the response body.
      byte[] responseBody = method.getResponseBody();
      iCal=BiweeklyManager.parse(new String(responseBody));
    } finally {
      // Release the connection.
      method.releaseConnection();
    }
    return iCal;
}

And the stacktrace is the following :
java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:519)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.<init>(SSLSocketImpl.java:394)
        at com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl.createSocket(SSLSocketFactoryImpl.java:123)
        at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:81)
        at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:126)
        at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)

Do you know why I can't access to the url in this cases, and what can I do to access it ?
Thanks a lot for your answers :)

A: Are you in a corporate environment ? This sounds like a proxy setting issue, especially given that you you access it from your browser.
Try curl with the --proxy option (see for example Linux curl command with proxy)


text:
Q: How to change the text and its color using the value of a variable (i) hi i'm trying to change the text and its color depending upon the value of the variable "i" and not using any eventlisteners! i'm getting cannot set property 'innerHTML' of null error is there any fix to this! thank you!

var i = 0;
var images= [];
var time = 3000;
var eventaction=0;
var timeoutId;

var dynamictext=document.querySelector("dynamictext");

images[0] = "https://i.pinimg.com/236x/f4/92/39/f492399e154bd9f564d7fc5299c19911--purple-rain-deep-purple.jpg";
images[1] = "https://image.shutterstock.com/image-photo/purple-butterfly-isolated-on-white-260nw-44004850.jpg";
images[2] = "https://www.birdscanada.org/images/inbu_norm_q_townsend.jpg";

function changeImg()
{if(i<images.length-1)
{i++;
}else
{i=0;}
document.getElementById('sliders').src=images[i];eventaction=0;
dynamictextchanger();
}
timeoutId=setTimeout("changeImg()", time);
}

function dynamictextchanger()
{
   if(i==1)
    {
      dynamictext.innerHTML="Starter";
      dynamicetxt.style.color="black";
    }
    else if(i==2)
    {
      dynamictext.innerHTML="veg";
      dynamicetxt.style.color="green";
    }
    else if(i==3)
    {
      dynamictext.innerHTML="nonveg";
      dynamicetxt.style.color="red";
    }
  }

window.onload=changeImg;

<button class="button button3" id="leftbutton"> previous</button>

<button class="button button3" id="rightbutton">next</button>

A: This code has way too many errors. I don't even know where to start. But some of these fixes should get you up and running.

*

*Incorrect variable dynamicetxt.

*Missing hash # symbol in querySelector method

*Extra }

var i = 0;
var images= [];
var time = 3000;
var eventaction=0;
var timeoutId;

var dynamictext = document.querySelector("#dynamictext");

images[0] = "https://i.pinimg.com/236x/f4/92/39/f492399e154bd9f564d7fc5299c19911--purple-rain-deep-purple.jpg";
images[1] = "https://image.shutterstock.com/image-photo/purple-butterfly-isolated-on-white-260nw-44004850.jpg";
images[2] = "https://www.birdscanada.org/images/inbu_norm_q_townsend.jpg";

function changeImg()
{

if(i < images.length - 1) i++;
else i = 0;

document.getElementById('sliders').src=images[i];

eventaction=0;
dynamictextchanger(i);

timeoutId = setTimeout(changeImg, time);
}

function dynamictextchanger(i)
{
   if(i==0)
    {
      dynamictext.innerHTML="Starter";
      dynamictext.style.color="black";
    }
    else if(i==1)
    {
      dynamictext.innerHTML="veg";
      dynamictext.style.color="green";
    }
    else if(i==2)
    {
      dynamictext.innerHTML="nonveg";
      dynamictext.style.color="red";
    }
  }

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

<button class="button button3" id="leftbutton"> previous</button>

<button class="button button3" id="rightbutton">next</button>

A: You have forgotten the # sign on this line:
var dynamictext=document.querySelector("#dynamictext");


text:
Q: Second derivative of Kullback–Leibler divergence The Kullback-Leibler divergence is defined here. I have to find the second derivative of $\textrm{KL}(p(s, \theta)||\mu(s) q(\theta, s))$ regarding $p(s, \theta)$, where $p(s, \theta)$ is a joint probability (and therefore, $\frac{1}{p(s, \theta)} \geq 0$), and $\frac{\partial^2 p(s, \theta)}{\partial p(s,\theta)} = 0$.
By definition, $\textrm{KL}(p(s, \theta)||\mu(s) q(\theta, s)) = \sum\limits_{i} P(i) \log \frac{P(i)}{Q(i)}$, where $Q(s,\theta)=\mu(s) q(\theta, s)$. The final result of the derivation must show that the second derivative of $\textrm{KL}(p(s, \theta)||\mu(s) q(\theta, s))$ is non-negative. My colleague scribbled these steps before leaving:
$ \frac{\partial^2 \sum\limits_{i} p(s, \theta) \log \frac{p(s,\theta)}{Q(s, \theta)}}{\partial p(s,\theta)|s,\theta} = \\
 P(s,\theta) \log P(s,\theta)-P(s,\theta) \log Q(s,\theta) = \\
 \log P(s,\theta) * \frac{1}{P(s,\theta)} = \\
 \log P(s,\theta) - \log Q(s,\theta) = \\
 \frac{1}{P(s,\theta)} \geq 0.$
But this was really fast, and his handwriting isn't the best. Therefore, there might be some details wrong (and he might also have made a mistake). I'm guessing in the second line, some of terms must be derivated (as if it were a first derivation of a multiplication $(fg)' = f'g + fg'$), but the minus sign doesn't correspond and we are doing a second derivation. I'm also assuming he omitted the $\sum$. On the third line, I guess the second half of the equation equals $0$ and he derived the $\log$ into $\frac{1}{P(s,\theta)}$, but why is there a $\log$ still? On the fourth line there are other $\log$s, which I have no idea where they came from, but if we derive everything, we reach the final line, which we know is positive, and the proof ends.
I tried to reach the solution on my own, like this
$ \frac{\partial^2 \sum\limits_{i} P(i) \log \frac{P(i)}{Q(i)}}
 {\partial P(i)} = \sum\limits_{i} P'' \log \frac{P}{Q} + 2 P' \log '\frac{P}{Q} + P \log '' \frac{P}{Q} = \sum\limits_{i} 0 + 2\frac{Q}{P} + P \frac{PQ'-QP'}{P^2} = \sum\limits_{i} 2\frac{Q}{P} + \frac{PQ'-QP'}{P} = \sum\limits_{i} 2\frac{Q}{P} - \frac{Q}{P} = \sum\limits_{i} \frac{Q}{P}
 $
But I can't really move from here to the final solution. What did I do wrong? What was my colleague doing?

A: Found it. I was missing the fact that $\log(\frac{A}{B})=\log(A)-\log(B)$. From there, we can easily do
\begin{align}
 & \!\!\!\!\!\!\!\!\frac{\partial^2 \textrm{KL}(p(s, \theta)||\mu(s) q(\theta|s))}{\partial p(s,\theta)^2} =   \\
 & = \frac{\partial^2 p(s, \theta) \log \frac{p(s,\theta)}{Q(s,\theta)}}{\partial p(s,\theta)^2} = \nonumber\\
 & = \frac{\partial^2 p(s, \theta) \log p(s,\theta) - p(s, \theta) \log Q(s,\theta)}{\partial p(s,\theta)^2}  = \nonumber\\
 & = \frac{\partial^2 p(s, \theta) \log p(s,\theta)}{\partial p(s,\theta)^2} - \frac{\partial^2 p(s, \theta) \log Q(s,\theta)}{\partial p(s,\theta)^2} = \nonumber\\
 & = \frac{\partial^2 p(s, \theta)}{\partial p(s,\theta)^2} \log p(s,\theta) + 2 \frac{\partial p(s, \theta) \log p(s,\theta)}{\partial p(s,\theta)} + p(s, \theta) \frac{\partial^2 \log p(s,\theta)}{\partial p(s,\theta)^2} - 0 = \nonumber\\
 & = 0 + \frac{2}{p(s,\theta)} + p(s, \theta) \frac{\partial \frac{1}{p(s,\theta)}}{\partial p(s,\theta)} = \nonumber\\
 & = \frac{2}{p(s,\theta)} - \frac{1}{p(s,\theta)} = \nonumber\\
 & = \frac{1}{p(s,\theta)} \geq 0 \nonumber\\
\end{align}


text:
Q: Google tag manager problem - Firing an event early, before "container loaded" message I am trying to capture IP address, hash it and store the value in session-scoped dimension in Google Analytics
First, I am firing a custom JS tag to get user IP using this method :
  function getIP(json) {
    dataLayer.push({"event":"ipEvent","ipAddress" : json.ip});
  }
</script>

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

The script creates an "ipEvent" which pulls the user IP and triggers the "hash 2 ip scrambled" event to hash the values.
Everything works fine but the problem is when I need to send hashed values via Pageview which is executed on [3] Container loaded.
You can see from the screenshot that the script to get IP was executed before "[3] Container loaded" message but an actual event happened after.
Any idea how this can be done (get "ipEvent" before [3] Container loaded)

A: No need to fire a tag for this. Well, maybe to load the hashing code. But I would just use some simple hashing function and run it inline rather than loading it from elsewhere. Unneeded network requests should be avoided.
Move your main hashing logic to a CJS variable and return the hash instead of touching the datalayer.
Now reference your shiny CJS variable in whatever tag you wanna use it in. Or, better yet, in GA config variable. Up to you really.
As a result: everything works, but no changes to DOM and to the global JS scope.

A: Your JSONP request is asynchronous - you send the request and the callback is executed when the results come back.
To make sure that the result of the ip api call is pushed reliably as the first event, you would have to make a synchronous call, which ipify does IMO not support (I might be wrong here) and which you do not want, because you would need to stop execution of everything else in your GTM installation. In that case you would also have to handle timeouts somehow etc. Not a good idea (and even if you resolve it outside GTM, you do not know when the result from the API call comes back).
If you really want to make sure that the IP is available in a given tag, use a tag sequence. In that case you need to include an onHtmlSuccess call in your callback function, which signals that your setup tag has executed and subsequent tags can be triggered. From the top of my head, it should look something like this:
<script>
function getIP(json) {
    dataLayer.push({"event":"ipEvent","ipAddress" : json.ip});
     var gtm = window.google_tag_manager[{{Container ID}}];
    gtm.onHtmlSuccess({{HTML ID}});
  }
</script>

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

Use this as setup tag in a tag sequence for the tags that require the IP. Set the follow up tag to only fire when the setup tag was successful, and set the setup tag to fire only once per page, so that the API call is not repeated for every tag.
While this does not make your tag fire before the first event (so technically it does not answer your question) it does make sure that tags require the IP are deferred until the IP is available, which as a result is probably somewhat close to what you want.


text:
Q: VSIX Package doesn't include referenced project's dependencies We have a visual studio package (VS Package) that references a class library project (Project A).  Project A in turn references another class library project (Project B).
So the dependency structure looks like this:  VS Package > Project A > Project B
All projects exist inside the same solution and the dependencies have been set up as proper project references.
If I build the package in visual studio and look in the bin/Debug folder all necessary assemblies are there including Project B's.  However when the package is deployed, only Project A's assemblies are present and Project B's are missing.  How do I tell visual studio to include the indirect dependency of Project B in the package?
This MSDN document suggests that "By default in a multi-project solution, if a project that outputs to a VSIX package includes a reference to another project in the same solution, it includes the dependencies of that project."
However I am finding that this is simply not the case.
My question is very similar to this one except that I am having trouble with the main project assembly and not the localization satellite assemblies.  The answer in this other post does not work for me because it seems to only work for satellite assemblies.
Is there some other Output Group that I can specify to direct the package to include indirect dependencies as well?
Thanks for looking.

A: The simplest thing to do in this particular case is reference Project B from the VSPackage project and set the "Reference Output Assembly" property to False to avoid introducing a compile-time dependency.

A: I had a similar problem: My VS Package project referenced another VS package project (~Project A) which in turn referenced a bunch of other projects (~Project B) containing the meat of our extension.
Inspired by this answer: VSIX package doesn't include localized resources of referenced assembly, I added 'BuiltProjectOutputGroup;BuiltProjectOutputGroupDependencies;GetCopyToOutputDirectoryItems;SatelliteDllsProjectOutputGroup' to the Output Groups Included in VSIX property of the reference from VS Package to Project A.
This had the effect of dropping all the dependency DLLs in the ...\Debug\ folder for my VS Project, but they still didn't get included in the VSIX.
Finally I went and added the BuiltProjectOutputGroup;BuiltProjectOutputGroupDependencies;GetCopyToOutputDirectoryItems;SatelliteDllsProjectOutputGroup flags to all the references from my Project A to each of my Project Bs - then they all got included in the VSIX.
(BTW this is with with Visual Studio 2013, but it doesn't seem to have change much since 2010)


text:
Q: ios : UITableView is showing data when i tap on it Hello i'm creating custom contact view using UITableView. I fetched all contacts and using table relodData but it not showing in table. On a single tap on table then data is visible. In view will appear i'm calling to fetch all contacts in phone and on completion it will reload tableView to make contact visible but it shows if i tap on it or open other view and come back.
#import "CMContatcsVC.h"
#import "CMContatcsTableCell.h"

@implementation CMContatcsVC

//======================================================================================================================================================
#pragma mark - VIEW LIFE CYCLE
//======================================================================================================================================================

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];

    [self fetchAllContactsCompletionHandler:^(BOOL granted, NSError * _Nullable error) {

        [self.tableView reloadData];
        NSLog(@"COUNT_IN_COMPLETION_HANDLER :: %lu", (unsigned long)self.contactArray.count);
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

//======================================================================================================================================================
#pragma mark - TABLE VIEW DELEGATES METHODS
//======================================================================================================================================================

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"TABLE SECTION");
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"TABLE ROWS :: %lu",(unsigned long)self.contactArray.count);
    return self.contactArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSLog(@"TABLE CELL FPR ROW");
    CMContatcsTableCell *contactCell = (CMContatcsTableCell *)[tableView dequeueReusableCellWithIdentifier:@"CMContatcsTableCell" forIndexPath:indexPath];

    @try
    {
        CMCustomContacts * contact = [self.contactArray objectAtIndex:indexPath.row];
        [contactCell.profileImgView setImage:contact.profileImage];
        [contactCell.nameLabel setText:contact.firstName];
        NSLog(@"TABLE CELL CNT NAME :: %@", contact.firstName);
        [contactCell.contactLabel setText:[contact.phoneArray objectAtIndex:0]];
    }
    @catch (NSException *exception)
    {
        NSLog(@"TABLE CELL EXCEPTION :: %@", exception.description);
    }
    @finally
    {}

    return contactCell;
}

//======================================================================================================================================================
#pragma mark - FETCH ALL CONTACTS
//======================================================================================================================================================

-(void)fetchAllContactsCompletionHandler:(void(^)(BOOL granted, NSError * _Nullable error))completion
{
    self.contactArray = [[NSMutableArray alloc] init];

    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        if (granted)
        {
            NSArray *keys = @[CNContactNamePrefixKey, CNContactFamilyNameKey, CNContactGivenNameKey,
                              CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey];

            NSString *containerId = store.defaultContainerIdentifier;
            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
            NSError *error;
            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];

            if (error)
            {
                NSLog(@"ERROR IN FETCHING CONTACTS :: %@", error.description);
            }
            else
            {
                for (CNContact *contact in cnContacts)
                {
                    @try
                    {
                        CMCustomContacts *newContact = [[CMCustomContacts alloc] init];
                        newContact.phoneArray = [[NSMutableArray alloc] init];
                        newContact.emailArray = [[NSMutableArray alloc] init];

                        newContact.firstName = contact.givenName;
                        newContact.lastName = contact.familyName;

                        UIImage *image = [UIImage imageWithData:contact.imageData];
                        newContact.profileImage = image;

                        for (CNLabeledValue *label in contact.phoneNumbers)
                        {
                            NSString *phone = [label.value stringValue];
                            if ([phone length] > 0)
                            {
                                [newContact.phoneArray addObject:phone]; NSLog(@"PHONE :: %@",phone);
                            }
                        }

                        for (CNLabeledValue *label in contact.emailAddresses)
                        {
                            NSString *email = label.value;
                            if ([email length] > 0)
                            {
                                [newContact.emailArray addObject:email];  NSLog(@"EMAIL :: %@",email);
                            }
                        }

                        [self.contactArray addObject:newContact];
                    }
                    @catch (NSException *exception)
                    {
                        NSLog(@"EXCEPTION IN CONTACTS :: %@", exception.description);
                    }
                    @finally
                    {
                        NSLog(@"FINALLY");
                    }
                }

                NSLog(@"COUNT OF CONTACTS :: %lu", (unsigned long)self.contactArray.count);
            }
        }
        completion(granted, error);
    }];
}

@end

A: Always update your UI on main thread, so call reloadData of TableView on main thread like this.
[self fetchAllContactsCompletionHandler:^(BOOL granted, NSError * _Nullable error) {

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    }
    NSLog(@"COUNT_IN_COMPLETION_HANDLER :: %lu", (unsigned long)self.contactArray.count);
}];


text:
Q: JIRA - pass credentials for a webrequest to API? Trying to build a service that will grab info on a JIRA ticket based on an ID passed to it.
I'm calling the API to take the ID passed to the service, tack it onto the URL for the API and get the JSON object.
Problem is, it appears one must be logged on or registered on JIRA in order to use the API.
So if I use the code below to make my request, I get a 404 error, as I do on any browser which I've not used to log onto Jira
public string Get(string id)
 {
 string html = string.Empty;
 string url = @"https://company.atlassian.net/rest/api/latest/issue/" + id;

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
 using (Stream stream = response.GetResponseStream())
 using (StreamReader reader = new StreamReader(stream))
 {
 html = reader.ReadToEnd();
 }

return html;

 }

I can add credentials to the request like so
 request.Credentials = new NetworkCredential("vinnie@company.com","mypassword");

but I've no idea exactly what needs sending. I've tried the email address with which I'm set up in Jira but that doesn't work.
I have a suspicion that Jira adds a cookie to my browser which it uses to validate after the initial config - is that so?  If so, what can I add/include on my web request to get it to run?
Am I just wildly off on the right way to access it? Or are there changes that can be made to the Jira side to allow requests?

A: You have to encode your credentials in Base64 format first and then these credentials can be put into your request as shown below:
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string base64Credentials = Convert.ToBase64String(byteCredentials);

request.Headers.Add("Authorization", "Basic " + base64Credentials);

Hope you're able to solve your problem by this approach!


text:
Q: Pass a protocol as a method argument First let me explain what I don't mean. I don't want to type an argument to a protocol:
-(void)someMethod:(id<SomeProtocol>)someArgument;

What I do want to is to pass a protocol to a method in the same way I can pass a Class to a method (The following is incorrect, but it hopefully explains what I want to do):
-(void)someMethod:(Protocol)someArgument;

I would then like to be able to use the Protocol to check whether a set of objects implement it.

A: Protocol is a class, so you just write - (void)someMethod:(Protocol *)someArgument like with any other object type. You can see this in the declaration for conformsToProtocol::
+ (BOOL)conformsToProtocol:(Protocol *)aProtocol

A: - (void) executeRequest:(id<Protocol1>)request andCompletion:(id<Protocol2>)response

the only way to pass protocol into an argument
because id<..> means it needs to conform to that protocol before pass throw the argument

A: If you know the name of a protocol at coding-time, use @protocol(SomeProtocol) to get a pointer to that protocol, similar to how you'd use @selector(x).
Beyond that, you just refer to protocols with the class identifier Protocol -- so you're method declaration would look like:
-(void)someMethod:(Protocol*)someArgument

You can see an example in the docs for NSObject conformsToProtocol:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/conformsToProtocol:

A: I don't recommend using protocol. It will obscure which interface your code actually relies on. Use id<yourprotocol>*.  This is actually how the cocoa frameworks pass protocols. Forgive the use of words if I don't it thinks I'm trying to do HTML.


text:
Q: DirectX11 pixel shader in pipeline is missing I'm writing a program which displays a MS3D model using DirectX, and unfortunately, the result shows nothing on the screen.
When I use the Graphics Debugger from Visual Studio 13, I notice that the pixel shader is missing from the pipeline, as it is shown in the below picture

This is my pixel shader source code:
 cbuffer SkinningTransforms
 {
    matrix WorldMatrix;
    matrix ViewProjMatrix;
 };
//--------------------------------------------------------------------------------
// Inter-stage structures
//--------------------------------------------------------------------------------
struct VS_INPUT
{
    float3  position        : POSITION;
    int4    bone            : BONEID;
    float4  weights         : BONEWEIGHT;
    float3  normal          : NORMAL;
    float3  tangent         : TANGENT;
    float2  tex             : TEXCOORD;
};
//--------------------------------------------------------------------------------
struct VS_OUTPUT
{
    float4 position         : SV_Position;
    float3 normal           : NORMAL;
    float3 light            : LIGHT;
    float2 tex              : TEXCOORDS;
};

Texture2D       ColorTexture : register( t0 );
SamplerState    LinearSampler : register( s0 );

//--------------------------------------------------------------------------------
VS_OUTPUT VSMAIN( in VS_INPUT input )
{
    VS_OUTPUT output;
    //Transform vertex and pass them to the pixel shader
    return output;
}

//--------------------------------------------------------------------------------
float4 PSMAIN( in VS_OUTPUT input ) : SV_Target
{
    // Calculate the lighting
    float3 n = normalize( input.normal );
    float3 l = normalize( input.light );

    float4 texColor = ColorTexture.Sample( LinearSampler, input.tex );

    float4 color = texColor * (max(dot(n,l),0) + 0.05f );
    return( color );
}

As I was known from Graphics Debugger, all of the graphics event are right. I listed in below important events, which might be relating to Pixel Shader:
106:(obj:4) ID3D11Device::CreateDepthStencilView(obj:24,NULL,obj:25)*
108:(obj:5) ID3D11DeviceContext::OMSetRenderTargets(8,{obj:1,NULL,NULL,NULL,NULL,NULL,NULL,NULL},obj:25)*
109:(obj:5) ID3D11DeviceContext::ClearRenderTargetView(obj:1,addr:21)*
111:(obj:5) ID3D11DeviceContext::ClearDepthStencilView(obj:25,1,1.000f,0)*
119:(obj:4) ID3D11Device::CreateSamplerState(addr:24,obj:27)*
134:(obj:4) ID3D11Device::CreatePixelShader(addr:27,21056,NULL,obj:30)*
135:CreateObject(D3D11 Pixel Shader,obj:30)
136:(obj:5) ID3D11DeviceContext::PSSetShader(obj:30,NULL,0)*
137:(obj:5) ID3D11DeviceContext::PSSetSamplers(0,1,{obj:27})*
139:(obj:4) ID3D11Device::CreateTexture2D(addr:28,addr:5,obj:31)*
140:CreateObject(D3D11 Texture2D,obj:31)
142:(obj:4) ID3D11Device::CreateShaderResourceView(obj:31,NULL,obj:32)*
143:CreateObject(D3D11 Shader Resource View,obj:32)
144:(obj:5) ID3D11DeviceContext::PSSetShaderResources(0,1,{obj:32})*
146:(obj:4) ID3D11Device::CreateRasterizerState(addr:29,obj:33)*
147:CreateObject(D3D11 Rasterizer State,obj:33)
152:(obj:5) ID3D11DeviceContext::RSSetState(obj:33)*
154:(obj:5) ID3D11DeviceContext::RSSetViewports(1,addr:30)*
156:(obj:4) ID3D11Device::CreateBlendState(addr:11,obj:34)*
157:CreateObject(D3D11 Blend State,obj:34)
159:(obj:5) ID3D11DeviceContext::OMSetBlendState(obj:34,addr:31,-1)*
162:(obj:4) ID3D11Device::CreateDepthStencilState(addr:32,obj:35)*
163:CreateObject(D3D11 Depth-Stencil State,obj:35)
165:(obj:5) ID3D11DeviceContext::OMSetDepthStencilState(obj:35,0)*

I debugged all of the function in the above list, and all of them return OK. Nothing wrong.
My question is what is the reason the pixex shader is missing from pipleline, which in turn may result in the empty screen.

A: Adding to the other answers, constant buffer organization can be the cause of this problem. In my case, the pixel shader was missing from the pipeline but also the vertex shader wasn't transforming the vertices correctly. Upon inspection it was revealed that the world matrix had incorrect values because the boolean value at the top of the constant buffer was causing data misalignment. HLSL packs data into 16 byte boundries which are so called vectors that have 4 components. A boolean is 4 bytes which is the same with a float.
cbuffer cbPerObject : register( b1 )
{
    bool gUseTexture ;

    row_major float4x4 gWorld ;
    row_major float4x4 gWorldInvTranspose ;
    row_major float4x4 gWorldViewProj ;
    row_major float4x4 gTexTransform ;
    Material gMaterial ;
} ;

So in the constant buffer above, the boolean + the first 3 components of the first row of the world matrix gets mapped to the first vector and this causes everything to get shifted by 3 components, misaligning the world matrix (and the other matrices following and possibly other data).
Two possible solutions :

*

*Move the boolean to the end of the structure. I did this and it worked.

*Add a 3-component sized padding variable between the world matrix and the boolean.
I tried this by adding an XMFLOAT3 in the c++ structure and a float3 in HLSL. This worked too.

Long story short, pay attention to HLSL packing.
EDIT : At the time I thought these methods worked, as all variables except the boolean had correct values. I didn't use the bool at the time so I assumed that was fine too. Turns out it's not.
HLSL bools and c++ bools have different sizes. HLSL bools are 4 bytes, whereas c++ bools are implementation defined (1 byte on my machine for example). Anyways, they will most likely be different and it causes problems.
Either use Windows BOOL type or another appropriately-sized value like an int or a uint.
Take a look at https://gamedev.stackexchange.com/a/22605.
Also the second to last post here explains the situation clearly (this link is referenced in the answer in the gamedev link above also).
Beware though because packing is still an issue. Even if you use a BOOL or a uint or whatever, if you place it in the beginning in the above structure as before, you will get incorrect values in your constant buffer. So take both of these issues (data alignment and the boolean problem) into consideration when working with constant buffers.

A: As I wrote in my comment, I had a similar problem.
In my case, the pixel shader was correctly bound (see http://msdn.microsoft.com/en-us/library/jj191650.aspx). Furthermore, I ensured by debugging the vertex shader that the result of the Transformation should be visible and hence should generate visible fragments.
In this case (which seems to be the same you describe), make sure that your rasteriser state is correct. You might want to check that it is actually set (using the graphics object view of the immediate context) and that it lets your geometry through. For debugging purposes, I found it helpful disabling backface culling. I use
D3D11_RASTERIZER_DESC rasterDesc;
ZeroMemory(&rasterDesc, sizeof(rasterDesc));
rasterDesc.CullMode = D3D11_CULL_MODE::D3D11_CULL_NONE;
rasterDesc.FillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID;


text:
Q: How to setup OpenVPN server to work like a proxy I'm trying to setup openvpn on Amazon EC2.
To check it I'm using http://whatismyipaddress.com.
Currently I can connect to my remote server with:
sudo openvpn --config /etc/openvpn/openvpnuser1.conf

After connection the server log has:
Sun Jun 11 08:44:06 2017 us=235368 GET INST BY REAL: 176.XX.193.73:54967 [succeeded]
Sun Jun 11 08:44:06 2017 us=235386 user1/176.XX.193.73:54967 UDPv4 READ [69] from [AF_INET]176.XX.193.73:54967: P_DATA_V1 kid=0 DATA 117650fd 4f53ac24 d1614c31 f40cd5d1 49c86aa0 066fc87e 7e1db1fb 47321f9[more...]
Sun Jun 11 08:44:06 2017 us=235393 user1/176.XX.193.73:54967 TLS: tls_pre_decrypt, key_id=0, IP=[AF_INET]176.XX.193.73:54967
Sun Jun 11 08:44:06 2017 us=235405 user1/176.XX.193.73:54967 DECRYPT IV: 066fc87e 7e1db1fb 47321f94 d4f764ee
Sun Jun 11 08:44:06 2017 us=235416 user1/176.XX.193.73:54967 DECRYPT TO: 00000008 fa2a187b f3641eb4 cb07ed2d 0a981fc7 48
Sun Jun 11 08:44:06 2017 us=235425 user1/176.XX.193.73:54967 PID_TEST [0] [SSL-0] [>EEEEEE] 0:7 0:8 t=1497170646[0] r=[0,64,15,0,1] sl=[57,7,64,528]
Sun Jun 11 08:44:06 2017 us=235431 user1/176.XX.193.73:54967 RECEIVED PING PACKET
Sun Jun 11 08:44:06 2017 us=235437 PO_CTL rwflags=0x0001 ev=4 arg=0x55687fb01180
Sun Jun 11 08:44:06 2017 us=235441 PO_CTL rwflags=0x0001 ev=5 arg=0x55687fb01068
Sun Jun 11 08:44:06 2017 us=235448 I/O WAIT TR|Tw|SR|Sw [8/142628]

Also the client raised additional interface & gained IP address (ifconfig):
tun1      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.0.0.6  P-t-P:10.0.0.5  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

So, I assume that openvpn connection has been established. But unfortunately the http://whatismyipaddress.com still shows my (client) real IP add.

Client config:
client
dev tun
proto udp
remote 52.XX.48.224 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca /etc/openvpn/ca.crt
cert /etc/openvpn/user1.crt
key /etc/openvpn/user1.key
tls-auth /etc/openvpn/ccd/ta.key 1
cipher AES-256-CBC
ns-cert-type server
comp-lzo
log /var/log/openvpn.log
verb 3
sndbuf 0
rcvbuf 0

Server config:
port 1194
proto udp
dev tun
ca /etc/openvpn/ca.crt
cert /etc/openvpn/ServerV1.crt
key /etc/openvpn/ServerV1.key
dh /etc/openvpn/dh2048.pem
tls-auth /etc/openvpn/ccd/ta.key 0
cipher AES-256-CBC
server 10.0.0.0 255.255.255.0
keepalive 10 120
persist-key
persist-tun
client-config-dir /etc/openvpn/ccd
status ServerV1-status.log
log /var/log/ServerV1.log
sndbuf 0
rcvbuf 0
push "redirect-geteway def1"
push "dhcp-options DNS 8.8.8.8"
comp-lzo
verb 15

Server forwarding enabled
cat /proc/sys/net/ipv4/conf/all/forwarding
1

iptables edited with:
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth1 -j MASQUERADE
iptables -L -t nat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  ip-10-0-0-0.eu-central-1.compute.internal/24  anywhere

A: Hrm.  I think you might want to be a little more explicit in your iptables config.
#Allow new OpenVPN connections from the outside
iptables -A INPUT -i eth1 -m state --state NEW -p udp --dport 1194 -j ACCEPT
# Allow all tun interfaces to talk to me
iptables -A input -i tun+ -j ACCEPT
# And to talk through me
iptables -A FORWARD -i tun+ -j ACCEPT
iptables -A FORWARD -i tun+ -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -o tun+ -m state --state RELATED,ESTABLISHED -j ACCEPT

At the top of your conf should fix you up...your default policy everywhere is accept, and your masquerade line looks ok to me...your traffic isn't passing over the tunnel once it's negiotaited (0 RX/0 TX), because you haven't added anything to your input chain....

A: It seems you have a typo in your server config:
    push "redirect-geteway def1"

should be
    push "redirect-gateway def1"

and that could very much be the reason the client is not setting a default route through the tunnel once it is established.
Hope it helps!


text:
Q: VSURF and randomForest I'm trying to use VSURF and randomForest in R, but the functions in the libraries like predict.VSURF, predict.randomForest and plot.VSURF are not working and I'm getting the following error:
Error: could not find function "predict.VSURF"
Here's a reproducible example:
library(randomForest)
library(VSURF)
data(cars)
fit <- VSURF(x = cars[1:402,2:ncol(cars)], y = cars[1:402,1])
#At this step I get the error: Error: could not find function "predict.VSURF"
preds <- predict.VSURF(fit, newdata = cars[403:804,2:ncol(cars)])

A: R will recognize fit as a VSURF class object and call VSURF.predict for it. You just use predict() instead.
Also, in looking at your example, VSURF seems to fail for only one x variable throwing this error:

Error in matrix(NA, nrow = nfor.thres, ncol = ncol(x)) :
    non-numeric matrix extent

Using mtcars and only predict(), VSURF works fine for me.
data("mtcars")
fit <- VSURF(x = mtcars[1:25,2:ncol(mtcars)], y = mtcars[1:25,1])
preds <- predict(fit, newdata = mtcars[26:32, 2:ncol(mtcars)])


text:
Q: Rails shuffle form input data in view? I have five form inputs as text, and basically I want to randomly show them on each page load for the user. Right now it shows up as 1-5, but I want it random everytime.
show.html.erb

<%= @post.answer_choice %>

<%= @post.answer_choice_2 %>

<%= @post.answer_choice_3 %>

<%= @post.answer_choice_4 %>

<%= @post.answer_choice_5 %>

I'm trying the .sample method(?) on the form input variables, but it doesn't do anything or show up in the view.
posts_controller.rb
...
@randomize_posts = ["@post.answer_choice", "@post.answer_choice_2", "@post.answer_choice_3", "@post.answer_choice_4", "@post.answer_choice_5"].sample
...

A: I would use the shuffle method on @randomize_posts then use that in the view
posts_controller.rb
@randomize_posts = [
  @post.answer_choice,
  @post.answer_choice_2,
  @post.answer_choice_3,
  @post.answer_choice_4,
  @post.answer_choice_5
].shuffle

show.html.erb
<% @randomize_posts.each do |answer_choice| %>

<%= answer_choice %>

<% end %>

A: You could use select to get each attribute in your object that match with answer in its name, and then get the values, like:
@randomize_posts = @post.attributes.select { |name, _| name =~ /answer/ }.values.shuffle

Then in your view:
<% @randomize_posts.each do |answer| %>

<%= answer %>

<% end %>

As you have your @post object, you can access its attributes by using @post.attributes, this would give you a hash like:
@post.attributes
=> {
 "id"=>1,
 "answer_choice"=>"answer_choice",
 "answer_choice2"=>"answer_choice2",
 ... # Plus other additional attributes

Having a hash then you can use select, to "filter" over those attributes where the name matches with the word answer (the name is the hash key, and is the only thing needed, so you can avoid using the value and that's why I used _). So you get something like:
@post.attributes.select { |name, _| name =~ /answer/ }
# => { "answer_choice"=>"answer_choice", "answer_choice2"=>"answer_choice2" ... }

So from the hash you can get only the values as hash.values:
["answer_choice", "answer_choice2" ...]

And you get an array, and now you can use shuffle on it.


text:
Q: Swift Auto Documentation jazzy for pod folder only I am writing an SKD in Swift and I have an example project as a target.  The target is there for testing the network calls that the SDK makes.
My project structure looks something like this
-project
  ->sampleViewController
  ->storyboard
  ->plist
-pods
  ->core
    ->development
      -> Main
        -> Network
        -> Objects
        -> Protocols
        -> Structs
  -> RxSwift
  -> Fakery
  -> tw10

All of the files in folders that are subfolders of 'development' all are commented swift files and when option clicked show the notes I am hoping to export
I have downloaded jazzy and I cannot see a way to specify a path extension more over it appears to build the project and take out the comments of the target.
However I don't want this as all the code in my target is not what I am going to be shipping when I am done.
My question is, Is there a way to pass a folder extension e.g. ("/mac/project/target/development") to jazzy (or any other gem or program) so that I can auto generate the documentation for my code? Or does anyone know of a better solution or library I could use before I type it all out!

A: When you run jazzy -h and you can see
    --source-directory DIRPATH   The directory that contains the source to be documented
-e, --exclude file1,file2,…fileN Files to be excluded from documentation

Just play around :).

A: Just write:
jazzy --podspec PathOfYourPodspec

...and your documentation folder will be created.


text:
Q: Numpy vectorization for nearest neighbor calculation in semi-sparse arrays I have a question for you guys concerning vectorization with numpy.
I have a semi-sparse matrix where the non-zero elements are either +1 or –1 and are ordered randomly in a numpy array (let's call lattice) such that a 'site' at lattice[i,j] has nearest neighbors at lattice[i+1,j+1], lattice[i+1,j-1], lattice[i-1,j+1], and lattice[i-1,j-1]:
lattice = np.array([[1,  0, -1,  0],
                    [0,  1,  0, -1],
                    [1,  0,  1,  0],
                    [0,  1,  0, -1]])

There's a function F that maps the configuration stored in lattice to a scalar value. Not sure how to display mathjax / latex here but I'll do my best with typing it out.
F(lattice) =  a * sum( lattice[i,j] ) + b * sum( lattice[i,j] * lattice[i±1, j±1] )
The first expression is a sum over all of the lattice sites which are scaled by a, and the second sum is over all of the lattice sites and their product with each site's set of nearest neighbors, scaled by b.
In an effort to simplify all of this, when I generate my lattice, I create a dictionary for which each key corresponds to a tuple of indices for each site in lattice, and the value stored there is a list of tuples pointing to the nearest neighbors, i.e.
sites = { (i,j) : [ (i+1, j+1), (i+1, j-1), (i-1,j+1), (i-1,j-1) ]}

I can definitely take advantage of vectorization to compute the first sum, but I'm having trouble finding a way to vectorize the second sum, since the sum over nearest neighbors depends on the particular set of indices of the lattice site being considered.
def F(a,b, lattice, sites):
    """
    Parameters
    ----------
    a: float
    b: float
    lattice: np.ndarray, shape [nx, ny]
    sites: dict
         Keys are tuples of the lattice site indices, returns a list
         of tuples of the site's nearest neighbors

    Returns
    -------
    c: float
    """

    #-- Compute the first sum
    c = a * np.sum( (np.ma.masked_equal(lattice,0) + 1) / 2. )

    #-- Compute the second sum
    c += np.array([ [ b*lattice[i,j]*lattice[x,y] for (x,y) in sites[(i,j)] ] for (i,j) in sites.keys() ]).sum()

    return c

This gives ok performance, but when I consider large lattices, calculating that second sum with the list comprehension really starts to kill my performance.
Do you guys have any idea how I could go about vectorizing the second sum?
I was thinking a bit about somehow using the strides of the numpy array to calculate this but I'm not if that is (a) feasible and (b) worthwhile.

A: If you create an auxiliary array like this:
lattice_neighbor_sum = np.zeros_like(lattice)
lattice_neighbor_sum[:, :-1] += lattice[:, 1:]
lattice_neighbor_sum[:, 1:] += lattice[:, :-1]
lattice_neighbor_sum[:-1] += lattice[1:]
lattice_neighbor_sum[1:] += lattice[:-1]

the result for your sample input will be:
>>> lattice_neighbor_sum
array([[ 0,  1,  0, -1,  0],
       [ 3,  0,  0,  0, -1],
       [ 0,  4,  0, -2,  0],
       [ 2,  0,  1,  0, -2]])

And with a little application of the distributive property, your computation can be rewritten as:
a * np.sum(lattice) + b * np.sum(lattice * lattice_neighbor_sum)

A: @Jaime, I played around with the answer you provided and came up with this somewhat modified approach. Also, I apologize but I made a mistake in my initial lattice definition (supposed to be even numbers of rows and columns), so the one I use here is slightly different than the one I supplied you with.  If we take the following lattice:
lattice = np.array([[1,  0, -1,  0],
                    [0,  1,  0, -1],
                    [1,  0,  1,  0],
                    [0,  1,  0, -1]])

And create the auxiliary array in a slightly different way:
neigh_sum = np.zeros_like(lattice)
#-- neighbors at (i-1, j+1)
neigh_sum += np.pad(lattice, ((1,0),(1,0)), 'constant')[:-1,:-1]
#-- neighbors at (i+1, j+1)
neigh_sum += np.pad(lattice, ((1,0),(0,1)), 'constant')[:-1,1:]
#-- neighbors at (i+1, j-1)
neigh_sum += np.pad(lattice, ((0,1),(0,1)), 'constant')[1:,1:]
#-- neighbors at (i-1,j-1)
neigh_sum += np.pad(lattice, ((0,1),(1,0)), 'constant')[1:,:-1]

Using this approach, I obtain:
neigh_sum = array([[ 1,  0,  0,  0],
                   [ 0,  2,  0,  0],
                   [ 2,  0,  0,  0],
                   [ 0,  2,  0,  1]])

Then I can use the line you suggested to compute the total sum:
c = a * np.sum(lattice) + b * np.sum(lattice * neigh_sum)


text:
Q: restkit json example I'm just starting off with RestKit for iOS.
after figuring out some concepts and head-points for the RestKit, I've moved to start some practical training on RestKit. But what I've found is all the examples and the tutorials about RestKit are outdated and there is no example on the new version .
What i want is a small and simple example on how Restkit deal with JSON (Request and Response) and how to use ObjectMapping 2.0 (live example)
I've been reading through this web page since 3 days and i came over all of it's stuff and acquire a good amount of knowledge about it, but still with no benefit for what I want.
Thx in advance

A: You best place to start is download restKit from github and working through the examples that are built in.
https://github.com/RestKit/RestKit/tree/master/Examples
That is a good place to start and generally kept up to date.

A: Blake has written a great writeup at https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md I don't know if was update to handle the very recent release but it certainly worked on the previous one.