text:
Q: Arranging one field in array I have been having trouble trying to arrange the minutes from highest to lowest after the original table has been displayed in the console. The program takes a comma-delimited file and prints it on the console but I need to rearrange it after loading the file.
This is the original table
ID                       Last Name                First Name               Phone Number             Minutes
1 Doe Jane 905-222-2222 888
2 Doe John 905-555-5555 1020
3 Morrison Jim 905-777-777 700
4 Mitchell Joni 416-333-3333 112
5  Barnett Courtney 905-666-6666 455
The minutes should have been displayed like this, just after the original table
ID                       Last Name                First Name               Phone Number             Minutes
1 Doe Jane 905-222-2222 1020
2 Doe John 905-555-5555 888
3 Morrison Jim 905-777-777 700
4 Mitchell Joni 416-333-3333 455
5  Barnett Courtney 905-666-6666 112
this is my code
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <array>

using namespace std;

int main()
{

    int const NUM_RECORDS = 6;
    int const NUM_FIELDS = 5;

    ifstream inputFile;
    inputFile.open("L02_input.csv");

    if (inputFile.is_open())
    {
        string line = "";
        int foundPos = 0, startPos = 0, y = 0;
        array<string, NUM_FIELDS> record;

        for (int x = 0; x < NUM_RECORDS; x++)
        {

            getline(inputFile, line);

            foundPos = 0, startPos = 0, y = 0;
            while ((foundPos = line.find_first_of(',', startPos)) != -1) {
                record[y] = (line.substr(startPos, foundPos - startPos));
                y++;
                startPos = foundPos + 1;
            }
            record[y] = (line.substr(startPos, foundPos - startPos));
            y++;

            for (int z = 0; z < y; z++)
            {
                cout << record[z];
                if (z < y - 1) {

                    for (int a = 0; a < 25 - record[z].length(); a++)
                        cout << ' ';
                }
            }

            if (x == 0)
            {
                cout << '\n';
                for (int a = 0; a < 110; a++)
                    cout << '-';
            }
            cout << '\n';
            int n = sizeof(record) / sizeof(record[0]);
            sort(record[4], record[4] + n, greater<int>());
            for (int i = 0; i < n; ++i)
                cout << record[i] << " ";

        }
        inputFile.close();

    }

    cout << "\n\n\n<PRESS ENTER>";
    cin.clear();
    cin.ignore(32767, '\n');

    return 0;
}

this is what I tried for the minutes first, but it shows nothing on screen
int n = sizeof(record) / sizeof(record[0]);
            sort(record[4], record[4] + n, greater<int>());
            for (int i = 0; i < n; ++i)
                cout << record[i] << " ";


text:
Q: Mixed-effect output of lmer showing more slopes than anticipated My data consists of a numerical, continuous variable and 4 independent variables, plus two sources of random variation. I am running mixed-effects model in R with the lmer() function.
head(MM_Table2)
      Name                    Condition Channel EpochCountStd EpochCountDeviant ErpMinTime ErpMinVoltage ErpMinAv Frequency
380   AY11042016B1-Deci.EEG      HFMM     AF3           423               103        203          -1.2     -1.1      High
388 AvdP23052016B1-Deci.EEG      HFMM     AF3           410               101        144          -3.7     -3.2      High
397   EW20042016B1-Deci.EEG      HFMM     AF3           457               118        123          -2.6     -2.3      High
413  IG160312016B1-Deci.EEG      HFMM     AF3           435               105        214          -2.2     -1.6      High
422  IJB18042016B1-Deci.EEG      HFMM     AF3           408               110        121          -1.3     -1.1      High
439   MC31032016B1-Deci.EEG      HFMM     AF3           438               101        116          -4.0     -3.3      High
   Hemisphere     Region      Lexicality Subject    Block    Hemisphere.Centered Region.Centered Lexicality.Centered
380       Left AnterioFrontal       Word Subject08  -2.5                  -1              -2                   1
388       Left AnterioFrontal       Word Subject14  -2.5                  -1              -2                   1
397       Left AnterioFrontal       Word Subject12  -2.5                  -1              -2                   1
413       Left AnterioFrontal       Word Subject02  -2.5                  -1              -2                   1
422       Left AnterioFrontal       Word Subject10  -2.5                  -1              -2                   1
439       Left AnterioFrontal       Word Subject05  -2.5                  -1              -2                   1
          Frequency.Centered
380                  1
388                  1
397                  1
413                  1
422                  1
439                  1

I learned that it's best to recode your fixed effects with numbers that sum to zero. For example, one of my fixed effects is called Lexicality, and has two levels: Word and PseudoWord. I created a new column in my data.frame called Lexicality.Centered, where I renamed the variable. Word is 1 and PseudoWord is -1. I did the same with all binary fixed effects.
I also have a fixed effect with more than two levels. I created a new column where I recoded the names of the levels of these factor. One such factor, Hemisphere, has 3 levels: Right, Mid and left. Since I want to compare Left vs Right, I coded Left as -1, Right as 1 and Mid as 0. I thought this would result in a comparison of Left vs Right, ignoring the Mid level.
However, the summary of the model gives me two slopes for Hemisphere. This suggests the 0 level is also having a slope estimated:
Fixed effects:
                                         Estimate Std. Error t value
(Intercept)                              -2.29676    0.34969  -6.568
Lexicality.Centered1                      0.27649    0.20105   1.375
Frequency.Centered1                      -0.02772    0.03777  -0.734
Hemisphere.Centered1                      0.04911    0.04344   1.130
Hemisphere.Centered2                     -0.06459    0.05045  -1.280
Region.Centered1                          0.01830    0.03705   0.494
Lexicality.Centered1:Frequency.Centered1  0.14925    0.03773   3.956

Am I interpreting this correctly? Is the Mid level, coded as 0, also being given a slope? If so, then what contrast should I use to compare left vs right, ignoring the mid level?
PS: I am aware I could specify the contrasts in the model, without having to create extra columns. I wish to do so however, because it allows me to keep track of the contrasts I am doing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the meaning of "just as well" in this context?
The family cemetery sat at the bottom of the hill from the mansion.
  Dan thought it was kind of stupid they'd hired a hearse to carry Grace
  a hundred yards down the driveway. They could've put wheels on the
  coffin like they have on suitcases and that would've worked just as
  well.

Does this "just as well" have the same meaning of "just as well" in "It's just as well we'd prepared everything beforehand."

A: The phrase in the first sentence equates to "equally well".
The phrase in the second sentence equates to "it's a good thing."
So, no, they do not have the same meaning.


text:
Q: Improving query time for auto complete box with millions of record I have a very basic requirement. I have a table that store city id (primary key) and city name (nvarchar value). The remaining information is stored in a separate table. In my UI, I have an auto complete box, that lists all cities when user start typing. After selection, application gets the data for that particular city to fill up.
The main table with just two columns for city id and name, is indexed on name. I am currently running following query to get the list of names.
Select cityname from citylist where cityname like '%' + citynamevar + '%'

This query is supposed to give me the list of all names that contain the value typed by user. It currently takes about 2 minutes to run on approx. 600k records.
I have also added a way to display 10 records in the beginning, while the query executes. But even then, it is not helping the case as remaining data loads way too slow.
I am trying to find ways I can improve this query time. Till now I have found about full text search, which I believe should help. I was just wondering if there is any other method I can try or any trick to get the query to respond fast enough.
I am currently using SQL server 2012. I tried running the query directly outside the application, using ssms too. And even then it took the same amount of time. Indexing sped up the query by about 20% but not enough to be meaningful.
Edit:
No idea why I am not able to comment anymore on this post. Anyway, it is a test build to see how much impact auto complete boxes will have. It is running on my personal laptop (core i5, basic mobile GPU). I am using SQL server 2012, .net 4.5 with wpf.
I can ask user to reduce the search space by entering country name. But this is supposed to be a generic solution. In some cases, we don't have any way to reduce the search space. And it has to be a "contains" search, instead of "starts with". Which might be the reason why indexing hardly had any impact.
The table is just 600k records, out of which we need to display 1000-10k. The query is executed only once when user type the third character, after which remaining characters are sorted within the application from that 1000-10k records. I can reduce the impact by increasing the character count to 5, but then user will be unable to see any suggestions for most city names.

A: Have you thought about restricting the search in the UI?  Don't start the autocomplete query until after they've typed 3 or 4 characters. Then instead of looking for 6000 A*, the first jump would be a fraction of that number still.
Also, @Jonathan Fite 's comment about removing the leading % is also a good way to reduce time.  Unless, your users start looking for ew Yor, or shington...

A: A leading % kills use of an index
Most users want autocomplete based on first characters anyway
Most users don't care about more than 1000
Have an index on city
select top (1000) city
from citylist
where cityname like citynamevar + '%'
order by city;

If you can have them select a state from pull down
select top (1000) city
from citylist
where cityname like citynamevar + '%'
and state = statenamevar
order by city;

If you are in desktop app then download the city to a collection and search the collection.  You end up with a lot of round trips to the database and returning the same data multiple times
A trick I also use is wait 1/10 seconds before sending off the request so they can slam in multiple 4+ characters.
If they want more than 1000 then give them a button or use a key (like tab) to mean get more

A: Full text search fits more into your scenario. A full text search uses inverted index - think of it as an index structure that stores words or number mapping to its location in database.
There are good amount of changes in sql server 2012 for full text search.
Check Full-Text Search (SQL Server)

A LIKE query against millions of rows of text data can take minutes to return; whereas a full-text query can take only seconds or less against the same data, depending on the number of rows that are returned.


