text:
Q: Why does my Android ListAdapter only show one item? In my Android app I'm trying to build my very first custom listadapter. I now managed to get it to display one item, but unfortunately one item only where there are 8 in the list. My adapter looks like this:
public class PossibilitiesAdapter extends BaseAdapter {
    private AdapterCallbacks callbacks;
    private List<String> possibilitiesList = new ArrayList<String>();
    private LayoutInflater inflater;

    public PossibilitiesAdapter(Context context) {
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void setPossibilitiesList(List<String> possibilitiesList) {
        for (String possibility : possibilitiesList) {
            addItem(possibility);
        }
    }

    public void addItem (final String item) {
        possibilitiesList.add(item);
        notifyDataSetChanged();
    }

    private class ViewHolder {
        TextView possibilityTitle;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.list_item_posibility, viewGroup, false);
        holder.possibilityTitle = (TextView) convertView.findViewById(R.id.text_possibility);
        holder.possibilityTitle.setText(possibilitiesList.get(position));

        return convertView;
    }

    @Override
    public int getCount() {
        return possibilitiesList.size();
    }
    // And here are some more things like getItemId() and getItem()
}

and I set the possibilitiesList from my fragment like so:
List<String> list = Arrays.asList(getResources().getStringArray(R.array.the_possibilities));
Log.e(this, new Integer(list.size()).toString()); // Outputs 8, so there are enough in the array.
adapter.setPossibilitiesList(list);

My fragment_possibilities.xml looks like this:

<ListView
    android:id="@+id/list_possibilities"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

and my list_item_possibility.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text_possibility"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

So the problem is that it only displays the first item, and nothing more. Does anybody know what the problem is and how I can fix it?

A: Are you nesting your list inside a ScrollView? It would be a typically behaving that it only shows one item. Try to avoid it o use the following method.
/**
 * read all adapter views and calculate total length
 *
 * @param listView
 */
public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        return;
    }

    int totalHeight = 0;
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    setListViewHeight(listView, totalHeight);
}

/**
 * set listview height
 *
 * @param listView
 * @param height
 */
public static void setListViewHeight(ListView listView, int height) {
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = height + (listView.getDividerHeight() * (listView.getAdapter().getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

No that will not work, as I said, you cant put a ListView Inside a ScrollView.
Try this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
    android:id="@+id/list_possibilities"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

A: your getView Method is implemented wrong, more precisely the view holder pattern.
im guessing you see the right amount of entries but all with same content
try this:
@Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
    ViewHolder holder = null;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.list_item_posibility, viewGroup, false);
        holder = new Holder();
        holder.possibilityTitle = (TextView) convertView.findViewById(R.id.text_possibility);
            convertView.setTag(holder);
    } else {
        holder = (ViewHolder)convertView.getTag();
    }

    holder.possibilityTitle.setText(possibilitiesList.get(position));

    return convertView;
}

and somehow i think your setPossibilitesMethod seems odd. id probably use something like this
public void setPossibilitiesList(List<String> possibilitiesList) {
    this.possibilitiesList = possibilitiesList;
    notifyDataSetChanged();
}

public void addItem (final String item) {
    possibilitiesList.add(item);
    notifyDataSetChanged();
}

public void addItems (List<String> possibilitiesList) {
    this.possibilitiesList.addAll(possibilitiesList);
    notifyDataSetChanged();
}

and you can shorten the code for the retrieval of the inflaterService like this:
public PossibilitiesAdapter(Context context) {
    inflater = LayoutInflater.fromContext(context);
}

In addition you dont have to cast it
updated
@Override
public int getCount(){
    for (String possibility : this.possibilities){
        System.out.println(possibility);
    }
    int size = this.possibilities();
    System.out.println("getCount: " + size);
    return size;
}

A: Change the method addItem and remove notify from there , add notify after the for in the metghod setList

A: The most possible case is you are getting possibilitiesList.size() as 1 when you execute getCount() method. Print a log to check the value.


text:
Q: How to use `image` to display a matrix in its conventional layout? I have a matrix defined as follows
dataMatrix <- matrix(rnorm(400), nrow=40)

then dataMatix is plotted to the screen using the following
image(1:10, 1:40, t(dataMatrix)[, nrow(dataMatrix):1])

can someone explain how the third argument of the image function works ? I'm particularly confused by what happens inside []. Thanks

A: There is nothing better than an illustrative example. Consider a 4 * 2 integer matrix of 8 elements:
d <- matrix(1:8, 4)
#     [,1] [,2]
#[1,]    1    5
#[2,]    2    6
#[3,]    3    7
#[4,]    4    8

If we image this matrix with col = 1:8, we will have a one-to-one map between colour and pixel: colour i is used to shade pixel with value i. In R, colours can be specified with 9 integers from 0 to 8 (where 0 is "white"). You can view non-white values by
barplot(rep.int(1,8), col = 1:8, yaxt = "n")

If d is plotted in conventional display, we should see the following colour blocks:
black  |  cyan
red    |  purple
green  |  yellow
blue   |  gray

Now, let's see what image would display:
image(d, main = "default", col = 1:8)

We expect a (4 row, 2 column) block display, but we get a (2 row, 4 column) display. So we want to transpose d then try again:
td <- t(d)
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    3    4
#[2,]    5    6    7    8

image(td, main = "transpose", col = 1:8)

Em, better, but it seems that the row ordering is reversed, so we want to flip it. In fact, such flipping should be performed between columns of td because there are 4 columns for td:
## reverse the order of columns
image(td[, ncol(td):1], main = "transpose + flip", col = 1:8)

Yep, this is what we want! We now have a conventional display for matrix.
Note that ncol(td) is just nrow(d), and td is just t(d), so we may also write:
image(t(d)[, nrow(d):1])

which is what you have right now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AMQ Consumers choose which queue to process Given the following scenario:
I have a system that creates, updates and deletes records.  For each of these actions I need to do something (lets say write the events to a log as a silly example) however I need to process these events for each record in order - Meaning I can't log the delete before I have done the create, or any of the previous updates.  I also can't log the update before I have logged the create.
I am investigating Queues in order to preserve sequence. However I don't really want RecordID_2 to be held up behind RecordID_14  The records do not need to be processed in sequence as much as the actions on each record have to.  Hence I don't think I can/should use one queue.
As I don't have hundreds of RecordID_XX active at the same time, I was thinking of having a queue for each RecordID_XX so if several updates can in for that one RecordID each event for that record would be added to that same queue and be processed in order  (I.e. Create first, Update_1 after Create is complete, Update_2 is processed after Update_1 is complete etc), however if additional events for a different record came in they would be added to their own queue.  If the queue is empty for a period of time it simply gets deleted.  I realize that this may result in a queue getting one message and then being deleted as there were no updates before the idle timeout expired.  (This does not seem at all efficient)
Based on Andres T Finnell's excellent answer to this question.
I was thinking of doing the following
Producer (Web Service) -> Queue_Original <- Dispatcher  -> RecordID_14
                                                        -> RecordID_2
                                                        -> RecordID_8
                                                        -> RecordID_15

Some of the "logging" may take long.  So I want to be able to have a few consumers listening for these queues.
Lets say I have Consumer_1 and Consumer_2 (I may want to add Consumer_3 later to assist with growing load)
What I would like is Consumer_1 to do a getDistinations()
 where the broker will return [RecordID_14, RecordID_2, RecordID_8, RecordID_15]
Questions:

*

*Is it possible for Consumer_1 to iterate through the list of queues returned from the broker looking for the first available queue that does not have a Consumer_X connected to it and begin processing the 1st message on this queue?

*And then each subsequent Consumer to do the same until it finds the next queue without a Consumer connected to it?

*Would Advisory-Messages be the thing to use here?

*Am I going down the wrong path completely? Is there a better approach
to handling this scenario?


text:
Q: Mimic main window addDockWidget layout behavior for QDialog I like the default handling/layout that adding a dock widget to the main window with addDockWidget() provides.  Specifically the following:

*

*Uses a QSplitter (I assume) which allows user to resize 2 dock widget and central widget.

*Cannot shrink the dock widget below it's minimum size hint.

*When dragging the size of the entire window the dock widget stays it's original size (i.e. it's different than dragging the splitter).  Thus, the central widget grows when dragging the entire window instead of both dock and central widget growing.

I'd like to mimic this behavior, but on a QDialog since I can't just call addDockWidget().  I'm not really concerned about being able to drag the dock widget around and drop it on other corners, etc.  I just want a QLayout setup that can do the above 3 things.

A: You can use a QMainWindow instead of a QDialog in order to get dockwidget functionality for a dialog. You should not notice any difference in performace between QMainWindow and QDialog.


text:
Q: Error Creating a 7-zip installer package If this is not the correct place to ask this, I apologize.
I use 7zip to create an installer package. Recently, my computer was updated, and I can no longer get it to work. I use a Windows Installer from Visual Studio 2010 to create the installation package, which I add to a file called setup.7z. I have confirmed that the files are archived correctly. I then call
copy /b 7zsd.sfx + config.txt + setup.7z setup.exe
which packages everything into a single file called "setup.exe". Clicking on this would start the installer.
After the update, I can still make the file, and it looks just fine. However, if I try to click on it, I get a message saying 7-Zip: Unsupported method.
I have 7-Zip version 18.05 (x86) installed. Honestly, I am not sure where I got the 7zsd.sfx file, but do remember having to hunt it down. It has no versioning, but was last modified on 7/13/2007. I don't know if the version matters, since you shouldn't need 7-Zip installed since this is a self-extracting file. However, it may be that the older version isn't able to unzip something zipped by a newer version.

A: I think the problem is in different versions of 7zip and 7zip.sfx used. Unfortunately SFX file is absent in most recent 7zip packages.
Here is link to 7zip_extra from some old version that has both SFX file and .bat file to create the installer.
Works fine for me.

A: Setup Tools: Why 7-Zip? There is a plethora of alternatives for creating (real) setups - and several are free: How to create windows installer (several links to tools for creating all kinds of setups). Brief descriptions below as well - under "Alternatives" (free tools, or tools with free features). These tools have been tested extensively to ensure running with minimal dependencies. Just something to keep in mind and evaluate I guess.
7-Zip

Guess: first install the C/ C++ runtimes and see if the problem goes away. Next check the compression - and then the LZMA SDK
  as described below?

Unsupported Compression?: 7-Zip: Unsupported method - use LZMA? I suppose this problem could still occur though that answer is a couple of years old.
Missing Runtime?: You might also want to do a dependency walker check on that setup.exe to see if it depends on something that is missing on the box (for example MSVCRT.dll - or another runtime library). Just download the tool. Easy to use. Or maybe first try to install commonly used C/C++ runtimes. Also, Dependency Walker is aging and shows garbage at times. There is the newer Dependencies - but it is not quite prime-time yet, but try it (click Releases tab). It has been updated to handle Windows API-sets and WinSxS (side-by-side assemblies). Note: several security software on virustotal.com detect Dependencies as a "risk tool, not a virus" (it is open source).
LZMA SDK: The 7zSD.sfx file would likely be from the LZMA SDK. And the command line you describe can be found in the main 7-Zip help file (not the SDK, but the one coming with the regular 7-zip installation). Section "-sfx (Create SFX archive) switch" : Command Line Version => Switches => -sfc (Create SFX Archive.

Alternatives
Visual Studio 2017: The newest, free version of Visual Studio: Visual Studio Community 2017 can create setup.exe files via its Microsoft Visual Studio 2017 Installer Projects (this extension must be installed after installing Visual Studio 2017).
WiX: The Open Source WiX toolkit can create setup.exe files with its Burn component. A WiX Burn ad-hoc sample- just to get the general idea - it has a learning curve. No GUI to help you, it is all XML-based. Use with or without Visual Studio.

Advanced Installer: I believe Advanced Installer can compile a setup.exe even in their free version. Despite a somewhat large download, I think this would work for you and be quick.

UPDATE on Advanced Installer: The free edition can only build MSI files, EXE bootstrappers can be built with the paid editions (any of them).
dotNetInstaller: There is also the dotNetInstaller Setup Bootstrapper - which I have never used. Here it is on github.com (source).

Inno or NSIS: These free non-MSI installers can easily create a setup.exe for you that has been
  optimized for minimal dependencies. I haven't used them much, but they
  are well-known. NSIS seems to create archive files compatible with Zip tools.

IExpress et al: There are security vulnerabilities that affect these self-extracting packages. Another reason I recommend a "real" deployment tool with dedicated resources to fix such things quickly, despite the niceness of having a setup.exe that can be opened directly in 7-zip.

File Extraction
On the topic of extracting files from setup.exe files of various types:

*

*MSI: Extract MSI from EXE - all MSI files can be extracted, and setup.exe files created with WiX can also be extracted

*NSIS & Inno: It looks like NSIS creates files compatible with 7-Zip (comprehensible compression), not so with Inno by the looks of it.

Some Links:

*

*Wix and .NET Framework (prerequisites)

*What is the difference between 7zip's 7z.sfx and 7zsd.sfx?

*

*https://en.wikipedia.org/wiki/Self-extracting_archive#Overview : "For a decompression utility to correctly expand an archive of either
  the self-extracting or standard variety, it must be able to operate on
  both the file format and algorithm used. The exact executable code
  placed at the beginning of a self-extracting archive may therefore
  need to be varied depending on what options were used to create the
  archive. The decompression routines will be different for a LZMA 7z
  archive when compared with a LZMA2 7z archive, for example."


text:
Q: Can't find manually added records using the search box? I'm migrating a webapp using jhipster so I already have a database with a lot of records that have to be in the new application.
Once I created the entity I added the records from my old database using:
INSERT INTO <table> SELECT * FROM <old-database>.<table>;

When I execute the webapp and search for a record in the entity view it doesn't show any old records (only the ones added using the Add button in the webapp).
I'm using MySQL for dev and prod, and I selected ElasticSearch when I was generating the app. The entity view shows the table with all the old records, but when I search for one using the search box it doesn't find them.
What am I doing wrong? Is that the correct way to insert the data?

A: using JHipster together with elasticsearch assumes, your app is fully aware of managing its search index. While inserting data on your own, your search index becomes inconsistent to your database, what is obvious.
In your case I suggest to install the JHipster elasticsearch reindexer module, which enables you to reindex the search index at any time you want. After reindexing, your old data should also appear in your JHipster application


text:
Q: Facebook Connect Publish Stream JS Help My site allow users to login via Facebook Connect and also allows them to update a status field our site. I want to include a checkbox below the status update field that will allow them to post this update to their Facebook profile as well if they so choose. In order to do this I need the user to grant our application permissions to post to their Facebook profile which is supported by prompting the user for 'publish_stream' permission using the JS function FB.Connect.showPermissionDialog http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.showPermissionDialog.
The problem I'm having is figuring out if I need to prompt the user to do this. Basically the user experience I'd like to have is that when the user checks this box for the first time I want them to be prompted to grant this permission. Once that has been granted I won't need to prompt them in the future if they check that box again. I can't seem to figure out what JS to include in the onclick action of that checkbox that will check to see if the user has granted this permission and if not then prompt them, otherwise do nothing. Also after checking the box and granting the permission I want to do nothing (no page reload) but if they reject the request to grant permission I'd like the checkbox to be unchecked. I think I may need to use the FB.ApiClient.users_hasAppPermission JS function http://developers.facebook.com/docs/?u=facebook.jslib.FB.ApiClient.users_hasAppPermission but am still confused on what this would look like. The psuedo code for this would be:
onclick="
     if(user_already_granted_permission) { do_nothing; }
     else {
         prompt_user_to_grant_permission {
             wait_for_response_from_permission_dialog {
                 if(permission_granted) { do_nothing; }
                 else { uncheck_checkbox; }
             }
         }
     }
"

One other thing worth noting is that I've already verified the user is logged in through Facebook Connect when the page was rendered. I'm hoping someone else using Facebook Connect has already been able to figure this one out. Thanks in advance for your help!

A: I recently developed an online demo that uses Facebook Connect and gets the friend list of a given user - it's not the same as your case, but I used FB.Facebook.apiClient.requireLogin to get the user logged, like this:
var api_key = 'd04fba62ff27c6c84a6b767d404bcec3';
var channel_path = '/xd_receiver.htm';

/* initialize facebook API */
FB_RequireFeatures(['Api'], function() {
    FB.Facebook.init(api_key, channel_path);

    var api = FB.Facebook.apiClient;

    api.requireLogin(function(exception){
        // user is logged in and my application
        // has permissions to get friend list
    });
});

A: You can do something like this:

FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(has_perms) {
    if(has_perms) {
        // User has granted the publish_stream permission
    } else {
        // User has not granted the publish_stream permission
    }
});

The second param for the users_hasAppPermission function is a callback which returns the result of the check.


text:
Q: How to change page and call function at the same time? HELP! Event onClick needs to send data to the server and change the page at the same time. Here is my code ,but data is send with method POST ,but page are not changing...
 const commandButton = document.getElementById("order");
  commandButton.onclick = function () {
    createOrder(); // A function that sends users data to server with POST method
    window.location.href = "http://127.0.0.1:5500/front/html/confirmation.html";
  };

  function createOrder() {
    const firstName = document.getElementById("firstName").value;
    const lastName = document.getElementById("lastName").value;
    const address = document.getElementById("address").value;
    const city = document.getElementById("city").value;
    const email = document.getElementById("email").value;
    const newCustomer = {
      // newCustomer is an object which will be changed into string with JSON.stringify
      contact: {
        firstName: firstName,
        lastName: lastName,
        address: address,
        city: city,
        email: email,
      },
      products: panier,
    };

A: I think the problem is because you haven't prevent form from making it's own general request, try using event.preventDefault(); in onclick handler to prevent form doing it's general operation and check that solves problem or not.
const commandButton = document.getElementById("order");
commandButton.onclick = function (event) {
  event.preventDefault();
  createOrder(); // A function that sends users data to server with POST method
  window.location.href = "http://127.0.0.1:5500/front/html/confirmation.html";
};


text:
Q: Generate a deterministic random number from any number From a number x, I want a function to get a random number y, uniformly distributed. For same x, the function should return same y.
I tried:
float func(int x) {
  return new Random(x).nextFloat();
}

but apparently only the sequence of numbers provided by a seeded Random is uniformly distributed, not first values. Is this possible?

A: First, note that both int and float are 32bit datatypes in Java. So what you're asking for is essentially a good hash function. If you want your random function to be 1:1, then this becomes a psuedomrandom permutation. So pick your favorite hash function and then reinterpret the bits as a float (not a cast)
public float f(x) {
   // Pick your favorite hash function here
   int hash = (int)(x * 2654435761L) // Fibonacci hash
   return Float.intBitsToFloat(hash);
}


text:
Q: Where to put file in Microsoft Visual Studio so that it will find them automatically? I've written a program at home on Linux and I have some files that are read in automatically. They are in the same directory as the main.cpp file and when I compile and run using
g++ -Wall main.cpp && ./a.out
the program finds the files, reads them in and works, using this function:
std::vector<std::string> returnFile(std::string filename) {
    std::ifstream infile;
    std::vector<std::string> contents;
    infile.open(filename.c_str());
    for (std::string line; std::getline(infile, line); ) {
        contents.push_back(line);
    }
    infile.close();
    return contents;
}

On Windows, using Microsoft Visual Studio 2010, where do I put the file so that I can run:
returnFile("myFile.txt");
and it will find the file?

A: During normal compilation:
- the root directory is your Project direcoty.
(where your Project.vcxproj file is)
After Release:
- the root directory will be the one of your executeable.


text:
Q: Stop background fetch task iOS I'm using performFetchWithCompletionHandler for background fetch.
When I want to start backgroundFetch i use UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum).
But i want to stop this background fetch. How can i do this ?