text:
Q: In WordPress why does my site look like like this when I import a demo? I'm a beginner in WordPress. I installed the OceanWP theme then imported a demo for it.
This is what the website is supposed to look like:

And this is what it looks like after I import the demo and open it:

A: Try this thing once:

*

*Go to Wp-admin

*Go to Settings > Permalinks

*Hit "Save changes" at the bottom.

This will do a flush and will make the links work.
If this doesn't work for you let me know.


text:
Q: Double Foreign key in postgresql I am trying to use a double primary key as a foreign key.
Create table AAA (
   AAA_id int primary key
);

create table BBB (
   AAA_id int,
   BBB_name character varying(20),
   primary key (AAA_id, BBB_name)
);

create table CCC (
    AAA_id,
    BBB_name,
    DDD_id,

    ... ???
);

table AAA is an object
table BBB is many to one with AAA, and holds aliases of AAA
I am trying to create a pivot table, CCC which holds a many to one between DDD and BBB.
I guess I want something like
create table CCC (
    AAA_id,
    BBB_name,
    DDD_id,
    foreign key (AAA_id, BBB_name) references BBB(AAA_id, BBB_name) on update cascade
);

where both AAA_id and BBB_name are foreign keys, but they are also always referring to the same row in BBB.
but of course that's not valid. what is the best way to produce this type of behavior in postgreSQL?

A: Create temp table AAA (
   AAA_id int primary key
);

create temp table BBB (
   AAA_id int not null references AAA (AAA_id),
   BBB_name character varying(20) not null,
   primary key (AAA_id, BBB_name)
);

create temp table CCC (
    AAA_id int not null,
    BBB_name character varying(20) not null,
    DDD_id integer not null,
    -- Guessing at the primary key.
    primary key (AAA_id, BBB_name, DDD_id),
    foreign key (AAA_id, BBB_name) references BBB (AAA_id, BBB_name)
        on update cascade
);

Since {AAA_id, BBB_name} uniquely identify a row in BBB, the foreign key {AAA_id, BBB_name} in CCC will also reference one unique row in BBB.


text:
Q: Is there any way to make proportionate margins using pure CSS? Without using a preprocessor like Sass or Less, is there any way to make the margins of a series of elements proportional to their content?
So picture a horizontal navbar with 5 items. The text of each item is different, some are long and some are short, like this:
Menu |  Technology and Society | Laurem Ipsum | More Filler Text | Contact

I want to space these out proportionately so that the total width is 100% of the parent container and each item gets space and margin proportionate to the amount of text it contains without any of them having too much or too little margin. You can see how there's blank space at the end of the line-- that, for example, should not be there. Too much space is apportioned to the final element.
Is this possible with pure CSS?
If not, how can it be done with Sass or Less?
Note: I'm trying to see how this can be done dynamically, not by hard-specifying the width percents. I mean is there a way to use CSS so that it just does it automatically no matter how I change the text.

A: Only way is using display: table/table-cell values.

Menu

Technology and Society

Laurem Ipsum

More Filler Text

Contact

http://jsfiddle.net/og8m3g2m/


text:
Q: Coldspring 2.0 and Fusebox 5.5 (XML) My app uses Fusebox 5.5 and Coldspring 1.2.  I'm trying to migrate to Coldspring 2.0.  In Fusebox_lexicon/coldspring/initialize.cfm there is the following block of code:
// set ColdSpring in this fusebox instance's application space
    fb_appendLine('<cfset myFusebox.getApplication().getApplicationData().#fb_.coldspringfactory# = createObject("component", "coldspring.beans.DefaultXmlBeanFactory").init( defaultProperties="#fb_.defaultproperties#" )/>');
    fb_.i = 1;
    // load all bean definitions
    for ( fb_.i = 1; fb_.i lte arraylen( fb_.verbInfo.beans ); fb_.i = fb_.i + 1){
        fb_appendLine('<cfset myFusebox.getApplication().getApplicationData().#fb_.coldspringfactory#.loadBeansFromXmlFile( beanDefinitionFile="#fb_.verbInfo.beans[fb_.i]#" ) />');
    }

Now I know that coldspring.beans.DefaultXmlBeanFactory  has now moved to coldspring.beans.xml.XmlBeanFactory, but the problem is that loadBeansFromXmlFile no longer exists.
Is there an equivalent in version 2.0?  Should I be editing this file at all?
thanks

A:
I actually started looking at alternative frameworks, including Coldbox following this. I was initially concerned that CF10 / Coldspring 1.2 would not play nice (the code analyzer throws up some areas of concern), but now I think it may be OK.


text:
Q: How to make my app receive location intents like Google Maps If you opened a link like this  on your android phone Google maps will automatically open and show you the location on it's map.
I want to make my app receive intents if the user opened a link like this and also i want to get the lat,long from that link.
Is this Possible ?

A: Assuming the link is stored as String variable link
Now,
String[] split_link = link.split(Pattern.quote("@"));
String[] post_link = split_link[1].split(Pattern.quote(","));

double lattitude = Double.parseDouble(post_link[0]);
double longitude = Double.parseDouble(post_link[1]);

Try This!!


text:
Q: SQL SSRS Remove Blank Space after hiding a column I am creating a report that consists of a simple data dump tablix.
Here is what my tablix looks like.

I am giving the user an option on what to group by, using a parameter, with their option being None, Master Code, and Sub Code.
I am following this tutorial
https://www.sqlservercentral.com/articles/dynamic-grouping-in-ssrs-reports
So as you can see, all the way to the left, I have a column called Group Desc which tells the user what the data is being grouped by, if it is being grouped.
Except in there, the Group header is a row, while mine is a column.
I wrote the expression to hide the column, and it works, but it leaves a huge blank space where the column was.
So when selecting something to group by, it works perfectly. However, when selecting the option none, to indicate I don't want to group by anything, it hides that column like specified in the expression, but leaves a blank space where it was.

I need a way to hide the column and remove the blank space that it fills. Is that possible in SSRS?


text:
Q: Prime Faces IE7 Z-index problems I am not having any joy over at the Prime Faces forum on my question about IE7 and was hoping someone here might be able to help.
Basically two problems:

*

*IE7 Z-index problem of the modal popup showing on top of the site's logo. (The logo has an absolute position to make it sit on top of the design)

*The modal window does not open to the right size, it's smaller in IE8 and greater.

Problem here is that I don't have full control of the site. I basically am trying to make things work in the Developer Toolbar and then sending the changes back to the developers.
Here is a video to show the two points of issue as mentioned above.
http://screencast.com/t/aW1ecqIuNi
Many thanks


text:
Q: How to set a whitelist in web view with Android Management API I am using Chrome Managed Configurations to set a whitelist with this code in my policy:
{
    "packageName": "com.android.chrome",
    "managedConfiguration": {
        'URLBlacklist': ['*'],
        'URLWhitelist': ['chrome://*', 'google.com', 'stackoverflow.com'],
        'ForceGoogleSafeSearch': True,
        'NTPContentSuggestionsEnabled': False,
    }
}

Now, in the Chrome enterprise docs it says there is a way to apply the same settings to Android Web view with the com.android.browser:URLBlacklist restriction, but it does not explain where I would put this in my policy.
The following code does not work:
{
    "packageName": "com.android.chrome",
    "managedConfiguration": {
        'com.android.browser:URLBlacklist': ['reddit.com', 'youtube.com'],
        'com.android.browser:URLWhitelist': ['stackoverflow.com', 'google.com']
    }
}

It shows an error in chrome://policy on the phone.
com.android.browser is not even a real app.
Where do I need to use this com.android.browser:URLBlacklist to apply restrictions to all web views on the phone?

A: You have to set the blacklist/whitelist for each app individually.
For example:
{
    "packageName": "com.jetblue.JetBlueAndroid",
    "managedConfiguration": {
        'com.android.browser:URLBlacklist': ['*'],
        'com.android.browser:URLWhitelist': ['jetblue.com']
    }
}

This code blocks all domains within the JetBlue app besides for JetBlue.com
There are some things to be aware of:
1. Be careful not to block any domains the app needs to function (including login pages, etc.).
2. If an app uses a direct API to display content, not a web view, then these restrictions will not apply.


text:
Q: How to transfer large file between me and my friend?
Possible Duplicate:
Free way to share large files over the Internet?
Transfering large files over internet

Are there some utilities, which allow to transfer files from peer to peer at full channel speed, like torrent clients or download manages do?
I.e. I want to send big file to my friend for free.
The main feature is transferring with multiple channels simultaneosly.

A: For one-time use, the simplest solution to get working is the file-transfer feature of a chat program.  Let it run overnight.

A: Multiple channel transfer only works when you are transferring either to or from multiple peers. For example, in the case of a fully seeded Torrent, you're downloading from sometimes hundreds of different sources, each one giving only relatively small amount of data and using a relatively low amount of bandwidth. All those small bits coming together into your computer at once results in a very high speed download only at your end.
If you're transferring a file between yourself and a friend, you're probably only looking at one computer at either end, so you will not get the multiple-peer, maximum bandwidth utilization of a popular Torrent.
So if you can't get the multi-channel, you're left with "free" and probably hopefully easy.
In this case you'll need to configure your firewall and router, and probably install software to facilitate the transfer.
The most mature and direct method that doesn't require any third party apps or cloud hosting will be FTP.
Using a free tool such as FileZilla (which is multiplatform and free), which is an FTP client that also has a fully functional FTP server, you can "host" the file on one computer and allow the other computer to connect and move or copy the file using the maximum available bandwidth of the slowest connection of the two.
However, as alluded to earlier, personal firewalls and routers and modems block this sort of thing normally because FTP servers open to the internet are not usually things you want on an average user's computer. So you'll need to configure your firewall and router and probably modem to allow this transfer.

A: I used to share my file/volume with FTP, but due to firewalls, proxies and whatsnot that people sit behind its usually quite tricky to get it working. Ever since torrent became an option I have used that successfully in pretty much any thinkable situation, and its always worked great for me and my friends.

A: if the files is truly huge and your connection is not capable of handling sustained 1-5MBs, it might be faster to burn it onto a CD and simply mail it. Low-tech approach but it's still relevant!


text:
Q: rollback transaction based on condition I want to abort batch sql query transactions if column value is less than or equal to user's input value and alert user.
Here's what happens:

*

*available_qty value is subtracted from user's input qty value and the value is updated in food_menu table.

*user's order records are inserted into food_order table.

Here's my query:
    foreach($menuData as $item=>$qty)
    {
        if(empty($qty) || $qty == '0')
            continue;
        $sqlArray[] = "INSERT INTO food_order
        (user_id, item_id, quantity, order_type, updated_on, updated_by, created_by, created_on)
        VALUES ($uid, $item, $qty, '$menu_type', NOW(), $uid, $uid, NOW())";
        $sqlArray[] = "UPDATE food_menu SET available_qty = IF($qty >= available_qty, available_qty - $qty, available_qty) WHERE item_id = $item AND type = '$menu_type' AND DATE(updated_on) = CURRENT_DATE";
    }
    return (boolean) $this->db->exec($sqlArray);

*

*if $qty value is greater than available_qty field value, I want to abort the whole series of transactions in $sqlArray[].

Can I do that in the query itself?

A: I think a much better approach is to check the available quantity with remaining quantity before the start of your insert and update statement. But for the sake of information you can try the following:
Create a before update trigger on food_menu table. In the trigger check the available quantity of it is negative meaning the order quantity is more than available quantity then use the SIGNAL statement to raise an error which you will have to catch in your code and do the rollback and show appropriate message to the user.


text:
Q: Restlet client use authentication key Using restlet JEE 2.3.2.
I have a client id and secret to interact with the server restful API. Submitting that info gets me back an authorization key that must be used for subsequent request. In curl, I can make queries using that key and can get data back:
curl -XGET "Authorization c79cec57-a52f-4e04-f3ca-55ea2a202114" "https://some/restful/endpoint"

How do I set my client resource to submit that authorization key? The online docs doesn't seem to cover this scenario.