text:
Q: Is it possible to have a Phonegap app start up automatically when an android tablet powers on? We're giving android tablets to several clients to showcase some apps we've built, and we want to create another app to automatically start up as soon as the device is powered on (and perhaps only the first time it's powered on) to convey with some graphics and text that we have these other apps installed they should check out. Can I do this with PhoneGap or do I have to create a Java-based android app? Thanks very much.

A: Actually it is possible to do, a good example of what is required is posted in this thread
How to Start an Application on Startup?. The Java code would have to make its way as a custom phonegap plug-in as you're using phonegap..

A: Yes you can do that using the Autostart plugin (also compatible with PhoneGap Build).


text:
Q: question about logically true statements? "Is the statement
$(∃xQ(x) ∧ ∃xR(x)) ↔ ∃x(Q(x) ∧ R(x))$
logically true? If it is, explain why. If it isn't, give an interpretation under which it is false."
because this question exclusively uses ∃x, does that mean we only need to find ONE interpretation for which it is true? so if we defined
$R(x)$ $=$ '$x$ is even'
and
$Q(x)$ $=$ '$x$ is prime'
and worked out both sides to be true, that would mean this statement is logically true, correct? if and only if both are true or both are false
so for for $(∃xQ(x) ∧ ∃xR(x))$ we could interpret as "for some integer $x$, $x$ is even and for some integer $x$, $x$ is prime" meaning there exists an integer that is prime and an integer that is even? and the second statement we could say "for some integer $x$, $x$ is prime and even" meaning there exists a number that is both prime and even. so both sides are true, therefore the statement is logically true, correct?

A: In the universe of natural numbers  $\exists x\left[x=4\right]\wedge\exists x\left[x=7\right]$ is a true
statement, but $\exists x\left[x=4\wedge x=7\right]$ is not a true
statement.

A: What do you think of "There are cats who are alive and there are cats who are dead" versus "There are cats who are alive and dead" ?


text:
Q: How do you create a PageFieldFilterWebPart by PowerShell? I'm trying to create a PageFieldFilterWebPart by PowerShell. If I use the PageContextFilterWebPart I success to create it, but I can't configure it. Anyone who have done this? If I success with this I also wan't to connect this to a document web part.
$WebUrl = "[weburl]"
$PageUrl = "[pageurl]"
$ZoneName = "Zon1"
$ZoneIndex = "1"

$web = Get-SPWeb -Identity $WebUrl

$webPart = new-object Microsoft.SharePoint.Portal.WebControls.PageContextFilterWebPart
$webPart.ParameterName = "Category" # Error: 'ParameterName' is a ReadOnly property.
$webPart.FilterName = "Category"

$page = $web.GetFile($PageUrl)
$page.CheckOut()

$webpartmanager = $web.GetLimitedWebPartManager($PageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpartmanager.AddWebPart($WebPart, $ZoneName, $ZoneIndex);

$page.CheckIn("")

$web.Dispose()

Is this the way to go or is there another?


text:
Q: Function vs fat arrow So, if we take this function for example:
function executeCallback (callback) {
  callback();
}

Now, it doesn't matter if I place a fat arrow or a normal function, both will work, like these:
executeCallback(function () {
  alert('This is a function');
})

executeCallback(() => {
  alert('This is a fat arrow function');
})

So, except for shorter syntax. What exactly is the difference between both and how does it effect object oriented programming?

A: For more in depth info, see this answer on SO. Also, See this here.
A Few Reasons

More intuitive handling of current object context.
ES6 Arrow
this.nums.forEach((v) => {
    if (v % 5 === 0)
        this.fives.push(v) //this actually points to the context of the callback
});

Ecmascript 5
//  variant 1
var self = this;
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        self.fives.push(v);
});

//  variant 2
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}, this);

//  variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}.bind(this));

More expressive closure syntax.
ES6 Arrow
odds  = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums  = evens.map((v, i) => v + i)

Ecmascript 5
odds  = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums  = evens.map(function (v, i) { return v + i; });

A: *

*the arrow function automatically bind the current context to the this so you won't need to do myfunction.bind(this, args)


text:
Q: Unexpected error in flutter without any errors Im getting this unexpected error without changed in the code and no error being pointed

Exception caught by scheduler library ═════════════════════════════════
'package:flutter/src/widgets/binding.dart': Failed assertion: line 849 pos 12: '!debugBuildingDirtyElements': is not true.

Any idea what is it?


text:
Q: C - memory management I just wrote some C code:
#include <stdlib.h>
#include <time.h>
#include <string.h>

typedef struct {
    void **data;
    time_t lastModified;
} container;

container *container_init() {
    container *c = malloc(sizeof(container));
    void *data = NULL;
    c->data = &data;
    c->lastModified = time(NULL);
    return c;
}

void *container_getData(container *c) {
    void **containerData = c->data;
    return *containerData;
}

// only pass manually allocated data that can be free()'d!
void container_setData(container *c, void *data) {
    free(container_getData(c));
    c->data = &data;
}

void container_free(container *c) {
    free(container_getData(c)); // <--- THIS LINE
    free(c);
}

int main(int argc, const char *argv[]) {
    for (int i = 0; i < 100000000; i++) {
        char *data = strdup("Hi, I don't understand pointers!");
        container *c = container_init();
        container_setData(c, data);
        container_free(c);
    }
}

My logic was the following: When I call container_setData(), the old data is free()'d and a pointer to the new data is stored. That new data will have to be released at some point. That happens for the last time during the call to container_free().
I have marked a line in the container_free() function. I would have sworn I'd need that line in order to prevent a memory leak. However, I can't use the line ("object beeing freed was not allocated") and there's no memory leak if I delete it. How does the string from my loop ever get released?!
Could someone explain where the error is?

A: c->data = &data;

stores the address of the pointer data (the argument to your function), not the actual pointer. I.e., you're storing a pointer to a temporary.
You could have built the container structure with just a void *data member.

A: To explain larsmans answer with code make these changes:
typedef struct {
    void *data;
    time_t lastModified;
} container;

void *container_getData(container *c) {
   return c->data;
}

void container_setData(container *c, void *data) {
    free(c->data);
    c->data = data;
}

void container_free(container *c) {
    free(c->data);
    free(c);
}

And other changes too -- this just gets you on the right track.


text:
Q: Populate data into spinner dynamically I'm currently stuck on how I'm going to display my data to my spinner. So basically I am using Websocket to receive data and run it on my UI thread my problem is that there is no list of data showing in my spinner.
Here is my code:
    WayPointData = new SubscribedData<>();
    final Type WayPointType = new TypeToken<SubscribedData<WayPoint>>() {
    }.getType();

    /** an ID for the spinner **/
    spin = (Spinner) findViewById(R.id.spinner);

    final SpinnerAdapter adapter = new ArrayAdapter<String>(Pop.this, android.R.layout.simple_spinner_item);
    spin.setAdapter(adapter);

    rosbridge = new RosbridgeListener("ws://10.24.204.231:9090");
    rosbridge.setOnDataReceivedListener(new RosbridgeMessageListener() {

        /**
         * a running thread that when the connection is made the data of the topic will serialize and deserialized java objects
         * to (and from) JSON.
         * @param msg
         */
        @Override
        public void onDataReceived(final String msg) {
            try {
                runOnUiThread(  new Runnable() {
                    @Override
                    public void run() {
                        try {
                            WayPointData = new Gson().fromJson(msg,WayPointType);
                            JSONObject jsonObject = new JSONObject();
                            JSONArray wayPointJsonArray = jsonObject.getJSONObject("msg").getJSONArray("waypoints");
                            for (int i = 0; i < wayPointJsonArray.length(); i++) {
                                JSONObject wayPointJsonObject = wayPointJsonArray.getJSONObject(i);
                                // Parse name
                                String name = wayPointJsonObject.getString("name");
                                WayPoint wayPoint = new WayPoint();
                                wayPoint.name = name;

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

                /** a msg that will display once the data is received **/
                Log.d("B9T", String.format("Received data: %s", msg));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

    spin.setAdapter(adapter);
    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int p, long id) {
            WayPoint wayPoint = (WayPoint) parent.getItemAtPosition(p);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

Thanks to anyone who can help me!

A: add array when you initing your adapter:
final SpinnerAdapter adapter = new ArrayAdapter<String>(Pop.this, android.R.layout.simple_spinner_item, yourStringArray);

if you make changes later (will receive list from server) just setup array that you used before with new data and use adapter.notifyDataSetChanged()

A: Here I can see you don't pass json string to JSONObject that's why your main JSON object is an empty json object.
You should pass the JSON string to the JSONObject parameter like below.
JSONObject jsonObject = new JSONObject(msg); // here you have to add your json string in JSONObject parameter

Hope it helps you.


text:
Q: Invalid argument supplied for foreach() I am trying to install a theme locally but when I go to do it I get the following error:
( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\wp-content\themes\royalestate\slider.php on line 4
Call Stack
#   Time    Memory  Function    Location
1   0.0005  369184  {main}( )   ..\index.php:0
2   0.0007  372840  require( 'C:\wamp\www\wp-blog-header.php' ) ..\index.php:17
3   1.3620  21193256    require_once( 'C:\wamp\www\wp-includes\template-loader.php'   ) ..\wp-blog-header.php:16
4   1.3635  21212432    include( 'C:\wamp\www\wp-content\themes\royalestate\homepage.php' ) ..\template-loader.php:47
5   1.4038  21296984    include( 'C:\wamp\www\wp-content\themes\royalestate\slider.php' )   ..\homepage.php:12

If my problem lies in the slider code then that is below, but I don't think there should be as I installed it fresh out of the box.

                <?php $slider_ctr = 0; foreach($slides as $num => $slide) : if ($slider_ctr < 5) : $image_aq = aq_resize($slide['src'], 100, 73, true);
                ?><li data-thumb="<?php echo aq_resize($slide['src'], 100, 73, true) ?>">
                    <a href="<?php echo $slide['link'] ?>"><img alt="" src="<?php echo aq_resize($slide['src'], 676, 290, true) ?>"/>

<?php echo $slide['title'] ?>

<?php echo $slide['caption'] ?>

<?php
                $slider_ctr++; endif; endforeach; ?>

Your help would be much appreciated.
Cheers,
Rags

A: Warning: Invalid argument supplied for foreach()

this is issued when a non-array object or value is passed in to foreach loop.
You might want to var_dump($slides); and see what it holds. It most likely holds a boolean false or null value.
Before using foreach loop I would check if $slides is an array
 if (is_array($slides)) {
   foreach($slides as $slide) {
     ...
   }
 }

A: To prevent this, put
if(is_array($slides))

before the foreach


text:
Q: Users of Intranet site on IIS7.5 prompted for username/password I have an intrasite from a third-party that we just transitioned from IIS 6 on Windows 2003 to a Windows 2008 R2 server with IIS 7.5.  On the old system, the user would connect ot the website and be automatically authenticated and be able to view the pages.
Now on the new server, the user is presented with a username/password prompt, like Basic Auth.  If they type in their domain username and password, it'll authenticate them.
I'm trying to figure out why it's not doing automatic Windows authentication.  I've verifie that the website "Authentication" tab only has Windows authentication turned on, no Basic or other methods are supported.  I also went into Providers and set it to only use NTLM.  I used Policy Editor to make several adjustments to the NTLM security settings and LAN Manager to allow NTLM.
The client browser is IE 8 and it has Windows Integration Authentication enabled.
I'm at a complete loss as to why the automatic Windows authentication isn't working.

A: Try adding the new site URL to the trusted sites list in IE and give it another shot.


text:
Q: In python, how can i use a loop to name panda data frames? What I'm trying to do is to use pandas to create as many separate data arrays as there are runs of my data set. The approach needs to be vary depending on the data file read in, so I want the run number, the second column, to be used to identify the data and separate it into separate data sets.
So I have a data set that looks like:
1.350000035018e-03  1.000000000000e+00  -1.617387196395e-14
2.850000048056e-03  1.000000000000e+00  -2.752685546875e-06
4.350000061095e-03  1.000000000000e+00  -2.062988281250e-06
(couple hundred lines later)
1.350000035018e-03  2.000000000000e+00  -1.617387196395e-14
2.850000048056e-03  2.000000000000e+00  -2.752685546875e-06
4.350000061095e-03  2.000000000000e+00  -2.062988281250e-06
(however many readings later)
1.350000035018e-03  35.000000000000e+00 -1.617387196395e-14
2.850000048056e-03  35.000000000000e+00 -2.752685546875e-06
4.350000061095e-03  35.000000000000e+00 -2.062988281250e-06

I want to process it into:
data1 = some number 1.0 some number
        some number 1.0 some number

data2 = some number 2.0 some number
        some number 2.0 some number

datan= some number n some number
       some number n some number

So far my code:

    f =r'C:~.dat'

    #store data using pandas
    data = pd.read_csv( f, sep = '\t', comment = '#', names = ['V','n','I'] )

    #observe data format
    print(data)

                 V     n             I
    0      0.001350   1.0 -1.617387e-14
    1      0.002850   1.0 -2.752686e-06
    2      0.004350   1.0 -2.062988e-06

    #count the loops for autamted graph plotting
    num = 1
    for i in range (len(data)):
        if i > 0:
            if data['n'][i]> data['n'][i-1]:
                num = num + 1
    #
    print('there are '+str(num)+' runs')

    #seperate data based on loop #n
    for i in range (num):

        run = data.groupby(data.n)
        data+str(i) = run.get_group(i)
        print(data+str(i))
    #

using the data grouping method works, but I cant figure out a way to use the loop number as a name variable, any help/suggestions would be highly appreciated?

A: I'm not entirely sure I understand correctly what you're trying to achieve. But if you aim to have data like this:
1.350000035018e-03  1  -1.617387196395e-14
2.850000048056e-03  2  -2.752685546875e-06
4.350000061095e-03  3  -2.062988281250e-06

do you really need the n column?
Isn't that just the data.index + 1?
(the index in your example is [0, 1, 2], and you're looking for [1, 2, 3], so you might be able to do something like data.n = [i + 1 for i in data.index])

A: Do you need to explicitly name your dataframes or can it be part of a list or dict?
For instance, you could do something like this...
import pandas as pd

f =r'C:~.dat'

#store data using pandas
data = pd.read_csv( f, sep = '\t', comment = '#', names = ['V','n','I'] )

data_list = []
# get unique run entries
runs = data["n"].unique()

# save each run's corresponding dataframe into data_list
for run in runs:
    data_sub = data[data["n"] == run]
    data_list.append(data_sub)

# access it by doing something as follows
for idx, run in enumerate(runs):
    print("Working on run {}".format(run))
    df_to_operate_on = data_list[idx]


text:
Q: How do I program tests in R so that they print nicely? Statistical tests in R generate lists, but then when you call the test, the printing of these lists gives a special user-friendly structure to assist the reader.  To see what I'm talking about, consider an example where you use the t.test function in the stats package.
#Run a T-test on some example data
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50);
TEST <- stats::t.test(X,Y);

#Show structure of the TEST object
str(TEST);
List of 9
 $ statistic  : Named num -0.134
  ..- attr(*, "names")= chr "t"
 $ parameter  : Named num 10.2
  ..- attr(*, "names")= chr "df"
 $ p.value    : num 0.896
 $ conf.int   : num [1:2] -12.3 10.9
  ..- attr(*, "conf.level")= num 0.95
 $ estimate   : Named num [1:2] 32.8 33.5
  ..- attr(*, "names")= chr [1:2] "mean of x" "mean of y"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "difference in means"
 $ alternative: chr "two.sided"
 $ method     : chr "Welch Two Sample t-test"
 $ data.name  : chr "X and Y"
 - attr(*, "class")= chr "htest"

This object is a list with nine elements, some of which are named via attributes.  However, when I print the TEST object, the returned information is structured in a different way than the standard printing of a list.
#Print the TEST object
TEST;

        Welch Two Sample t-test

data:  X and Y
t = -0.13444, df = 10.204, p-value = 0.8957
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.27046  10.87046
sample estimates:
mean of x mean of y
     32.8      33.5

As you can see, this printed output is much more user-friendly than the standard printing for a list.  I would like to be able to program statistical tests in R which generate a list of outputs similar to the above, but which print in this user-friendly way.

My Questions: Why does R print the output of the list TEST in this special way?  If I create a list of outputs of a statistical test (e.g., like the above), how can I set the object to print in this way?

A: Use one of the methods below that meets your needs the best.
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39)
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50)
TEST <- stats::t.test(X,Y)

#default; printing data of htest class
print(TEST)

#printing every element of the list
lapply(TEST, print)
print.listof(TEST)

#printing the results as a dataframe
broom::tidy(TEST) #output of this one is included just for illustration

    # A tibble: 1 x 10
  estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method                  alternative
     <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>
1     -0.7      32.8      33.5    -0.134   0.896      10.2    -12.3      10.9 Welch Two Sample t-test two.sided

To address OP's follow-up question:
"Each" class of data has a method of printing. As I outlined in my answer, print function looks at TEST and as it is class of htest it uses print.htest.
class(TEST)
# [1] "htest"

head(methods(print))
# [1] "print.acf"         "print.AES"         "print.all_vars"    "print.anova"
# [5] "print.anova.lme"   "print.ansi_string"

In my freshly opened R session, I have 185 different methods. As you loads libraries, the number will go higher.
If you want to dig deeper, then you need to look at the source code of print which can be found here: R source code on GitHub

A: This answer is put together from helpful comments and answers by other users, but I wanted to give an elaborated answer here to make things more explicit, for the benefit of users who are not already familiar with some of these issues.  The object created by the t.test function is an object of class htest, and this type of object has a special method of printing under the print.htest setting in the global environment.  That printing method draws out information from the list, but prints it in the user-friendly way you see in the output in the question.
If you want to replicate this type of printing for a new statistical test that you are programming yourself, then you will need to structure your new test so that it outputs a htest object, with the required elements of the list, and the required class.  Here is an example from another answer where a hypothesis test set out in Tarone (1979) is programmed as a htest object:
Tarone.test <- function(N, M) {

    #Check validity of inputs
    if(any(M > N)) { stop("Error: Observed count value exceeds binomial trials"); }

    #Set hypothesis test objects
    method      <- "Tarone's Z test";
    alternative <- "greater";
    null.value  <- 0;
    attr(null.value, "names") <- "dispersion parameter";
    data.name   <- paste0(deparse(substitute(M)), " successes from ",
                          deparse(substitute(N)), " counts");

    #Calculate test statistics
    estimate    <- sum(M)/sum(N);
    attr(estimate, "names") <- "proportion parameter";

    S           <- sum((M - N*estimate)^2/(estimate*(1 - estimate)));
    statistic   <- (S - sum(N))/sqrt(2*sum(N*(N-1)));
    attr(statistic, "names") <- "z";

    p.value     <- 2*pnorm(-abs(statistic), 0, 1);
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(statistic = statistic, p.value = p.value, estimate = estimate,
                        null.value = null.value, alternative = alternative,
                        method = method, data.name = data.name);
    class(TEST) <- "htest";

    TEST; }

In this example, the function calculates all the required elements of the htest object and then creates this object as a list with that class.  It is important to include the command class(TEST) <- "htest" in the code, so that the object created is not just a regular list.  Inclusion of that command will ensure that the output object is of the proper class, and so it will print in a user-friendly way.  To see this, we can generate some data and apply the test:
#Generate example data
N <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
M <- c( 9, 10, 22, 15,  8, 19, 16, 19, 15, 10);

#Apply Tarone's test to the example data
TEST <- Tarone.test(N, M);
TEST;

        Tarone's Z test

data:  M successes from N counts
z = 2.5988, p-value = 0.009355
alternative hypothesis: true dispersion parameter is greater than 0
sample estimates:
proportion parameter
           0.4359756

Here we see that our newly created hypothesis-testing function gives us output that has a similar user-friendly structure to the t.test.  In this example we have given different names to the testing method and the elements of the test, and these appear in the descriptive output when printed.


text:
Q: I want to make a google doc a place where I can drop code that will automatically update on a web page As an example, say I have an image on my page that I need to change every week.  Instead of going into the code and changing the picture, I'd like to somehow put a reference to specific cell in a "published to web" google doc in place of my image in the code so I can just change the name of the image in the google doc and the new image will show up on my webpage.  I want to accomplish this so I can have several people (who can't code) be able to change the image from their computers.  I know it's possible, but I don't even know where to start.  Anyone know how to set this up this?  Thanks for the help!

A: One way to do it, when you File > Publish to the web, Google Docs will generate an iframe embed code that looks something like this:
<iframe src="https://docs.google.com/document/d/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq/pub?embedded=true"></iframe>

You can insert the iframe into your webpage. You can check on "Automatically republish when changes are made" so your users would just need to modify the document when they need to change the image.
However, I'd highly recommend that using a proper CMS would be much better, or at least build a rough authentication and CRUD to update the image.


text:
Q: OpenCV: process every frame I want to write a cross-platform application using OpenCV for video capture. In all the examples, i've found frames from the camera are processed using the grab function and waiting for a while. And i want to process every frame in a sequence. I want to define my own callback function, which will be executed every time, when a new frame is ready to be processed (like in directshow for Windows, when you defining and putting into the graph your own filter for such purposes).
So the question is: how can i do this?

A: According to the code below, all callbacks would have to follow this definition:
IplImage* custom_callback(IplImage* frame);

This signature means the callback is going to be executed on each frame retrieved by the system. On my example, make_it_gray() allocates a new image to save the result of the grayscale conversion and returns it. This means you must free this frame later on your code. I added comments on the code about it.
Note that if your callback demands a lot of processing, the system might skip a few frames from the camera. Consider the suggestions Paul R and diverscuba23 did.
#include <stdio.h>
#include "cv.h"
#include "highgui.h"

typedef IplImage* (*callback_prototype)(IplImage*);

/*
 * make_it_gray: our custom callback to convert a colored frame to its grayscale version.
 * Remember that you must deallocate the returned IplImage* yourself after calling this function.
 */
IplImage* make_it_gray(IplImage* frame)
{
    // Allocate space for a new image
    IplImage* gray_frame = 0;
    gray_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, 1);
    if (!gray_frame)
    {
      fprintf(stderr, "!!! cvCreateImage failed!\n" );
      return NULL;
    }

    cvCvtColor(frame, gray_frame, CV_RGB2GRAY);
    return gray_frame;
}

/*
 * process_video: retrieves frames from camera and executes a callback to do individual frame processing.
 * Keep in mind that if your callback takes too much time to execute, you might loose a few frames from
 * the camera.
 */
void process_video(callback_prototype custom_cb)
{
    // Initialize camera
    CvCapture *capture = 0;
    capture = cvCaptureFromCAM(-1);
    if (!capture)
    {
      fprintf(stderr, "!!! Cannot open initialize webcam!\n" );
      return;
    }

    // Create a window for the video
    cvNamedWindow("result", CV_WINDOW_AUTOSIZE);

    IplImage* frame = 0;
    char key = 0;
    while (key != 27) // ESC
    {
      frame = cvQueryFrame(capture);
      if(!frame)
      {
          fprintf( stderr, "!!! cvQueryFrame failed!\n" );
          break;
      }

      // Execute callback on each frame
      IplImage* processed_frame = (*custom_cb)(frame);

      // Display processed frame
      cvShowImage("result", processed_frame);

      // Release resources
      cvReleaseImage(&processed_frame);

      // Exit when user press ESC
      key = cvWaitKey(10);
    }

    // Free memory
    cvDestroyWindow("result");
    cvReleaseCapture(&capture);
}

int main( int argc, char **argv )
{
    process_video(make_it_gray);

    return 0;
}

EDIT:
I changed the code above so it prints the current framerate and performs a manual grayscale conversion. They are small tweaks on the code and I did it for education purposes so one knows how to perform operations at pixel level.
#include <stdio.h>
#include <time.h>

#include "cv.h"
#include "highgui.h"

typedef IplImage* (*callback_prototype)(IplImage*);

/*
 * make_it_gray: our custom callback to convert a colored frame to its grayscale version.
 * Remember that you must deallocate the returned IplImage* yourself after calling this function.
 */
IplImage* make_it_gray(IplImage* frame)
{
    // New IplImage* to store the processed image
    IplImage* gray_frame = 0;

    // Manual grayscale conversion: ugly, but shows how to access each channel of the pixels individually
    gray_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, frame->nChannels);
    if (!gray_frame)
    {
      fprintf(stderr, "!!! cvCreateImage failed!\n" );
      return NULL;
    }

    for (int i = 0; i < frame->width * frame->height * frame->nChannels; i += frame->nChannels)
    {
        gray_frame->imageData[i] = (frame->imageData[i] + frame->imageData[i+1] + frame->imageData[i+2])/3;   //B
        gray_frame->imageData[i+1] = (frame->imageData[i] + frame->imageData[i+1] + frame->imageData[i+2])/3; //G
        gray_frame->imageData[i+2] = (frame->imageData[i] + frame->imageData[i+1] + frame->imageData[i+2])/3; //R
    }

    return gray_frame;
}

/*
 * process_video: retrieves frames from camera and executes a callback to do individual frame processing.
 * Keep in mind that if your callback takes too much time to execute, you might loose a few frames from
 * the camera.
 */
void process_video(callback_prototype custom_cb)
{
    // Initialize camera
    CvCapture *capture = 0;
    capture = cvCaptureFromCAM(-1);
    if (!capture)
    {
      fprintf(stderr, "!!! Cannot open initialize webcam!\n" );
      return;
    }

    // Create a window for the video
    cvNamedWindow("result", CV_WINDOW_AUTOSIZE);

    double elapsed = 0;
    int last_time = 0;
    int num_frames = 0;

    IplImage* frame = 0;
    char key = 0;
    while (key != 27) // ESC
    {
      frame = cvQueryFrame(capture);
      if(!frame)
      {
          fprintf( stderr, "!!! cvQueryFrame failed!\n" );
          break;
      }

      // Calculating framerate
      num_frames++;
      elapsed = clock() - last_time;
      int fps = 0;
      if (elapsed > 1)
      {
          fps = floor(num_frames / (float)(1 + (float)elapsed / (float)CLOCKS_PER_SEC));
          num_frames = 0;
          last_time = clock() + 1 * CLOCKS_PER_SEC;
          printf("FPS: %d\n", fps);
      }

      // Execute callback on each frame
      IplImage* processed_frame = (*custom_cb)(frame);

      // Display processed frame
      cvShowImage("result", processed_frame);

      // Release resources
      cvReleaseImage(&processed_frame);

      // Exit when user press ESC
      key = cvWaitKey(10);
    }

    // Free memory
    cvDestroyWindow("result");
    cvReleaseCapture(&capture);
}

int main( int argc, char **argv )
{
    process_video(make_it_gray);

    return 0;
}

A: Quick thoughts would be to have 2 threads, the first thread is responsible for grabbing the frames and notifiy the second thread when they are available (places them in a processing queue), the second thread does all your processing in an event loop type manner.
See boost::thread and boost::signals2 as those two together should provide most of the framework (except for the queue) for what I described above.


text:
Q: Is there any way to disable Tailwind's responsive? I am planing to integrate Tailwind in my existing project. I don't want it response as I resize the screen, because I have to design separately for Desktop and Mobile. For Desktop
when resize screen I want to keep my design not responsive so that user can have horizontal scroll view at the bottom.

A: Tailwind is mobile-first by default.
What you can do to keep your "mobile" styles and add Tailwind for "desktop" is use a prefix for the Tailwind utility classes.
And with a breakpoint prefix, eg md or lg
// config.tailwind.js
module.exports = {
  prefix: 'tw-',
  theme: {
    extend: {
      // ...
    },
  },
  plugins: [],
}

You can check a simple demo here: https://play.tailwindcss.com/wef6kKa9D1

A: You can design your site based on breakpoints and you can customize breakpoints check here. Add all classes with pre-fix lg or xl like, lg:bg-red-400. so this css add only after specific breakpoints.

A: You can disable container on config.
Add this to tailwind.config.cjs, inside module.exports :
corePlugins: {
container: false
}
It disabled all media queries on class container. Try it bro


text:
Q: Is this a bug in xmllint or xmlstarlet pattern matching? Here is my product.xml file contents:
<ProductCode>ABC</ProductCode>

And here is the corresponding validating schema, product.xsd file contents:
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema
version="1.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:element name="ProductCode">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:minLength value="1"/>
            <xsd:maxLength value="15"/>
            <xsd:pattern value="[\P{Ll}]*"></xsd:pattern>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>

</xsd:schema>

I open a command line shell, and used xmlstarlet to validate the xml:
xmlstarlet val -e --xsd product.xsd product.xml
product.xml:1.31: Element 'ProductCode': [facet 'pattern'] The value 'ABC' is not accepted by the pattern '[\P{Ll}]*'.
product.xml:1.31: Element 'ProductCode': 'ABC' is not a valid value of the local atomic type.
product.xml - invalid

Then, i tried to use xmllint to validate the xml:
└xmllint -schema product.xsd product.xml
<?xml version="1.0"?>
<ProductCode>ABC</ProductCode>
Element 'ProductCode': [facet 'pattern'] The value 'ABC' is not accepted by the pattern '[\P{Ll}]*'.
Element 'ProductCode': 'ABC' is not a valid value of the local atomic type.
product.xml fails to validate

I spent a couple of hours tinkering with it and I found that I can make it work by removing the enclosing brackets:
<xsd:pattern value="\P{Ll}*"></xsd:pattern>

I can retain the enclosing brackets and make it work by using the /p inclusive pattern category and preceding it by a negation ^:
<xsd:pattern value="[^\p{Ll}]*"></xsd:pattern>

It seems, that there is a bug in the underlying implementation of xmllint and xmlstarlet and I need confirmation if indeed this is the case.
The versions I used are:
xmllint:
xmllint --version
xmllint: using libxml version 20904
compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 FTP HTTP DTDValid HTML Legacy C14N Catalog XPath XPointer XInclude Iconv ISO8859X Unicode Regexps Automata Expr Schemas Schematron Modules Debug Zlib Lzma

xmlstarlet:
xmlstarlet --version
1.6.1
compiled against libxml2 2.9.1, linked with 20904
compiled against libxslt 1.1.28, linked with 10129

Additional Info
Using python as coded in the snippets in python XML schema validation snippets, i found that product.xsd does not validate product.xml also. It's hard to believe that python also has this bug. So therefore, I am now seeking some kind of explanation why the pattern expression in product.xsd is not working.
The question is: why is the enclosing bracket not able to work with the exclusive /P{Ll} ?
More Additional Info
On the other hand, using the scala snippet here,it is able to validate product.xml via product.xsd. So now, we can confirm that the pattern syntax in product.xsd is correct. Yet, xmllint, xmlstarlet and python could not validate it. What is going on here?


text:
Q: Numerical solution of HJB (Hamilton-Jacobi-Bellman equations) in practice I am struggling to understand what the use of HJB equations in order to solve optimal control problems is in practice. I found the following approach in the book "Stochastic Controls" by Jiongmin Yong and Xun Yu Zhou on p.163:
1.) Solve the HJB-equation to find the value function,
2.) Minimize/Maximize the Hamiltonian pointwise to find the optimal control,
3.) Solve the ODE, since the optimal control is known.
While I do understand the above, I don't understand why apart from certain specific cases where the Hamiltonian is explicitly known, solving the HJB should be more efficient than simply minimizing the cost functional with dynamic programming or some type of gradient descent.
As far as I understand it, in order to solve the HJB-equation numerically, I have to discretize all equations in time and space and then have to solve a minimization problem. Solving this minimization problem again as according to step 2 seems completely redundant.
Am I missing something? Why are HJB equations useful in practice?

A: When you directly minimize the cost functional (for instance using a discretization in time so that the integral becomes a summation), you are solving the optimal control problem for a single initial point $x_0$. Moreover, you will find an open-loop control, i.e. a function $t \mapsto u^*(t)$, which is not robust to perturbations in the dynamics (see Open-loop vs closed-loop).
When you solve the HJB equation, instead, you are simultaneously solving the problem for all values of $x_0$, and you can even provide an optimal control in feedback form.
Regarding the question on the double minimization problem, you are right. There is a double minimization problem, but

*

*The dimension of the minimization problem is the dimension of the control space, which is typically very small, so it not very expensive.

*Simulations have shown that the first minimization, the one while solving the HJB in step 1, does not need to be solved accurately, so one can discretize the control space with few controls and minimize over a finite set of possible control values. The second minimization problem, however, must be solved more accurately.

I recommend this book for more details.


text:
Q: CKEDITOR mathjax formula is not loading properly in jquery Iam trying to display mathjax formula in ckeditor. If page reloads , the formula is loading propoerly in ckeditor , if it's jquery function call ckeditor formula is not loading properly. I want to load the mathjax formula properly through jquery function. Iam using ckeditor version "4.4.6 DEV"
formula is displaying in ckeditor while triggers jquery to load data into ckeditor:
(x = {-b \pm \sqrt{b^2-4ac} \over 2a})
code is:
// To load data in ckeditor
$('#cke_editor1 iframe').contents().find('body').html(element.body);

//ckeditor code
$('#editor1').ckeditor(
    function(){
      editorReady = true;
      // global!
      // used to be an assumption in jquery.init.editor.js
      // callback means we can always tell for sure, this helps with jasmine tests
    },
    {
      skin: 'cgp',
      forcePasteAsPlainText: true,
      resize_enabled: true,
      height: 450,
      extraPlugins: 'embed,attachment,multimedia,cg_inputctrl,footnotes',
        //,mathjax
        // mathJaxLib: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML',
        // mathJaxClass: 'equation',
      toolbarCanCollapse: false,
      magicline_everywhere: true,
      magicline_tabuList: ['data-tabu'],
      toolbar:[
            [ 'Italic',
                'NumberedList', 'BulletedList', 'Blockquote','Footnotes','Superscript', 'Subscript', 'Table', 'SpecialChar', 'Mathjax',
                'Link', 'Unlink',
                'simpleImage', 'flvPlayer', 'flvPlayerAudio', 'Attachment', 'oembed',
                'Copy', 'Paste', 'Find',
                'Undo', 'Redo',
                'Maximize']],
      keystrokes:
        [
          [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
          [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],

          [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],

          [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
          [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
          [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],

          [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],

          [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],

          [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ],
          [ CKEDITOR.CTRL + 66 /*B*/, 'doNothing' ],
          [ CKEDITOR.CTRL + 85 /*U*/, 'doNothing' ]
        ],
      contentsCss: [ CKEDITOR.basePath + 'contents.css',
                     "<%= application_asset_path('cg_gui/annotations.css') %>"],

      filebrowserBrowseUrl: urlFor("/cg_ck_multimedia/attachments"),
      filebrowserSimpleImageBrowseLinkUrl: urlFor("/cg_ck_multimedia/images"),
      // video custom placeholder images also browsed here
      filebrowserSimpleImageBrowseUrl: urlFor("/cg_ck_multimedia/images"),
      filebrowserFlvPlayerBrowseUrl: urlFor("/cg_ck_multimedia/videos"),
      filebrowserFlvPlayerAudioBrowseUrl: urlFor("/cg_ck_multimedia/audios"),
      // ckeditor window widths should be >= 640wx420h or ckeditor will resize them
      filebrowserSimpleImageWindowWidth: 920,
      filebrowserSimpleImageWindowHeight: 535,
      filebrowserFlvPlayerWindowWidth: 920,
      filebrowserFlvPlayerWindowHeight: 535,
      filebrowserFlvPlayerAudioWindowWidth: 920,
      filebrowserFlvPlayerAudioWindowHeight: 535,
      filebrowserWindowWidth: 920,
      filebrowserWindowHeight: 535,
      filebrowserSimpleImageUploadUrl: urlFor("/cg_ck_multimedia/images"),
      filebrowserFlvPlayerUploadUrl: urlFor("/cg_ck_multimedia/videos"),
      filebrowserFlvPlayerAudioUploadUrl: urlFor("/cg_ck_multimedia/audios"),
      filebrowserUploadUrl: urlFor("/cg_ck_multimedia/attachments")

    });
    })();

A: If I understand you correctly you want to dynamically modify editor HTML e.g. by ajax call and add content containing mathjax formula.
The problem with your code is that you are trying to manually modify editor HTML using jQuery, so it won't be able to parse mathjax formula. You should always modify editor content using its functions. E.g. you could use editor.setData function to set content with mathjax formula:
editor.setData( '
A\\(1 + 1 = 2\\)B
' );

Also, don't forget that you have to wrap mathjax formula with span element and correct class name which could be changed using CKEDITOR.config.mathjaxClass configuration property. The default one is math-tex.


text:
Q: Proving this map to be quotient map( Closed /open sets in more than 1 dimensions)
Let p :$ \mathbb{R}^2 \to [0,\infty)$ by p((x,y))= $x^2 +y^2$ and suppose $[0,\infty)$ has the subspace topology induced by usual topology on $\mathbb{R}$. Show that p is a quotient map.

There is a theorem tahtif p is continuous ,surjective, open or closed then p is quotient map.
I was trying to use this result here but the problem is that I am not sure on how to prove that If map is closed/open or not and that is arising as it's a 2-variable map.

So, can you please help me with the how maps are proved to be Open / closed in more than one dimensions? It will be hard if I take a open/closed map and try to find its range and checking the set wheter it's open or not?

So, Can you please tell of a more elegant stratergy?
OR If there is a different but less brute method of proving the map to be quotient map that is also welcome.
Thanks for your time!

A: A map $f$ is open if the image of any open set $\mathcal{O}$ is open. I.e., if $f(\mathcal{O})$ is open.
The standard open sets in $\mathbb{R}^2$ are of the form $B_{r}((a,b)) = \{(x-a)^2 + (y-b)^2<r^2 \}$. I.e., a ball of radius r about the point $(a,b)$. These form a basis for the topology on $\mathbb{R}^2$, so it suffices to check that $f(B_r(a,b))$ is open for any choice of $r$, $a$ and $b$.
Now, the map $f$ takes in a point $(x,y)$ and outputs $x^2+y^2$. That is, the length from the origin (modulus) squared. So, $f$ will take in all the points of $B_r(a,b)$ and output all the possible lengths squared. So, we need to find the range of lengths. This is determined by the point in $B_r(a,b)$ closest to the origin and the point in $B_r(a,b)$ farthest from the origin.
These points are easy to find. Take a line passing through the origin and the point (a,b). This line will intersect the circle in two spots: $P_1$ and $P_2$. Let's say that $P_1$ and $P_2$ are distances $r_1$ and $r_2$ from the origin respectively. Without loss of generality, assume that $r_1<r_2$.
Now, I claim that $f(B_r(a,b)) = (r_1,r_2)$, which is indeed open. Why might that be?


text:
Q: Best way to change React state at  level based on sub-components I have a React app that has a top-level <App /> component (built starting from create-react-app). My top level component looks something like this:

<Switch>
  {routes.map((route, index) => <Route key={index} {...route} />)}
  <Route component={NotFound} />
</Switch>

(routes is an array of { component:, to: } objects). Each component rendered by <Route> uses a sub-component called <Page> where I set a title and wrap some content:
<Page title="About Us">

Content here

</Page>

Sometimes a page might use a different theme which I want to apply to the  when that page is being viewed:
<Page title="About Us" theme="alt">

What I'm looking to do is change appTitle and theme state in <App /> when each component is rendered. What is the best way to do this? Using one of React's life-cycle hooks? Some other method to change the "top-level" state? How can I pass an action down to these components through the react-router <Route> component if so?

A: You can pass a function to each component, and call that function when each child gets mounted, with componentDidMount lifecycle method.
<Switch>
  {routes.map((route, index) => {
    const Comp = route.component;
    return <Route
      key={index}
      { ...route}
      // overwrite the component prop with another component
      component={
        (routeProps) => (
          <Comp
            {...routeProps}
            childHasMounted={() => this.setState({ name: route.name })}
          />
        )
      }
    />
  })}
  <Route component={NotFound} />
</Switch>

// child.js
class Child extends React.Component {
  componentDidMount() {
    this.props.childHasMounted();
  }
}

A: Flip the structure on its head. Have every "page" component control their own layout.
Make a layout higher order component (function that takes a component class and returns a component class):
function LayoutHOC({ title, theme, component: ContentComponent }) {
    return class LayoutWrapper extends React.Component {
        render() {
            return (

                    <Page title={title} theme={them}>
                        <ContentComponent {...this.props} />
                    </Page>

            )
        }
    }
}

Make the folder structure domain specific, as in pages/about/MyAboutPage.jsx to hold the main component content.
Then make pages/about/index.js and export the content component wrapped in the layout higher order component.
index.js:
import MyAboutPage from './MyAboutPage';
export default LayoutHOC({ title: 'my title', theme: 'alt', component: MyAboutPage })

Then in your routes you can import About from './pages/about' (since it uses index.js you don't have to worry about nested folder structure).
The downside is you have to create an index.js for each domain/route. The upside is your content component doesn't know about its layout, and every page/route can controll its own header/footer however you want.
This pattern is stolen from this React boilerplate project


text:
Q: It's true that $ |\log^2(z)| \leqslant |\log(R)|^2 + |i \arg(z)|^2 $ where $z \in \mathbb{C}$ In some residue integral, when one have to prove that an integral
vanish at infinity, I've found in some textbooks the inequality:
$$ |\log^2(z)| \leqslant |\log(R)|^2 + |i\ \arg(z)|^2 $$
Where $z= Re^{i \arg(z)} \in \mathbb{C}$.
How can I prove this ? And furthermore, there is a more general procedure to find inequality involving $| \log^p(z)|$ ? Thanks

A:
The last one is a well known inequalitie, i think it's the triangle inequalitie


text:
Q: Exchange Mailbox Sharing Issues Exchange 2010 running on Win 2012 Standard (VM). Users using Outlook 2010
Shared mailbox between 3 users for one mail address. One user is receiving up-to date data, other users dont have the same data/emails.
The same user has a full view of everything that came in from Friday->Monday, Around 20 new emails, the other users have about 6 "NEW" emails in the same mailbox.
This is a secondary mailbox for all users.
Have so far. Manually updated from outlook, recreated profiles, checked view settings and reset using the outlook cmd switch, restarted information store and made sure mailboxes are mounted correctly.
Anything else anyone can think off?

A: We've found that having the user who only sees some of the messages add and remove a search from the Outlook search box seems to fix the problem.


text:
Q: Pragmatically enable GPS from AlertBox I built an Android app using C# on Xamarin Platform Visual Studio.
I am trying to build an AlertDialog that allows the user to Enable GPS directly from the app. Or even send him to the location settings. So far i have this code that checks if GPS in enabled or not. All i need is how to make an OnClick button on AlertDialog that even enables GPS from app or opens settings.
 LocationManager lm = (LocationManager)GetSystemService(Context.LocationService);
        bool gps_enabled = false;
        bool network_enabled = false;
        gps_enabled = lm.IsProviderEnabled(LocationManager.GpsProvider);
        network_enabled = lm.IsProviderEnabled(LocationManager.NetworkProvider);
if (!gps_enabled && !network_enabled)
        {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.SetTitle("Warning");
            dialog.SetMessage("Your phone location is not enabled" + "\n" + "Please enable your location and run SpeedReport again");
            dialog.SetPositiveButton("Enable", (object sender1, DialogClickEventArgs e1) => {/*i guess i need to enter some code here*/});

A: Have a look at this one:
https://developer.xamarin.com/api/field/Android.Provider.Settings.ActionLocationSourceSettings/
You have to write something like:
var locationIntent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
locationIntent.SetFlags(ActivityFlags.NewTask);
context.StartActivity(locationIntent);


text:
Q: Create a new node.js process per page I am pretty sure this question is asked a lot but cannot find the right search terms to find the answer.
Let's say I have a site, example.com and I have two pages, example.com/game1.html and example.com/game2.html
I would like to host two node.js processes to listen to requests to these pages (where both games require different code). I also want to be able to upgrade these processes without shutting a main process down.
I suspect it has something to do with creating a "main" node process and then redirecting these page calls to the right process. Is there a good module for this?

A: The usual way to direct two URLs such as:
http://example.com/game1.html
http://example.com/game2.html

to separate servers is to use a proxy such as NGINX.  The proxy runs on example.com and port 80 so it gets all the requests.  Your other servers run locally on separate ports (no need for them to be directly reachable by the public).  You configure NGINX so that when it sees http://example.com/game1.html the request is forwarded to your first server on whatever port it is running on.  When it sees http://example.com/game2.html the request is forwarded to your second server on whatever other port it is running on.
After installing NGINX, all of this logic can be configured through its configuration file.


text:
Q: How to force file download in the browser, nginx server I currently have 2 image locations and they may the formats (jpg,jpeg,png,gif)
i.domain.com/simage.jpg thumbnail
i.domain.com/image.jpg high quality
i.domain.com/o/image.jpg full resolution

Does anyone know how I can force image files in /o/ to download rather than render in the web browser?
Here's my conf file: http://pastebin.com/dP8kZMzx
#setup subdomain i.domain.com
server {
    server_name i.domain.com;
    access_log /var/log/nginx/i..com.access.log;
    error_log /var/log/nginx/i.domain.com.error.log;

    root /var/www/domain.com/test1/images;
    index index.php index.html index.htm;

    #error_page 403 = /notfound.jpg;
    #error_page 500 = /notfound.jpg;

    location / {
        #change this to a 404 img file .jpg
        try_files $uri $uri/ /notfound.jpg;

        rewrite  "/s([A-Za-z0-9.]+)?" /small/$1 break;
        rewrite  "/o/([A-Za-z0-9.]+)?" /orig/$1 break;
        rewrite  "/([A-Za-z0-9.]+)?" /medium/$1 break;
    }

}

A: Below config works for me.
server {
    ...
    # Django media
    location /media  {
        alias /var/www/media;
        types { application/octet-stream .pdf; }
        default_type application/octet-stream;
    }
    ...
}

But the pdf file needs to ends with lowercase pdf for download to work. I still don't know the syntax to add both .pdf and .PDF to above config file. Any suggestion?
The answer is based on info from http://210mike.com/force-file-download-nginx-apache/

A: You just need to return HTTP header Content-disposition:
location ~* /orig/(.+\.jpg)$ {
    add_header Content-disposition "attachment; filename=$1";
}

A: I have been trying to get this functionality into my own nginx server.
I have a folder on server that I would like to have open for anyone who knows the path.
To do that I added a /file/ location into my nginx config file.
server {
   listen 80;
   server_name example.com;

   location /file/ {
       alias /var/openStuff/file/;
       add_header Content-disposition "attachment";
   }
}

Any request to example.com/file/x will go to /var/openStuff/file and look for x and force the browser to download the file
This will also work if the path is /file/stuff/things.txt and will serve it from /var/openStuff/file/stuff/things.txt

A: A little mixing did the job for me. Forced to download a CRX file instead of installing or displaying.
## Download crx
location ~* \.crx$ {
    add_header Content-disposition "attachment; filename=$1";
}


text:
Q: React Native - using hooks with render() I'm trying to use a font (google fonts) in a react native app. I'm having a problem with the hook:
const [fontsLoaded ,setFontsLoaded] = useState(false);

I believe the problem is around the render() prop. Can anyone advise me on where I should add the above code to get this woking?
My Code is:
import React, { Component, useState } from 'react';
import * as Font from 'expo-font';
import { StyleSheet, Text, View } from 'react-native';
import { AppLoading } from 'expo';

 const getFonts = () => Font.loadAsync({
    'lobster': require('./assets/fonts/Lobster-Regular.ttf')
    });

export default class App extends Component {
  render() {
    const [fontsLoaded ,setFontsLoaded] = useState(false);
    const gradientHeight=500;
    const gradientBackground  = '#12C1E5';
    const data = Array.from({ length: gradientHeight });

    if(fontsLoaded){
      return (
        <View style={styles.container}>
          <View style={styles.centering}>
            <Text style={styles.titleText}>Test Title</Text>
          </View>
          <View style={{flex:1}}>
            {data.map((_, i) => (
              <View
                key={i}
                style={{
                  position: 'absolute',
                  backgroundColor: gradientBackground,
                  height: 1,
                  bottom: (gradientHeight - i),
                  right: 0,
                  left: 0,
                  zIndex: 2,
                  opacity: (1 / gradientHeight) * (i + 2)
                }}
              >
              </View>
            ))}
          </View>
        </View>
      );
    } else {
      return (
        <AppLoading
          startAsync={getFonts}
          onFinish={() => setFontsLoaded(true)}
        />
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0e99b5',
    },
  centering: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  titleText: {
    color: 'orange',
    fontSize: 40,
  }
});

The error I'm getting is:
Error: Invalid hook call.

I'm just trying to use the custom font and check that the font is loaded before rendering to the screen.

A: You can't use hooks inside a class component. Hooks are introduced by React to be used in functional components. So you have two options either

*

*use setState in your current class component OR

*convert your class component to functional component.

I'll suggest that you go with functional component as you are not using any life cycles of class component.
If you go with the first approach you can change your code as below:-
export default class App extends Component {
  state = {
    fontsLoaded: false,
  };

  updateFontsLoadedState = () => {
    this.setState({ fontsLoaded: true });
  }

  render() {
    const { fontsLoaded } = this.state;
    const gradientHeight=500;
    const gradientBackground  = '#12C1E5';
    const data = Array.from({ length: gradientHeight });

    if(fontsLoaded){
      return (
        <View style={styles.container}>
          <View style={styles.centering}>
            <Text style={styles.titleText}>Test Title</Text>
          </View>
          <View style={{flex:1}}>
            {data.map((_, i) => (
              <View
                key={i}
                style={{
                  position: 'absolute',
                  backgroundColor: gradientBackground,
                  height: 1,
                  bottom: (gradientHeight - i),
                  right: 0,
                  left: 0,
                  zIndex: 2,
                  opacity: (1 / gradientHeight) * (i + 2)
                }}
              >
              </View>
            ))}
          </View>
        </View>
      );
    } else {
      return (
        <AppLoading
          startAsync={getFonts}
          onFinish={this.updateFontsLoadedState}
        />
      );
    }
  }
}

If you want to use better approach, use hooks and convert this to functional component then you can do that as below:-
export default function App(props) {
    const [fontsLoaded ,setFontsLoaded] = useState(false);
    const gradientHeight=500;
    const gradientBackground  = '#12C1E5';
    const data = Array.from({ length: gradientHeight });

    if(fontsLoaded){
      return (
        <View style={styles.container}>
          <View style={styles.centering}>
            <Text style={styles.titleText}>Test Title</Text>
          </View>
          <View style={{flex:1}}>
            {data.map((_, i) => (
              <View
                key={i}
                style={{
                  position: 'absolute',
                  backgroundColor: gradientBackground,
                  height: 1,
                  bottom: (gradientHeight - i),
                  right: 0,
                  left: 0,
                  zIndex: 2,
                  opacity: (1 / gradientHeight) * (i + 2)
                }}
              >
              </View>
            ))}
          </View>
        </View>
      );
    } else {
      return (
        <AppLoading
          startAsync={getFonts}
          onFinish={() => setFontsLoaded(true)}
        />
      );
    }
}


text:
Q: Capitalization variants of nameref Several packages that generate inline text (i.e. glossaries, cleverref) have commands to let the author choose capitalization. In particular, glossaries seems to be able to do parts of this automatically.
However, nameref (of the nameref package) is unable to change the capitalization of the referenced text. As nameref is often used to reference section titles which are capitalized text starts looking wrong, when the capitalization is kept up mid sentence.
While there is one answer on here that solves this problem, it relies on inserting a macro infront of every letter for which the capitalization should be adjusted.

*

*Given that commands for modifying capitalization are available (\MakeUppercase, \MakeLowercase, \makefirstuc), why is it so hard to provide nameref commands that return the name in all lowercase or all but the first letter lowercase?

*Would it be possible to protect parts of a heading from capitalization changes? (i.e. \MakeUppercase{so\MakeLowercase{WhAT}} returns SOwhat (see Texbook page 42 for details))
i.e:
\section{This is about \MakeUppercase{PCI}e on Mainboards}

\nameref    -> This is about PCIe on Mainboards    normal
\lcnameref  -> this is about PCIe on mainboards    LowerCase
\ucnameref  -> This Is About PCIe On Mainboards    UpperCase
\fucnameref -> This is about PCIe on mainboards    FirstUpperCase

I tried extending nameref by copying the definition of \nameref and wrapping all occurences of \@thirdoffive{#1} in \MakeLowercase however the result was quite unexpected: for the input This Is a Section I got 11This Is a Sectionsection.1.
I actually had to copy the .sty file, as using \makeatletter/\makeatother in the preamble for the new definition resulted in warnings about undefined macros.

A: hyperref/nameref makes extensive use of the \AtBeginDocument-hook.
In case you wish to redefine some internals of the nameref-package, you need to use the \AtBeginDocument-hook, too.
Otherwise your changes done in the preamble will be overridden when hyperref/nameref's \AtBeginDocument-thingies are carried out.
The example below delivers three macros \fucnameref, \ucnameref and \lcnameref.
For case-changing the macros from Nicola Talbot's mfirstuc-package are used.
Thus within the arguments of sectioning-commands you can use the tricks explained in the manual of that package.
I highly recommend reading that manual as it also explains the many pitfalls with that package.
With that package you can use a preceding empty group {} for preventing evaluation of commands. E.g., you can use {}\MakeUppercase and {}\MakeLowercase for ensuring uppercased-letters/lowercased-letters.
\documentclass{article}
\usepackage{hyperref}[2018/02/06 v6.86b Hypertext links for LaTeX]
\usepackage{mfirstuc}[2017/11/14 v2.06 (NLCT)]

\makeatletter
\AtBeginDocument{%
  \newcommand\My@Macro[1]{#1}%
  \newcommand\My@Thirdoffive[5]{\My@Macro{#3}}%
  \renewcommand*\@namerefstar[1]{%
    \HyRef@StarSetRef{#1}\My@Thirdoffive
  }%
  \renewcommand*\T@nameref[1]{%
    \begingroup
    \let\label\@gobble
    \NR@setref{#1}\My@Thirdoffive{#1}%
    \endgroup
  }%
  \DeclareRobustCommand\fucnameref{%
    \@ifstar\fucnameref@star\fucnameref@nostar
  }%
  \newcommand\callemakefirstuc[1]{%
    \MakeLowercase{\emakefirstuc{#1}}%
  }%
  \newcommand\fucnameref@star[1]{%
    \begingroup
    \let\My@Macro=\callemakefirstuc
    \nameref*{#1}%
    \endgroup
  }%
  \newcommand\fucnameref@nostar[1]{%
    \begingroup
    \let\My@Macro=\callemakefirstuc
    \nameref{#1}%
    \endgroup
  }%
  \DeclareRobustCommand\ucnameref{%
    \@ifstar\ucnameref@star\ucnameref@nostar
  }%
  \newcommand\ucnameref@star[1]{%
    \begingroup
    \MFUhyphentrue
    \let\My@Macro=\ecapitalisefmtwords
    \nameref*{#1}%
    \endgroup
  }%
  \newcommand\ucnameref@nostar[1]{%
    \begingroup
    \MFUhyphentrue
    \let\My@Macro=\ecapitalisefmtwords
    \nameref{#1}%
    \endgroup
  }%
  \DeclareRobustCommand\lcnameref{%
    \@ifstar\lcnameref@star\lcnameref@nostar
  }%
  \newcommand\lcnameref@star[1]{%
    \begingroup
    \let\My@Macro=\MakeLowercase
    \nameref*{#1}%
    \endgroup
  }%
  \newcommand\lcnameref@nostar[1]{%
    \begingroup
    \let\My@Macro=\MakeLowercase
    \nameref{#1}%
    \endgroup
  }%
}%
\makeatother

\newcommand\SomeSectionTitle{%
  Some very Nice section Title with
  {}\texorpdfstring{{}\MakeUppercase{pci}}{PCI} and
  {}\texorpdfstring{{}\MakeLowercase{PCI}}{{}pci}%
}

\begin{document}

\parindent=0ex
\parskip=\baselineskip

\begin{verbatim}
\newcommand\SomeSectionTitle{%
  Some very Nice section Title with
  {}\texorpdfstring{{}\MakeUppercase{pci}}{PCI} and
  {}\texorpdfstring{{}\MakeLowercase{PCI}}{{}pci}%
}

\section{\SomeSectionTitle}\label{NiceLabel}
\end{verbatim}

yields:

\section{\SomeSectionTitle}\label{NiceLabel}

\verb|\nameref{NiceLabel}| yields:\\ \nameref{NiceLabel}

\verb|\fucnameref{NiceLabel}| yields:\\ \fucnameref{NiceLabel}

\verb|\ucnameref{NiceLabel}| yields:\\ \ucnameref{NiceLabel}

\verb|\lcnameref{NiceLabel}| yields:\\ \lcnameref{NiceLabel}

\verb|\nameref*{NiceLabel}| yields:\\ \nameref*{NiceLabel}

\verb|\fucnameref*{NiceLabel}| yields:\\ \fucnameref*{NiceLabel}

\verb|\ucnameref*{NiceLabel}| yields:\\ \ucnameref*{NiceLabel}

\verb|\lcnameref*{NiceLabel}| yields:\\ \lcnameref*{NiceLabel}

\end{document}

Edit on Friday, September 7, 2018:
Please don't try to nest calls to \fucnameref or  to \ucnameref or to \lcnameref—i.e., don't do try things like
\section{Some Nice Section}\label{NiceSection}
...
\section{annotations to \lcnameref*{NiceSection}}\label{Annotations}
...
\fucnameref{Annotations}


text:
Q: Uniqueness of Ruby Instances If I create two String instances with the same content separately they are identical. This is not the case with custom classes by default (see example below).
If I have my own class (Test below) and I have a variable (@v below) which is unique, ie. two Test instances with the same @v should be treated as identical, then how would I go about telling Ruby this is the case?
Consider this example:
class Test
  def initialize(v)
    @v = v
  end
end

a = {Test.new('a') => 1, Test.new('b') => 2}

a.delete(Test.new('a'))

p a
# # Desired output:
# => {#<Test:0x100124ef8 @v="b">=>2}

A: You need to define an == method that defines what equality means for your class. In this case, you would want:
class Test
  def initialize(v)
    @v = v
  end
  def ==(other)
    @v == other.instance_variable_get(:@v)
  end
end

A: You are using objects of class Test as keys for the hash. In order for that to function properly (and consequently a.delete), you need to define two methods inside Test: Test#hash and Test#eql?
From: http://ruby-doc.org/core/classes/Hash.html

Hash uses key.eql? to test keys for
  equality. If you need to use instances
  of your own classes as keys in a Hash,
  it is recommended that you define both
  the eql? and hash methods. The hash
  method must have the property that
  a.eql?(b) implies a.hash == b.hash.

A: I found a different way to tackle this, by keeping track of all the instances of Test internally I can return the premade instance rather than making a new one and telling ruby they're equivalent:
class Test
  def self.new(v)
    begin
      return @@instances[v] if @@instances[v]
    rescue
    end

    new_test = self.allocate
    new_test.instance_variable_set(:@v,v)
    (@@instances ||= {})[v] = new_test
  end
end

Now Test.new('a') == Test.new('a') and Test.new('a') === Test.new('a') :)

A: Most of the time, an object you need to be comparable and/or hashable is composed of member variables which are either primitives (integers, strings, etc) or are themselves comparable/hashable.  In those cases, this module:
module Hashable

  include Comparable

  def ==(other)
    other.is_a?(self.class) && other.send(:parts) == parts
  end
  alias_method :eql?, :==

  def hash
    parts.hash
  end

end

can simply be included in your class to take care of all of the busywork.  All you have to do is define a "parts" method that returns all of the values that comprise the object's state:
class Foo

  include Hashable

  def initialize(a, b)
    @a = a
    @b = b
  end

  private

  def parts
    [@a, @b]
  end

end

Objects built this way are comparable (they have <, <=, ==, >=, >, != and equ?) and they can be hash keys.


text:
Q: How to null check MySQL JSON column property? I'm working with MySQL 8.0.21. I need to write a query that works with the JSON column type.
Some of the data inside the JSON documents have null values and I want to filter out these null values.
Examples of possible rows, most properties in the JSON document have been removed for simplicity:
jsonColumn
'{"value":96.0}'
'{"value":null}' -- This is the row I am trying to filter out
NULL

Here is what I've tried:
-- Removed columns where jsonColumn was NULL but, NOT columns where jsonColumn->'$.value' was null.
SELECT *
FROM

WHERE jsonColumn->'$.value' IS NOT NULL;

-- Note the unquote syntax, ->>. The code above uses ->.
-- Produced the same result as the code above.
SELECT *
FROM

WHERE jsonColumn->>'$.value' IS NOT NULL;

-- Produced same result as the two above. Not surprised because -> is an alias of JSON_EXTRACT
SELECT *
FROM

WHERE JSON_EXTRACT(jsonColumn, '$.value') IS NOT NULL;

-- Produced same result as the three above. Not surprised because ->> is an alias of JSON_EXTRACT
SELECT *
FROM

WHERE JSON_UNQUOTE(JSON_EXTRACT(jsonColumn, '$.value')) IS NOT NULL;

-- Didn't really expect this to work. It didn't work. For some reason it filters out all records from the select.
SELECT *
FROM

WHERE jsonColumn->'$.value' != NULL;

-- Unquote syntax again. Produced the same result as the code above.
SELECT *
FROM

WHERE jsonColumn->>'$.value' != NULL;

-- Didn't expect this to work. Filters out all records from the select.
SELECT *
FROM

WHERE JSON_EXTRACT(jsonColumn, '$.value') != NULL;

-- Didn't expect this to work. Filters out all records from the select.
SELECT *
FROM

WHERE JSON_UNQUOTE(JSON_EXTRACT(jsonColumn, '$.value')) != NULL;

-- I also tried adding a boolean value to one of the JSON documents, '{"test":true}'. These queries did not select the record with this JSON document.
SELECT *
FROM

WHERE jsonColumn->'$.test' IS TRUE;
SELECT *
FROM

WHERE jsonColumn->>'$.test' IS TRUE;

A few interesting things I noticed...
Comparing other values worked. For example...
-- This query seems to work fine. It filters out all records except those where jsonColumn.value is 96.
SELECT *
FROM

WHERE jsonColumn->'$.value' = 96;

Another interesting thing I noticed, which was mentioned in the comments for some of the examples above, was some odd behaviour for the null checks.
If jsonColumn was null, the null checks would filter out the record even know I was accessing jsonColumn->'$.value'.
Not sure if this is clear, so let me elaborate a little...
-- WHERE jsonColumn->>'$.value' IS NOT NULL
jsonColumn
'{"value":96.0}'
'{"value":null}' -- This is the row I am trying to filter out. It does NOT get filtered out.
NULL -- This row does get filtered out.

According this post, using ->> and JSON_UNQUOTE & JSON_EXTRACT with IS NOT NULL comparisons should have worked. I assume it worked back then.
Honestly feeling like this may be a bug with the IS statement and JSON column type. There is already weird behaviour where it's comparing against the JSON document rather than the JSON document's values.
Regardless, is there any way to accomplish this? Or are the ways I've been trying confirmed to be the correct way and this is just a bug?

A: Following Barmar's comment...

Apparently this changed sometime before 8.0.13. forums.mysql.com/read.php?176,670072,670072

A workaround in the forum post seems to use JSON_TYPE. Looks like a terrible workaround tbh.
SET @doc = JSON_OBJECT('a', NULL);
SELECT JSON_UNQUOTE(IF(JSON_TYPE(JSON_EXTRACT(@doc,'$.a')) = 'NULL', NULL, JSON_EXTRACT(@doc,'$.a'))) as C1,
JSON_UNQUOTE(JSON_EXTRACT(@doc,'$.b')) as C2;

The forum post says (regarding code posted before the workaround)...

C2 is effectively set as NULL, but C1 is returned as the 4 char 'null' string.

So I started messing around with string comparisons...
// This filtered out NULL jsonColumn but, NOT NULL jsonColumn->'$.value'
SELECT *
FROM

WHERE jsonColumn->'$.value' != 'null';

jsonColumn
'{"value":96.0}'
'{"value":"null"}' -- Not originally apart of my dataset but, this does get filtered out. Which is very interesting...
'{"value":null}' -- This does NOT get filtered out.
NULL -- This row does get filtered out.

// This filtered out both NULL jsonColumn AND NULL jsonColumn->'$.value'
SELECT *
FROM

WHERE jsonColumn->>'$.value' != 'null';

jsonColumn
'{"value":96.0}'
'{"value":"null"}' -- Not originally apart of my dataset but, this does get filtered out.
'{"value":null}' -- This does get filtered out.
NULL -- This row does get filtered out.

A: A more easier approach is using LIKE as the operator
SELECT *
FROM
WHERE jsonColumn->'$.value' LIKE LOWER('NULL');
and LOWER is used to validate if it is null or NULL because in my testing it did differ