A: if the scheme is not important, you can use a "Custom" scheme, (as it is mandatory in HTTP specification"). In order to avoid the warning "scheme is not supported by restlet engine", just register one, as follow:
You can achieve what you need using a "custom" scheme, as follow.
    // Declare a custom Authenticator helper, if it is not standard
    Engine.getInstance().getRegisteredAuthenticators().add(new AuthenticatorHelper(ChallengeScheme.CUSTOM, true, false) {});

    // set up the reusable challenge response
    ChallengeResponse cred = new ChallengeResponse(ChallengeScheme.CUSTOM);
    cred.setRawValue("12344");

    ClientResource cr = new ClientResource("http://localhost:8183/");
    cr.setChallengeResponse(cred);
    cr.get();

If you want an empty scheme, you can do as follow:
    ChallengeResponse cred = new ChallengeResponse(new ChallengeScheme("",""));
    cred.setRawValue("12345");

A: In this case, I think that you can use challenge response as described since such feature builds the Authorization header using format Authorization: Scheme ChallengeResponseContent:
ClientResource resource = new ClientResource(resouceURL);
String token = "myToken";
ChallengeResponse cr = new ChallengeResponse(
             ChallengeScheme.HTTP_OAUTH_BEARER);
cr.setRawValue(token);
resource.setChallengeResponse(cr);
(...)

As a matter of fact, Restlet requires a challenge scheme that will be added before the token (or something else) within the value of the header Authorization. See extract from class AuthenticatorUtils#formatRequest:
public static String formatRequest(ChallengeRequest challenge,
        Response response, Series<Header> httpHeaders) {
    String result = null;

    if (challenge == null) {
        Context.getCurrentLogger().warning(
                "No challenge response to format.");
    } else if (challenge.getScheme() == null) {
        Context.getCurrentLogger().warning(
                "A challenge response must have a scheme defined.");
    } else if (challenge.getScheme().getTechnicalName() == null) {
        Context.getCurrentLogger().warning(
                "A challenge scheme must have a technical name defined.");
    } else {
        ChallengeWriter cw = new ChallengeWriter();
        cw.append(challenge.getScheme().getTechnicalName()).appendSpace();
        int cwInitialLength = cw.getBuffer().length();

        if (challenge.getRawValue() != null) {
            cw.append(challenge.getRawValue());
        } else {
    (...)

In your case, I think that you need to build the header Authorization by yourself as described below:
ClientResource resource = new ClientResource(resouceURL);
String token = "myToken";
resource.getRequest().getHeaders().add("Authorization", token);
resource.get();

You can also implement a custom client resource for your needs in order to automatically apply the token:
public class ProtectedClientResource extends ClientResource {
    private String token;

    public ProtectedClientResource(String uri) {
        super(uri);
    }

    @Override
    public Response handleOutbound(Request request) {
        if (token!=null) {
            request.getHeaders().add("Authorization", token);
        }
        return super.handleOutbound(request);
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}

Hope it helps you,
Thierry


text:
Q: What type of singularity $\sin(\frac{1}{\cos(\frac{1}{z})})$ has? (GATE 2009)
Determine the type of singularity at $z = 0$ of the following function and why?

$$f(z) = \sin \left(\frac{1}{\cos (\frac{1}{z})}\right).$$
I have no idea.
Thank you for your answer.

A: The singularity at $z=0$ is not isolated (since $\cos(1/z) = 0$ for a sequence of points tending to $z=0$). The usual classification into removable singularities, poles and essential singularities is only applicable to isolated singularities.
(Your textbook may have another convention.)


text:
Q: Let X be a set, How to show $\lim\limits_{x \to \infty} d(x_n,y_n) = d(x,y)$ for two sequences $x_n,y_n \in X$ and $ x,y \in X$ Let $(X, d)$ be a metric space, let $x_n$ and $y_n$ be two sequences in $X$ and $x, y ∈ X$. Suppose that
$x_n$ converges with respect $d$ to $x$ and $y_n$ converges with respect to $d$ to $y$. Show that $\lim\limits_{x \to \infty} d(x_n,y_n) = d(x,y)$
hint : use triangle inequality several times.
I attempted this question by applying triangle inequality to the $d(x,y)$, where I get for $x,y,z \in X$, $d(x,y) \leq d(x,z) + d(z,y)$. but I don't see this leading anywhere.
Intuitively, I also feel like there is no need to apply the triangular inequality. Isn't it true that since $x_n \to x, y_n \to y$, I can write
$\lim\limits_{x \to \infty} d(x_n,y_n) = d(x,y)$ and be done with it?
Thank you for the help guys.

A: $$d(x_n,y_n)\le d(x_n,x)+d(x,y)+d(y,y_n)$$
and
$$d(x,y)\le d(x,x_n)+d(x_n,y_n)+d(y_n,y)$$
Now apply the limits.


text: Q: body-parser deprecated undefined extended: provide extended option. how to solve this error I am trying to set up database to use with javescript code. When I run my code, I keep getting this PS C:\Users\HP\Documents\VisualCode\js_code> node app.js body-parser deprecated undefined extended: provide extended option app.js:21:20 Server has started GET / 304 37.114 ms - - { Neo4jError: getaddrinfo ENOTFOUND locthost locthost:7687


text:
Q: What is the difference between genetic and evolutionary algorithms? Is there a difference between genetic algorithms and evolutionary algorithms?
I have read multiple papers, talking about genetic or evolutionary algorithms, and while very similar, I think they may not be the same thing.

A: From Z. Michalewicz 1996 - "Genetic Algorithms + Data Structures = Evolution Programs" [p.289]:

Evolution programs borrow heavily from genetic algorithms. However,
  they incorporate problem-specific knowledge by using "natural" data
  structures and problem-sensitive "genetic" operators. The basic
  difference between GAs and EPs is that the former are classified as
  weak, problem-independent methods, which is not the case for the
  latter.

So a GA should be able to solve any of the problems one solves with an EP/EA, but an EP/EA won't be able to solve all problems solved by the GA.
Of course, one pays with efficiency for the generality of GA.
Also, it seems that an algorithm is not an EA/EP if candidate solutions do not exchange information directly with each other (D. Simon 2013 - "Evolutionary Optimization Algorithms" [p.243]).
PS: D. Simon 2013 - "Evolutionary Optimization Algorithms" is an AMAZING book!

A: A genetic algorithm is a class of evolutionary algorithm. Although genetic algorithms are the most frequently encountered type of evolutionary algorithm, there are other types, such as Evolution Strategy. So, evolutionary algorithms encompass genetic algorithms, and more.

A: I know this thread is old but I myself had trouble understanding it simply from one place, therefore explaining it here.
Algorithms that follow laws of evolution are called "Evolutionary algorithms". There are two sub-classes of EA. One, Genetic Algorithm that uses crossover, along with mutation as GA operators.Second, Evolutionary programming, that uses only mutation as its operator.

A: Genetic algorithms use crossover (hence the 'gene' in their name) and mutation to search the space of possible solutions.
Evolutionary programming uses primarily mutation.
As posted already, both are types of evolutionary algorithms.

A: Evolutionary Strategies (Rechenberg 1973) and Genetic Algorithms (Holland 1975) are based on Darwins Evolutionary Theories. Evolutionary Strategies are the basis on Evolutionary Computation, hence Evolutionary Algorithms. In principal genetic algorithms (GA) are a sub-class of EA.
In contrast to EA, GA requires uses genetic representation in the sense of computational representation (genotype) and its real world representation (phenotype).


text:
Q: How do I make a recursive jQuery template (tmpl) availbe outside of my plugin? I have a Json object that I'm dumping into a jQuery template (tmpl). It needs to be recursive because the Json object can be n-levels deep. This code works. However, if I wrap it in a function (it belongs in a jQuery plugin i'm writing), it stops working. To see what I mean simply uncomment the function wrapper in the Javascript.
Play with it: http://jsfiddle.net/dbme/tkdZg/6/
HTML:

Javascript:
//(function ($) {
//    $.fn.SomePlugin = function() {
var movies = {
    "data": {
        "identifiers":{
            "type":0, "id":"makeunique_907827h"
        }
    },
    "children": {
        "data": {
            "identifiers": {
                "type":1, "id":"makeunique_716786g"
            }
        },
        "children": {
            "data": {
                "identifiers": {
                    "type":1, "id":"makeunique_234355g"
                }
            }
        }
    }
};

/* Render the template with the data */
var evntTemplate = $( "#evntTemplate" ).template( "evntTemplate" );
$.tmpl(evntTemplate, movies).appendTo("#eventList");
    //};
//}( jQuery ));

More info: I'm using RequireJS to load the files and kick off the whole process. I think that's what's killing the scope. Here's the code for that:
require(["jquery", "jquery.tmpl", "jquery.someplugin"], function($) {
    $(function() {
        $('body').SomePlugin();
    });
});

A: It is because you are not passing the jquery object as parameter to your function wrapper.
Working Example: http://jsfiddle.net/tkdZg/3
Change it to:
(function($) {
var movies = {
    "data": {
        "identifiers":{
            "type":0, "id":"makeunique_907827h"
        }
    },
    "children": {
        "data": {
            "identifiers": {
                "type":1, "id":"makeunique_716786g"
            }
        },
        "children": {
            "data": {
                "identifiers": {
                    "type":1, "id":"makeunique_234355g"
                }
            }
        }
    }
};

/* Render the template with the data */
var evntTemplate = $( "#evntTemplate" ).template( "evntTemplate" );
$.tmpl(evntTemplate, movies).appendTo("#eventList");
})($); //########################


text:
Q: Using RediSearch with NRediSearch (C#), how to apply OR clause on two numeric fields like i.CountyId == id || i.CityId == id I am developing a .Net Core web app with RediSearch. Previously I have used in-app memory cache, but I have to change it to distributed cache. The issue is, the web app has very complex searches which must be handled from cache. I though I just move the cache to Redis and must filter in Linq will stay the same just as with in-app memory cache, but if you have 500K+ entries in Redis, using a docker image on the same host took around 4 sec just to load these entries into a variable so this is not an option.
I have now implemented RediSearch with NRediSearch which seem to handle the load pretty well. The issue I have now, I have a search with multiple location fields.
Example
class Item{
    public int Id {get;set;}
    public int CountyId {get;set;}
    public int CityId {get;set;}
}
class Location{
    public int LocationId {get;set;}
    public bool IsCounty {get;set;}
}

I need to translate the following Linq command into RediSearch
public List<Item> Search(List<Location> location){
    var result = items.Where(i => location.Any(l => l.IsCounty && l.Id == i.CountyId) || location.Any(l => !l.IsCounty && i.CityId == l.Id))
}

I have read the RediSearch documentation, but have not found any answer yet. I have to do this in one search because of sorting.

A: I have found he answer.
FT.SEARCH idx "@title|body:(hello world) @url|image:mydomain"

Probably if NRediSearch can handle this or operator within a new query, if not, must be implemented straight through it's client

A: you can use my library i build over nredisearch. but it works for simple linq queries. its not work on nested objects. I will be glad if you contribute to its development.
if we talk about your example you have to duplicate your data for each location like this:
class Item {

    public int Id {get;set;}
    public int CountyId {get;set;}
    public int CityId {get;set;}
    public int LocationId {get;set;}
    public bool IsCounty {get;set;}
}

and you can search this daha with my library.
RedisworkCore
PackageManager:
Install-Package RedisworkCore
Dotnet CLI:
dotnet add package RedisworkCore
and you can create context like entityframework:
public class Person
{
    [RedisKey(0)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Lastname { get; set; }
}

public class SimpleContext : RedisContext
{
    public Rediset<Person> Persons { get; set; }
    public SimpleContext(RedisContextOptions options) : base(options) { }
}

then you can use Find, Where, Any, All, SortBy, SortByDescending, Skip, Take similar LINQ.
static async Task Main(string[] args)
{

  RedisContextOptions options = new RedisContextOptions
  {
    HostAndPort = "localhost:6379"
  };

  using (var context = new SimpleContext(options))
  {
    var person = new Person
    {
      Id = 26,
      Name = "Emre",
      Lastname = "Hızlı"
    };
    context.Persons.Add(person);
    await context.SaveChangesAsync();
  }

  using (var context = new SimpleContext(options))
  {
    Person person = await context.Persons.Find(26);
    List<Person> persons = await context.Persons.Where(x => x.Id > 0).ToListAsync();
  }

}

Notes:

*

*You should save your data with redisworkcore otherwise it won't work.

*Performance tests were not conducted. It may work better if I can get support as open source.


text:
Q: To find a locus of a point P inside triangle ABC ABC is a triangle. P is a point inside ABC such that its distances from the sides of Triangle ABC are x, y, z. If a, b, c and k are given set of constants, prove that the locus of P such that ax+by+cz=k is either an empty set or a line segment or coincides with the sets of all points in triangle ABC
Now, for the locus of point P to set of all points in triangle, the constants would have have to sides of the triangle and k would have to be twice the area of triangle ABC.
I can't figure anything out for the locus to be straight line however and that lead me to thinking ' What if I shouldn't be relating the distances to the area of the triangle'
One other approach I tried was to assume that locus coninciding with all points would only apply for equilateral triangles, for locus to be a straight line the triangle would have to be a isoceles and for locus to be an empty set, the triangle would be scalene one.
It would be incredibly helpful if someone could point whether I should relate the various cases of the locus to types of triangles or to given constants or to something else.

A: If $\alpha$, $\beta$, $\gamma$ are the lengths of the sides, and $s$ is double the area of the triangle, then
$$
\alpha x+\beta y+\gamma z=s,
\quad\text{that is:}\quad
z={s-\alpha x-\beta y\over\gamma}.
$$
Substitute that into $ax+by+cz=k$ and you'll get (in general) a linear equation in $x$, $y$, which can be shown to represent a line.

A: First, we simplify the problem by allowing for signed distances, and consider points outside the triangle.
We will show that the set of points that satisfy $ax+by+cz=k$ is either the null set, a line or the entire plane. Then, when restricted to the (interior) of the triangle, this becomes a null set, a line segment, or the entire interior, so the result follows.
Hint: For a point $P$, if the side lengths of the triangle are $l_a, l_b, l_c$, then $l_a x + l_b y + l_c z = 2 \Delta $.
Hint: Hence, it follows that $ax+by+cz=k$ is the entire plane iff $a:b:c:k = l_a : l_b: l_c : 2 \Delta$.
If $a:b:c = l_a : l_b: l_c $, then we either get the entire plane or the null set.
Henceforth, assume $a:b:c \neq l_a : l_b: l_c $.
Hint: For fixed values of $a, b, c, k$, if $P_1$ and $P_2$ are distinct points that satisfy the equation, then so does the entire line segment $P_1 P_2$.
Corollary: The solution set is a (affine) sub-space. It remains to show that the solution set cannot be a single point.
Hint: For fixed values of $a, b, c, k$, if there is (at least) 1 point that satisfies it, then there are at least 2 distinct points that satisfy it.
Suppose we have the solution $P_1 = (x_1, y_1, z_1)$, then the point $P_2 = (x_1 + bl_c - cl_b, y_1 +cl_a - al_c, z_1 + al_b-bl_a)$ will also satisfy both equations (expand and cancel terms). These are distinct points if $a:b:c \neq l_a : l_b: l_c $.


text:
Q: My enemy isn't moving when my character is standing still I'm currently coding a game on python, and I need a way for the enemy to run towards the player. It has to have a constant velocity of 5 pixels a cycle and this is my current code:
def move(self,character):
    characterposition = Vector(character.posx,character.posy)
    self.position = Vector(self.posx,self.posy)
    dist = characterposition.subtract(self.position)
    dist.normal(dist.length())
    length = dist.length()
    ratio = self.speed/math.sqrt(length)
    self.posx += dist.x * ratio
    self.posy += dist.y * ratio

this seems to be working until my character stops moving. When the character stops moving, the enemy stops as well. This is a problem and I would appreciate any suggestions.
Edit: Heres my loop.

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             pygame.quit()
             run = False
             continue
        updatecharacterposition()
        collided = checkforbarriercollision()
        badguy.move(character)
        if collided:
            print("YOU LOST")
            pygame.quit()
            time.sleep(5)
    redrawgamewindow()

A: Is the indenting in the code above correct? It shows updatecharacterposition() and the lines after it inside the for event in pygame.event.get(): loop.
If that is really the case, then none of that code will get called if you are not getting any events. That would cause all of the movement to stop.
Try this:
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             pygame.quit()
             run = False
             continue
    updatecharacterposition()
    collided = checkforbarriercollision()
    badguy.move(character)
    if collided:
        print("YOU LOST")
        pygame.quit()
        time.sleep(5)
    redrawgamewindow()

On a side note, it seems odd to me that badguy.move(character) is after the collision check. Usually you would move everything (the player and the 'badguy') and then do the collision check.


text:
Q: Remux Videos for iTunes Playability? What video formats are usable within iTunes, specifically for syncability/playability on iOS devices?
I understand that we're talking about a number of different things here:

*

*Container format

*Video codec

*Audio codec

*Subtitle format

I have a fairly extensive library of many different kinds of videos, and the prevailing formats are MKV and AVI.  I don't really know what codecs are most common in my library, but they pretty much fall under the generic MPEG4 banner, I suppose.
Whenever I research this question on my own, Google results are saturated with transcoding utilities (both paid and free).  Sure, transcoding makes for a simple "one click and it magically makes my home video play on my iPad" solution, but for my library it presents a few problems:

*

*Loss of quality

*Significant investment in time and computing resources

Is it possible that most of what I have is close enough and just needs to be re-muxed into a different container format?  Is there a utility (even command-line) which I could try for this?  How would I use that utility to remux and not transcode?

A: I have been fighting this issue myself, with some success - but mostly, I have reverted to getting more of my collection in MP4 in the first place.
Subler is a must have to begin. It effortlessly does remuxing of MKV to MP4, including soft subtitles and iTunes Metadata. So for most MKVs, it is a breeze to get them into iTunes in a tidy manner.
When it comes to AVI and other formats, it's a bit trickier. AVI tend to be used with video codecs such as DivX or XviD, and although they could be remuxed into an MP4 container, it seems iTunes will not read it.
If you wanna play around with remuxing, your best bet is ffmpeg. You will need to compile it yourself or Google for binaries.
I'd advice you to convert your MKVs using Subler, and to re-rip/re-download the AVIs in a newer format where possible. What is left you can transcode using Handbrake.


text:
Q: Applying function for manipulating RGB values of an image I would like to apply a self-defined RGB-based function for manipulating an image. My current solution works but is very slow:
from PIL import Image
import numpy as np

# Load Data and get RBG values
im = Image.open(file_name).convert('RGB')
pixels = np.array(im)
s = pixels.shape
p = pixels.reshape((s[0]*s[1], s[2]))

# Apply Funtion (Subtraction + Max Operator)
p = np.array([[rgb[0], max(rgb[1] - rgb[1]*0.5, 0), rgb[2]] for i, rgb in enumerate(p)])

# Generate Image
img = Image.fromarray(np.uint8(p.reshape(s)))
img.save(file_name + '_new.png')

A: The following vectorized code will give an identical output:
from PIL import Image
import numpy as np

# Load Data and get RBG values
im = Image.open(file_name).convert('RGB')
pixels = np.array(im)

# Apply Funtion (Subtraction + Max Operator)
pixels[:, :, 1] = np.maximum(pixels[:, :, 1]-0.5*pixels[:, :, 1], 0)

# Generate Image
img = Image.fromarray(pixels)
img.save(file_name + '_new.png')

I tested both versions with a (400, 400, 3) PNG image. Your initial solution takes about 1.2 seconds, whereas my code needs about 0.85 seconds. So, even your initial code is not that slow, from my point of view. Maybe for larger images, the difference will (also) increase.
Hope that helps!
EDIT: Ok, I did another test with a (8239, 1349, 3) PNG image. Your code needs 79.8 seconds, my (still) about 0.85 seconds. So, yes, the vectorized code seems way faster. ;-)


text:
Q: building a tf.estimator input_fn: feature is not in features dictionary I have a corpus of records that represent matchups in a video game. I want to feed this to a tf.estimator.DNNClassifier.
The records contain text representations of the 5 heroes on team 0 and the 5 heroes on team 1, the map the game was played on, and the winner of the game. I want to represent these three features as three sparse vectors.
I'm not using pandas or numpy right now. I would prefer to keep it as simple as possible for the time being, until I can elaborate my tf knowledge. (But no simpler!).
Perhaps the best way to ask the question is to show what I have and ask for help filling in the blank, at make_input_fn
import tensorflow as tf
import packunpack as source
import tempfile
from collections import namedtuple

GameRecord = namedtuple('GameRecord', 'team_0 team_1 game_map winner')
def parse(line):
    parts = line.rstrip().split("\t")
    return GameRecord(
        game_map = parts[1],
        team_0 = parts[2].split(","),
        team_1 = parts[3].split(","),
        winner = int(parts[4]))

def conjugate(record):
    return GameRecord(
        team_0 = record.team_1,
        team_1 = record.team_0,
        game_map = record.game_map,
        winner = 0 if record.winner == 1 else 1)

def sparse_team(team):
    return tf.SparseTensor(indices=team, values = [1] * len(team), dense_shape=[len(source.heroes_array)])

def sparse_map(i):
    return tf.SparseTensor(indices=[i], values = [1], dense_shape=[len(source.maps_array)])

def make_input_fn(filename, shuffle = True, add_conjugate_games = True):
    def _fn():
        records = []
        with open(filename, "r") as raw:
            i = 0
            for line in raw:
                record = parse(line)
                records.append(record)
                if add_conjugate_games:
                    # the team_0 and team_1 designations are arbitrary, and so the same inference should be drawn from a game and its "conjugate" game
                    records.append(conjugate(record))

        team_0s = map(lambda r: sparse_team(r.team_0), records)
        team_1s = map(lambda r: sparse_team(r.team_1), records)
        maps = map(lambda r: sparse_map(r.game_map), records)
        winners = map(lambda r: tf.constant([r.winner]), records)

        return ({
                    team_0: team_0s,
                    team_1: team_1s,
                    game_map: maps,
                },
                winners)
        #Please help me finish this function?

    return _fn

team_0 = tf.feature_column.embedding_column(
    tf.feature_column.categorical_column_with_vocabulary_list("team_0", source.heroes_array), 1)
team_1 = tf.feature_column.embedding_column(
    tf.feature_column.categorical_column_with_vocabulary_list("team_1", source.heroes_array), 1)
game_map = tf.feature_column.embedding_column(
    tf.feature_column.categorical_column_with_vocabulary_list("game_map", source.maps_array), 1)

model_dir = tempfile.mkdtemp()
m = tf.estimator.DNNClassifier(
    model_dir=model_dir,
    hidden_units = [1024, 512, 256],
    feature_columns=[team_0, team_1, game_map])

def main():
    m.train(input_fn=make_input_fn("validation.txt"))

if __name__ == "__main__":
    main()

I've been all over the docs today, but all of the code examples I can find show how to feed pandas and numpy data structures into input_fn, and obsure the underlying mechanics of the process by calling out to helper functions that don't work for me.
(e.g.,   https://www.tensorflow.org/get_started/input_fn
and
https://www.tensorflow.org/tutorials/wide)
tf version 1.4.0-dev20171008
When I run I get this stack trace. I think it doesn't like the return value from _fn. But that dictionary does have the names of the features that I gave to the model AFAICT.
 File "estimator.py", line 72, in <module>
    main()
  File "estimator.py", line 69, in main
    m.train(input_fn=make_input_fn("validation.txt"))
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator.py", line 711, in _train_model
    features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator.py", line 694, in _call_model_fn
    model_fn_results = self._model_fn(features=features, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/canned/dnn.py", line 334, in _model_fn
    config=config)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/canned/dnn.py", line 190, in _dnn_model_fn
    logits = logit_fn(features=features, mode=mode)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/canned/dnn.py", line 89, in dnn_logit_fn
    features=features, feature_columns=feature_columns)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/feature_column/feature_column.py", line 230, in input_lay
er
    trainable=trainable)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/feature_column/feature_column.py", line 1834, in _get_den
se_tensor
    inputs, weight_collections=weight_collections, trainable=trainable)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/feature_column/feature_column.py", line 2119, in _get_spa
rse_tensors
    return _CategoricalColumn.IdWeightPair(inputs.get(self), None)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/feature_column/feature_column.py", line 1533, in get
    transformed = column._transform_feature(self)  # pylint: disable=protected-access
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/feature_column/feature_column.py", line 2087, in _transfo
rm_feature
    input_tensor = _to_sparse_input(inputs.get(self.key))
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/feature_column/feature_column.py", line 1529, in get
    raise ValueError('Feature {} is not in features dictionary.'.format(key))
ValueError: Feature team_0 is not in features dictionary.

A: I think you should check your data and make sure the field you are missing (team_0) is showing up correctly. It could be many things like ill formed data or the field name might be incorrectly spelt in the training data source.


text:
Q: Is this right way to retrive data from context to solve full page caching issue in product detail page Magento2? I have refer sign in functionality on header where use customer data from context to check that customet is logged in or not?
So Can we use similar concept for product detail page?
Is this right way or more reliable way than private content?
Can anyone help please?


text:
Q: What is the difference between UIViewController and UIInputViewController ios swift Here I'am working on CustomKeyboardExtension. In my extensible .swift class file the class definition starts with UIInputViewController
class KeyboardViewController: UIInputViewController {

    @IBOutlet var nextKeyboardButton: UIButton!

    override func updateViewConstraints() {
        super.updateViewConstraints()

        // Add custom view sizing constraints here
    }
}

So what is the difference between UIViewController and UIInputViewController.

A: UIInputViewController is a subclass of UIViewController. It has all the same functionality as UIViewController but also includes some extra logic. It is specifically designed for creating custom keyboards.
What all features are added into UIInputViewController is best seen in official documentation.


text:
Q: Keep calling activity and clear other activities before that I am calling activities in the following order A>B>C>D, now I want to call Activity A and clear B and C but keep D. I am calling A with Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP. But all the activities apart from A is getting cleared. Any body has any idea how to clear B and C and keep D>A.

A: You can move A to the top (from D) by doing this in D:
Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

There aren't any simple flags you can use to get rid of B and C. I would suggest that you have B and C register a BroadcastReceiver that listens for a specific ACTION. After you launch A from D, you can then send a broadcast Intent that will cause B and C to finish themselves. For example, in B and C do this:
// Declare receiver as member variable
BroadcastReceiver exitReceiver = new BroadcastReceiver() {
    @Override
    void onReceive (Context context, Intent intent) {
        // This Activity is no longer needed, finish it
        finish();
    }
}

in onCreate() register the receiver:
registerReceiver(exitReceiver, new IntentFilter(ACTION_EXIT));

don't forget to unregister the receiver in onDestroy()!
In D, when you launch A, send a broadcast Intent containing ACTION_EXIT to make B and C finish, like this:
sendBroadcast(new Intent(ACTION_EXIT));

A: Add this in your manifest for Class B, C.
<activity
android:name=".AnyActivity"
android:noHistory="true" />


text:
Q: Set Focus on Open Powerpoint Presentation I open a couple of Powerpoint presentations using the same process but multiple instances:
Imports Microsoft.Office.Core
Imports Microsoft.Office.Interop

and then use this code:
Private Sub OpenSlideShow(FullPath As String)
Dim powerpointApp = New Microsoft.Office.Interop.PowerPoint.Application()
powerpointApp.Visible = MsoTriState.msoTrue
Dim presentaions = powerpointApp.Presentations
Dim myPresentation = presentaions.Open(FullPath, MsoTriState.msoTrue,            MsoTriState.msoFalse,MsoTriState.msoFalse)
Dim slideShowSettings = myPresentation.SlideShowSettings
slideShowSettings.Run()
End Sub

MY PROBLEM:
How do I set focus to any one of the powerpoint presentations when it is open but does not have focus?
I have tried AppActivate but nothing. I have tried SetForegroundWindow but neither seem to work.
Does anyone have a clue?


text:
Q: How do you make this menu slide using JQuery? I was able to get this far with creating my sliding menu, however, I'm not sure what I've entered wrong because the menu won't slide for me. I'm trying to get the menu to slide to the right when the 'tab' is clicked, then when the 'tab' is click again, I want the menu to retract to the left side of the screen.
In short, my question is:
1. Why won't the menu slide?
  <meta charset="utf-8" />

                   about me

                    book

            resume

                    ask

                    archive

title

websitetitle

 +

A: It seems to work in this form:
<!DOCTYPE html>

<meta charset="utf-8" />

                    about me

                    book

            resume

                    ask

                    archive

title name

 website name

+

The $(".tab") was wrong, it should have been $("#tab").  The first one would select a
 while the second one matches the
. Also the CSS could have been wrong too. It's better to use


text:
Q: PyQGIS: moving legend with changed reference point I am trying to create a print layout using PyQGIS. As part of that, I want to move my legend to the bottom right corner of the map, using the lower right corner of the legend as the reference point. Unfortunately I am struggling to get this to work. My code is shown below, including the printing I have been doing to troubleshoot.
layout = project.layoutManager().layoutByName(layout_name)
legend.setId('Legend')
layout.addLayoutItem(legend)
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(0.3))
legend.setTitle('Legend')
fontsize = 16
legend.setStyleFont(QgsLegendStyle.Title, QFont("Arial", 24))
legend.setStyleFont(QgsLegendStyle.Group, QFont("Arial", fontsize))
legend.setStyleFont(QgsLegendStyle.Subgroup, QFont("Arial", fontsize))
legend.setStyleFont(QgsLegendStyle.Symbol, QFont("Arial", fontsize))
legend.setStyleFont(QgsLegendStyle.SymbolLabel, QFont("Arial", fontsize))
layout.addLayoutItem(legend)
legend.setResizeToContents(True)
legend.redraw()
legend.refreshItemSize()
print(legend.sizeWithUnits())
print(legend.referencePoint())
print(legend.pagePositionWithUnits())
legend.setReferencePoint(QgsLayoutItem.LowerRight)
legend.attemptMove(QgsLayoutPoint(409, 284, QgsUnitTypes.LayoutMillimeters), useReferencePoint=True)
print(legend.sizeWithUnits())
print(legend.referencePoint())
print(legend.pagePositionWithUnits())
legend.refreshItemPosition()

This gives the following readout:
<QgsLayoutSize: 0 x 0 mm >
0
<QgsLayoutPoint: 0, 0 mm >
<QgsLayoutSize: 0 x 0 mm >
8
<QgsLayoutPoint: 409, 284 mm >

From the printout, I can see that the reference point of the lower right corner has been correctly set, and that point has been moved correctly. The problem seems to be that for some reason my legend has no size! It renders correctly on the print layout (except for being in the wrong place).
Can anyone help me to understand why this might be the case, and what I could do to correct this?
Pictures below showing the result (top) and intended result (bottom)

A: From your screenshot, it is clear that your legend is being added to your layout, "except for being in the wrong place".
You haven't shown or explained how you calculated the layout point values for the attemptMove() parameter, so I would suspect this may be the problem.
I would suggest that, instead of hardcoding the values, a better approach may be to retrieve the height and width values of either your layout page or map item and pass those subtracted by a small amount, to ensure that the legend is positioned correctly.
I tested using the code snippet below to position the lower right corner of the legend relative to the bottom right of a layout map item:
layout = QgsProject.instance().layoutManager().layoutByName('Test Layout')

# Retrieve width & height values of map item
map_item = [i for i in layout.items() if isinstance(i, QgsLayoutItemMap)][0]
map_width = map_item.sizeWithUnits().width()
map_height = map_item.sizeWithUnits().height()

legend = QgsLayoutItemLegend(layout)
layout.addLayoutItem(legend)
legend.setId('Legend')
layout.addLayoutItem(legend)
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(0.3))
legend.setTitle('Legend')

legend.setReferencePoint(QgsLayoutItem.LowerRight)

# Pass map width & height values (subtract a small amount) for position of legend lower-right corner
legend.attemptMove(QgsLayoutPoint(map_width-1, map_height-1, QgsUnitTypes.LayoutMillimeters), useReferencePoint=True)

Result:

If you want to position the legend relative to the bottom right of the layout page, you can retrieve the page height and width with this snippet:
pages = layout.pageCollection()
page = pages.page(0)
page_width = page.pageSize().width()
page_height = page.pageSize().height()


text:
Q: Circles tangent to a parabola For the past two weeks I was struggling with solving the following problem.
Description of variables:
$(x_n,y_n)$ - center point of the circle $C_n$
$r_n$ - radius of the circle $C_n$
Given the curve $k:y=x^2,x\geqslant0$, and knowing that for every $n\in\mathbb{N} \wedge  n>0$ $C_n$ is tangent to $k$, the $OX$ axis and externally tangent to $C_{n-1}$, find the explicit formula for $x_n$, $y_n$ and $r_n$ given the initial condition $C_0: (x-x_0)^2+(y-y_0)^2=r_0^2$, where $C_0$ is tangent to $OX$ and $k$.
It is obvious that $r_n=y_n$, but I did not manage to derive a sensible system of equations.
I said "sensible", because this is the only one I could think of:
$\begin{cases} \frac{x_T-x_n}{y_n-y_T}=2x_T \\ y_T=x_T^2\\\sqrt{(x_T-x_n)^2+(y_T-y_n)^2}=y_n \\ \sqrt{(x_n-x_{n-1})^2+(y_n-y_{n-1})^2}=y_n+y_{n-1} \end{cases}$
Is there no more convenient way to approach this?
Thank you for any help in advance.

A: This is not intended to be an answer as such but more of a suggestion as to how one might be able to proceed further.
It seems that the equation satisfied by the coordinates of the centre $(x,y)$ of any circle which touches the parabola and the $x$ axis is itself very complicated: $$x^2=\left(\frac{8y-1+\sqrt{16y+1}}{8}\right)\left(\frac{3+\sqrt{16y+1}}{4}\right)^2$$
Despite its appearance this is a fairly innocent-looking curve passing as you would expect between the parabola $y=x^2$ and the $x$ axis.
This was obtained by just considering the requirement that each circle must touch the parabola and the $x$ axis. Therefore somehow this would need to be coupled with the requirement that the circles touch each other in series, which can be written as $$x_{n+1}=x_n+2\sqrt{y_ny_{n+1}}$$
But I don't know how to link these up. Any ideas?

A: Standard  parametric equn of parabola $ y = x^2 / (4 f) $ is
( in this case we can take $ f= \frac14 $ )
$$ x = 2 f t ; \, y = f t^2; \, t = \tan \phi $$
Radius of contacting circle $ = y  \sec\phi   = f t^2 \sqrt{1+t^2} $
Distance to right of parabola point x-coordinate is $ y\,  t = f t^3  $
So the center of circle on x-axis $ ( 2 f t + f t^3, 0) $
Rest you can proceed.
EDIT1:
Contacting circles as shown.
$r$ is radius of bigger contact circle given independently as in sketch.
$$ x = 2 ft + r \sin \phi = 2 f t  + \frac {r  t}{ \sqrt{1+t^2}}$$
$$ y = ft^2 - \frac{r}{ \sqrt{1+t^2} }   $$
So you can solve for  $ t =  \tan \phi $ when $ y=r $ from the resulting sixth degree transcendental equation :
$$  \frac{f\; t^2}{r}= 1 -\frac{1}{ \sqrt{1+t^2} } $$


text:
Q: SwiftUI fullScreenCover without animations How can I disable animations on fullScreenCover ? I want the view to show up directly, not have it slide in from the bottom.
Thanks
Edit: it seems the question got closed because of lack of "debugging details". Seriously?
The above call defaults to a slide in animation, I just want to know how to do it without animations. No idea what "debugging details" are required here ...


text:
Q: How to get Response in form of an Array Code
package com;

public class Employee {

    private String name;

    private String empId;

    public Employee(String name, String empId) {
        super();
        this.name = name;
        this.empId = empId;
    }

    // equals and hashcode

}

package com;

import java.util.LinkedHashSet;
import java.util.Set;

public class TestEmp {

    public static void main(String[] args) {
        Employee emp1 = new Employee("Luke", "11");
        Employee emp2 = new Employee("Luke2", "12");

        Set<Employee> empSet = new LinkedHashSet<>();

        empSet.add(emp1);
        empSet.add(emp2);

        Object obj[] = empSet.toArray();

        System.out.println(obj);
    }

}

When i print i get the response it is showing as [Ljava.lang.Object;@7852e922
I need response in form of an Employee Array , can you please help how to get this in form of an array
The response needs to form of an Array of Employees

A: You would need to implement a toString method in the Employee class
public static class Employee {

        private String name;

        private String empId;

        public Employee(String name, String empId) {
            super();
            this.name = name;
            this.empId = empId;
        }

        @Override
        public String toString() {
            return "Employee{" +
                    "name='" + name + '\'' +
                    ", empId='" + empId + '\'' +
                    '}';
        }
    }

Main
public static void main(String[] args){
        Employee emp1 = new Employee("Luke","11");
        Employee emp2 = new Employee("Luke2","12");

        Set<Employee> empSet = new LinkedHashSet<>();

        empSet.add(emp1);
        empSet.add(emp2);
        System.out.println(empSet);

    }

Output:
[Employee{name='Luke', empId='11'}, Employee{name='Luke2', empId='12'}]

A: Override toString method in Employee class :
@Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", empId='" + empId + '\'' +
                '}';
    }

Use Arrays.toString to print in TestEmp class:
    System.out.println(Arrays.toString(obj));

A: java.lang.Object;@7852e922 is the Object address of Object obj[] =  empSet.toArray()
I give you an idea about using reflect to get value from Object Class and then store it into 2D arrays.
My idea does not need to overwrite toString() method but truely store value into an arrays.
I think empArray it is what you want.

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class TestEmp {
    public static void main(String[] args) throws IllegalAccessException {
        // TODO Auto-generated method stub

        Employee emp1 = new Employee("Luke", "11");
        Employee emp2 = new Employee("Luke2", "12");

        Set<Employee> empSet = new LinkedHashSet<>();

        empSet.add(emp1);
        empSet.add(emp2);

        Object obj[] = empSet.toArray();

        Field[] fs = Employee.class.getDeclaredFields();
        String [][] empArray = new String[obj.length][fs.length];

        for(int i=0; i<obj.length; i++){
            Class a = (Class) obj[i].getClass();
            for(int j=0; j<fs.length; j++){
                Field f = fs[j];
                f.setAccessible(true);
                Object val = f.get(obj[i]);
                empArray[i][j] = (String) val;
            }
        }
        Arrays.asList(empArray).forEach(x -> System.out.println(x[0]+" "+x[1]));
    }
}

And the result is :
Luke 11
Luke2 12


text:
Q: AttributeError: 'numpy.int64' object has no attribute '__dict__' but float64 works I am facing a very strange issue : json.dumps(np.int64(1), default=lambda o: o.__dict__) returns : AttributeError: 'numpy.int64' object has no attribute '__dict__'
While json.dumps(np.float64(1), default=lambda o: o.__dict__) returns correctly : '1.0'
Only difference is going from int64 to float64... Any suggestion ?

A: numpy.float64 inherits from float, so json.dumps handles instances like a regular float, and doesn't use your default callback.
numpy.int64 doesn't inherit from int (and cannot reasonably do so due to conflicting semantics and memory layout), so json.dumps tries to use your default callback, which fails because numpy.int64 instances don't have a __dict__.


text:
Q: Intersections with elliptic curves on a K3 surface This is a fairly simple question.
Suppose $E$ is an elliptic curve on a K3 surface $X$. Can we say that $E$ must intersect any curve $D\subset X$ of genus $g(D)\geq3$ ?

A: In fact this is true for curves of genus at least 2.
For an elliptic curve $E$ in a $K3$ surface $X$, adjunction tells us that we have $E^2=0$. Then Riemann–Roch says that $h^0(X,E) \geq 2$; on the other hand, the ideal sheaf sequence for $E$ says that $h^0(X,E) \leq 2$. So in fact $h^0(X,E)=2$.
So the line bundle corresponding to $E$ has 2 linearly independent sections; since $E^2=0$ we conclude that the bundle is globally generated, so gives us a fibration $f:X \rightarrow \mathbf P^1$ with $E$ as one of the sections.
But then the only curves on $X$ which can be disjoint from $E$ are components of the fibres of $f$, which have genus 1 (if they are smooth fibres) or 0 (if they are components of reducible fibres).


text:
Q: What's the correct pattern for threading in a python qt5 application? I'm trying to write a pyqt5 application with a long running, but not CPU intensive process. I'd like to be able to run it without hanging the UI, so I'm trying to use threading, but since it doesn't seem like I can just run a thread and have it stop after its gone through its code so that it can be run again, I've tried setting up the thread to wait for a variable to change before running.
I know this can't be the correct pattern for running long processes in a pyqt app.
import time
import threading
from PyQt5 import QtWidgets, uic

class MyApp(QtWidgets.QMainWindow):
    _run_thread = False

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = uic.loadUi('myapp.ui', self)

        self.ui.start_thread_button.clicked.connect(self._run_thread_function)

        self._thread = threading.Thread(target=self._run_thread_callback)
        self._thread.daemon = True
        self._thread.start()

        self.ui.show()

    def _run_thread_callback(self):
        while True:
            if self._run_thread:
                print("running thread code...")
                time.sleep(10)
                print("thread code finished")
                self._run_thread = False

    def _run_thread_function(self):
        print("starting thread...")
        self._run_thread = True

def main():
    app = QtWidgets.QApplication(sys.argv)
    MyApp()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

A: Below is a simple demo showing how to start and stop a worker thread, and safely comminucate with the gui thread.
import sys
from PyQt5 import QtCore, QtWidgets

class Worker(QtCore.QThread):
    dataSent = QtCore.pyqtSignal(dict)

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self._stopped = True
        self._mutex = QtCore.QMutex()

    def stop(self):
        self._mutex.lock()
        self._stopped = True
        self._mutex.unlock()

    def run(self):
        self._stopped = False
        for count in range(10):
            if self._stopped:
                break
            self.sleep(1)
            data = {
                'message':'running %d [%d]' % (
                    count, QtCore.QThread.currentThreadId()),
                'time': QtCore.QTime.currentTime(),
                'items': [1, 2, 3],
                }
            self.dataSent.emit(data)

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.edit = QtWidgets.QPlainTextEdit()
        self.edit.setReadOnly(True)
        self.button = QtWidgets.QPushButton('Start')
        self.button.clicked.connect(self.handleButton)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self._worker = Worker()
        self._worker.started.connect(self.handleThreadStarted)
        self._worker.finished.connect(self.handleThreadFinished)
        self._worker.dataSent.connect(self.handleDataSent)

    def handleThreadStarted(self):
        self.edit.clear()
        self.button.setText('Stop')
        self.edit.appendPlainText('started')

    def handleThreadFinished(self):
        self.button.setText('Start')
        self.edit.appendPlainText('stopped')

    def handleDataSent(self, data):
        self.edit.appendPlainText('message [%d]' %
            QtCore.QThread.currentThreadId())
        self.edit.appendPlainText(data['message'])
        self.edit.appendPlainText(data['time'].toString())
        self.edit.appendPlainText(repr(data['items']))

    def handleButton(self):
        if self._worker.isRunning():
            self._worker.stop()
        else:
            self._worker.start()

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 100, 400, 400)
    window.show()
    sys.exit(app.exec_())


text:
Q: Why are quantifiers needed in Tuple Relational Calculus? Why are quantifiers needed in Tuple Relational Calculus?
Lets say I have this statement:

{S.sname | S in Student and (exists G in Grade )(S.s# = G.s#)};

Why can't I just use this instead?

{S.sname | S in Student and  G in Grade and S.s# = G.s#};

A: The queries return the same value. But in the second example you could also ask for the G.grade of the student whereas in the first you can't. The right hand side of a Tuple Relational Calculus expression describes a set of tuples of which only the attributes from the left hand side are kept. Here the two right hand side expressions describe different sets of tuples, but the projection on the left hand side happens to leave the same value from both.
The difference between
r IN R AND EXISTS s IN S (etc)
r IN R AND s IN S ANDetc
is that the relation described by first only has the attributes of R whereas the relation described by the second has the attributes of R & S.
Suppose any relation T with attributes ... holds the rows where some expression T(...) holds. Then <...> IN T if and only if T(...).
Then we can describe the two relations above as the tuples satisfying (respectively)
R(...) AND EXISTSattributes in S & etc but not in R(S(...) ANDetc)
R(...) AND S(...) ANDetc
This notation (more or less) is called Domain Relational Calculus.
Suppose we define the following operators on relations:
PROJECTsome attributes of TT holds the rows where EXISTSother attributes of TT(...)
T NATURAL JOIN U holds the rows where T(...) AND U(...)
Then we can describe the two relations above as the tuples in (respectively)
R NATURAL JOIN PROJECTattributes in S & etc also in R(S NATURAL JOINetc)
R NATURAL JOIN S NATURAL JOINetc
This notation is called Relational Algebra.


text:
Q: Opera unite as a daemon Is it possible to run an opera unite server without the browser?
Say for instance I want to use my always-on FreeBSD server, which doesn't run X.

A: It actually needs a running X to draw the widgets: unless the application has an option to be ran as a daemon or something, there's no straight way.
But let's think: if we can redirect its display socket via SSH, maybe, we can accept all X requests and just do nothing? YES! Here's the receipt:
First, you'll need to ssh -X user@server opera from a remote machine to setup opera via GUI to have it running. Done? Ok, close it then.
Now you can fool it to think X is running: Xvfb - a "fake X server" - is made for this kind of thing: it emulates a dumb framebuffer using virtual memory. There's a script xvfb-run in the xorg-server package that makes it easy. Note that you still have to install the X server to get Xvfb (unless there's a separate port out there).
Cheers!


text:
Q: Obtain insertion time of a tuple in an existing table in PostgreSQL 9.3 I am running PostgreSQL 9.3 (in a hot standby setup) on Ubuntu 14.04 LTS.
I would like to display the growth (e.g. amount of tuples) of a table over time. The table does not contain a "timestamp" (or equivalent out of historical reasons) column.
Is their a way in PostgreSQL 9.3 to query information about the insertion time of a tuple in a table?

A: Doing a workaround might give you the statistics on growth of a table over time. In Postgres 9.3 there is a feature called The statistics collector.
This might do the trick:

*

*enable Run-Time Statistics

*create the desired analysis function using pg_stat_all_tables

*

*query how many new tuples have been inserted with n_tup_ins (see Table 27-5 pg_stat_all_tables View)

*calculate the difference to an older value to get the actual number of inserted tuples in a defined time-frame

Or you can take a look at the Zalando PGObserver.
Hope this helps.


text:
Q: Sort database results by the polymorphic relationship in Laravel I have an issue for sorting results by polymorphic relation in Laravel .
Suppose we have two table like this :
users table :
- integer id
- string  name

meta table :
- integer id
- string  key
- string  value
- string  owner_type
- integer owner_id

Relation between users table and meta table is polymorphic relation.
So we have some users that each of them has some meta
This is a hypothetical example of database records ( with meta )
id      1
name    "user1"
meta :
   id           3
   key          "test"
   value        "3"
   owner_type   "App\\User"
   owner_id     1

   id           2
   key          "some other key"
   value        "some other value"
   owner_type   "App\\User"
   owner_id     1

id      2
name    "user2"
meta :
   id           3
   key          "test"
   value        "2"
   owner_type   "App\\User"
   owner_id     2

Now I want sort users results by meta value column where key is test .
something like this :
$results = User::with(['meta' => function($q){
     $q->where('key' , 'test');
}])->orderBy('meta.value')->get();

But of course the code above does not work
What's your solution ?
If we want get users from database and sort results by value of a meta  witch has a special key what we should do ?
note : I want sort the data before getting results

A: What about a join?
$results = User::join('meta', 'users.id', '=', 'meta.owner_id')
                   ->where('meta.key','=','test')
                   ->orderBy('meta.value')
                   ->select('users.id', 'users.name')
                   ->get();


text:
Q: I need to change the code in file.class and then save it at same format (file.class) I need to change the code in file.class and then save it at same format (file.class) ,please anyone can help me ?
thanks

A: decompile the class using java decompilers . I prefer JD-compiler.
create eclipse project and build project include other dependent class files in a jar.


text:
Q: SlidingUpPanel with TabLayout and scrollable views My app uses the SlidingUpPanel library. The main sliding up panel holds a RelativeLayout and a LinearLayout as its two children. The TabLayout is in the LinearLayout. Two of the tabs contain scrollable views and the third does not. All of the tabs are fragments.
The sliding up panel works as expected for the non-scrollable view and handles the first scrollable event on the scrollable views. However, the moment I release my finger, the scroll capability goes away and the view sticks.
Looking at other stackoverflow questions, I have tried setting the drag view and setting the scrollview as the documentation suggests but no dice. The view still sticks after the first scroll event.
I also implemented a ScrollableViewHelper as the documentation recommended but that didn't seem to help at all.
Here is a video of the behavior I am describing

SlidingUpPanel documentation on scrollable views
https://github.com/umano/AndroidSlidingUpPanel#scrollable-sliding-views
SlidingUpPanel Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/eventDetailsFullLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.sothree.slidinguppanel.SlidingUpPanelLayout
        android:id="@+id/eventDetailsSlidingUpPanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        sothree:umanoShadowHeight="4dp">

        <RelativeLayout
            android:id="@+id/eventDetailsHeaderLayout"
            android:paddingTop="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:id="@+id/eventDetailsEventImageLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <android.support.v7.widget.AppCompatImageView
                    android:id="@+id/eventDetailsEventBanner"
                    android:layout_width="match_parent"
                    android:layout_height="120dp"
                    android:background="@color/gray"
                    android:scaleType="fitXY" />

                <LinearLayout
                    android:layout_width="72dp"
                    android:layout_height="72dp"
                    android:layout_centerInParent="true"
                    android:background="@drawable/grey_circle"
                    android:gravity="center">

                    <android.support.v7.widget.AppCompatImageView
                        android:id="@+id/eventDetailsEventLogo"
                        android:layout_width="56dp"
                        android:layout_height="56dp"
                        android:gravity="center"
                        app:srcCompat="@drawable/ic_storefront" />
                </LinearLayout>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/eventDetailsEventImageLayout"
                android:layout_margin="16dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/eventDetailsEventName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/darkDarkGray"
                    android:textSize="18sp"
                    app:fontFamily="sans-serif-medium" />

            </LinearLayout>
        </RelativeLayout>

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

            <android.support.design.widget.TabLayout
                android:id="@+id/eventDetailsTabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorColor="@color/teal"
                app:tabSelectedTextColor="@color/teal"
                app:tabTextColor="@color/gray" />

            <android.support.v4.view.ViewPager
                android:id="@+id/eventDetailsViewPager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>
    </com.sothree.slidinguppanel.SlidingUpPanelLayout>
</LinearLayout>


text:
Q: Opposite function to add_rownames in dplyr As an intermediate step I generate a data frame with one column as character strings and the rest are numbers. I'd like to convert it to a matrix, but first I have to convert that character column into row names and remove it from the data frame.
Is there a simpe way to do this in dplyr? A function like to_rownames() that is opposite to add_rownames()?
I saw a solution using a custom function, but it's really out of dplyr philosophy.

A: This provides NSE & standard eval functions:
library(dplyr)

df <- data_frame(a=sample(letters, 4), b=c(1:4), c=c(5:8))

reset_rownames <- function(df, col="rowname") {
  stopifnot(is.data.frame(df))
  col <- as.character(substitute(col))
  reset_rownames_(df, col)
}

reset_rownames_ <- function(df, col="rowname") {
  stopifnot(is.data.frame(df))
  nm <- data.frame(df)[, col]
  df <- df[, !(colnames(df) %in% col)]
  rownames(df) <- nm
  df
}

m <- "rowname"

head(as.matrix(reset_rownames(add_rownames(mtcars), "rowname")))
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

head(as.matrix(reset_rownames_(add_rownames(mtcars), m)))
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Perhaps to_rownames() or set_rownames() makes more sense. ¯\_(ツ)_/¯ YMMV.

A: You can now use the tibble-package:
tibble::column_to_rownames()

A: If you really need a matrix you can just save the character column to a separate variable, drop it, and then create the matrix
library(dplyr)

df <- data_frame(a = sample(letters, 4), b = c(1:4), c = c(5:8))

letters <- df %>% select(a)
a.matrix <- df %>% select(-a) %>% as.matrix

Not sure what you are going to do after that, but this gets you as far as you asked for...


text:
Q: Yoneda embedding preserves finite coproducts For the Yoneda Embedding, where $\mathcal{T}$ is an algebraic theory,
$$
Y_\mathcal{T}: \mathcal{T}^\mathrm{op} \to Alg \mathcal{T}
$$
it is claimed that $Y_\mathcal{T}$ preserves finite coproducts. The argument provided is as follows

I am not quite sure how the last line proves that $\mathcal{T}(t_1 \times t_2, -)$ is a co-product of $\mathcal{T}(t_1, -)$ and $\mathcal{T}(t_2, -)$. It seems that all that is shown is
$$
[Y_\mathcal{T}(t_1 + t_2), A] \cong [\mathcal{T}(t_1 \times t_2 , -), A]\cong A(t_1 \times t_2) \cong A(t_1) \times A(t_2) \cong [\mathcal{T}(t_1, -) , A] \times [\mathcal{T}(t_2, -) , A] \cong [\mathcal{T}(t_1, -)\times \mathcal{T}(t_2, -)  , A]\cong [Y_\mathcal{T}(t_1)\times Y_\mathcal{T}( t_2), A] .
$$
But I am not sure how to use that to show the claimed sentence.

A: Your last two isomorphims are wrong, or more precisely, the second-to-last isomorphism is wrong. The universal property of the coproduct gives you an isomorphism
$$[\mathcal{T}(t_1, -) , A] \times [\mathcal{T}(t_2, -) , A] \cong [\mathcal{T}(t_1, -)+ \mathcal{T}(t_2, -)  , A] = [Y_\mathcal{T}(t_1)+Y_\mathcal{T}(t_2),A],$$
which concludes the proof.